sqlite3.c 6.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.12.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. /************** Begin file sqliteInt.h ***************************************/
  26. /*
  27. ** 2001 September 15
  28. **
  29. ** The author disclaims copyright to this source code. In place of
  30. ** a legal notice, here is a blessing:
  31. **
  32. ** May you do good and not evil.
  33. ** May you find forgiveness for yourself and forgive others.
  34. ** May you share freely, never taking more than you give.
  35. **
  36. *************************************************************************
  37. ** Internal interface definitions for SQLite.
  38. **
  39. */
  40. #ifndef _SQLITEINT_H_
  41. #define _SQLITEINT_H_
  42. /*
  43. ** Make sure that rand_s() is available on Windows systems with MSVC 2005
  44. ** or higher.
  45. */
  46. #if defined(_MSC_VER) && _MSC_VER>=1400
  47. # define _CRT_RAND_S
  48. #endif
  49. /*
  50. ** Include the header file used to customize the compiler options for MSVC.
  51. ** This should be done first so that it can successfully prevent spurious
  52. ** compiler warnings due to subsequent content in this file and other files
  53. ** that are included by this file.
  54. */
  55. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  56. /************** Begin file msvc.h ********************************************/
  57. /*
  58. ** 2015 January 12
  59. **
  60. ** The author disclaims copyright to this source code. In place of
  61. ** a legal notice, here is a blessing:
  62. **
  63. ** May you do good and not evil.
  64. ** May you find forgiveness for yourself and forgive others.
  65. ** May you share freely, never taking more than you give.
  66. **
  67. ******************************************************************************
  68. **
  69. ** This file contains code that is specific to MSVC.
  70. */
  71. #ifndef _MSVC_H_
  72. #define _MSVC_H_
  73. #if defined(_MSC_VER)
  74. #pragma warning(disable : 4054)
  75. #pragma warning(disable : 4055)
  76. #pragma warning(disable : 4100)
  77. #pragma warning(disable : 4127)
  78. #pragma warning(disable : 4130)
  79. #pragma warning(disable : 4152)
  80. #pragma warning(disable : 4189)
  81. #pragma warning(disable : 4206)
  82. #pragma warning(disable : 4210)
  83. #pragma warning(disable : 4232)
  84. #pragma warning(disable : 4244)
  85. #pragma warning(disable : 4305)
  86. #pragma warning(disable : 4306)
  87. #pragma warning(disable : 4702)
  88. #pragma warning(disable : 4706)
  89. #endif /* defined(_MSC_VER) */
  90. #endif /* _MSVC_H_ */
  91. /************** End of msvc.h ************************************************/
  92. /************** Continuing where we left off in sqliteInt.h ******************/
  93. /*
  94. ** Special setup for VxWorks
  95. */
  96. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  97. /************** Begin file vxworks.h *****************************************/
  98. /*
  99. ** 2015-03-02
  100. **
  101. ** The author disclaims copyright to this source code. In place of
  102. ** a legal notice, here is a blessing:
  103. **
  104. ** May you do good and not evil.
  105. ** May you find forgiveness for yourself and forgive others.
  106. ** May you share freely, never taking more than you give.
  107. **
  108. ******************************************************************************
  109. **
  110. ** This file contains code that is specific to Wind River's VxWorks
  111. */
  112. #if defined(__RTP__) || defined(_WRS_KERNEL)
  113. /* This is VxWorks. Set up things specially for that OS
  114. */
  115. #include <vxWorks.h>
  116. #include <pthread.h> /* amalgamator: dontcache */
  117. #define OS_VXWORKS 1
  118. #define SQLITE_OS_OTHER 0
  119. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  120. #define SQLITE_OMIT_LOAD_EXTENSION 1
  121. #define SQLITE_ENABLE_LOCKING_STYLE 0
  122. #define HAVE_UTIME 1
  123. #else
  124. /* This is not VxWorks. */
  125. #define OS_VXWORKS 0
  126. #define HAVE_FCHOWN 1
  127. #define HAVE_READLINK 1
  128. #define HAVE_LSTAT 1
  129. #endif /* defined(_WRS_KERNEL) */
  130. /************** End of vxworks.h *********************************************/
  131. /************** Continuing where we left off in sqliteInt.h ******************/
  132. /*
  133. ** These #defines should enable >2GB file support on POSIX if the
  134. ** underlying operating system supports it. If the OS lacks
  135. ** large file support, or if the OS is windows, these should be no-ops.
  136. **
  137. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  138. ** system #includes. Hence, this block of code must be the very first
  139. ** code in all source files.
  140. **
  141. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  142. ** on the compiler command line. This is necessary if you are compiling
  143. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  144. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  145. ** without this option, LFS is enable. But LFS does not exist in the kernel
  146. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  147. ** portability you should omit LFS.
  148. **
  149. ** The previous paragraph was written in 2005. (This paragraph is written
  150. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  151. ** you should probably leave LFS enabled. But some embedded platforms might
  152. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  153. **
  154. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  155. */
  156. #ifndef SQLITE_DISABLE_LFS
  157. # define _LARGE_FILE 1
  158. # ifndef _FILE_OFFSET_BITS
  159. # define _FILE_OFFSET_BITS 64
  160. # endif
  161. # define _LARGEFILE_SOURCE 1
  162. #endif
  163. /* What version of GCC is being used. 0 means GCC is not being used */
  164. #ifdef __GNUC__
  165. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  166. #else
  167. # define GCC_VERSION 0
  168. #endif
  169. /* Needed for various definitions... */
  170. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  171. # define _GNU_SOURCE
  172. #endif
  173. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  174. # define _BSD_SOURCE
  175. #endif
  176. /*
  177. ** For MinGW, check to see if we can include the header file containing its
  178. ** version information, among other things. Normally, this internal MinGW
  179. ** header file would [only] be included automatically by other MinGW header
  180. ** files; however, the contained version information is now required by this
  181. ** header file to work around binary compatibility issues (see below) and
  182. ** this is the only known way to reliably obtain it. This entire #if block
  183. ** would be completely unnecessary if there was any other way of detecting
  184. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  185. ** some MinGW-specific macros). When compiling for MinGW, either the
  186. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  187. ** defined; otherwise, detection of conditions specific to MinGW will be
  188. ** disabled.
  189. */
  190. #if defined(_HAVE_MINGW_H)
  191. # include "mingw.h"
  192. #elif defined(_HAVE__MINGW_H)
  193. # include "_mingw.h"
  194. #endif
  195. /*
  196. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  197. ** define is required to maintain binary compatibility with the MSVC runtime
  198. ** library in use (e.g. for Windows XP).
  199. */
  200. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  201. defined(_WIN32) && !defined(_WIN64) && \
  202. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  203. defined(__MSVCRT__)
  204. # define _USE_32BIT_TIME_T
  205. #endif
  206. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  207. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  208. ** MinGW.
  209. */
  210. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  211. /************** Begin file sqlite3.h *****************************************/
  212. /*
  213. ** 2001 September 15
  214. **
  215. ** The author disclaims copyright to this source code. In place of
  216. ** a legal notice, here is a blessing:
  217. **
  218. ** May you do good and not evil.
  219. ** May you find forgiveness for yourself and forgive others.
  220. ** May you share freely, never taking more than you give.
  221. **
  222. *************************************************************************
  223. ** This header file defines the interface that the SQLite library
  224. ** presents to client programs. If a C-function, structure, datatype,
  225. ** or constant definition does not appear in this file, then it is
  226. ** not a published API of SQLite, is subject to change without
  227. ** notice, and should not be referenced by programs that use SQLite.
  228. **
  229. ** Some of the definitions that are in this file are marked as
  230. ** "experimental". Experimental interfaces are normally new
  231. ** features recently added to SQLite. We do not anticipate changes
  232. ** to experimental interfaces but reserve the right to make minor changes
  233. ** if experience from use "in the wild" suggest such changes are prudent.
  234. **
  235. ** The official C-language API documentation for SQLite is derived
  236. ** from comments in this file. This file is the authoritative source
  237. ** on how SQLite interfaces are supposed to operate.
  238. **
  239. ** The name of this file under configuration management is "sqlite.h.in".
  240. ** The makefile makes some minor changes to this file (such as inserting
  241. ** the version number) and changes its name to "sqlite3.h" as
  242. ** part of the build process.
  243. */
  244. #ifndef _SQLITE3_H_
  245. #define _SQLITE3_H_
  246. #include <stdarg.h> /* Needed for the definition of va_list */
  247. /*
  248. ** Make sure we can call this stuff from C++.
  249. */
  250. #if 0
  251. extern "C" {
  252. #endif
  253. /*
  254. ** Provide the ability to override linkage features of the interface.
  255. */
  256. #ifndef SQLITE_EXTERN
  257. # define SQLITE_EXTERN extern
  258. #endif
  259. #ifndef SQLITE_API
  260. # define SQLITE_API
  261. #endif
  262. #ifndef SQLITE_CDECL
  263. # define SQLITE_CDECL
  264. #endif
  265. #ifndef SQLITE_STDCALL
  266. # define SQLITE_STDCALL
  267. #endif
  268. /*
  269. ** These no-op macros are used in front of interfaces to mark those
  270. ** interfaces as either deprecated or experimental. New applications
  271. ** should not use deprecated interfaces - they are supported for backwards
  272. ** compatibility only. Application writers should be aware that
  273. ** experimental interfaces are subject to change in point releases.
  274. **
  275. ** These macros used to resolve to various kinds of compiler magic that
  276. ** would generate warning messages when they were used. But that
  277. ** compiler magic ended up generating such a flurry of bug reports
  278. ** that we have taken it all out and gone back to using simple
  279. ** noop macros.
  280. */
  281. #define SQLITE_DEPRECATED
  282. #define SQLITE_EXPERIMENTAL
  283. /*
  284. ** Ensure these symbols were not defined by some previous header file.
  285. */
  286. #ifdef SQLITE_VERSION
  287. # undef SQLITE_VERSION
  288. #endif
  289. #ifdef SQLITE_VERSION_NUMBER
  290. # undef SQLITE_VERSION_NUMBER
  291. #endif
  292. /*
  293. ** CAPI3REF: Compile-Time Library Version Numbers
  294. **
  295. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  296. ** evaluates to a string literal that is the SQLite version in the
  297. ** format "X.Y.Z" where X is the major version number (always 3 for
  298. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  299. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  300. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  301. ** numbers used in [SQLITE_VERSION].)^
  302. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  303. ** be larger than the release from which it is derived. Either Y will
  304. ** be held constant and Z will be incremented or else Y will be incremented
  305. ** and Z will be reset to zero.
  306. **
  307. ** Since version 3.6.18, SQLite source code has been stored in the
  308. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  309. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  310. ** a string which identifies a particular check-in of SQLite
  311. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  312. ** string contains the date and time of the check-in (UTC) and an SHA1
  313. ** hash of the entire source tree.
  314. **
  315. ** See also: [sqlite3_libversion()],
  316. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  317. ** [sqlite_version()] and [sqlite_source_id()].
  318. */
  319. #define SQLITE_VERSION "3.12.1"
  320. #define SQLITE_VERSION_NUMBER 3012001
  321. #define SQLITE_SOURCE_ID "2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d"
  322. /*
  323. ** CAPI3REF: Run-Time Library Version Numbers
  324. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  325. **
  326. ** These interfaces provide the same information as the [SQLITE_VERSION],
  327. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  328. ** but are associated with the library instead of the header file. ^(Cautious
  329. ** programmers might include assert() statements in their application to
  330. ** verify that values returned by these interfaces match the macros in
  331. ** the header, and thus ensure that the application is
  332. ** compiled with matching library and header files.
  333. **
  334. ** <blockquote><pre>
  335. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  336. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  337. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  338. ** </pre></blockquote>)^
  339. **
  340. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  341. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  342. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  343. ** function is provided for use in DLLs since DLL users usually do not have
  344. ** direct access to string constants within the DLL. ^The
  345. ** sqlite3_libversion_number() function returns an integer equal to
  346. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  347. ** a pointer to a string constant whose value is the same as the
  348. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  349. **
  350. ** See also: [sqlite_version()] and [sqlite_source_id()].
  351. */
  352. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  353. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
  354. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
  355. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
  356. /*
  357. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  358. **
  359. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  360. ** indicating whether the specified option was defined at
  361. ** compile time. ^The SQLITE_ prefix may be omitted from the
  362. ** option name passed to sqlite3_compileoption_used().
  363. **
  364. ** ^The sqlite3_compileoption_get() function allows iterating
  365. ** over the list of options that were defined at compile time by
  366. ** returning the N-th compile time option string. ^If N is out of range,
  367. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  368. ** prefix is omitted from any strings returned by
  369. ** sqlite3_compileoption_get().
  370. **
  371. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  372. ** and sqlite3_compileoption_get() may be omitted by specifying the
  373. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  374. **
  375. ** See also: SQL functions [sqlite_compileoption_used()] and
  376. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  377. */
  378. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  379. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
  380. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
  381. #endif
  382. /*
  383. ** CAPI3REF: Test To See If The Library Is Threadsafe
  384. **
  385. ** ^The sqlite3_threadsafe() function returns zero if and only if
  386. ** SQLite was compiled with mutexing code omitted due to the
  387. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  388. **
  389. ** SQLite can be compiled with or without mutexes. When
  390. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  391. ** are enabled and SQLite is threadsafe. When the
  392. ** [SQLITE_THREADSAFE] macro is 0,
  393. ** the mutexes are omitted. Without the mutexes, it is not safe
  394. ** to use SQLite concurrently from more than one thread.
  395. **
  396. ** Enabling mutexes incurs a measurable performance penalty.
  397. ** So if speed is of utmost importance, it makes sense to disable
  398. ** the mutexes. But for maximum safety, mutexes should be enabled.
  399. ** ^The default behavior is for mutexes to be enabled.
  400. **
  401. ** This interface can be used by an application to make sure that the
  402. ** version of SQLite that it is linking against was compiled with
  403. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  404. **
  405. ** This interface only reports on the compile-time mutex setting
  406. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  407. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  408. ** can be fully or partially disabled using a call to [sqlite3_config()]
  409. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  410. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  411. ** sqlite3_threadsafe() function shows only the compile-time setting of
  412. ** thread safety, not any run-time changes to that setting made by
  413. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  414. ** is unchanged by calls to sqlite3_config().)^
  415. **
  416. ** See the [threading mode] documentation for additional information.
  417. */
  418. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
  419. /*
  420. ** CAPI3REF: Database Connection Handle
  421. ** KEYWORDS: {database connection} {database connections}
  422. **
  423. ** Each open SQLite database is represented by a pointer to an instance of
  424. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  425. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  426. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  427. ** and [sqlite3_close_v2()] are its destructors. There are many other
  428. ** interfaces (such as
  429. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  430. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  431. ** sqlite3 object.
  432. */
  433. typedef struct sqlite3 sqlite3;
  434. /*
  435. ** CAPI3REF: 64-Bit Integer Types
  436. ** KEYWORDS: sqlite_int64 sqlite_uint64
  437. **
  438. ** Because there is no cross-platform way to specify 64-bit integer types
  439. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  440. **
  441. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  442. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  443. ** compatibility only.
  444. **
  445. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  446. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  447. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  448. ** between 0 and +18446744073709551615 inclusive.
  449. */
  450. #ifdef SQLITE_INT64_TYPE
  451. typedef SQLITE_INT64_TYPE sqlite_int64;
  452. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  453. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  454. typedef __int64 sqlite_int64;
  455. typedef unsigned __int64 sqlite_uint64;
  456. #else
  457. typedef long long int sqlite_int64;
  458. typedef unsigned long long int sqlite_uint64;
  459. #endif
  460. typedef sqlite_int64 sqlite3_int64;
  461. typedef sqlite_uint64 sqlite3_uint64;
  462. /*
  463. ** If compiling for a processor that lacks floating point support,
  464. ** substitute integer for floating-point.
  465. */
  466. #ifdef SQLITE_OMIT_FLOATING_POINT
  467. # define double sqlite3_int64
  468. #endif
  469. /*
  470. ** CAPI3REF: Closing A Database Connection
  471. ** DESTRUCTOR: sqlite3
  472. **
  473. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  474. ** for the [sqlite3] object.
  475. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  476. ** the [sqlite3] object is successfully destroyed and all associated
  477. ** resources are deallocated.
  478. **
  479. ** ^If the database connection is associated with unfinalized prepared
  480. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  481. ** will leave the database connection open and return [SQLITE_BUSY].
  482. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  483. ** and/or unfinished sqlite3_backups, then the database connection becomes
  484. ** an unusable "zombie" which will automatically be deallocated when the
  485. ** last prepared statement is finalized or the last sqlite3_backup is
  486. ** finished. The sqlite3_close_v2() interface is intended for use with
  487. ** host languages that are garbage collected, and where the order in which
  488. ** destructors are called is arbitrary.
  489. **
  490. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  491. ** [sqlite3_blob_close | close] all [BLOB handles], and
  492. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  493. ** with the [sqlite3] object prior to attempting to close the object. ^If
  494. ** sqlite3_close_v2() is called on a [database connection] that still has
  495. ** outstanding [prepared statements], [BLOB handles], and/or
  496. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  497. ** of resources is deferred until all [prepared statements], [BLOB handles],
  498. ** and [sqlite3_backup] objects are also destroyed.
  499. **
  500. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  501. ** the transaction is automatically rolled back.
  502. **
  503. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  504. ** must be either a NULL
  505. ** pointer or an [sqlite3] object pointer obtained
  506. ** from [sqlite3_open()], [sqlite3_open16()], or
  507. ** [sqlite3_open_v2()], and not previously closed.
  508. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  509. ** argument is a harmless no-op.
  510. */
  511. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
  512. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
  513. /*
  514. ** The type for a callback function.
  515. ** This is legacy and deprecated. It is included for historical
  516. ** compatibility and is not documented.
  517. */
  518. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  519. /*
  520. ** CAPI3REF: One-Step Query Execution Interface
  521. ** METHOD: sqlite3
  522. **
  523. ** The sqlite3_exec() interface is a convenience wrapper around
  524. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  525. ** that allows an application to run multiple statements of SQL
  526. ** without having to use a lot of C code.
  527. **
  528. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  529. ** semicolon-separate SQL statements passed into its 2nd argument,
  530. ** in the context of the [database connection] passed in as its 1st
  531. ** argument. ^If the callback function of the 3rd argument to
  532. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  533. ** coming out of the evaluated SQL statements. ^The 4th argument to
  534. ** sqlite3_exec() is relayed through to the 1st argument of each
  535. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  536. ** is NULL, then no callback is ever invoked and result rows are
  537. ** ignored.
  538. **
  539. ** ^If an error occurs while evaluating the SQL statements passed into
  540. ** sqlite3_exec(), then execution of the current statement stops and
  541. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  542. ** is not NULL then any error message is written into memory obtained
  543. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  544. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  545. ** on error message strings returned through the 5th parameter of
  546. ** sqlite3_exec() after the error message string is no longer needed.
  547. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  548. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  549. ** NULL before returning.
  550. **
  551. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  552. ** routine returns SQLITE_ABORT without invoking the callback again and
  553. ** without running any subsequent SQL statements.
  554. **
  555. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  556. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  557. ** callback is an array of pointers to strings obtained as if from
  558. ** [sqlite3_column_text()], one for each column. ^If an element of a
  559. ** result row is NULL then the corresponding string pointer for the
  560. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  561. ** sqlite3_exec() callback is an array of pointers to strings where each
  562. ** entry represents the name of corresponding result column as obtained
  563. ** from [sqlite3_column_name()].
  564. **
  565. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  566. ** to an empty string, or a pointer that contains only whitespace and/or
  567. ** SQL comments, then no SQL statements are evaluated and the database
  568. ** is not changed.
  569. **
  570. ** Restrictions:
  571. **
  572. ** <ul>
  573. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  574. ** is a valid and open [database connection].
  575. ** <li> The application must not close the [database connection] specified by
  576. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  577. ** <li> The application must not modify the SQL statement text passed into
  578. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  579. ** </ul>
  580. */
  581. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  582. sqlite3*, /* An open database */
  583. const char *sql, /* SQL to be evaluated */
  584. int (*callback)(void*,int,char**,char**), /* Callback function */
  585. void *, /* 1st argument to callback */
  586. char **errmsg /* Error msg written here */
  587. );
  588. /*
  589. ** CAPI3REF: Result Codes
  590. ** KEYWORDS: {result code definitions}
  591. **
  592. ** Many SQLite functions return an integer result code from the set shown
  593. ** here in order to indicate success or failure.
  594. **
  595. ** New error codes may be added in future versions of SQLite.
  596. **
  597. ** See also: [extended result code definitions]
  598. */
  599. #define SQLITE_OK 0 /* Successful result */
  600. /* beginning-of-error-codes */
  601. #define SQLITE_ERROR 1 /* SQL error or missing database */
  602. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  603. #define SQLITE_PERM 3 /* Access permission denied */
  604. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  605. #define SQLITE_BUSY 5 /* The database file is locked */
  606. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  607. #define SQLITE_NOMEM 7 /* A malloc() failed */
  608. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  609. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  610. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  611. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  612. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  613. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  614. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  615. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  616. #define SQLITE_EMPTY 16 /* Database is empty */
  617. #define SQLITE_SCHEMA 17 /* The database schema changed */
  618. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  619. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  620. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  621. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  622. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  623. #define SQLITE_AUTH 23 /* Authorization denied */
  624. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  625. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  626. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  627. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  628. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  629. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  630. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  631. /* end-of-error-codes */
  632. /*
  633. ** CAPI3REF: Extended Result Codes
  634. ** KEYWORDS: {extended result code definitions}
  635. **
  636. ** In its default configuration, SQLite API routines return one of 30 integer
  637. ** [result codes]. However, experience has shown that many of
  638. ** these result codes are too coarse-grained. They do not provide as
  639. ** much information about problems as programmers might like. In an effort to
  640. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  641. ** support for additional result codes that provide more detailed information
  642. ** about errors. These [extended result codes] are enabled or disabled
  643. ** on a per database connection basis using the
  644. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  645. ** the most recent error can be obtained using
  646. ** [sqlite3_extended_errcode()].
  647. */
  648. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  649. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  650. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  651. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  652. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  653. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  654. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  655. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  656. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  657. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  658. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  659. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  660. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  661. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  662. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  663. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  664. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  665. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  666. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  667. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  668. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  669. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  670. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  671. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  672. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  673. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  674. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  675. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  676. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  677. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  678. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  679. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  680. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  681. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  682. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  683. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  684. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  685. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  686. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  687. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  688. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  689. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  690. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  691. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  692. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  693. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  694. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  695. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  696. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  697. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  698. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  699. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  700. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  701. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  702. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  703. /*
  704. ** CAPI3REF: Flags For File Open Operations
  705. **
  706. ** These bit values are intended for use in the
  707. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  708. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  709. */
  710. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  711. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  712. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  713. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  714. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  715. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  716. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  717. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  718. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  719. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  720. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  721. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  722. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  723. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  724. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  725. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  726. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  727. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  728. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  729. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  730. /* Reserved: 0x00F00000 */
  731. /*
  732. ** CAPI3REF: Device Characteristics
  733. **
  734. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  735. ** object returns an integer which is a vector of these
  736. ** bit values expressing I/O characteristics of the mass storage
  737. ** device that holds the file that the [sqlite3_io_methods]
  738. ** refers to.
  739. **
  740. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  741. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  742. ** mean that writes of blocks that are nnn bytes in size and
  743. ** are aligned to an address which is an integer multiple of
  744. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  745. ** that when data is appended to a file, the data is appended
  746. ** first then the size of the file is extended, never the other
  747. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  748. ** information is written to disk in the same order as calls
  749. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  750. ** after reboot following a crash or power loss, the only bytes in a
  751. ** file that were written at the application level might have changed
  752. ** and that adjacent bytes, even bytes within the same sector are
  753. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  754. ** flag indicate that a file cannot be deleted when open. The
  755. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  756. ** read-only media and cannot be changed even by processes with
  757. ** elevated privileges.
  758. */
  759. #define SQLITE_IOCAP_ATOMIC 0x00000001
  760. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  761. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  762. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  763. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  764. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  765. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  766. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  767. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  768. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  769. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  770. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  771. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  772. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  773. /*
  774. ** CAPI3REF: File Locking Levels
  775. **
  776. ** SQLite uses one of these integer values as the second
  777. ** argument to calls it makes to the xLock() and xUnlock() methods
  778. ** of an [sqlite3_io_methods] object.
  779. */
  780. #define SQLITE_LOCK_NONE 0
  781. #define SQLITE_LOCK_SHARED 1
  782. #define SQLITE_LOCK_RESERVED 2
  783. #define SQLITE_LOCK_PENDING 3
  784. #define SQLITE_LOCK_EXCLUSIVE 4
  785. /*
  786. ** CAPI3REF: Synchronization Type Flags
  787. **
  788. ** When SQLite invokes the xSync() method of an
  789. ** [sqlite3_io_methods] object it uses a combination of
  790. ** these integer values as the second argument.
  791. **
  792. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  793. ** sync operation only needs to flush data to mass storage. Inode
  794. ** information need not be flushed. If the lower four bits of the flag
  795. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  796. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  797. ** to use Mac OS X style fullsync instead of fsync().
  798. **
  799. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  800. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  801. ** settings. The [synchronous pragma] determines when calls to the
  802. ** xSync VFS method occur and applies uniformly across all platforms.
  803. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  804. ** energetic or rigorous or forceful the sync operations are and
  805. ** only make a difference on Mac OSX for the default SQLite code.
  806. ** (Third-party VFS implementations might also make the distinction
  807. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  808. ** operating systems natively supported by SQLite, only Mac OSX
  809. ** cares about the difference.)
  810. */
  811. #define SQLITE_SYNC_NORMAL 0x00002
  812. #define SQLITE_SYNC_FULL 0x00003
  813. #define SQLITE_SYNC_DATAONLY 0x00010
  814. /*
  815. ** CAPI3REF: OS Interface Open File Handle
  816. **
  817. ** An [sqlite3_file] object represents an open file in the
  818. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  819. ** implementations will
  820. ** want to subclass this object by appending additional fields
  821. ** for their own use. The pMethods entry is a pointer to an
  822. ** [sqlite3_io_methods] object that defines methods for performing
  823. ** I/O operations on the open file.
  824. */
  825. typedef struct sqlite3_file sqlite3_file;
  826. struct sqlite3_file {
  827. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  828. };
  829. /*
  830. ** CAPI3REF: OS Interface File Virtual Methods Object
  831. **
  832. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  833. ** [sqlite3_file] object (or, more commonly, a subclass of the
  834. ** [sqlite3_file] object) with a pointer to an instance of this object.
  835. ** This object defines the methods used to perform various operations
  836. ** against the open file represented by the [sqlite3_file] object.
  837. **
  838. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  839. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  840. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  841. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  842. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  843. ** to NULL.
  844. **
  845. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  846. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  847. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  848. ** flag may be ORed in to indicate that only the data of the file
  849. ** and not its inode needs to be synced.
  850. **
  851. ** The integer values to xLock() and xUnlock() are one of
  852. ** <ul>
  853. ** <li> [SQLITE_LOCK_NONE],
  854. ** <li> [SQLITE_LOCK_SHARED],
  855. ** <li> [SQLITE_LOCK_RESERVED],
  856. ** <li> [SQLITE_LOCK_PENDING], or
  857. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  858. ** </ul>
  859. ** xLock() increases the lock. xUnlock() decreases the lock.
  860. ** The xCheckReservedLock() method checks whether any database connection,
  861. ** either in this process or in some other process, is holding a RESERVED,
  862. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  863. ** if such a lock exists and false otherwise.
  864. **
  865. ** The xFileControl() method is a generic interface that allows custom
  866. ** VFS implementations to directly control an open file using the
  867. ** [sqlite3_file_control()] interface. The second "op" argument is an
  868. ** integer opcode. The third argument is a generic pointer intended to
  869. ** point to a structure that may contain arguments or space in which to
  870. ** write return values. Potential uses for xFileControl() might be
  871. ** functions to enable blocking locks with timeouts, to change the
  872. ** locking strategy (for example to use dot-file locks), to inquire
  873. ** about the status of a lock, or to break stale locks. The SQLite
  874. ** core reserves all opcodes less than 100 for its own use.
  875. ** A [file control opcodes | list of opcodes] less than 100 is available.
  876. ** Applications that define a custom xFileControl method should use opcodes
  877. ** greater than 100 to avoid conflicts. VFS implementations should
  878. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  879. ** recognize.
  880. **
  881. ** The xSectorSize() method returns the sector size of the
  882. ** device that underlies the file. The sector size is the
  883. ** minimum write that can be performed without disturbing
  884. ** other bytes in the file. The xDeviceCharacteristics()
  885. ** method returns a bit vector describing behaviors of the
  886. ** underlying device:
  887. **
  888. ** <ul>
  889. ** <li> [SQLITE_IOCAP_ATOMIC]
  890. ** <li> [SQLITE_IOCAP_ATOMIC512]
  891. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  892. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  893. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  894. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  895. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  896. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  897. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  898. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  899. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  900. ** </ul>
  901. **
  902. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  903. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  904. ** mean that writes of blocks that are nnn bytes in size and
  905. ** are aligned to an address which is an integer multiple of
  906. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  907. ** that when data is appended to a file, the data is appended
  908. ** first then the size of the file is extended, never the other
  909. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  910. ** information is written to disk in the same order as calls
  911. ** to xWrite().
  912. **
  913. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  914. ** in the unread portions of the buffer with zeros. A VFS that
  915. ** fails to zero-fill short reads might seem to work. However,
  916. ** failure to zero-fill short reads will eventually lead to
  917. ** database corruption.
  918. */
  919. typedef struct sqlite3_io_methods sqlite3_io_methods;
  920. struct sqlite3_io_methods {
  921. int iVersion;
  922. int (*xClose)(sqlite3_file*);
  923. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  924. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  925. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  926. int (*xSync)(sqlite3_file*, int flags);
  927. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  928. int (*xLock)(sqlite3_file*, int);
  929. int (*xUnlock)(sqlite3_file*, int);
  930. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  931. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  932. int (*xSectorSize)(sqlite3_file*);
  933. int (*xDeviceCharacteristics)(sqlite3_file*);
  934. /* Methods above are valid for version 1 */
  935. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  936. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  937. void (*xShmBarrier)(sqlite3_file*);
  938. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  939. /* Methods above are valid for version 2 */
  940. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  941. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  942. /* Methods above are valid for version 3 */
  943. /* Additional methods may be added in future releases */
  944. };
  945. /*
  946. ** CAPI3REF: Standard File Control Opcodes
  947. ** KEYWORDS: {file control opcodes} {file control opcode}
  948. **
  949. ** These integer constants are opcodes for the xFileControl method
  950. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  951. ** interface.
  952. **
  953. ** <ul>
  954. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  955. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  956. ** opcode causes the xFileControl method to write the current state of
  957. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  958. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  959. ** into an integer that the pArg argument points to. This capability
  960. ** is used during testing and is only available when the SQLITE_TEST
  961. ** compile-time option is used.
  962. **
  963. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  964. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  965. ** layer a hint of how large the database file will grow to be during the
  966. ** current transaction. This hint is not guaranteed to be accurate but it
  967. ** is often close. The underlying VFS might choose to preallocate database
  968. ** file space based on this hint in order to help writes to the database
  969. ** file run faster.
  970. **
  971. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  972. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  973. ** extends and truncates the database file in chunks of a size specified
  974. ** by the user. The fourth argument to [sqlite3_file_control()] should
  975. ** point to an integer (type int) containing the new chunk-size to use
  976. ** for the nominated database. Allocating database file space in large
  977. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  978. ** improve performance on some systems.
  979. **
  980. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  981. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  982. ** to the [sqlite3_file] object associated with a particular database
  983. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  984. **
  985. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  986. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  987. ** to the [sqlite3_file] object associated with the journal file (either
  988. ** the [rollback journal] or the [write-ahead log]) for a particular database
  989. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  990. **
  991. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  992. ** No longer in use.
  993. **
  994. ** <li>[[SQLITE_FCNTL_SYNC]]
  995. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  996. ** sent to the VFS immediately before the xSync method is invoked on a
  997. ** database file descriptor. Or, if the xSync method is not invoked
  998. ** because the user has configured SQLite with
  999. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1000. ** of the xSync method. In most cases, the pointer argument passed with
  1001. ** this file-control is NULL. However, if the database file is being synced
  1002. ** as part of a multi-database commit, the argument points to a nul-terminated
  1003. ** string containing the transactions master-journal file name. VFSes that
  1004. ** do not need this signal should silently ignore this opcode. Applications
  1005. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1006. ** disrupt the operation of the specialized VFSes that do require it.
  1007. **
  1008. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1009. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1010. ** and sent to the VFS after a transaction has been committed immediately
  1011. ** but before the database is unlocked. VFSes that do not need this signal
  1012. ** should silently ignore this opcode. Applications should not call
  1013. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1014. ** operation of the specialized VFSes that do require it.
  1015. **
  1016. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1017. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1018. ** retry counts and intervals for certain disk I/O operations for the
  1019. ** windows [VFS] in order to provide robustness in the presence of
  1020. ** anti-virus programs. By default, the windows VFS will retry file read,
  1021. ** file write, and file delete operations up to 10 times, with a delay
  1022. ** of 25 milliseconds before the first retry and with the delay increasing
  1023. ** by an additional 25 milliseconds with each subsequent retry. This
  1024. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1025. ** to be adjusted. The values are changed for all database connections
  1026. ** within the same process. The argument is a pointer to an array of two
  1027. ** integers where the first integer i the new retry count and the second
  1028. ** integer is the delay. If either integer is negative, then the setting
  1029. ** is not changed but instead the prior value of that setting is written
  1030. ** into the array entry, allowing the current retry settings to be
  1031. ** interrogated. The zDbName parameter is ignored.
  1032. **
  1033. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1034. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1035. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1036. ** write ahead log and shared memory files used for transaction control
  1037. ** are automatically deleted when the latest connection to the database
  1038. ** closes. Setting persistent WAL mode causes those files to persist after
  1039. ** close. Persisting the files is useful when other processes that do not
  1040. ** have write permission on the directory containing the database file want
  1041. ** to read the database file, as the WAL and shared memory files must exist
  1042. ** in order for the database to be readable. The fourth parameter to
  1043. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1044. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1045. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1046. ** WAL persistence setting.
  1047. **
  1048. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1049. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1050. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1051. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1052. ** xDeviceCharacteristics methods. The fourth parameter to
  1053. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1054. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1055. ** mode. If the integer is -1, then it is overwritten with the current
  1056. ** zero-damage mode setting.
  1057. **
  1058. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1059. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1060. ** a write transaction to indicate that, unless it is rolled back for some
  1061. ** reason, the entire database file will be overwritten by the current
  1062. ** transaction. This is used by VACUUM operations.
  1063. **
  1064. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1065. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1066. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1067. ** final bottom-level VFS are written into memory obtained from
  1068. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1069. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1070. ** The caller is responsible for freeing the memory when done. As with
  1071. ** all file-control actions, there is no guarantee that this will actually
  1072. ** do anything. Callers should initialize the char* variable to a NULL
  1073. ** pointer in case this file-control is not implemented. This file-control
  1074. ** is intended for diagnostic use only.
  1075. **
  1076. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1077. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1078. ** [VFSes] currently in use. ^(The argument X in
  1079. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1080. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1081. ** to a pointer to the top-level VFS.)^
  1082. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1083. ** upper-most shim only.
  1084. **
  1085. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1086. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1087. ** file control is sent to the open [sqlite3_file] object corresponding
  1088. ** to the database file to which the pragma statement refers. ^The argument
  1089. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1090. ** pointers to strings (char**) in which the second element of the array
  1091. ** is the name of the pragma and the third element is the argument to the
  1092. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1093. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1094. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1095. ** or the equivalent and that string will become the result of the pragma or
  1096. ** the error message if the pragma fails. ^If the
  1097. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1098. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1099. ** file control returns [SQLITE_OK], then the parser assumes that the
  1100. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1101. ** prepared statement if result string is NULL, or that returns a copy
  1102. ** of the result string if the string is non-NULL.
  1103. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1104. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1105. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1106. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1107. ** file control occurs at the beginning of pragma statement analysis and so
  1108. ** it is able to override built-in [PRAGMA] statements.
  1109. **
  1110. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1111. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1112. ** file-control may be invoked by SQLite on the database file handle
  1113. ** shortly after it is opened in order to provide a custom VFS with access
  1114. ** to the connections busy-handler callback. The argument is of type (void **)
  1115. ** - an array of two (void *) values. The first (void *) actually points
  1116. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1117. ** busy-handler, this function should be invoked with the second (void *) in
  1118. ** the array as the only argument. If it returns non-zero, then the operation
  1119. ** should be retried. If it returns zero, the custom VFS should abandon the
  1120. ** current operation.
  1121. **
  1122. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1123. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1124. ** to have SQLite generate a
  1125. ** temporary filename using the same algorithm that is followed to generate
  1126. ** temporary filenames for TEMP tables and other internal uses. The
  1127. ** argument should be a char** which will be filled with the filename
  1128. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1129. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1130. **
  1131. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1132. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1133. ** maximum number of bytes that will be used for memory-mapped I/O.
  1134. ** The argument is a pointer to a value of type sqlite3_int64 that
  1135. ** is an advisory maximum number of bytes in the file to memory map. The
  1136. ** pointer is overwritten with the old value. The limit is not changed if
  1137. ** the value originally pointed to is negative, and so the current limit
  1138. ** can be queried by passing in a pointer to a negative number. This
  1139. ** file-control is used internally to implement [PRAGMA mmap_size].
  1140. **
  1141. ** <li>[[SQLITE_FCNTL_TRACE]]
  1142. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1143. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1144. ** This file control is used by some VFS activity tracing [shims].
  1145. ** The argument is a zero-terminated string. Higher layers in the
  1146. ** SQLite stack may generate instances of this file control if
  1147. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1148. **
  1149. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1150. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1151. ** pointer to an integer and it writes a boolean into that integer depending
  1152. ** on whether or not the file has been renamed, moved, or deleted since it
  1153. ** was first opened.
  1154. **
  1155. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1156. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1157. ** opcode causes the xFileControl method to swap the file handle with the one
  1158. ** pointed to by the pArg argument. This capability is used during testing
  1159. ** and only needs to be supported when SQLITE_TEST is defined.
  1160. **
  1161. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1162. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1163. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1164. ** available. The WAL subsystem issues this signal during rare
  1165. ** circumstances in order to fix a problem with priority inversion.
  1166. ** Applications should <em>not</em> use this file-control.
  1167. **
  1168. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1169. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  1170. ** VFS should return SQLITE_NOTFOUND for this opcode.
  1171. **
  1172. ** <li>[[SQLITE_FCNTL_RBU]]
  1173. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  1174. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  1175. ** this opcode.
  1176. ** </ul>
  1177. */
  1178. #define SQLITE_FCNTL_LOCKSTATE 1
  1179. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1180. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1181. #define SQLITE_FCNTL_LAST_ERRNO 4
  1182. #define SQLITE_FCNTL_SIZE_HINT 5
  1183. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1184. #define SQLITE_FCNTL_FILE_POINTER 7
  1185. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1186. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1187. #define SQLITE_FCNTL_PERSIST_WAL 10
  1188. #define SQLITE_FCNTL_OVERWRITE 11
  1189. #define SQLITE_FCNTL_VFSNAME 12
  1190. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1191. #define SQLITE_FCNTL_PRAGMA 14
  1192. #define SQLITE_FCNTL_BUSYHANDLER 15
  1193. #define SQLITE_FCNTL_TEMPFILENAME 16
  1194. #define SQLITE_FCNTL_MMAP_SIZE 18
  1195. #define SQLITE_FCNTL_TRACE 19
  1196. #define SQLITE_FCNTL_HAS_MOVED 20
  1197. #define SQLITE_FCNTL_SYNC 21
  1198. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1199. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1200. #define SQLITE_FCNTL_WAL_BLOCK 24
  1201. #define SQLITE_FCNTL_ZIPVFS 25
  1202. #define SQLITE_FCNTL_RBU 26
  1203. #define SQLITE_FCNTL_VFS_POINTER 27
  1204. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  1205. /* deprecated names */
  1206. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1207. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1208. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1209. /*
  1210. ** CAPI3REF: Mutex Handle
  1211. **
  1212. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1213. ** abstract type for a mutex object. The SQLite core never looks
  1214. ** at the internal representation of an [sqlite3_mutex]. It only
  1215. ** deals with pointers to the [sqlite3_mutex] object.
  1216. **
  1217. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1218. */
  1219. typedef struct sqlite3_mutex sqlite3_mutex;
  1220. /*
  1221. ** CAPI3REF: OS Interface Object
  1222. **
  1223. ** An instance of the sqlite3_vfs object defines the interface between
  1224. ** the SQLite core and the underlying operating system. The "vfs"
  1225. ** in the name of the object stands for "virtual file system". See
  1226. ** the [VFS | VFS documentation] for further information.
  1227. **
  1228. ** The value of the iVersion field is initially 1 but may be larger in
  1229. ** future versions of SQLite. Additional fields may be appended to this
  1230. ** object when the iVersion value is increased. Note that the structure
  1231. ** of the sqlite3_vfs object changes in the transaction between
  1232. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1233. ** modified.
  1234. **
  1235. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1236. ** structure used by this VFS. mxPathname is the maximum length of
  1237. ** a pathname in this VFS.
  1238. **
  1239. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1240. ** the pNext pointer. The [sqlite3_vfs_register()]
  1241. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1242. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1243. ** searches the list. Neither the application code nor the VFS
  1244. ** implementation should use the pNext pointer.
  1245. **
  1246. ** The pNext field is the only field in the sqlite3_vfs
  1247. ** structure that SQLite will ever modify. SQLite will only access
  1248. ** or modify this field while holding a particular static mutex.
  1249. ** The application should never modify anything within the sqlite3_vfs
  1250. ** object once the object has been registered.
  1251. **
  1252. ** The zName field holds the name of the VFS module. The name must
  1253. ** be unique across all VFS modules.
  1254. **
  1255. ** [[sqlite3_vfs.xOpen]]
  1256. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1257. ** is either a NULL pointer or string obtained
  1258. ** from xFullPathname() with an optional suffix added.
  1259. ** ^If a suffix is added to the zFilename parameter, it will
  1260. ** consist of a single "-" character followed by no more than
  1261. ** 11 alphanumeric and/or "-" characters.
  1262. ** ^SQLite further guarantees that
  1263. ** the string will be valid and unchanged until xClose() is
  1264. ** called. Because of the previous sentence,
  1265. ** the [sqlite3_file] can safely store a pointer to the
  1266. ** filename if it needs to remember the filename for some reason.
  1267. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1268. ** must invent its own temporary name for the file. ^Whenever the
  1269. ** xFilename parameter is NULL it will also be the case that the
  1270. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1271. **
  1272. ** The flags argument to xOpen() includes all bits set in
  1273. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1274. ** or [sqlite3_open16()] is used, then flags includes at least
  1275. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1276. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1277. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1278. **
  1279. ** ^(SQLite will also add one of the following flags to the xOpen()
  1280. ** call, depending on the object being opened:
  1281. **
  1282. ** <ul>
  1283. ** <li> [SQLITE_OPEN_MAIN_DB]
  1284. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1285. ** <li> [SQLITE_OPEN_TEMP_DB]
  1286. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1287. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1288. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1289. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1290. ** <li> [SQLITE_OPEN_WAL]
  1291. ** </ul>)^
  1292. **
  1293. ** The file I/O implementation can use the object type flags to
  1294. ** change the way it deals with files. For example, an application
  1295. ** that does not care about crash recovery or rollback might make
  1296. ** the open of a journal file a no-op. Writes to this journal would
  1297. ** also be no-ops, and any attempt to read the journal would return
  1298. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1299. ** file will be doing page-aligned sector reads and writes in a random
  1300. ** order and set up its I/O subsystem accordingly.
  1301. **
  1302. ** SQLite might also add one of the following flags to the xOpen method:
  1303. **
  1304. ** <ul>
  1305. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1306. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1307. ** </ul>
  1308. **
  1309. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1310. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1311. ** will be set for TEMP databases and their journals, transient
  1312. ** databases, and subjournals.
  1313. **
  1314. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1315. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1316. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1317. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1318. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1319. ** be created, and that it is an error if it already exists.
  1320. ** It is <i>not</i> used to indicate the file should be opened
  1321. ** for exclusive access.
  1322. **
  1323. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1324. ** to hold the [sqlite3_file] structure passed as the third
  1325. ** argument to xOpen. The xOpen method does not have to
  1326. ** allocate the structure; it should just fill it in. Note that
  1327. ** the xOpen method must set the sqlite3_file.pMethods to either
  1328. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1329. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1330. ** element will be valid after xOpen returns regardless of the success
  1331. ** or failure of the xOpen call.
  1332. **
  1333. ** [[sqlite3_vfs.xAccess]]
  1334. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1335. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1336. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1337. ** to test whether a file is at least readable. The file can be a
  1338. ** directory.
  1339. **
  1340. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1341. ** output buffer xFullPathname. The exact size of the output buffer
  1342. ** is also passed as a parameter to both methods. If the output buffer
  1343. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1344. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1345. ** to prevent this by setting mxPathname to a sufficiently large value.
  1346. **
  1347. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1348. ** interfaces are not strictly a part of the filesystem, but they are
  1349. ** included in the VFS structure for completeness.
  1350. ** The xRandomness() function attempts to return nBytes bytes
  1351. ** of good-quality randomness into zOut. The return value is
  1352. ** the actual number of bytes of randomness obtained.
  1353. ** The xSleep() method causes the calling thread to sleep for at
  1354. ** least the number of microseconds given. ^The xCurrentTime()
  1355. ** method returns a Julian Day Number for the current date and time as
  1356. ** a floating point value.
  1357. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1358. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1359. ** a 24-hour day).
  1360. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1361. ** date and time if that method is available (if iVersion is 2 or
  1362. ** greater and the function pointer is not NULL) and will fall back
  1363. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1364. **
  1365. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1366. ** are not used by the SQLite core. These optional interfaces are provided
  1367. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1368. ** system calls with functions under its control, a test program can
  1369. ** simulate faults and error conditions that would otherwise be difficult
  1370. ** or impossible to induce. The set of system calls that can be overridden
  1371. ** varies from one VFS to another, and from one version of the same VFS to the
  1372. ** next. Applications that use these interfaces must be prepared for any
  1373. ** or all of these interfaces to be NULL or for their behavior to change
  1374. ** from one release to the next. Applications must not attempt to access
  1375. ** any of these methods if the iVersion of the VFS is less than 3.
  1376. */
  1377. typedef struct sqlite3_vfs sqlite3_vfs;
  1378. typedef void (*sqlite3_syscall_ptr)(void);
  1379. struct sqlite3_vfs {
  1380. int iVersion; /* Structure version number (currently 3) */
  1381. int szOsFile; /* Size of subclassed sqlite3_file */
  1382. int mxPathname; /* Maximum file pathname length */
  1383. sqlite3_vfs *pNext; /* Next registered VFS */
  1384. const char *zName; /* Name of this virtual file system */
  1385. void *pAppData; /* Pointer to application-specific data */
  1386. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1387. int flags, int *pOutFlags);
  1388. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1389. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1390. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1391. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1392. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1393. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1394. void (*xDlClose)(sqlite3_vfs*, void*);
  1395. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1396. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1397. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1398. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1399. /*
  1400. ** The methods above are in version 1 of the sqlite_vfs object
  1401. ** definition. Those that follow are added in version 2 or later
  1402. */
  1403. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1404. /*
  1405. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1406. ** Those below are for version 3 and greater.
  1407. */
  1408. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1409. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1410. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1411. /*
  1412. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1413. ** New fields may be appended in future versions. The iVersion
  1414. ** value will increment whenever this happens.
  1415. */
  1416. };
  1417. /*
  1418. ** CAPI3REF: Flags for the xAccess VFS method
  1419. **
  1420. ** These integer constants can be used as the third parameter to
  1421. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1422. ** what kind of permissions the xAccess method is looking for.
  1423. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1424. ** simply checks whether the file exists.
  1425. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1426. ** checks whether the named directory is both readable and writable
  1427. ** (in other words, if files can be added, removed, and renamed within
  1428. ** the directory).
  1429. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1430. ** [temp_store_directory pragma], though this could change in a future
  1431. ** release of SQLite.
  1432. ** With SQLITE_ACCESS_READ, the xAccess method
  1433. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1434. ** currently unused, though it might be used in a future release of
  1435. ** SQLite.
  1436. */
  1437. #define SQLITE_ACCESS_EXISTS 0
  1438. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1439. #define SQLITE_ACCESS_READ 2 /* Unused */
  1440. /*
  1441. ** CAPI3REF: Flags for the xShmLock VFS method
  1442. **
  1443. ** These integer constants define the various locking operations
  1444. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1445. ** following are the only legal combinations of flags to the
  1446. ** xShmLock method:
  1447. **
  1448. ** <ul>
  1449. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1450. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1451. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1452. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1453. ** </ul>
  1454. **
  1455. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1456. ** was given on the corresponding lock.
  1457. **
  1458. ** The xShmLock method can transition between unlocked and SHARED or
  1459. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1460. ** and EXCLUSIVE.
  1461. */
  1462. #define SQLITE_SHM_UNLOCK 1
  1463. #define SQLITE_SHM_LOCK 2
  1464. #define SQLITE_SHM_SHARED 4
  1465. #define SQLITE_SHM_EXCLUSIVE 8
  1466. /*
  1467. ** CAPI3REF: Maximum xShmLock index
  1468. **
  1469. ** The xShmLock method on [sqlite3_io_methods] may use values
  1470. ** between 0 and this upper bound as its "offset" argument.
  1471. ** The SQLite core will never attempt to acquire or release a
  1472. ** lock outside of this range
  1473. */
  1474. #define SQLITE_SHM_NLOCK 8
  1475. /*
  1476. ** CAPI3REF: Initialize The SQLite Library
  1477. **
  1478. ** ^The sqlite3_initialize() routine initializes the
  1479. ** SQLite library. ^The sqlite3_shutdown() routine
  1480. ** deallocates any resources that were allocated by sqlite3_initialize().
  1481. ** These routines are designed to aid in process initialization and
  1482. ** shutdown on embedded systems. Workstation applications using
  1483. ** SQLite normally do not need to invoke either of these routines.
  1484. **
  1485. ** A call to sqlite3_initialize() is an "effective" call if it is
  1486. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1487. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1488. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1489. ** of sqlite3_initialize() does any initialization. All other calls
  1490. ** are harmless no-ops.)^
  1491. **
  1492. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1493. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1494. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1495. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1496. **
  1497. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1498. ** is not. The sqlite3_shutdown() interface must only be called from a
  1499. ** single thread. All open [database connections] must be closed and all
  1500. ** other SQLite resources must be deallocated prior to invoking
  1501. ** sqlite3_shutdown().
  1502. **
  1503. ** Among other things, ^sqlite3_initialize() will invoke
  1504. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1505. ** will invoke sqlite3_os_end().
  1506. **
  1507. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1508. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1509. ** the library (perhaps it is unable to allocate a needed resource such
  1510. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1511. **
  1512. ** ^The sqlite3_initialize() routine is called internally by many other
  1513. ** SQLite interfaces so that an application usually does not need to
  1514. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1515. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1516. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1517. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1518. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1519. ** are omitted and the application must call sqlite3_initialize() directly
  1520. ** prior to using any other SQLite interface. For maximum portability,
  1521. ** it is recommended that applications always invoke sqlite3_initialize()
  1522. ** directly prior to using any other SQLite interface. Future releases
  1523. ** of SQLite may require this. In other words, the behavior exhibited
  1524. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1525. ** default behavior in some future release of SQLite.
  1526. **
  1527. ** The sqlite3_os_init() routine does operating-system specific
  1528. ** initialization of the SQLite library. The sqlite3_os_end()
  1529. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1530. ** performed by these routines include allocation or deallocation
  1531. ** of static resources, initialization of global variables,
  1532. ** setting up a default [sqlite3_vfs] module, or setting up
  1533. ** a default configuration using [sqlite3_config()].
  1534. **
  1535. ** The application should never invoke either sqlite3_os_init()
  1536. ** or sqlite3_os_end() directly. The application should only invoke
  1537. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1538. ** interface is called automatically by sqlite3_initialize() and
  1539. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1540. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1541. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1542. ** When [custom builds | built for other platforms]
  1543. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1544. ** option) the application must supply a suitable implementation for
  1545. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1546. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1547. ** must return [SQLITE_OK] on success and some other [error code] upon
  1548. ** failure.
  1549. */
  1550. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
  1551. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
  1552. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
  1553. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
  1554. /*
  1555. ** CAPI3REF: Configuring The SQLite Library
  1556. **
  1557. ** The sqlite3_config() interface is used to make global configuration
  1558. ** changes to SQLite in order to tune SQLite to the specific needs of
  1559. ** the application. The default configuration is recommended for most
  1560. ** applications and so this routine is usually not necessary. It is
  1561. ** provided to support rare applications with unusual needs.
  1562. **
  1563. ** <b>The sqlite3_config() interface is not threadsafe. The application
  1564. ** must ensure that no other SQLite interfaces are invoked by other
  1565. ** threads while sqlite3_config() is running.</b>
  1566. **
  1567. ** The sqlite3_config() interface
  1568. ** may only be invoked prior to library initialization using
  1569. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1570. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1571. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1572. ** Note, however, that ^sqlite3_config() can be called as part of the
  1573. ** implementation of an application-defined [sqlite3_os_init()].
  1574. **
  1575. ** The first argument to sqlite3_config() is an integer
  1576. ** [configuration option] that determines
  1577. ** what property of SQLite is to be configured. Subsequent arguments
  1578. ** vary depending on the [configuration option]
  1579. ** in the first argument.
  1580. **
  1581. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1582. ** ^If the option is unknown or SQLite is unable to set the option
  1583. ** then this routine returns a non-zero [error code].
  1584. */
  1585. SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
  1586. /*
  1587. ** CAPI3REF: Configure database connections
  1588. ** METHOD: sqlite3
  1589. **
  1590. ** The sqlite3_db_config() interface is used to make configuration
  1591. ** changes to a [database connection]. The interface is similar to
  1592. ** [sqlite3_config()] except that the changes apply to a single
  1593. ** [database connection] (specified in the first argument).
  1594. **
  1595. ** The second argument to sqlite3_db_config(D,V,...) is the
  1596. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1597. ** that indicates what aspect of the [database connection] is being configured.
  1598. ** Subsequent arguments vary depending on the configuration verb.
  1599. **
  1600. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1601. ** the call is considered successful.
  1602. */
  1603. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
  1604. /*
  1605. ** CAPI3REF: Memory Allocation Routines
  1606. **
  1607. ** An instance of this object defines the interface between SQLite
  1608. ** and low-level memory allocation routines.
  1609. **
  1610. ** This object is used in only one place in the SQLite interface.
  1611. ** A pointer to an instance of this object is the argument to
  1612. ** [sqlite3_config()] when the configuration option is
  1613. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1614. ** By creating an instance of this object
  1615. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1616. ** during configuration, an application can specify an alternative
  1617. ** memory allocation subsystem for SQLite to use for all of its
  1618. ** dynamic memory needs.
  1619. **
  1620. ** Note that SQLite comes with several [built-in memory allocators]
  1621. ** that are perfectly adequate for the overwhelming majority of applications
  1622. ** and that this object is only useful to a tiny minority of applications
  1623. ** with specialized memory allocation requirements. This object is
  1624. ** also used during testing of SQLite in order to specify an alternative
  1625. ** memory allocator that simulates memory out-of-memory conditions in
  1626. ** order to verify that SQLite recovers gracefully from such
  1627. ** conditions.
  1628. **
  1629. ** The xMalloc, xRealloc, and xFree methods must work like the
  1630. ** malloc(), realloc() and free() functions from the standard C library.
  1631. ** ^SQLite guarantees that the second argument to
  1632. ** xRealloc is always a value returned by a prior call to xRoundup.
  1633. **
  1634. ** xSize should return the allocated size of a memory allocation
  1635. ** previously obtained from xMalloc or xRealloc. The allocated size
  1636. ** is always at least as big as the requested size but may be larger.
  1637. **
  1638. ** The xRoundup method returns what would be the allocated size of
  1639. ** a memory allocation given a particular requested size. Most memory
  1640. ** allocators round up memory allocations at least to the next multiple
  1641. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1642. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1643. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1644. ** that causes the corresponding memory allocation to fail.
  1645. **
  1646. ** The xInit method initializes the memory allocator. For example,
  1647. ** it might allocate any require mutexes or initialize internal data
  1648. ** structures. The xShutdown method is invoked (indirectly) by
  1649. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1650. ** by xInit. The pAppData pointer is used as the only parameter to
  1651. ** xInit and xShutdown.
  1652. **
  1653. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1654. ** the xInit method, so the xInit method need not be threadsafe. The
  1655. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1656. ** not need to be threadsafe either. For all other methods, SQLite
  1657. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1658. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1659. ** it is by default) and so the methods are automatically serialized.
  1660. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1661. ** methods must be threadsafe or else make their own arrangements for
  1662. ** serialization.
  1663. **
  1664. ** SQLite will never invoke xInit() more than once without an intervening
  1665. ** call to xShutdown().
  1666. */
  1667. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1668. struct sqlite3_mem_methods {
  1669. void *(*xMalloc)(int); /* Memory allocation function */
  1670. void (*xFree)(void*); /* Free a prior allocation */
  1671. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1672. int (*xSize)(void*); /* Return the size of an allocation */
  1673. int (*xRoundup)(int); /* Round up request size to allocation size */
  1674. int (*xInit)(void*); /* Initialize the memory allocator */
  1675. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1676. void *pAppData; /* Argument to xInit() and xShutdown() */
  1677. };
  1678. /*
  1679. ** CAPI3REF: Configuration Options
  1680. ** KEYWORDS: {configuration option}
  1681. **
  1682. ** These constants are the available integer configuration options that
  1683. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1684. **
  1685. ** New configuration options may be added in future releases of SQLite.
  1686. ** Existing configuration options might be discontinued. Applications
  1687. ** should check the return code from [sqlite3_config()] to make sure that
  1688. ** the call worked. The [sqlite3_config()] interface will return a
  1689. ** non-zero [error code] if a discontinued or unsupported configuration option
  1690. ** is invoked.
  1691. **
  1692. ** <dl>
  1693. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1694. ** <dd>There are no arguments to this option. ^This option sets the
  1695. ** [threading mode] to Single-thread. In other words, it disables
  1696. ** all mutexing and puts SQLite into a mode where it can only be used
  1697. ** by a single thread. ^If SQLite is compiled with
  1698. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1699. ** it is not possible to change the [threading mode] from its default
  1700. ** value of Single-thread and so [sqlite3_config()] will return
  1701. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1702. ** configuration option.</dd>
  1703. **
  1704. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1705. ** <dd>There are no arguments to this option. ^This option sets the
  1706. ** [threading mode] to Multi-thread. In other words, it disables
  1707. ** mutexing on [database connection] and [prepared statement] objects.
  1708. ** The application is responsible for serializing access to
  1709. ** [database connections] and [prepared statements]. But other mutexes
  1710. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1711. ** environment as long as no two threads attempt to use the same
  1712. ** [database connection] at the same time. ^If SQLite is compiled with
  1713. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1714. ** it is not possible to set the Multi-thread [threading mode] and
  1715. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1716. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1717. **
  1718. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1719. ** <dd>There are no arguments to this option. ^This option sets the
  1720. ** [threading mode] to Serialized. In other words, this option enables
  1721. ** all mutexes including the recursive
  1722. ** mutexes on [database connection] and [prepared statement] objects.
  1723. ** In this mode (which is the default when SQLite is compiled with
  1724. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1725. ** to [database connections] and [prepared statements] so that the
  1726. ** application is free to use the same [database connection] or the
  1727. ** same [prepared statement] in different threads at the same time.
  1728. ** ^If SQLite is compiled with
  1729. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1730. ** it is not possible to set the Serialized [threading mode] and
  1731. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1732. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1733. **
  1734. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1735. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1736. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1737. ** The argument specifies
  1738. ** alternative low-level memory allocation routines to be used in place of
  1739. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1740. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1741. ** before the [sqlite3_config()] call returns.</dd>
  1742. **
  1743. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1744. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1745. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1746. ** The [sqlite3_mem_methods]
  1747. ** structure is filled with the currently defined memory allocation routines.)^
  1748. ** This option can be used to overload the default memory allocation
  1749. ** routines with a wrapper that simulations memory allocation failure or
  1750. ** tracks memory usage, for example. </dd>
  1751. **
  1752. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1753. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1754. ** interpreted as a boolean, which enables or disables the collection of
  1755. ** memory allocation statistics. ^(When memory allocation statistics are
  1756. ** disabled, the following SQLite interfaces become non-operational:
  1757. ** <ul>
  1758. ** <li> [sqlite3_memory_used()]
  1759. ** <li> [sqlite3_memory_highwater()]
  1760. ** <li> [sqlite3_soft_heap_limit64()]
  1761. ** <li> [sqlite3_status64()]
  1762. ** </ul>)^
  1763. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1764. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1765. ** allocation statistics are disabled by default.
  1766. ** </dd>
  1767. **
  1768. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1769. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1770. ** that SQLite can use for scratch memory. ^(There are three arguments
  1771. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1772. ** aligned memory buffer from which the scratch allocations will be
  1773. ** drawn, the size of each scratch allocation (sz),
  1774. ** and the maximum number of scratch allocations (N).)^
  1775. ** The first argument must be a pointer to an 8-byte aligned buffer
  1776. ** of at least sz*N bytes of memory.
  1777. ** ^SQLite will not use more than one scratch buffers per thread.
  1778. ** ^SQLite will never request a scratch buffer that is more than 6
  1779. ** times the database page size.
  1780. ** ^If SQLite needs needs additional
  1781. ** scratch memory beyond what is provided by this configuration option, then
  1782. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1783. ** ^When the application provides any amount of scratch memory using
  1784. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1785. ** [sqlite3_malloc|heap allocations].
  1786. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1787. ** fragmentation in low-memory embedded systems.
  1788. ** </dd>
  1789. **
  1790. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1791. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  1792. ** that SQLite can use for the database page cache with the default page
  1793. ** cache implementation.
  1794. ** This configuration option is a no-op if an application-define page
  1795. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  1796. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1797. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  1798. ** and the number of cache lines (N).
  1799. ** The sz argument should be the size of the largest database page
  1800. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1801. ** page header. ^The number of extra bytes needed by the page header
  1802. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  1803. ** ^It is harmless, apart from the wasted memory,
  1804. ** for the sz parameter to be larger than necessary. The pMem
  1805. ** argument must be either a NULL pointer or a pointer to an 8-byte
  1806. ** aligned block of memory of at least sz*N bytes, otherwise
  1807. ** subsequent behavior is undefined.
  1808. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  1809. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  1810. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  1811. ** is exhausted.
  1812. ** ^If pMem is NULL and N is non-zero, then each database connection
  1813. ** does an initial bulk allocation for page cache memory
  1814. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  1815. ** of -1024*N bytes if N is negative, . ^If additional
  1816. ** page cache memory is needed beyond what is provided by the initial
  1817. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  1818. ** additional cache line. </dd>
  1819. **
  1820. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1821. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1822. ** that SQLite will use for all of its dynamic memory allocation needs
  1823. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1824. ** [SQLITE_CONFIG_PAGECACHE].
  1825. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1826. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1827. ** [SQLITE_ERROR] if invoked otherwise.
  1828. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1829. ** An 8-byte aligned pointer to the memory,
  1830. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1831. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1832. ** to using its default memory allocator (the system malloc() implementation),
  1833. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1834. ** memory pointer is not NULL then the alternative memory
  1835. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1836. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1837. ** boundary or subsequent behavior of SQLite will be undefined.
  1838. ** The minimum allocation size is capped at 2**12. Reasonable values
  1839. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1840. **
  1841. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1842. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1843. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1844. ** The argument specifies alternative low-level mutex routines to be used
  1845. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1846. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1847. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1848. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1849. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1850. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1851. ** return [SQLITE_ERROR].</dd>
  1852. **
  1853. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1854. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1855. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1856. ** [sqlite3_mutex_methods]
  1857. ** structure is filled with the currently defined mutex routines.)^
  1858. ** This option can be used to overload the default mutex allocation
  1859. ** routines with a wrapper used to track mutex usage for performance
  1860. ** profiling or testing, for example. ^If SQLite is compiled with
  1861. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1862. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1863. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1864. ** return [SQLITE_ERROR].</dd>
  1865. **
  1866. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1867. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1868. ** the default size of lookaside memory on each [database connection].
  1869. ** The first argument is the
  1870. ** size of each lookaside buffer slot and the second is the number of
  1871. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1872. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1873. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1874. ** configuration on individual connections.)^ </dd>
  1875. **
  1876. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1877. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1878. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1879. ** the interface to a custom page cache implementation.)^
  1880. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1881. **
  1882. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1883. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1884. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1885. ** the current page cache implementation into that object.)^ </dd>
  1886. **
  1887. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1888. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1889. ** global [error log].
  1890. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1891. ** function with a call signature of void(*)(void*,int,const char*),
  1892. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1893. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1894. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1895. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1896. ** passed through as the first parameter to the application-defined logger
  1897. ** function whenever that function is invoked. ^The second parameter to
  1898. ** the logger function is a copy of the first parameter to the corresponding
  1899. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1900. ** [extended result code]. ^The third parameter passed to the logger is
  1901. ** log message after formatting via [sqlite3_snprintf()].
  1902. ** The SQLite logging interface is not reentrant; the logger function
  1903. ** supplied by the application must not invoke any SQLite interface.
  1904. ** In a multi-threaded application, the application-defined logger
  1905. ** function must be threadsafe. </dd>
  1906. **
  1907. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1908. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1909. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1910. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1911. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1912. ** [sqlite3_open16()] or
  1913. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1914. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1915. ** connection is opened. ^If it is globally disabled, filenames are
  1916. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1917. ** database connection is opened. ^(By default, URI handling is globally
  1918. ** disabled. The default value may be changed by compiling with the
  1919. ** [SQLITE_USE_URI] symbol defined.)^
  1920. **
  1921. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1922. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  1923. ** argument which is interpreted as a boolean in order to enable or disable
  1924. ** the use of covering indices for full table scans in the query optimizer.
  1925. ** ^The default setting is determined
  1926. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1927. ** if that compile-time option is omitted.
  1928. ** The ability to disable the use of covering indices for full table scans
  1929. ** is because some incorrectly coded legacy applications might malfunction
  1930. ** when the optimization is enabled. Providing the ability to
  1931. ** disable the optimization allows the older, buggy application code to work
  1932. ** without change even with newer versions of SQLite.
  1933. **
  1934. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1935. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1936. ** <dd> These options are obsolete and should not be used by new code.
  1937. ** They are retained for backwards compatibility but are now no-ops.
  1938. ** </dd>
  1939. **
  1940. ** [[SQLITE_CONFIG_SQLLOG]]
  1941. ** <dt>SQLITE_CONFIG_SQLLOG
  1942. ** <dd>This option is only available if sqlite is compiled with the
  1943. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1944. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1945. ** The second should be of type (void*). The callback is invoked by the library
  1946. ** in three separate circumstances, identified by the value passed as the
  1947. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1948. ** passed as the second argument has just been opened. The third argument
  1949. ** points to a buffer containing the name of the main database file. If the
  1950. ** fourth parameter is 1, then the SQL statement that the third parameter
  1951. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1952. ** the connection being passed as the second parameter is being closed. The
  1953. ** third parameter is passed NULL In this case. An example of using this
  1954. ** configuration option can be seen in the "test_sqllog.c" source file in
  1955. ** the canonical SQLite source tree.</dd>
  1956. **
  1957. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1958. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1959. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1960. ** that are the default mmap size limit (the default setting for
  1961. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1962. ** ^The default setting can be overridden by each database connection using
  1963. ** either the [PRAGMA mmap_size] command, or by using the
  1964. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1965. ** will be silently truncated if necessary so that it does not exceed the
  1966. ** compile-time maximum mmap size set by the
  1967. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1968. ** ^If either argument to this option is negative, then that argument is
  1969. ** changed to its compile-time default.
  1970. **
  1971. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1972. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1973. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  1974. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  1975. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1976. ** that specifies the maximum size of the created heap.
  1977. **
  1978. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  1979. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  1980. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  1981. ** is a pointer to an integer and writes into that integer the number of extra
  1982. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  1983. ** The amount of extra space required can change depending on the compiler,
  1984. ** target platform, and SQLite version.
  1985. **
  1986. ** [[SQLITE_CONFIG_PMASZ]]
  1987. ** <dt>SQLITE_CONFIG_PMASZ
  1988. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  1989. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  1990. ** sorter to that integer. The default minimum PMA Size is set by the
  1991. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  1992. ** to help with sort operations when multithreaded sorting
  1993. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  1994. ** to be sorted exceeds the page size times the minimum of the
  1995. ** [PRAGMA cache_size] setting and this value.
  1996. **
  1997. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  1998. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  1999. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2000. ** becomes the [statement journal] spill-to-disk threshold.
  2001. ** [Statement journals] are held in memory until their size (in bytes)
  2002. ** exceeds this threshold, at which point they are written to disk.
  2003. ** Or if the threshold is -1, statement journals are always held
  2004. ** exclusively in memory.
  2005. ** Since many statement journals never become large, setting the spill
  2006. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2007. ** I/O required to support statement rollback.
  2008. ** The default value for this setting is controlled by the
  2009. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2010. ** </dl>
  2011. */
  2012. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2013. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2014. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2015. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2016. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2017. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  2018. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2019. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2020. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2021. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2022. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2023. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2024. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2025. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2026. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2027. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2028. #define SQLITE_CONFIG_URI 17 /* int */
  2029. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2030. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2031. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2032. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2033. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2034. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2035. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2036. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2037. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2038. /*
  2039. ** CAPI3REF: Database Connection Configuration Options
  2040. **
  2041. ** These constants are the available integer configuration options that
  2042. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2043. **
  2044. ** New configuration options may be added in future releases of SQLite.
  2045. ** Existing configuration options might be discontinued. Applications
  2046. ** should check the return code from [sqlite3_db_config()] to make sure that
  2047. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2048. ** non-zero [error code] if a discontinued or unsupported configuration option
  2049. ** is invoked.
  2050. **
  2051. ** <dl>
  2052. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2053. ** <dd> ^This option takes three additional arguments that determine the
  2054. ** [lookaside memory allocator] configuration for the [database connection].
  2055. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2056. ** pointer to a memory buffer to use for lookaside memory.
  2057. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2058. ** may be NULL in which case SQLite will allocate the
  2059. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2060. ** size of each lookaside buffer slot. ^The third argument is the number of
  2061. ** slots. The size of the buffer in the first argument must be greater than
  2062. ** or equal to the product of the second and third arguments. The buffer
  2063. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2064. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2065. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2066. ** configuration for a database connection can only be changed when that
  2067. ** connection is not currently using lookaside memory, or in other words
  2068. ** when the "current value" returned by
  2069. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2070. ** Any attempt to change the lookaside memory configuration when lookaside
  2071. ** memory is in use leaves the configuration unchanged and returns
  2072. ** [SQLITE_BUSY].)^</dd>
  2073. **
  2074. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2075. ** <dd> ^This option is used to enable or disable the enforcement of
  2076. ** [foreign key constraints]. There should be two additional arguments.
  2077. ** The first argument is an integer which is 0 to disable FK enforcement,
  2078. ** positive to enable FK enforcement or negative to leave FK enforcement
  2079. ** unchanged. The second parameter is a pointer to an integer into which
  2080. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2081. ** following this call. The second parameter may be a NULL pointer, in
  2082. ** which case the FK enforcement setting is not reported back. </dd>
  2083. **
  2084. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2085. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2086. ** There should be two additional arguments.
  2087. ** The first argument is an integer which is 0 to disable triggers,
  2088. ** positive to enable triggers or negative to leave the setting unchanged.
  2089. ** The second parameter is a pointer to an integer into which
  2090. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2091. ** following this call. The second parameter may be a NULL pointer, in
  2092. ** which case the trigger setting is not reported back. </dd>
  2093. **
  2094. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  2095. ** <dd> ^This option is used to enable or disable the two-argument
  2096. ** version of the [fts3_tokenizer()] function which is part of the
  2097. ** [FTS3] full-text search engine extension.
  2098. ** There should be two additional arguments.
  2099. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  2100. ** positive to enable fts3_tokenizer() or negative to leave the setting
  2101. ** unchanged.
  2102. ** The second parameter is a pointer to an integer into which
  2103. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  2104. ** following this call. The second parameter may be a NULL pointer, in
  2105. ** which case the new setting is not reported back. </dd>
  2106. **
  2107. ** </dl>
  2108. */
  2109. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2110. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2111. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2112. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  2113. /*
  2114. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2115. ** METHOD: sqlite3
  2116. **
  2117. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2118. ** [extended result codes] feature of SQLite. ^The extended result
  2119. ** codes are disabled by default for historical compatibility.
  2120. */
  2121. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
  2122. /*
  2123. ** CAPI3REF: Last Insert Rowid
  2124. ** METHOD: sqlite3
  2125. **
  2126. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2127. ** has a unique 64-bit signed
  2128. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2129. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2130. ** names are not also used by explicitly declared columns. ^If
  2131. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2132. ** is another alias for the rowid.
  2133. **
  2134. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  2135. ** most recent successful [INSERT] into a rowid table or [virtual table]
  2136. ** on database connection D.
  2137. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  2138. ** ^If no successful [INSERT]s into rowid tables
  2139. ** have ever occurred on the database connection D,
  2140. ** then sqlite3_last_insert_rowid(D) returns zero.
  2141. **
  2142. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2143. ** method, then this routine will return the [rowid] of the inserted
  2144. ** row as long as the trigger or virtual table method is running.
  2145. ** But once the trigger or virtual table method ends, the value returned
  2146. ** by this routine reverts to what it was before the trigger or virtual
  2147. ** table method began.)^
  2148. **
  2149. ** ^An [INSERT] that fails due to a constraint violation is not a
  2150. ** successful [INSERT] and does not change the value returned by this
  2151. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2152. ** and INSERT OR ABORT make no changes to the return value of this
  2153. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2154. ** encounters a constraint violation, it does not fail. The
  2155. ** INSERT continues to completion after deleting rows that caused
  2156. ** the constraint problem so INSERT OR REPLACE will always change
  2157. ** the return value of this interface.)^
  2158. **
  2159. ** ^For the purposes of this routine, an [INSERT] is considered to
  2160. ** be successful even if it is subsequently rolled back.
  2161. **
  2162. ** This function is accessible to SQL statements via the
  2163. ** [last_insert_rowid() SQL function].
  2164. **
  2165. ** If a separate thread performs a new [INSERT] on the same
  2166. ** database connection while the [sqlite3_last_insert_rowid()]
  2167. ** function is running and thus changes the last insert [rowid],
  2168. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2169. ** unpredictable and might not equal either the old or the new
  2170. ** last insert [rowid].
  2171. */
  2172. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
  2173. /*
  2174. ** CAPI3REF: Count The Number Of Rows Modified
  2175. ** METHOD: sqlite3
  2176. **
  2177. ** ^This function returns the number of rows modified, inserted or
  2178. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2179. ** statement on the database connection specified by the only parameter.
  2180. ** ^Executing any other type of SQL statement does not modify the value
  2181. ** returned by this function.
  2182. **
  2183. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2184. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2185. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2186. **
  2187. ** Changes to a view that are intercepted by
  2188. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2189. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2190. ** DELETE statement run on a view is always zero. Only changes made to real
  2191. ** tables are counted.
  2192. **
  2193. ** Things are more complicated if the sqlite3_changes() function is
  2194. ** executed while a trigger program is running. This may happen if the
  2195. ** program uses the [changes() SQL function], or if some other callback
  2196. ** function invokes sqlite3_changes() directly. Essentially:
  2197. **
  2198. ** <ul>
  2199. ** <li> ^(Before entering a trigger program the value returned by
  2200. ** sqlite3_changes() function is saved. After the trigger program
  2201. ** has finished, the original value is restored.)^
  2202. **
  2203. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2204. ** statement sets the value returned by sqlite3_changes()
  2205. ** upon completion as normal. Of course, this value will not include
  2206. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2207. ** value will be saved and restored after each sub-trigger has run.)^
  2208. ** </ul>
  2209. **
  2210. ** ^This means that if the changes() SQL function (or similar) is used
  2211. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2212. ** returns the value as set when the calling statement began executing.
  2213. ** ^If it is used by the second or subsequent such statement within a trigger
  2214. ** program, the value returned reflects the number of rows modified by the
  2215. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2216. **
  2217. ** See also the [sqlite3_total_changes()] interface, the
  2218. ** [count_changes pragma], and the [changes() SQL function].
  2219. **
  2220. ** If a separate thread makes changes on the same database connection
  2221. ** while [sqlite3_changes()] is running then the value returned
  2222. ** is unpredictable and not meaningful.
  2223. */
  2224. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
  2225. /*
  2226. ** CAPI3REF: Total Number Of Rows Modified
  2227. ** METHOD: sqlite3
  2228. **
  2229. ** ^This function returns the total number of rows inserted, modified or
  2230. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2231. ** since the database connection was opened, including those executed as
  2232. ** part of trigger programs. ^Executing any other type of SQL statement
  2233. ** does not affect the value returned by sqlite3_total_changes().
  2234. **
  2235. ** ^Changes made as part of [foreign key actions] are included in the
  2236. ** count, but those made as part of REPLACE constraint resolution are
  2237. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2238. ** are not counted.
  2239. **
  2240. ** See also the [sqlite3_changes()] interface, the
  2241. ** [count_changes pragma], and the [total_changes() SQL function].
  2242. **
  2243. ** If a separate thread makes changes on the same database connection
  2244. ** while [sqlite3_total_changes()] is running then the value
  2245. ** returned is unpredictable and not meaningful.
  2246. */
  2247. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
  2248. /*
  2249. ** CAPI3REF: Interrupt A Long-Running Query
  2250. ** METHOD: sqlite3
  2251. **
  2252. ** ^This function causes any pending database operation to abort and
  2253. ** return at its earliest opportunity. This routine is typically
  2254. ** called in response to a user action such as pressing "Cancel"
  2255. ** or Ctrl-C where the user wants a long query operation to halt
  2256. ** immediately.
  2257. **
  2258. ** ^It is safe to call this routine from a thread different from the
  2259. ** thread that is currently running the database operation. But it
  2260. ** is not safe to call this routine with a [database connection] that
  2261. ** is closed or might close before sqlite3_interrupt() returns.
  2262. **
  2263. ** ^If an SQL operation is very nearly finished at the time when
  2264. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2265. ** to be interrupted and might continue to completion.
  2266. **
  2267. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2268. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2269. ** that is inside an explicit transaction, then the entire transaction
  2270. ** will be rolled back automatically.
  2271. **
  2272. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2273. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2274. ** that are started after the sqlite3_interrupt() call and before the
  2275. ** running statements reaches zero are interrupted as if they had been
  2276. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2277. ** that are started after the running statement count reaches zero are
  2278. ** not effected by the sqlite3_interrupt().
  2279. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2280. ** SQL statements is a no-op and has no effect on SQL statements
  2281. ** that are started after the sqlite3_interrupt() call returns.
  2282. **
  2283. ** If the database connection closes while [sqlite3_interrupt()]
  2284. ** is running then bad things will likely happen.
  2285. */
  2286. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
  2287. /*
  2288. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2289. **
  2290. ** These routines are useful during command-line input to determine if the
  2291. ** currently entered text seems to form a complete SQL statement or
  2292. ** if additional input is needed before sending the text into
  2293. ** SQLite for parsing. ^These routines return 1 if the input string
  2294. ** appears to be a complete SQL statement. ^A statement is judged to be
  2295. ** complete if it ends with a semicolon token and is not a prefix of a
  2296. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2297. ** string literals or quoted identifier names or comments are not
  2298. ** independent tokens (they are part of the token in which they are
  2299. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2300. ** and comments that follow the final semicolon are ignored.
  2301. **
  2302. ** ^These routines return 0 if the statement is incomplete. ^If a
  2303. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2304. **
  2305. ** ^These routines do not parse the SQL statements thus
  2306. ** will not detect syntactically incorrect SQL.
  2307. **
  2308. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2309. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2310. ** automatically by sqlite3_complete16(). If that initialization fails,
  2311. ** then the return value from sqlite3_complete16() will be non-zero
  2312. ** regardless of whether or not the input SQL is complete.)^
  2313. **
  2314. ** The input to [sqlite3_complete()] must be a zero-terminated
  2315. ** UTF-8 string.
  2316. **
  2317. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2318. ** UTF-16 string in native byte order.
  2319. */
  2320. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
  2321. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
  2322. /*
  2323. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2324. ** KEYWORDS: {busy-handler callback} {busy handler}
  2325. ** METHOD: sqlite3
  2326. **
  2327. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2328. ** that might be invoked with argument P whenever
  2329. ** an attempt is made to access a database table associated with
  2330. ** [database connection] D when another thread
  2331. ** or process has the table locked.
  2332. ** The sqlite3_busy_handler() interface is used to implement
  2333. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2334. **
  2335. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2336. ** is returned immediately upon encountering the lock. ^If the busy callback
  2337. ** is not NULL, then the callback might be invoked with two arguments.
  2338. **
  2339. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2340. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2341. ** the busy handler callback is the number of times that the busy handler has
  2342. ** been invoked previously for the same locking event. ^If the
  2343. ** busy callback returns 0, then no additional attempts are made to
  2344. ** access the database and [SQLITE_BUSY] is returned
  2345. ** to the application.
  2346. ** ^If the callback returns non-zero, then another attempt
  2347. ** is made to access the database and the cycle repeats.
  2348. **
  2349. ** The presence of a busy handler does not guarantee that it will be invoked
  2350. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2351. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2352. ** to the application instead of invoking the
  2353. ** busy handler.
  2354. ** Consider a scenario where one process is holding a read lock that
  2355. ** it is trying to promote to a reserved lock and
  2356. ** a second process is holding a reserved lock that it is trying
  2357. ** to promote to an exclusive lock. The first process cannot proceed
  2358. ** because it is blocked by the second and the second process cannot
  2359. ** proceed because it is blocked by the first. If both processes
  2360. ** invoke the busy handlers, neither will make any progress. Therefore,
  2361. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2362. ** will induce the first process to release its read lock and allow
  2363. ** the second process to proceed.
  2364. **
  2365. ** ^The default busy callback is NULL.
  2366. **
  2367. ** ^(There can only be a single busy handler defined for each
  2368. ** [database connection]. Setting a new busy handler clears any
  2369. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2370. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2371. ** busy handler and thus clear any previously set busy handler.
  2372. **
  2373. ** The busy callback should not take any actions which modify the
  2374. ** database connection that invoked the busy handler. In other words,
  2375. ** the busy handler is not reentrant. Any such actions
  2376. ** result in undefined behavior.
  2377. **
  2378. ** A busy handler must not close the database connection
  2379. ** or [prepared statement] that invoked the busy handler.
  2380. */
  2381. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2382. /*
  2383. ** CAPI3REF: Set A Busy Timeout
  2384. ** METHOD: sqlite3
  2385. **
  2386. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2387. ** for a specified amount of time when a table is locked. ^The handler
  2388. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2389. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2390. ** the handler returns 0 which causes [sqlite3_step()] to return
  2391. ** [SQLITE_BUSY].
  2392. **
  2393. ** ^Calling this routine with an argument less than or equal to zero
  2394. ** turns off all busy handlers.
  2395. **
  2396. ** ^(There can only be a single busy handler for a particular
  2397. ** [database connection] at any given moment. If another busy handler
  2398. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2399. ** this routine, that other busy handler is cleared.)^
  2400. **
  2401. ** See also: [PRAGMA busy_timeout]
  2402. */
  2403. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
  2404. /*
  2405. ** CAPI3REF: Convenience Routines For Running Queries
  2406. ** METHOD: sqlite3
  2407. **
  2408. ** This is a legacy interface that is preserved for backwards compatibility.
  2409. ** Use of this interface is not recommended.
  2410. **
  2411. ** Definition: A <b>result table</b> is memory data structure created by the
  2412. ** [sqlite3_get_table()] interface. A result table records the
  2413. ** complete query results from one or more queries.
  2414. **
  2415. ** The table conceptually has a number of rows and columns. But
  2416. ** these numbers are not part of the result table itself. These
  2417. ** numbers are obtained separately. Let N be the number of rows
  2418. ** and M be the number of columns.
  2419. **
  2420. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2421. ** There are (N+1)*M elements in the array. The first M pointers point
  2422. ** to zero-terminated strings that contain the names of the columns.
  2423. ** The remaining entries all point to query results. NULL values result
  2424. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2425. ** string representation as returned by [sqlite3_column_text()].
  2426. **
  2427. ** A result table might consist of one or more memory allocations.
  2428. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2429. ** A result table should be deallocated using [sqlite3_free_table()].
  2430. **
  2431. ** ^(As an example of the result table format, suppose a query result
  2432. ** is as follows:
  2433. **
  2434. ** <blockquote><pre>
  2435. ** Name | Age
  2436. ** -----------------------
  2437. ** Alice | 43
  2438. ** Bob | 28
  2439. ** Cindy | 21
  2440. ** </pre></blockquote>
  2441. **
  2442. ** There are two column (M==2) and three rows (N==3). Thus the
  2443. ** result table has 8 entries. Suppose the result table is stored
  2444. ** in an array names azResult. Then azResult holds this content:
  2445. **
  2446. ** <blockquote><pre>
  2447. ** azResult&#91;0] = "Name";
  2448. ** azResult&#91;1] = "Age";
  2449. ** azResult&#91;2] = "Alice";
  2450. ** azResult&#91;3] = "43";
  2451. ** azResult&#91;4] = "Bob";
  2452. ** azResult&#91;5] = "28";
  2453. ** azResult&#91;6] = "Cindy";
  2454. ** azResult&#91;7] = "21";
  2455. ** </pre></blockquote>)^
  2456. **
  2457. ** ^The sqlite3_get_table() function evaluates one or more
  2458. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2459. ** string of its 2nd parameter and returns a result table to the
  2460. ** pointer given in its 3rd parameter.
  2461. **
  2462. ** After the application has finished with the result from sqlite3_get_table(),
  2463. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2464. ** release the memory that was malloced. Because of the way the
  2465. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2466. ** function must not try to call [sqlite3_free()] directly. Only
  2467. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2468. **
  2469. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2470. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2471. ** to any internal data structures of SQLite. It uses only the public
  2472. ** interface defined here. As a consequence, errors that occur in the
  2473. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2474. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2475. ** [sqlite3_errmsg()].
  2476. */
  2477. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  2478. sqlite3 *db, /* An open database */
  2479. const char *zSql, /* SQL to be evaluated */
  2480. char ***pazResult, /* Results of the query */
  2481. int *pnRow, /* Number of result rows written here */
  2482. int *pnColumn, /* Number of result columns written here */
  2483. char **pzErrmsg /* Error msg written here */
  2484. );
  2485. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
  2486. /*
  2487. ** CAPI3REF: Formatted String Printing Functions
  2488. **
  2489. ** These routines are work-alikes of the "printf()" family of functions
  2490. ** from the standard C library.
  2491. ** These routines understand most of the common K&R formatting options,
  2492. ** plus some additional non-standard formats, detailed below.
  2493. ** Note that some of the more obscure formatting options from recent
  2494. ** C-library standards are omitted from this implementation.
  2495. **
  2496. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2497. ** results into memory obtained from [sqlite3_malloc()].
  2498. ** The strings returned by these two routines should be
  2499. ** released by [sqlite3_free()]. ^Both routines return a
  2500. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2501. ** memory to hold the resulting string.
  2502. **
  2503. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2504. ** the standard C library. The result is written into the
  2505. ** buffer supplied as the second parameter whose size is given by
  2506. ** the first parameter. Note that the order of the
  2507. ** first two parameters is reversed from snprintf().)^ This is an
  2508. ** historical accident that cannot be fixed without breaking
  2509. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2510. ** returns a pointer to its buffer instead of the number of
  2511. ** characters actually written into the buffer.)^ We admit that
  2512. ** the number of characters written would be a more useful return
  2513. ** value but we cannot change the implementation of sqlite3_snprintf()
  2514. ** now without breaking compatibility.
  2515. **
  2516. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2517. ** guarantees that the buffer is always zero-terminated. ^The first
  2518. ** parameter "n" is the total size of the buffer, including space for
  2519. ** the zero terminator. So the longest string that can be completely
  2520. ** written will be n-1 characters.
  2521. **
  2522. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2523. **
  2524. ** These routines all implement some additional formatting
  2525. ** options that are useful for constructing SQL statements.
  2526. ** All of the usual printf() formatting options apply. In addition, there
  2527. ** is are "%q", "%Q", "%w" and "%z" options.
  2528. **
  2529. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2530. ** string from the argument list. But %q also doubles every '\'' character.
  2531. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2532. ** character it escapes that character and allows it to be inserted into
  2533. ** the string.
  2534. **
  2535. ** For example, assume the string variable zText contains text as follows:
  2536. **
  2537. ** <blockquote><pre>
  2538. ** char *zText = "It's a happy day!";
  2539. ** </pre></blockquote>
  2540. **
  2541. ** One can use this text in an SQL statement as follows:
  2542. **
  2543. ** <blockquote><pre>
  2544. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2545. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2546. ** sqlite3_free(zSQL);
  2547. ** </pre></blockquote>
  2548. **
  2549. ** Because the %q format string is used, the '\'' character in zText
  2550. ** is escaped and the SQL generated is as follows:
  2551. **
  2552. ** <blockquote><pre>
  2553. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2554. ** </pre></blockquote>
  2555. **
  2556. ** This is correct. Had we used %s instead of %q, the generated SQL
  2557. ** would have looked like this:
  2558. **
  2559. ** <blockquote><pre>
  2560. ** INSERT INTO table1 VALUES('It's a happy day!');
  2561. ** </pre></blockquote>
  2562. **
  2563. ** This second example is an SQL syntax error. As a general rule you should
  2564. ** always use %q instead of %s when inserting text into a string literal.
  2565. **
  2566. ** ^(The %Q option works like %q except it also adds single quotes around
  2567. ** the outside of the total string. Additionally, if the parameter in the
  2568. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2569. ** single quotes).)^ So, for example, one could say:
  2570. **
  2571. ** <blockquote><pre>
  2572. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2573. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2574. ** sqlite3_free(zSQL);
  2575. ** </pre></blockquote>
  2576. **
  2577. ** The code above will render a correct SQL statement in the zSQL
  2578. ** variable even if the zText variable is a NULL pointer.
  2579. **
  2580. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2581. ** be contained within double-quotes instead of single quotes, and it
  2582. ** escapes the double-quote character instead of the single-quote
  2583. ** character.)^ The "%w" formatting option is intended for safely inserting
  2584. ** table and column names into a constructed SQL statement.
  2585. **
  2586. ** ^(The "%z" formatting option works like "%s" but with the
  2587. ** addition that after the string has been read and copied into
  2588. ** the result, [sqlite3_free()] is called on the input string.)^
  2589. */
  2590. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
  2591. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
  2592. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
  2593. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
  2594. /*
  2595. ** CAPI3REF: Memory Allocation Subsystem
  2596. **
  2597. ** The SQLite core uses these three routines for all of its own
  2598. ** internal memory allocation needs. "Core" in the previous sentence
  2599. ** does not include operating-system specific VFS implementation. The
  2600. ** Windows VFS uses native malloc() and free() for some operations.
  2601. **
  2602. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2603. ** of memory at least N bytes in length, where N is the parameter.
  2604. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2605. ** memory, it returns a NULL pointer. ^If the parameter N to
  2606. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2607. ** a NULL pointer.
  2608. **
  2609. ** ^The sqlite3_malloc64(N) routine works just like
  2610. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2611. ** of a signed 32-bit integer.
  2612. **
  2613. ** ^Calling sqlite3_free() with a pointer previously returned
  2614. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2615. ** that it might be reused. ^The sqlite3_free() routine is
  2616. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2617. ** to sqlite3_free() is harmless. After being freed, memory
  2618. ** should neither be read nor written. Even reading previously freed
  2619. ** memory might result in a segmentation fault or other severe error.
  2620. ** Memory corruption, a segmentation fault, or other severe error
  2621. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2622. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2623. **
  2624. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2625. ** prior memory allocation X to be at least N bytes.
  2626. ** ^If the X parameter to sqlite3_realloc(X,N)
  2627. ** is a NULL pointer then its behavior is identical to calling
  2628. ** sqlite3_malloc(N).
  2629. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2630. ** negative then the behavior is exactly the same as calling
  2631. ** sqlite3_free(X).
  2632. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2633. ** of at least N bytes in size or NULL if insufficient memory is available.
  2634. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2635. ** of the prior allocation are copied into the beginning of buffer returned
  2636. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2637. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2638. ** prior allocation is not freed.
  2639. **
  2640. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2641. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2642. ** of a 32-bit signed integer.
  2643. **
  2644. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2645. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2646. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2647. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2648. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2649. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2650. ** the beginning of memory allocation, or if it points to a formerly
  2651. ** valid memory allocation that has now been freed, then the behavior
  2652. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2653. **
  2654. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2655. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2656. ** is always aligned to at least an 8 byte boundary, or to a
  2657. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2658. ** option is used.
  2659. **
  2660. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2661. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2662. ** implementation of these routines to be omitted. That capability
  2663. ** is no longer provided. Only built-in memory allocators can be used.
  2664. **
  2665. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2666. ** the system malloc() and free() directly when converting
  2667. ** filenames between the UTF-8 encoding used by SQLite
  2668. ** and whatever filename encoding is used by the particular Windows
  2669. ** installation. Memory allocation errors were detected, but
  2670. ** they were reported back as [SQLITE_CANTOPEN] or
  2671. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2672. **
  2673. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2674. ** must be either NULL or else pointers obtained from a prior
  2675. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2676. ** not yet been released.
  2677. **
  2678. ** The application must not read or write any part of
  2679. ** a block of memory after it has been released using
  2680. ** [sqlite3_free()] or [sqlite3_realloc()].
  2681. */
  2682. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
  2683. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
  2684. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
  2685. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
  2686. SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
  2687. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
  2688. /*
  2689. ** CAPI3REF: Memory Allocator Statistics
  2690. **
  2691. ** SQLite provides these two interfaces for reporting on the status
  2692. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2693. ** routines, which form the built-in memory allocation subsystem.
  2694. **
  2695. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2696. ** of memory currently outstanding (malloced but not freed).
  2697. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2698. ** value of [sqlite3_memory_used()] since the high-water mark
  2699. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2700. ** [sqlite3_memory_highwater()] include any overhead
  2701. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2702. ** but not overhead added by the any underlying system library
  2703. ** routines that [sqlite3_malloc()] may call.
  2704. **
  2705. ** ^The memory high-water mark is reset to the current value of
  2706. ** [sqlite3_memory_used()] if and only if the parameter to
  2707. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2708. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2709. ** prior to the reset.
  2710. */
  2711. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
  2712. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
  2713. /*
  2714. ** CAPI3REF: Pseudo-Random Number Generator
  2715. **
  2716. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2717. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2718. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2719. ** the build-in random() and randomblob() SQL functions. This interface allows
  2720. ** applications to access the same PRNG for other purposes.
  2721. **
  2722. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2723. ** ^The P parameter can be a NULL pointer.
  2724. **
  2725. ** ^If this routine has not been previously called or if the previous
  2726. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2727. ** seeded using randomness obtained from the xRandomness method of
  2728. ** the default [sqlite3_vfs] object.
  2729. ** ^If the previous call to this routine had an N of 1 or more and a
  2730. ** non-NULL P then the pseudo-randomness is generated
  2731. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2732. ** method.
  2733. */
  2734. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
  2735. /*
  2736. ** CAPI3REF: Compile-Time Authorization Callbacks
  2737. ** METHOD: sqlite3
  2738. **
  2739. ** ^This routine registers an authorizer callback with a particular
  2740. ** [database connection], supplied in the first argument.
  2741. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2742. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2743. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2744. ** points during the compilation process, as logic is being created
  2745. ** to perform various actions, the authorizer callback is invoked to
  2746. ** see if those actions are allowed. ^The authorizer callback should
  2747. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2748. ** specific action but allow the SQL statement to continue to be
  2749. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2750. ** rejected with an error. ^If the authorizer callback returns
  2751. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2752. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2753. ** the authorizer will fail with an error message.
  2754. **
  2755. ** When the callback returns [SQLITE_OK], that means the operation
  2756. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2757. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2758. ** authorizer will fail with an error message explaining that
  2759. ** access is denied.
  2760. **
  2761. ** ^The first parameter to the authorizer callback is a copy of the third
  2762. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2763. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2764. ** the particular action to be authorized. ^The third through sixth parameters
  2765. ** to the callback are zero-terminated strings that contain additional
  2766. ** details about the action to be authorized.
  2767. **
  2768. ** ^If the action code is [SQLITE_READ]
  2769. ** and the callback returns [SQLITE_IGNORE] then the
  2770. ** [prepared statement] statement is constructed to substitute
  2771. ** a NULL value in place of the table column that would have
  2772. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2773. ** return can be used to deny an untrusted user access to individual
  2774. ** columns of a table.
  2775. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2776. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2777. ** [truncate optimization] is disabled and all rows are deleted individually.
  2778. **
  2779. ** An authorizer is used when [sqlite3_prepare | preparing]
  2780. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2781. ** do not try to access data they are not allowed to see, or that they do not
  2782. ** try to execute malicious statements that damage the database. For
  2783. ** example, an application may allow a user to enter arbitrary
  2784. ** SQL queries for evaluation by a database. But the application does
  2785. ** not want the user to be able to make arbitrary changes to the
  2786. ** database. An authorizer could then be put in place while the
  2787. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2788. ** disallows everything except [SELECT] statements.
  2789. **
  2790. ** Applications that need to process SQL from untrusted sources
  2791. ** might also consider lowering resource limits using [sqlite3_limit()]
  2792. ** and limiting database size using the [max_page_count] [PRAGMA]
  2793. ** in addition to using an authorizer.
  2794. **
  2795. ** ^(Only a single authorizer can be in place on a database connection
  2796. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2797. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2798. ** The authorizer is disabled by default.
  2799. **
  2800. ** The authorizer callback must not do anything that will modify
  2801. ** the database connection that invoked the authorizer callback.
  2802. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2803. ** database connections for the meaning of "modify" in this paragraph.
  2804. **
  2805. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2806. ** statement might be re-prepared during [sqlite3_step()] due to a
  2807. ** schema change. Hence, the application should ensure that the
  2808. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2809. **
  2810. ** ^Note that the authorizer callback is invoked only during
  2811. ** [sqlite3_prepare()] or its variants. Authorization is not
  2812. ** performed during statement evaluation in [sqlite3_step()], unless
  2813. ** as stated in the previous paragraph, sqlite3_step() invokes
  2814. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2815. */
  2816. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  2817. sqlite3*,
  2818. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2819. void *pUserData
  2820. );
  2821. /*
  2822. ** CAPI3REF: Authorizer Return Codes
  2823. **
  2824. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2825. ** return either [SQLITE_OK] or one of these two constants in order
  2826. ** to signal SQLite whether or not the action is permitted. See the
  2827. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2828. ** information.
  2829. **
  2830. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2831. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2832. */
  2833. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2834. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2835. /*
  2836. ** CAPI3REF: Authorizer Action Codes
  2837. **
  2838. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2839. ** that is invoked to authorize certain SQL statement actions. The
  2840. ** second parameter to the callback is an integer code that specifies
  2841. ** what action is being authorized. These are the integer action codes that
  2842. ** the authorizer callback may be passed.
  2843. **
  2844. ** These action code values signify what kind of operation is to be
  2845. ** authorized. The 3rd and 4th parameters to the authorization
  2846. ** callback function will be parameters or NULL depending on which of these
  2847. ** codes is used as the second parameter. ^(The 5th parameter to the
  2848. ** authorizer callback is the name of the database ("main", "temp",
  2849. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2850. ** is the name of the inner-most trigger or view that is responsible for
  2851. ** the access attempt or NULL if this access attempt is directly from
  2852. ** top-level SQL code.
  2853. */
  2854. /******************************************* 3rd ************ 4th ***********/
  2855. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2856. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2857. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2858. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2859. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2860. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2861. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2862. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2863. #define SQLITE_DELETE 9 /* Table Name NULL */
  2864. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2865. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2866. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2867. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2868. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2869. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2870. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2871. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2872. #define SQLITE_INSERT 18 /* Table Name NULL */
  2873. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2874. #define SQLITE_READ 20 /* Table Name Column Name */
  2875. #define SQLITE_SELECT 21 /* NULL NULL */
  2876. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2877. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2878. #define SQLITE_ATTACH 24 /* Filename NULL */
  2879. #define SQLITE_DETACH 25 /* Database Name NULL */
  2880. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2881. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2882. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2883. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2884. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2885. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2886. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2887. #define SQLITE_COPY 0 /* No longer used */
  2888. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2889. /*
  2890. ** CAPI3REF: Tracing And Profiling Functions
  2891. ** METHOD: sqlite3
  2892. **
  2893. ** These routines register callback functions that can be used for
  2894. ** tracing and profiling the execution of SQL statements.
  2895. **
  2896. ** ^The callback function registered by sqlite3_trace() is invoked at
  2897. ** various times when an SQL statement is being run by [sqlite3_step()].
  2898. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2899. ** SQL statement text as the statement first begins executing.
  2900. ** ^(Additional sqlite3_trace() callbacks might occur
  2901. ** as each triggered subprogram is entered. The callbacks for triggers
  2902. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2903. **
  2904. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2905. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2906. **
  2907. ** ^The callback function registered by sqlite3_profile() is invoked
  2908. ** as each SQL statement finishes. ^The profile callback contains
  2909. ** the original statement text and an estimate of wall-clock time
  2910. ** of how long that statement took to run. ^The profile callback
  2911. ** time is in units of nanoseconds, however the current implementation
  2912. ** is only capable of millisecond resolution so the six least significant
  2913. ** digits in the time are meaningless. Future versions of SQLite
  2914. ** might provide greater resolution on the profiler callback. The
  2915. ** sqlite3_profile() function is considered experimental and is
  2916. ** subject to change in future versions of SQLite.
  2917. */
  2918. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2919. SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
  2920. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2921. /*
  2922. ** CAPI3REF: Query Progress Callbacks
  2923. ** METHOD: sqlite3
  2924. **
  2925. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2926. ** function X to be invoked periodically during long running calls to
  2927. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2928. ** database connection D. An example use for this
  2929. ** interface is to keep a GUI updated during a large query.
  2930. **
  2931. ** ^The parameter P is passed through as the only parameter to the
  2932. ** callback function X. ^The parameter N is the approximate number of
  2933. ** [virtual machine instructions] that are evaluated between successive
  2934. ** invocations of the callback X. ^If N is less than one then the progress
  2935. ** handler is disabled.
  2936. **
  2937. ** ^Only a single progress handler may be defined at one time per
  2938. ** [database connection]; setting a new progress handler cancels the
  2939. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2940. ** ^The progress handler is also disabled by setting N to a value less
  2941. ** than 1.
  2942. **
  2943. ** ^If the progress callback returns non-zero, the operation is
  2944. ** interrupted. This feature can be used to implement a
  2945. ** "Cancel" button on a GUI progress dialog box.
  2946. **
  2947. ** The progress handler callback must not do anything that will modify
  2948. ** the database connection that invoked the progress handler.
  2949. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2950. ** database connections for the meaning of "modify" in this paragraph.
  2951. **
  2952. */
  2953. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2954. /*
  2955. ** CAPI3REF: Opening A New Database Connection
  2956. ** CONSTRUCTOR: sqlite3
  2957. **
  2958. ** ^These routines open an SQLite database file as specified by the
  2959. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2960. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2961. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2962. ** returned in *ppDb, even if an error occurs. The only exception is that
  2963. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2964. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2965. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2966. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2967. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2968. ** an English language description of the error following a failure of any
  2969. ** of the sqlite3_open() routines.
  2970. **
  2971. ** ^The default encoding will be UTF-8 for databases created using
  2972. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2973. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2974. **
  2975. ** Whether or not an error occurs when it is opened, resources
  2976. ** associated with the [database connection] handle should be released by
  2977. ** passing it to [sqlite3_close()] when it is no longer required.
  2978. **
  2979. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2980. ** except that it accepts two additional parameters for additional control
  2981. ** over the new database connection. ^(The flags parameter to
  2982. ** sqlite3_open_v2() can take one of
  2983. ** the following three values, optionally combined with the
  2984. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2985. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2986. **
  2987. ** <dl>
  2988. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2989. ** <dd>The database is opened in read-only mode. If the database does not
  2990. ** already exist, an error is returned.</dd>)^
  2991. **
  2992. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2993. ** <dd>The database is opened for reading and writing if possible, or reading
  2994. ** only if the file is write protected by the operating system. In either
  2995. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2996. **
  2997. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2998. ** <dd>The database is opened for reading and writing, and is created if
  2999. ** it does not already exist. This is the behavior that is always used for
  3000. ** sqlite3_open() and sqlite3_open16().</dd>)^
  3001. ** </dl>
  3002. **
  3003. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  3004. ** combinations shown above optionally combined with other
  3005. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  3006. ** then the behavior is undefined.
  3007. **
  3008. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  3009. ** opens in the multi-thread [threading mode] as long as the single-thread
  3010. ** mode has not been set at compile-time or start-time. ^If the
  3011. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  3012. ** in the serialized [threading mode] unless single-thread was
  3013. ** previously selected at compile-time or start-time.
  3014. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  3015. ** eligible to use [shared cache mode], regardless of whether or not shared
  3016. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  3017. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  3018. ** participate in [shared cache mode] even if it is enabled.
  3019. **
  3020. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  3021. ** [sqlite3_vfs] object that defines the operating system interface that
  3022. ** the new database connection should use. ^If the fourth parameter is
  3023. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  3024. **
  3025. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  3026. ** is created for the connection. ^This in-memory database will vanish when
  3027. ** the database connection is closed. Future versions of SQLite might
  3028. ** make use of additional special filenames that begin with the ":" character.
  3029. ** It is recommended that when a database filename actually does begin with
  3030. ** a ":" character you should prefix the filename with a pathname such as
  3031. ** "./" to avoid ambiguity.
  3032. **
  3033. ** ^If the filename is an empty string, then a private, temporary
  3034. ** on-disk database will be created. ^This private database will be
  3035. ** automatically deleted as soon as the database connection is closed.
  3036. **
  3037. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  3038. **
  3039. ** ^If [URI filename] interpretation is enabled, and the filename argument
  3040. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  3041. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  3042. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  3043. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  3044. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  3045. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  3046. ** by default, but future releases of SQLite might enable URI filename
  3047. ** interpretation by default. See "[URI filenames]" for additional
  3048. ** information.
  3049. **
  3050. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  3051. ** authority, then it must be either an empty string or the string
  3052. ** "localhost". ^If the authority is not an empty string or "localhost", an
  3053. ** error is returned to the caller. ^The fragment component of a URI, if
  3054. ** present, is ignored.
  3055. **
  3056. ** ^SQLite uses the path component of the URI as the name of the disk file
  3057. ** which contains the database. ^If the path begins with a '/' character,
  3058. ** then it is interpreted as an absolute path. ^If the path does not begin
  3059. ** with a '/' (meaning that the authority section is omitted from the URI)
  3060. ** then the path is interpreted as a relative path.
  3061. ** ^(On windows, the first component of an absolute path
  3062. ** is a drive specification (e.g. "C:").)^
  3063. **
  3064. ** [[core URI query parameters]]
  3065. ** The query component of a URI may contain parameters that are interpreted
  3066. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3067. ** SQLite and its built-in [VFSes] interpret the
  3068. ** following query parameters:
  3069. **
  3070. ** <ul>
  3071. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3072. ** a VFS object that provides the operating system interface that should
  3073. ** be used to access the database file on disk. ^If this option is set to
  3074. ** an empty string the default VFS object is used. ^Specifying an unknown
  3075. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3076. ** present, then the VFS specified by the option takes precedence over
  3077. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3078. **
  3079. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3080. ** "rwc", or "memory". Attempting to set it to any other value is
  3081. ** an error)^.
  3082. ** ^If "ro" is specified, then the database is opened for read-only
  3083. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3084. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3085. ** "rw", then the database is opened for read-write (but not create)
  3086. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3087. ** been set. ^Value "rwc" is equivalent to setting both
  3088. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3089. ** set to "memory" then a pure [in-memory database] that never reads
  3090. ** or writes from disk is used. ^It is an error to specify a value for
  3091. ** the mode parameter that is less restrictive than that specified by
  3092. ** the flags passed in the third parameter to sqlite3_open_v2().
  3093. **
  3094. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3095. ** "private". ^Setting it to "shared" is equivalent to setting the
  3096. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3097. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3098. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3099. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3100. ** a URI filename, its value overrides any behavior requested by setting
  3101. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3102. **
  3103. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3104. ** [powersafe overwrite] property does or does not apply to the
  3105. ** storage media on which the database file resides.
  3106. **
  3107. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3108. ** which if set disables file locking in rollback journal modes. This
  3109. ** is useful for accessing a database on a filesystem that does not
  3110. ** support locking. Caution: Database corruption might result if two
  3111. ** or more processes write to the same database and any one of those
  3112. ** processes uses nolock=1.
  3113. **
  3114. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3115. ** parameter that indicates that the database file is stored on
  3116. ** read-only media. ^When immutable is set, SQLite assumes that the
  3117. ** database file cannot be changed, even by a process with higher
  3118. ** privilege, and so the database is opened read-only and all locking
  3119. ** and change detection is disabled. Caution: Setting the immutable
  3120. ** property on a database file that does in fact change can result
  3121. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3122. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3123. **
  3124. ** </ul>
  3125. **
  3126. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3127. ** error. Future versions of SQLite might understand additional query
  3128. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3129. ** additional information.
  3130. **
  3131. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3132. **
  3133. ** <table border="1" align=center cellpadding=5>
  3134. ** <tr><th> URI filenames <th> Results
  3135. ** <tr><td> file:data.db <td>
  3136. ** Open the file "data.db" in the current directory.
  3137. ** <tr><td> file:/home/fred/data.db<br>
  3138. ** file:///home/fred/data.db <br>
  3139. ** file://localhost/home/fred/data.db <br> <td>
  3140. ** Open the database file "/home/fred/data.db".
  3141. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3142. ** An error. "darkstar" is not a recognized authority.
  3143. ** <tr><td style="white-space:nowrap">
  3144. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3145. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3146. ** C:. Note that the %20 escaping in this example is not strictly
  3147. ** necessary - space characters can be used literally
  3148. ** in URI filenames.
  3149. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3150. ** Open file "data.db" in the current directory for read-only access.
  3151. ** Regardless of whether or not shared-cache mode is enabled by
  3152. ** default, use a private cache.
  3153. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3154. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3155. ** that uses dot-files in place of posix advisory locking.
  3156. ** <tr><td> file:data.db?mode=readonly <td>
  3157. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3158. ** </table>
  3159. **
  3160. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3161. ** query components of a URI. A hexadecimal escape sequence consists of a
  3162. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3163. ** specifying an octet value. ^Before the path or query components of a
  3164. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3165. ** hexadecimal escape sequences replaced by a single byte containing the
  3166. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3167. ** the results are undefined.
  3168. **
  3169. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3170. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3171. ** codepage is currently defined. Filenames containing international
  3172. ** characters must be converted to UTF-8 prior to passing them into
  3173. ** sqlite3_open() or sqlite3_open_v2().
  3174. **
  3175. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3176. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3177. ** features that require the use of temporary files may fail.
  3178. **
  3179. ** See also: [sqlite3_temp_directory]
  3180. */
  3181. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  3182. const char *filename, /* Database filename (UTF-8) */
  3183. sqlite3 **ppDb /* OUT: SQLite db handle */
  3184. );
  3185. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  3186. const void *filename, /* Database filename (UTF-16) */
  3187. sqlite3 **ppDb /* OUT: SQLite db handle */
  3188. );
  3189. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  3190. const char *filename, /* Database filename (UTF-8) */
  3191. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3192. int flags, /* Flags */
  3193. const char *zVfs /* Name of VFS module to use */
  3194. );
  3195. /*
  3196. ** CAPI3REF: Obtain Values For URI Parameters
  3197. **
  3198. ** These are utility routines, useful to VFS implementations, that check
  3199. ** to see if a database file was a URI that contained a specific query
  3200. ** parameter, and if so obtains the value of that query parameter.
  3201. **
  3202. ** If F is the database filename pointer passed into the xOpen() method of
  3203. ** a VFS implementation when the flags parameter to xOpen() has one or
  3204. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3205. ** P is the name of the query parameter, then
  3206. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3207. ** parameter if it exists or a NULL pointer if P does not appear as a
  3208. ** query parameter on F. If P is a query parameter of F
  3209. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3210. ** a pointer to an empty string.
  3211. **
  3212. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3213. ** parameter and returns true (1) or false (0) according to the value
  3214. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3215. ** value of query parameter P is one of "yes", "true", or "on" in any
  3216. ** case or if the value begins with a non-zero number. The
  3217. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3218. ** query parameter P is one of "no", "false", or "off" in any case or
  3219. ** if the value begins with a numeric zero. If P is not a query
  3220. ** parameter on F or if the value of P is does not match any of the
  3221. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3222. **
  3223. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3224. ** 64-bit signed integer and returns that integer, or D if P does not
  3225. ** exist. If the value of P is something other than an integer, then
  3226. ** zero is returned.
  3227. **
  3228. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3229. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3230. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3231. ** VFS method, then the behavior of this routine is undefined and probably
  3232. ** undesirable.
  3233. */
  3234. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3235. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3236. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3237. /*
  3238. ** CAPI3REF: Error Codes And Messages
  3239. ** METHOD: sqlite3
  3240. **
  3241. ** ^If the most recent sqlite3_* API call associated with
  3242. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3243. ** returns the numeric [result code] or [extended result code] for that
  3244. ** API call.
  3245. ** If the most recent API call was successful,
  3246. ** then the return value from sqlite3_errcode() is undefined.
  3247. ** ^The sqlite3_extended_errcode()
  3248. ** interface is the same except that it always returns the
  3249. ** [extended result code] even when extended result codes are
  3250. ** disabled.
  3251. **
  3252. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3253. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3254. ** ^(Memory to hold the error message string is managed internally.
  3255. ** The application does not need to worry about freeing the result.
  3256. ** However, the error string might be overwritten or deallocated by
  3257. ** subsequent calls to other SQLite interface functions.)^
  3258. **
  3259. ** ^The sqlite3_errstr() interface returns the English-language text
  3260. ** that describes the [result code], as UTF-8.
  3261. ** ^(Memory to hold the error message string is managed internally
  3262. ** and must not be freed by the application)^.
  3263. **
  3264. ** When the serialized [threading mode] is in use, it might be the
  3265. ** case that a second error occurs on a separate thread in between
  3266. ** the time of the first error and the call to these interfaces.
  3267. ** When that happens, the second error will be reported since these
  3268. ** interfaces always report the most recent result. To avoid
  3269. ** this, each thread can obtain exclusive use of the [database connection] D
  3270. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3271. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3272. ** all calls to the interfaces listed here are completed.
  3273. **
  3274. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3275. ** was invoked incorrectly by the application. In that case, the
  3276. ** error code and message may or may not be set.
  3277. */
  3278. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
  3279. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
  3280. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
  3281. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
  3282. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
  3283. /*
  3284. ** CAPI3REF: Prepared Statement Object
  3285. ** KEYWORDS: {prepared statement} {prepared statements}
  3286. **
  3287. ** An instance of this object represents a single SQL statement that
  3288. ** has been compiled into binary form and is ready to be evaluated.
  3289. **
  3290. ** Think of each SQL statement as a separate computer program. The
  3291. ** original SQL text is source code. A prepared statement object
  3292. ** is the compiled object code. All SQL must be converted into a
  3293. ** prepared statement before it can be run.
  3294. **
  3295. ** The life-cycle of a prepared statement object usually goes like this:
  3296. **
  3297. ** <ol>
  3298. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3299. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3300. ** interfaces.
  3301. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3302. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3303. ** to step 2. Do this zero or more times.
  3304. ** <li> Destroy the object using [sqlite3_finalize()].
  3305. ** </ol>
  3306. */
  3307. typedef struct sqlite3_stmt sqlite3_stmt;
  3308. /*
  3309. ** CAPI3REF: Run-time Limits
  3310. ** METHOD: sqlite3
  3311. **
  3312. ** ^(This interface allows the size of various constructs to be limited
  3313. ** on a connection by connection basis. The first parameter is the
  3314. ** [database connection] whose limit is to be set or queried. The
  3315. ** second parameter is one of the [limit categories] that define a
  3316. ** class of constructs to be size limited. The third parameter is the
  3317. ** new limit for that construct.)^
  3318. **
  3319. ** ^If the new limit is a negative number, the limit is unchanged.
  3320. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3321. ** [limits | hard upper bound]
  3322. ** set at compile-time by a C preprocessor macro called
  3323. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3324. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3325. ** ^Attempts to increase a limit above its hard upper bound are
  3326. ** silently truncated to the hard upper bound.
  3327. **
  3328. ** ^Regardless of whether or not the limit was changed, the
  3329. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3330. ** ^Hence, to find the current value of a limit without changing it,
  3331. ** simply invoke this interface with the third parameter set to -1.
  3332. **
  3333. ** Run-time limits are intended for use in applications that manage
  3334. ** both their own internal database and also databases that are controlled
  3335. ** by untrusted external sources. An example application might be a
  3336. ** web browser that has its own databases for storing history and
  3337. ** separate databases controlled by JavaScript applications downloaded
  3338. ** off the Internet. The internal databases can be given the
  3339. ** large, default limits. Databases managed by external sources can
  3340. ** be given much smaller limits designed to prevent a denial of service
  3341. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3342. ** interface to further control untrusted SQL. The size of the database
  3343. ** created by an untrusted script can be contained using the
  3344. ** [max_page_count] [PRAGMA].
  3345. **
  3346. ** New run-time limit categories may be added in future releases.
  3347. */
  3348. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
  3349. /*
  3350. ** CAPI3REF: Run-Time Limit Categories
  3351. ** KEYWORDS: {limit category} {*limit categories}
  3352. **
  3353. ** These constants define various performance limits
  3354. ** that can be lowered at run-time using [sqlite3_limit()].
  3355. ** The synopsis of the meanings of the various limits is shown below.
  3356. ** Additional information is available at [limits | Limits in SQLite].
  3357. **
  3358. ** <dl>
  3359. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3360. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3361. **
  3362. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3363. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3364. **
  3365. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3366. ** <dd>The maximum number of columns in a table definition or in the
  3367. ** result set of a [SELECT] or the maximum number of columns in an index
  3368. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3369. **
  3370. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3371. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3372. **
  3373. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3374. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3375. **
  3376. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3377. ** <dd>The maximum number of instructions in a virtual machine program
  3378. ** used to implement an SQL statement. This limit is not currently
  3379. ** enforced, though that might be added in some future release of
  3380. ** SQLite.</dd>)^
  3381. **
  3382. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3383. ** <dd>The maximum number of arguments on a function.</dd>)^
  3384. **
  3385. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3386. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3387. **
  3388. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3389. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3390. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3391. ** [GLOB] operators.</dd>)^
  3392. **
  3393. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3394. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3395. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3396. **
  3397. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3398. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3399. **
  3400. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3401. ** <dd>The maximum number of auxiliary worker threads that a single
  3402. ** [prepared statement] may start.</dd>)^
  3403. ** </dl>
  3404. */
  3405. #define SQLITE_LIMIT_LENGTH 0
  3406. #define SQLITE_LIMIT_SQL_LENGTH 1
  3407. #define SQLITE_LIMIT_COLUMN 2
  3408. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3409. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3410. #define SQLITE_LIMIT_VDBE_OP 5
  3411. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3412. #define SQLITE_LIMIT_ATTACHED 7
  3413. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3414. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3415. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3416. #define SQLITE_LIMIT_WORKER_THREADS 11
  3417. /*
  3418. ** CAPI3REF: Compiling An SQL Statement
  3419. ** KEYWORDS: {SQL statement compiler}
  3420. ** METHOD: sqlite3
  3421. ** CONSTRUCTOR: sqlite3_stmt
  3422. **
  3423. ** To execute an SQL query, it must first be compiled into a byte-code
  3424. ** program using one of these routines.
  3425. **
  3426. ** The first argument, "db", is a [database connection] obtained from a
  3427. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3428. ** [sqlite3_open16()]. The database connection must not have been closed.
  3429. **
  3430. ** The second argument, "zSql", is the statement to be compiled, encoded
  3431. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3432. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3433. ** use UTF-16.
  3434. **
  3435. ** ^If the nByte argument is negative, then zSql is read up to the
  3436. ** first zero terminator. ^If nByte is positive, then it is the
  3437. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3438. ** statement is generated.
  3439. ** If the caller knows that the supplied string is nul-terminated, then
  3440. ** there is a small performance advantage to passing an nByte parameter that
  3441. ** is the number of bytes in the input string <i>including</i>
  3442. ** the nul-terminator.
  3443. **
  3444. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3445. ** past the end of the first SQL statement in zSql. These routines only
  3446. ** compile the first statement in zSql, so *pzTail is left pointing to
  3447. ** what remains uncompiled.
  3448. **
  3449. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3450. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3451. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3452. ** string or a comment) then *ppStmt is set to NULL.
  3453. ** The calling procedure is responsible for deleting the compiled
  3454. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3455. ** ppStmt may not be NULL.
  3456. **
  3457. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3458. ** otherwise an [error code] is returned.
  3459. **
  3460. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3461. ** recommended for all new programs. The two older interfaces are retained
  3462. ** for backwards compatibility, but their use is discouraged.
  3463. ** ^In the "v2" interfaces, the prepared statement
  3464. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3465. ** original SQL text. This causes the [sqlite3_step()] interface to
  3466. ** behave differently in three ways:
  3467. **
  3468. ** <ol>
  3469. ** <li>
  3470. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3471. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3472. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3473. ** retries will occur before sqlite3_step() gives up and returns an error.
  3474. ** </li>
  3475. **
  3476. ** <li>
  3477. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3478. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3479. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3480. ** and the application would have to make a second call to [sqlite3_reset()]
  3481. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3482. ** interfaces, the underlying reason for the error is returned immediately.
  3483. ** </li>
  3484. **
  3485. ** <li>
  3486. ** ^If the specific value bound to [parameter | host parameter] in the
  3487. ** WHERE clause might influence the choice of query plan for a statement,
  3488. ** then the statement will be automatically recompiled, as if there had been
  3489. ** a schema change, on the first [sqlite3_step()] call following any change
  3490. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3491. ** ^The specific value of WHERE-clause [parameter] might influence the
  3492. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3493. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3494. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3495. ** </li>
  3496. ** </ol>
  3497. */
  3498. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  3499. sqlite3 *db, /* Database handle */
  3500. const char *zSql, /* SQL statement, UTF-8 encoded */
  3501. int nByte, /* Maximum length of zSql in bytes. */
  3502. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3503. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3504. );
  3505. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  3506. sqlite3 *db, /* Database handle */
  3507. const char *zSql, /* SQL statement, UTF-8 encoded */
  3508. int nByte, /* Maximum length of zSql in bytes. */
  3509. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3510. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3511. );
  3512. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  3513. sqlite3 *db, /* Database handle */
  3514. const void *zSql, /* SQL statement, UTF-16 encoded */
  3515. int nByte, /* Maximum length of zSql in bytes. */
  3516. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3517. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3518. );
  3519. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  3520. sqlite3 *db, /* Database handle */
  3521. const void *zSql, /* SQL statement, UTF-16 encoded */
  3522. int nByte, /* Maximum length of zSql in bytes. */
  3523. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3524. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3525. );
  3526. /*
  3527. ** CAPI3REF: Retrieving Statement SQL
  3528. ** METHOD: sqlite3_stmt
  3529. **
  3530. ** ^This interface can be used to retrieve a saved copy of the original
  3531. ** SQL text used to create a [prepared statement] if that statement was
  3532. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3533. */
  3534. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
  3535. /*
  3536. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3537. ** METHOD: sqlite3_stmt
  3538. **
  3539. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3540. ** and only if the [prepared statement] X makes no direct changes to
  3541. ** the content of the database file.
  3542. **
  3543. ** Note that [application-defined SQL functions] or
  3544. ** [virtual tables] might change the database indirectly as a side effect.
  3545. ** ^(For example, if an application defines a function "eval()" that
  3546. ** calls [sqlite3_exec()], then the following SQL statement would
  3547. ** change the database file through side-effects:
  3548. **
  3549. ** <blockquote><pre>
  3550. ** SELECT eval('DELETE FROM t1') FROM t2;
  3551. ** </pre></blockquote>
  3552. **
  3553. ** But because the [SELECT] statement does not change the database file
  3554. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3555. **
  3556. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3557. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3558. ** since the statements themselves do not actually modify the database but
  3559. ** rather they control the timing of when other statements modify the
  3560. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3561. ** sqlite3_stmt_readonly() to return true since, while those statements
  3562. ** change the configuration of a database connection, they do not make
  3563. ** changes to the content of the database files on disk.
  3564. */
  3565. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3566. /*
  3567. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3568. ** METHOD: sqlite3_stmt
  3569. **
  3570. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3571. ** [prepared statement] S has been stepped at least once using
  3572. ** [sqlite3_step(S)] but has neither run to completion (returned
  3573. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  3574. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3575. ** interface returns false if S is a NULL pointer. If S is not a
  3576. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3577. ** object, then the behavior is undefined and probably undesirable.
  3578. **
  3579. ** This interface can be used in combination [sqlite3_next_stmt()]
  3580. ** to locate all prepared statements associated with a database
  3581. ** connection that are in need of being reset. This can be used,
  3582. ** for example, in diagnostic routines to search for prepared
  3583. ** statements that are holding a transaction open.
  3584. */
  3585. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
  3586. /*
  3587. ** CAPI3REF: Dynamically Typed Value Object
  3588. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3589. **
  3590. ** SQLite uses the sqlite3_value object to represent all values
  3591. ** that can be stored in a database table. SQLite uses dynamic typing
  3592. ** for the values it stores. ^Values stored in sqlite3_value objects
  3593. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3594. **
  3595. ** An sqlite3_value object may be either "protected" or "unprotected".
  3596. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3597. ** will accept either a protected or an unprotected sqlite3_value.
  3598. ** Every interface that accepts sqlite3_value arguments specifies
  3599. ** whether or not it requires a protected sqlite3_value. The
  3600. ** [sqlite3_value_dup()] interface can be used to construct a new
  3601. ** protected sqlite3_value from an unprotected sqlite3_value.
  3602. **
  3603. ** The terms "protected" and "unprotected" refer to whether or not
  3604. ** a mutex is held. An internal mutex is held for a protected
  3605. ** sqlite3_value object but no mutex is held for an unprotected
  3606. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3607. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3608. ** or if SQLite is run in one of reduced mutex modes
  3609. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3610. ** then there is no distinction between protected and unprotected
  3611. ** sqlite3_value objects and they can be used interchangeably. However,
  3612. ** for maximum code portability it is recommended that applications
  3613. ** still make the distinction between protected and unprotected
  3614. ** sqlite3_value objects even when not strictly required.
  3615. **
  3616. ** ^The sqlite3_value objects that are passed as parameters into the
  3617. ** implementation of [application-defined SQL functions] are protected.
  3618. ** ^The sqlite3_value object returned by
  3619. ** [sqlite3_column_value()] is unprotected.
  3620. ** Unprotected sqlite3_value objects may only be used with
  3621. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3622. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3623. ** interfaces require protected sqlite3_value objects.
  3624. */
  3625. typedef struct Mem sqlite3_value;
  3626. /*
  3627. ** CAPI3REF: SQL Function Context Object
  3628. **
  3629. ** The context in which an SQL function executes is stored in an
  3630. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3631. ** is always first parameter to [application-defined SQL functions].
  3632. ** The application-defined SQL function implementation will pass this
  3633. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3634. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3635. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3636. ** and/or [sqlite3_set_auxdata()].
  3637. */
  3638. typedef struct sqlite3_context sqlite3_context;
  3639. /*
  3640. ** CAPI3REF: Binding Values To Prepared Statements
  3641. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3642. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3643. ** METHOD: sqlite3_stmt
  3644. **
  3645. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3646. ** literals may be replaced by a [parameter] that matches one of following
  3647. ** templates:
  3648. **
  3649. ** <ul>
  3650. ** <li> ?
  3651. ** <li> ?NNN
  3652. ** <li> :VVV
  3653. ** <li> @VVV
  3654. ** <li> $VVV
  3655. ** </ul>
  3656. **
  3657. ** In the templates above, NNN represents an integer literal,
  3658. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3659. ** parameters (also called "host parameter names" or "SQL parameters")
  3660. ** can be set using the sqlite3_bind_*() routines defined here.
  3661. **
  3662. ** ^The first argument to the sqlite3_bind_*() routines is always
  3663. ** a pointer to the [sqlite3_stmt] object returned from
  3664. ** [sqlite3_prepare_v2()] or its variants.
  3665. **
  3666. ** ^The second argument is the index of the SQL parameter to be set.
  3667. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3668. ** SQL parameter is used more than once, second and subsequent
  3669. ** occurrences have the same index as the first occurrence.
  3670. ** ^The index for named parameters can be looked up using the
  3671. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3672. ** for "?NNN" parameters is the value of NNN.
  3673. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3674. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3675. **
  3676. ** ^The third argument is the value to bind to the parameter.
  3677. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3678. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3679. ** is ignored and the end result is the same as sqlite3_bind_null().
  3680. **
  3681. ** ^(In those routines that have a fourth argument, its value is the
  3682. ** number of bytes in the parameter. To be clear: the value is the
  3683. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3684. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3685. ** is negative, then the length of the string is
  3686. ** the number of bytes up to the first zero terminator.
  3687. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3688. ** the behavior is undefined.
  3689. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3690. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3691. ** that parameter must be the byte offset
  3692. ** where the NUL terminator would occur assuming the string were NUL
  3693. ** terminated. If any NUL characters occur at byte offsets less than
  3694. ** the value of the fourth parameter then the resulting string value will
  3695. ** contain embedded NULs. The result of expressions involving strings
  3696. ** with embedded NULs is undefined.
  3697. **
  3698. ** ^The fifth argument to the BLOB and string binding interfaces
  3699. ** is a destructor used to dispose of the BLOB or
  3700. ** string after SQLite has finished with it. ^The destructor is called
  3701. ** to dispose of the BLOB or string even if the call to bind API fails.
  3702. ** ^If the fifth argument is
  3703. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3704. ** information is in static, unmanaged space and does not need to be freed.
  3705. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3706. ** SQLite makes its own private copy of the data immediately, before
  3707. ** the sqlite3_bind_*() routine returns.
  3708. **
  3709. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3710. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3711. ** to specify the encoding of the text in the third parameter. If
  3712. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3713. ** allowed values shown above, or if the text encoding is different
  3714. ** from the encoding specified by the sixth parameter, then the behavior
  3715. ** is undefined.
  3716. **
  3717. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3718. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3719. ** (just an integer to hold its size) while it is being processed.
  3720. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3721. ** content is later written using
  3722. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3723. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3724. **
  3725. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3726. ** for the [prepared statement] or with a prepared statement for which
  3727. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3728. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3729. ** routine is passed a [prepared statement] that has been finalized, the
  3730. ** result is undefined and probably harmful.
  3731. **
  3732. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3733. ** ^Unbound parameters are interpreted as NULL.
  3734. **
  3735. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3736. ** [error code] if anything goes wrong.
  3737. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3738. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3739. ** [SQLITE_MAX_LENGTH].
  3740. ** ^[SQLITE_RANGE] is returned if the parameter
  3741. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3742. **
  3743. ** See also: [sqlite3_bind_parameter_count()],
  3744. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3745. */
  3746. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3747. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3748. void(*)(void*));
  3749. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
  3750. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
  3751. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3752. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
  3753. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3754. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3755. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3756. void(*)(void*), unsigned char encoding);
  3757. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3758. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3759. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  3760. /*
  3761. ** CAPI3REF: Number Of SQL Parameters
  3762. ** METHOD: sqlite3_stmt
  3763. **
  3764. ** ^This routine can be used to find the number of [SQL parameters]
  3765. ** in a [prepared statement]. SQL parameters are tokens of the
  3766. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3767. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3768. ** to the parameters at a later time.
  3769. **
  3770. ** ^(This routine actually returns the index of the largest (rightmost)
  3771. ** parameter. For all forms except ?NNN, this will correspond to the
  3772. ** number of unique parameters. If parameters of the ?NNN form are used,
  3773. ** there may be gaps in the list.)^
  3774. **
  3775. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3776. ** [sqlite3_bind_parameter_name()], and
  3777. ** [sqlite3_bind_parameter_index()].
  3778. */
  3779. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
  3780. /*
  3781. ** CAPI3REF: Name Of A Host Parameter
  3782. ** METHOD: sqlite3_stmt
  3783. **
  3784. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3785. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3786. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3787. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3788. ** respectively.
  3789. ** In other words, the initial ":" or "$" or "@" or "?"
  3790. ** is included as part of the name.)^
  3791. ** ^Parameters of the form "?" without a following integer have no name
  3792. ** and are referred to as "nameless" or "anonymous parameters".
  3793. **
  3794. ** ^The first host parameter has an index of 1, not 0.
  3795. **
  3796. ** ^If the value N is out of range or if the N-th parameter is
  3797. ** nameless, then NULL is returned. ^The returned string is
  3798. ** always in UTF-8 encoding even if the named parameter was
  3799. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3800. ** [sqlite3_prepare16_v2()].
  3801. **
  3802. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3803. ** [sqlite3_bind_parameter_count()], and
  3804. ** [sqlite3_bind_parameter_index()].
  3805. */
  3806. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3807. /*
  3808. ** CAPI3REF: Index Of A Parameter With A Given Name
  3809. ** METHOD: sqlite3_stmt
  3810. **
  3811. ** ^Return the index of an SQL parameter given its name. ^The
  3812. ** index value returned is suitable for use as the second
  3813. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3814. ** is returned if no matching parameter is found. ^The parameter
  3815. ** name must be given in UTF-8 even if the original statement
  3816. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3817. **
  3818. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3819. ** [sqlite3_bind_parameter_count()], and
  3820. ** [sqlite3_bind_parameter_name()].
  3821. */
  3822. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3823. /*
  3824. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3825. ** METHOD: sqlite3_stmt
  3826. **
  3827. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3828. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3829. ** ^Use this routine to reset all host parameters to NULL.
  3830. */
  3831. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
  3832. /*
  3833. ** CAPI3REF: Number Of Columns In A Result Set
  3834. ** METHOD: sqlite3_stmt
  3835. **
  3836. ** ^Return the number of columns in the result set returned by the
  3837. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3838. ** statement that does not return data (for example an [UPDATE]).
  3839. **
  3840. ** See also: [sqlite3_data_count()]
  3841. */
  3842. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
  3843. /*
  3844. ** CAPI3REF: Column Names In A Result Set
  3845. ** METHOD: sqlite3_stmt
  3846. **
  3847. ** ^These routines return the name assigned to a particular column
  3848. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3849. ** interface returns a pointer to a zero-terminated UTF-8 string
  3850. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3851. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3852. ** that implements the [SELECT] statement. ^The second parameter is the
  3853. ** column number. ^The leftmost column is number 0.
  3854. **
  3855. ** ^The returned string pointer is valid until either the [prepared statement]
  3856. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3857. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3858. ** or until the next call to
  3859. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3860. **
  3861. ** ^If sqlite3_malloc() fails during the processing of either routine
  3862. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3863. ** NULL pointer is returned.
  3864. **
  3865. ** ^The name of a result column is the value of the "AS" clause for
  3866. ** that column, if there is an AS clause. If there is no AS clause
  3867. ** then the name of the column is unspecified and may change from
  3868. ** one release of SQLite to the next.
  3869. */
  3870. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
  3871. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
  3872. /*
  3873. ** CAPI3REF: Source Of Data In A Query Result
  3874. ** METHOD: sqlite3_stmt
  3875. **
  3876. ** ^These routines provide a means to determine the database, table, and
  3877. ** table column that is the origin of a particular result column in
  3878. ** [SELECT] statement.
  3879. ** ^The name of the database or table or column can be returned as
  3880. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3881. ** the database name, the _table_ routines return the table name, and
  3882. ** the origin_ routines return the column name.
  3883. ** ^The returned string is valid until the [prepared statement] is destroyed
  3884. ** using [sqlite3_finalize()] or until the statement is automatically
  3885. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3886. ** or until the same information is requested
  3887. ** again in a different encoding.
  3888. **
  3889. ** ^The names returned are the original un-aliased names of the
  3890. ** database, table, and column.
  3891. **
  3892. ** ^The first argument to these interfaces is a [prepared statement].
  3893. ** ^These functions return information about the Nth result column returned by
  3894. ** the statement, where N is the second function argument.
  3895. ** ^The left-most column is column 0 for these routines.
  3896. **
  3897. ** ^If the Nth column returned by the statement is an expression or
  3898. ** subquery and is not a column value, then all of these functions return
  3899. ** NULL. ^These routine might also return NULL if a memory allocation error
  3900. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3901. ** or column that query result column was extracted from.
  3902. **
  3903. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3904. ** UTF-16 encoded strings and the other functions return UTF-8.
  3905. **
  3906. ** ^These APIs are only available if the library was compiled with the
  3907. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3908. **
  3909. ** If two or more threads call one or more of these routines against the same
  3910. ** prepared statement and column at the same time then the results are
  3911. ** undefined.
  3912. **
  3913. ** If two or more threads call one or more
  3914. ** [sqlite3_column_database_name | column metadata interfaces]
  3915. ** for the same [prepared statement] and result column
  3916. ** at the same time then the results are undefined.
  3917. */
  3918. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
  3919. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
  3920. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
  3921. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
  3922. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
  3923. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3924. /*
  3925. ** CAPI3REF: Declared Datatype Of A Query Result
  3926. ** METHOD: sqlite3_stmt
  3927. **
  3928. ** ^(The first parameter is a [prepared statement].
  3929. ** If this statement is a [SELECT] statement and the Nth column of the
  3930. ** returned result set of that [SELECT] is a table column (not an
  3931. ** expression or subquery) then the declared type of the table
  3932. ** column is returned.)^ ^If the Nth column of the result set is an
  3933. ** expression or subquery, then a NULL pointer is returned.
  3934. ** ^The returned string is always UTF-8 encoded.
  3935. **
  3936. ** ^(For example, given the database schema:
  3937. **
  3938. ** CREATE TABLE t1(c1 VARIANT);
  3939. **
  3940. ** and the following statement to be compiled:
  3941. **
  3942. ** SELECT c1 + 1, c1 FROM t1;
  3943. **
  3944. ** this routine would return the string "VARIANT" for the second result
  3945. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3946. **
  3947. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3948. ** is declared to contain a particular type does not mean that the
  3949. ** data stored in that column is of the declared type. SQLite is
  3950. ** strongly typed, but the typing is dynamic not static. ^Type
  3951. ** is associated with individual values, not with the containers
  3952. ** used to hold those values.
  3953. */
  3954. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
  3955. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
  3956. /*
  3957. ** CAPI3REF: Evaluate An SQL Statement
  3958. ** METHOD: sqlite3_stmt
  3959. **
  3960. ** After a [prepared statement] has been prepared using either
  3961. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3962. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3963. ** must be called one or more times to evaluate the statement.
  3964. **
  3965. ** The details of the behavior of the sqlite3_step() interface depend
  3966. ** on whether the statement was prepared using the newer "v2" interface
  3967. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3968. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3969. ** new "v2" interface is recommended for new applications but the legacy
  3970. ** interface will continue to be supported.
  3971. **
  3972. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3973. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3974. ** ^With the "v2" interface, any of the other [result codes] or
  3975. ** [extended result codes] might be returned as well.
  3976. **
  3977. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3978. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3979. ** or occurs outside of an explicit transaction, then you can retry the
  3980. ** statement. If the statement is not a [COMMIT] and occurs within an
  3981. ** explicit transaction then you should rollback the transaction before
  3982. ** continuing.
  3983. **
  3984. ** ^[SQLITE_DONE] means that the statement has finished executing
  3985. ** successfully. sqlite3_step() should not be called again on this virtual
  3986. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3987. ** machine back to its initial state.
  3988. **
  3989. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3990. ** is returned each time a new row of data is ready for processing by the
  3991. ** caller. The values may be accessed using the [column access functions].
  3992. ** sqlite3_step() is called again to retrieve the next row of data.
  3993. **
  3994. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3995. ** violation) has occurred. sqlite3_step() should not be called again on
  3996. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3997. ** ^With the legacy interface, a more specific error code (for example,
  3998. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3999. ** can be obtained by calling [sqlite3_reset()] on the
  4000. ** [prepared statement]. ^In the "v2" interface,
  4001. ** the more specific error code is returned directly by sqlite3_step().
  4002. **
  4003. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  4004. ** Perhaps it was called on a [prepared statement] that has
  4005. ** already been [sqlite3_finalize | finalized] or on one that had
  4006. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  4007. ** be the case that the same database connection is being used by two or
  4008. ** more threads at the same moment in time.
  4009. **
  4010. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  4011. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  4012. ** other than [SQLITE_ROW] before any subsequent invocation of
  4013. ** sqlite3_step(). Failure to reset the prepared statement using
  4014. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  4015. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  4016. ** calling [sqlite3_reset()] automatically in this circumstance rather
  4017. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  4018. ** break because any application that ever receives an SQLITE_MISUSE error
  4019. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  4020. ** can be used to restore the legacy behavior.
  4021. **
  4022. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  4023. ** API always returns a generic error code, [SQLITE_ERROR], following any
  4024. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  4025. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  4026. ** specific [error codes] that better describes the error.
  4027. ** We admit that this is a goofy design. The problem has been fixed
  4028. ** with the "v2" interface. If you prepare all of your SQL statements
  4029. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  4030. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  4031. ** then the more specific [error codes] are returned directly
  4032. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  4033. */
  4034. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
  4035. /*
  4036. ** CAPI3REF: Number of columns in a result set
  4037. ** METHOD: sqlite3_stmt
  4038. **
  4039. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  4040. ** current row of the result set of [prepared statement] P.
  4041. ** ^If prepared statement P does not have results ready to return
  4042. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  4043. ** interfaces) then sqlite3_data_count(P) returns 0.
  4044. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  4045. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  4046. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  4047. ** will return non-zero if previous call to [sqlite3_step](P) returned
  4048. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  4049. ** where it always returns zero since each step of that multi-step
  4050. ** pragma returns 0 columns of data.
  4051. **
  4052. ** See also: [sqlite3_column_count()]
  4053. */
  4054. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
  4055. /*
  4056. ** CAPI3REF: Fundamental Datatypes
  4057. ** KEYWORDS: SQLITE_TEXT
  4058. **
  4059. ** ^(Every value in SQLite has one of five fundamental datatypes:
  4060. **
  4061. ** <ul>
  4062. ** <li> 64-bit signed integer
  4063. ** <li> 64-bit IEEE floating point number
  4064. ** <li> string
  4065. ** <li> BLOB
  4066. ** <li> NULL
  4067. ** </ul>)^
  4068. **
  4069. ** These constants are codes for each of those types.
  4070. **
  4071. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4072. ** for a completely different meaning. Software that links against both
  4073. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4074. ** SQLITE_TEXT.
  4075. */
  4076. #define SQLITE_INTEGER 1
  4077. #define SQLITE_FLOAT 2
  4078. #define SQLITE_BLOB 4
  4079. #define SQLITE_NULL 5
  4080. #ifdef SQLITE_TEXT
  4081. # undef SQLITE_TEXT
  4082. #else
  4083. # define SQLITE_TEXT 3
  4084. #endif
  4085. #define SQLITE3_TEXT 3
  4086. /*
  4087. ** CAPI3REF: Result Values From A Query
  4088. ** KEYWORDS: {column access functions}
  4089. ** METHOD: sqlite3_stmt
  4090. **
  4091. ** ^These routines return information about a single column of the current
  4092. ** result row of a query. ^In every case the first argument is a pointer
  4093. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4094. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4095. ** and the second argument is the index of the column for which information
  4096. ** should be returned. ^The leftmost column of the result set has the index 0.
  4097. ** ^The number of columns in the result can be determined using
  4098. ** [sqlite3_column_count()].
  4099. **
  4100. ** If the SQL statement does not currently point to a valid row, or if the
  4101. ** column index is out of range, the result is undefined.
  4102. ** These routines may only be called when the most recent call to
  4103. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4104. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4105. ** If any of these routines are called after [sqlite3_reset()] or
  4106. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4107. ** something other than [SQLITE_ROW], the results are undefined.
  4108. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4109. ** are called from a different thread while any of these routines
  4110. ** are pending, then the results are undefined.
  4111. **
  4112. ** ^The sqlite3_column_type() routine returns the
  4113. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4114. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4115. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4116. ** returned by sqlite3_column_type() is only meaningful if no type
  4117. ** conversions have occurred as described below. After a type conversion,
  4118. ** the value returned by sqlite3_column_type() is undefined. Future
  4119. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4120. ** following a type conversion.
  4121. **
  4122. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4123. ** routine returns the number of bytes in that BLOB or string.
  4124. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4125. ** the string to UTF-8 and then returns the number of bytes.
  4126. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4127. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4128. ** the number of bytes in that string.
  4129. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4130. **
  4131. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4132. ** routine returns the number of bytes in that BLOB or string.
  4133. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4134. ** the string to UTF-16 and then returns the number of bytes.
  4135. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4136. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4137. ** the number of bytes in that string.
  4138. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4139. **
  4140. ** ^The values returned by [sqlite3_column_bytes()] and
  4141. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4142. ** of the string. ^For clarity: the values returned by
  4143. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4144. ** bytes in the string, not the number of characters.
  4145. **
  4146. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4147. ** even empty strings, are always zero-terminated. ^The return
  4148. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4149. **
  4150. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  4151. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  4152. ** an unprotected sqlite3_value object may only be used safely with
  4153. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  4154. ** If the [unprotected sqlite3_value] object returned by
  4155. ** [sqlite3_column_value()] is used in any other way, including calls
  4156. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4157. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  4158. **
  4159. ** These routines attempt to convert the value where appropriate. ^For
  4160. ** example, if the internal representation is FLOAT and a text result
  4161. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4162. ** conversion automatically. ^(The following table details the conversions
  4163. ** that are applied:
  4164. **
  4165. ** <blockquote>
  4166. ** <table border="1">
  4167. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4168. **
  4169. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4170. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4171. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4172. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4173. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4174. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4175. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4176. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4177. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4178. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4179. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4180. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4181. ** <tr><td> TEXT <td> BLOB <td> No change
  4182. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4183. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4184. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4185. ** </table>
  4186. ** </blockquote>)^
  4187. **
  4188. ** Note that when type conversions occur, pointers returned by prior
  4189. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4190. ** sqlite3_column_text16() may be invalidated.
  4191. ** Type conversions and pointer invalidations might occur
  4192. ** in the following cases:
  4193. **
  4194. ** <ul>
  4195. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4196. ** sqlite3_column_text16() is called. A zero-terminator might
  4197. ** need to be added to the string.</li>
  4198. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4199. ** sqlite3_column_text16() is called. The content must be converted
  4200. ** to UTF-16.</li>
  4201. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4202. ** sqlite3_column_text() is called. The content must be converted
  4203. ** to UTF-8.</li>
  4204. ** </ul>
  4205. **
  4206. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4207. ** not invalidate a prior pointer, though of course the content of the buffer
  4208. ** that the prior pointer references will have been modified. Other kinds
  4209. ** of conversion are done in place when it is possible, but sometimes they
  4210. ** are not possible and in those cases prior pointers are invalidated.
  4211. **
  4212. ** The safest policy is to invoke these routines
  4213. ** in one of the following ways:
  4214. **
  4215. ** <ul>
  4216. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4217. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4218. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4219. ** </ul>
  4220. **
  4221. ** In other words, you should call sqlite3_column_text(),
  4222. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4223. ** into the desired format, then invoke sqlite3_column_bytes() or
  4224. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4225. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4226. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4227. ** with calls to sqlite3_column_bytes().
  4228. **
  4229. ** ^The pointers returned are valid until a type conversion occurs as
  4230. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4231. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4232. ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
  4233. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4234. ** [sqlite3_free()].
  4235. **
  4236. ** ^(If a memory allocation error occurs during the evaluation of any
  4237. ** of these routines, a default value is returned. The default value
  4238. ** is either the integer 0, the floating point number 0.0, or a NULL
  4239. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4240. ** [SQLITE_NOMEM].)^
  4241. */
  4242. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4243. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4244. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4245. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
  4246. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
  4247. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4248. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
  4249. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4250. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
  4251. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
  4252. /*
  4253. ** CAPI3REF: Destroy A Prepared Statement Object
  4254. ** DESTRUCTOR: sqlite3_stmt
  4255. **
  4256. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4257. ** ^If the most recent evaluation of the statement encountered no errors
  4258. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4259. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4260. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4261. ** [extended error code].
  4262. **
  4263. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4264. ** the life cycle of [prepared statement] S:
  4265. ** before statement S is ever evaluated, after
  4266. ** one or more calls to [sqlite3_reset()], or after any call
  4267. ** to [sqlite3_step()] regardless of whether or not the statement has
  4268. ** completed execution.
  4269. **
  4270. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4271. **
  4272. ** The application must finalize every [prepared statement] in order to avoid
  4273. ** resource leaks. It is a grievous error for the application to try to use
  4274. ** a prepared statement after it has been finalized. Any use of a prepared
  4275. ** statement after it has been finalized can result in undefined and
  4276. ** undesirable behavior such as segfaults and heap corruption.
  4277. */
  4278. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
  4279. /*
  4280. ** CAPI3REF: Reset A Prepared Statement Object
  4281. ** METHOD: sqlite3_stmt
  4282. **
  4283. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4284. ** object back to its initial state, ready to be re-executed.
  4285. ** ^Any SQL statement variables that had values bound to them using
  4286. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4287. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4288. **
  4289. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4290. ** back to the beginning of its program.
  4291. **
  4292. ** ^If the most recent call to [sqlite3_step(S)] for the
  4293. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4294. ** or if [sqlite3_step(S)] has never before been called on S,
  4295. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4296. **
  4297. ** ^If the most recent call to [sqlite3_step(S)] for the
  4298. ** [prepared statement] S indicated an error, then
  4299. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4300. **
  4301. ** ^The [sqlite3_reset(S)] interface does not change the values
  4302. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4303. */
  4304. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
  4305. /*
  4306. ** CAPI3REF: Create Or Redefine SQL Functions
  4307. ** KEYWORDS: {function creation routines}
  4308. ** KEYWORDS: {application-defined SQL function}
  4309. ** KEYWORDS: {application-defined SQL functions}
  4310. ** METHOD: sqlite3
  4311. **
  4312. ** ^These functions (collectively known as "function creation routines")
  4313. ** are used to add SQL functions or aggregates or to redefine the behavior
  4314. ** of existing SQL functions or aggregates. The only differences between
  4315. ** these routines are the text encoding expected for
  4316. ** the second parameter (the name of the function being created)
  4317. ** and the presence or absence of a destructor callback for
  4318. ** the application data pointer.
  4319. **
  4320. ** ^The first parameter is the [database connection] to which the SQL
  4321. ** function is to be added. ^If an application uses more than one database
  4322. ** connection then application-defined SQL functions must be added
  4323. ** to each database connection separately.
  4324. **
  4325. ** ^The second parameter is the name of the SQL function to be created or
  4326. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4327. ** representation, exclusive of the zero-terminator. ^Note that the name
  4328. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4329. ** ^Any attempt to create a function with a longer name
  4330. ** will result in [SQLITE_MISUSE] being returned.
  4331. **
  4332. ** ^The third parameter (nArg)
  4333. ** is the number of arguments that the SQL function or
  4334. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4335. ** aggregate may take any number of arguments between 0 and the limit
  4336. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4337. ** parameter is less than -1 or greater than 127 then the behavior is
  4338. ** undefined.
  4339. **
  4340. ** ^The fourth parameter, eTextRep, specifies what
  4341. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4342. ** its parameters. The application should set this parameter to
  4343. ** [SQLITE_UTF16LE] if the function implementation invokes
  4344. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4345. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4346. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4347. ** otherwise. ^The same SQL function may be registered multiple times using
  4348. ** different preferred text encodings, with different implementations for
  4349. ** each encoding.
  4350. ** ^When multiple implementations of the same function are available, SQLite
  4351. ** will pick the one that involves the least amount of data conversion.
  4352. **
  4353. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4354. ** to signal that the function will always return the same result given
  4355. ** the same inputs within a single SQL statement. Most SQL functions are
  4356. ** deterministic. The built-in [random()] SQL function is an example of a
  4357. ** function that is not deterministic. The SQLite query planner is able to
  4358. ** perform additional optimizations on deterministic functions, so use
  4359. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4360. **
  4361. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4362. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4363. **
  4364. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4365. ** pointers to C-language functions that implement the SQL function or
  4366. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4367. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4368. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4369. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4370. ** SQL function or aggregate, pass NULL pointers for all three function
  4371. ** callbacks.
  4372. **
  4373. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4374. ** then it is destructor for the application data pointer.
  4375. ** The destructor is invoked when the function is deleted, either by being
  4376. ** overloaded or when the database connection closes.)^
  4377. ** ^The destructor is also invoked if the call to
  4378. ** sqlite3_create_function_v2() fails.
  4379. ** ^When the destructor callback of the tenth parameter is invoked, it
  4380. ** is passed a single argument which is a copy of the application data
  4381. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4382. **
  4383. ** ^It is permitted to register multiple implementations of the same
  4384. ** functions with the same name but with either differing numbers of
  4385. ** arguments or differing preferred text encodings. ^SQLite will use
  4386. ** the implementation that most closely matches the way in which the
  4387. ** SQL function is used. ^A function implementation with a non-negative
  4388. ** nArg parameter is a better match than a function implementation with
  4389. ** a negative nArg. ^A function where the preferred text encoding
  4390. ** matches the database encoding is a better
  4391. ** match than a function where the encoding is different.
  4392. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4393. ** is a closer match than a function where the encoding difference is
  4394. ** between UTF8 and UTF16.
  4395. **
  4396. ** ^Built-in functions may be overloaded by new application-defined functions.
  4397. **
  4398. ** ^An application-defined function is permitted to call other
  4399. ** SQLite interfaces. However, such calls must not
  4400. ** close the database connection nor finalize or reset the prepared
  4401. ** statement in which the function is running.
  4402. */
  4403. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  4404. sqlite3 *db,
  4405. const char *zFunctionName,
  4406. int nArg,
  4407. int eTextRep,
  4408. void *pApp,
  4409. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4410. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4411. void (*xFinal)(sqlite3_context*)
  4412. );
  4413. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  4414. sqlite3 *db,
  4415. const void *zFunctionName,
  4416. int nArg,
  4417. int eTextRep,
  4418. void *pApp,
  4419. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4420. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4421. void (*xFinal)(sqlite3_context*)
  4422. );
  4423. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  4424. sqlite3 *db,
  4425. const char *zFunctionName,
  4426. int nArg,
  4427. int eTextRep,
  4428. void *pApp,
  4429. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4430. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4431. void (*xFinal)(sqlite3_context*),
  4432. void(*xDestroy)(void*)
  4433. );
  4434. /*
  4435. ** CAPI3REF: Text Encodings
  4436. **
  4437. ** These constant define integer codes that represent the various
  4438. ** text encodings supported by SQLite.
  4439. */
  4440. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4441. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4442. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4443. #define SQLITE_UTF16 4 /* Use native byte order */
  4444. #define SQLITE_ANY 5 /* Deprecated */
  4445. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4446. /*
  4447. ** CAPI3REF: Function Flags
  4448. **
  4449. ** These constants may be ORed together with the
  4450. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4451. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4452. ** [sqlite3_create_function_v2()].
  4453. */
  4454. #define SQLITE_DETERMINISTIC 0x800
  4455. /*
  4456. ** CAPI3REF: Deprecated Functions
  4457. ** DEPRECATED
  4458. **
  4459. ** These functions are [deprecated]. In order to maintain
  4460. ** backwards compatibility with older code, these functions continue
  4461. ** to be supported. However, new applications should avoid
  4462. ** the use of these functions. To encourage programmers to avoid
  4463. ** these functions, we will not explain what they do.
  4464. */
  4465. #ifndef SQLITE_OMIT_DEPRECATED
  4466. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
  4467. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
  4468. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4469. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
  4470. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
  4471. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4472. void*,sqlite3_int64);
  4473. #endif
  4474. /*
  4475. ** CAPI3REF: Obtaining SQL Values
  4476. ** METHOD: sqlite3_value
  4477. **
  4478. ** The C-language implementation of SQL functions and aggregates uses
  4479. ** this set of interface routines to access the parameter values on
  4480. ** the function or aggregate.
  4481. **
  4482. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4483. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4484. ** define callbacks that implement the SQL functions and aggregates.
  4485. ** The 3rd parameter to these callbacks is an array of pointers to
  4486. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4487. ** each parameter to the SQL function. These routines are used to
  4488. ** extract values from the [sqlite3_value] objects.
  4489. **
  4490. ** These routines work only with [protected sqlite3_value] objects.
  4491. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4492. ** object results in undefined behavior.
  4493. **
  4494. ** ^These routines work just like the corresponding [column access functions]
  4495. ** except that these routines take a single [protected sqlite3_value] object
  4496. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4497. **
  4498. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4499. ** in the native byte-order of the host machine. ^The
  4500. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4501. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4502. **
  4503. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4504. ** numeric affinity to the value. This means that an attempt is
  4505. ** made to convert the value to an integer or floating point. If
  4506. ** such a conversion is possible without loss of information (in other
  4507. ** words, if the value is a string that looks like a number)
  4508. ** then the conversion is performed. Otherwise no conversion occurs.
  4509. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4510. **
  4511. ** Please pay particular attention to the fact that the pointer returned
  4512. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4513. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4514. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4515. ** or [sqlite3_value_text16()].
  4516. **
  4517. ** These routines must be called from the same thread as
  4518. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4519. */
  4520. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
  4521. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
  4522. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
  4523. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
  4524. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
  4525. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
  4526. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
  4527. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
  4528. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
  4529. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
  4530. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
  4531. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
  4532. /*
  4533. ** CAPI3REF: Finding The Subtype Of SQL Values
  4534. ** METHOD: sqlite3_value
  4535. **
  4536. ** The sqlite3_value_subtype(V) function returns the subtype for
  4537. ** an [application-defined SQL function] argument V. The subtype
  4538. ** information can be used to pass a limited amount of context from
  4539. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  4540. ** routine to set the subtype for the return value of an SQL function.
  4541. **
  4542. ** SQLite makes no use of subtype itself. It merely passes the subtype
  4543. ** from the result of one [application-defined SQL function] into the
  4544. ** input of another.
  4545. */
  4546. SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
  4547. /*
  4548. ** CAPI3REF: Copy And Free SQL Values
  4549. ** METHOD: sqlite3_value
  4550. **
  4551. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  4552. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  4553. ** is a [protected sqlite3_value] object even if the input is not.
  4554. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  4555. ** memory allocation fails.
  4556. **
  4557. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  4558. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  4559. ** then sqlite3_value_free(V) is a harmless no-op.
  4560. */
  4561. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
  4562. SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
  4563. /*
  4564. ** CAPI3REF: Obtain Aggregate Function Context
  4565. ** METHOD: sqlite3_context
  4566. **
  4567. ** Implementations of aggregate SQL functions use this
  4568. ** routine to allocate memory for storing their state.
  4569. **
  4570. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4571. ** for a particular aggregate function, SQLite
  4572. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4573. ** to the new memory. ^On second and subsequent calls to
  4574. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4575. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4576. ** called once for each invocation of the xStep callback and then one
  4577. ** last time when the xFinal callback is invoked. ^(When no rows match
  4578. ** an aggregate query, the xStep() callback of the aggregate function
  4579. ** implementation is never called and xFinal() is called exactly once.
  4580. ** In those cases, sqlite3_aggregate_context() might be called for the
  4581. ** first time from within xFinal().)^
  4582. **
  4583. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4584. ** when first called if N is less than or equal to zero or if a memory
  4585. ** allocate error occurs.
  4586. **
  4587. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4588. ** determined by the N parameter on first successful call. Changing the
  4589. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4590. ** the same aggregate function instance will not resize the memory
  4591. ** allocation.)^ Within the xFinal callback, it is customary to set
  4592. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4593. ** pointless memory allocations occur.
  4594. **
  4595. ** ^SQLite automatically frees the memory allocated by
  4596. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4597. **
  4598. ** The first parameter must be a copy of the
  4599. ** [sqlite3_context | SQL function context] that is the first parameter
  4600. ** to the xStep or xFinal callback routine that implements the aggregate
  4601. ** function.
  4602. **
  4603. ** This routine must be called from the same thread in which
  4604. ** the aggregate SQL function is running.
  4605. */
  4606. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4607. /*
  4608. ** CAPI3REF: User Data For Functions
  4609. ** METHOD: sqlite3_context
  4610. **
  4611. ** ^The sqlite3_user_data() interface returns a copy of
  4612. ** the pointer that was the pUserData parameter (the 5th parameter)
  4613. ** of the [sqlite3_create_function()]
  4614. ** and [sqlite3_create_function16()] routines that originally
  4615. ** registered the application defined function.
  4616. **
  4617. ** This routine must be called from the same thread in which
  4618. ** the application-defined function is running.
  4619. */
  4620. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
  4621. /*
  4622. ** CAPI3REF: Database Connection For Functions
  4623. ** METHOD: sqlite3_context
  4624. **
  4625. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4626. ** the pointer to the [database connection] (the 1st parameter)
  4627. ** of the [sqlite3_create_function()]
  4628. ** and [sqlite3_create_function16()] routines that originally
  4629. ** registered the application defined function.
  4630. */
  4631. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
  4632. /*
  4633. ** CAPI3REF: Function Auxiliary Data
  4634. ** METHOD: sqlite3_context
  4635. **
  4636. ** These functions may be used by (non-aggregate) SQL functions to
  4637. ** associate metadata with argument values. If the same value is passed to
  4638. ** multiple invocations of the same SQL function during query execution, under
  4639. ** some circumstances the associated metadata may be preserved. An example
  4640. ** of where this might be useful is in a regular-expression matching
  4641. ** function. The compiled version of the regular expression can be stored as
  4642. ** metadata associated with the pattern string.
  4643. ** Then as long as the pattern string remains the same,
  4644. ** the compiled regular expression can be reused on multiple
  4645. ** invocations of the same function.
  4646. **
  4647. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4648. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4649. ** value to the application-defined function. ^If there is no metadata
  4650. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4651. ** returns a NULL pointer.
  4652. **
  4653. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4654. ** argument of the application-defined function. ^Subsequent
  4655. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4656. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4657. ** NULL if the metadata has been discarded.
  4658. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4659. ** SQLite will invoke the destructor function X with parameter P exactly
  4660. ** once, when the metadata is discarded.
  4661. ** SQLite is free to discard the metadata at any time, including: <ul>
  4662. ** <li> when the corresponding function parameter changes, or
  4663. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4664. ** SQL statement, or
  4665. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4666. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4667. ** allocation error occurs. </ul>)^
  4668. **
  4669. ** Note the last bullet in particular. The destructor X in
  4670. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4671. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4672. ** should be called near the end of the function implementation and the
  4673. ** function implementation should not make any use of P after
  4674. ** sqlite3_set_auxdata() has been called.
  4675. **
  4676. ** ^(In practice, metadata is preserved between function calls for
  4677. ** function parameters that are compile-time constants, including literal
  4678. ** values and [parameters] and expressions composed from the same.)^
  4679. **
  4680. ** These routines must be called from the same thread in which
  4681. ** the SQL function is running.
  4682. */
  4683. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
  4684. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4685. /*
  4686. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4687. **
  4688. ** These are special values for the destructor that is passed in as the
  4689. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4690. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4691. ** and will never change. It does not need to be destroyed. ^The
  4692. ** SQLITE_TRANSIENT value means that the content will likely change in
  4693. ** the near future and that SQLite should make its own private copy of
  4694. ** the content before returning.
  4695. **
  4696. ** The typedef is necessary to work around problems in certain
  4697. ** C++ compilers.
  4698. */
  4699. typedef void (*sqlite3_destructor_type)(void*);
  4700. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4701. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4702. /*
  4703. ** CAPI3REF: Setting The Result Of An SQL Function
  4704. ** METHOD: sqlite3_context
  4705. **
  4706. ** These routines are used by the xFunc or xFinal callbacks that
  4707. ** implement SQL functions and aggregates. See
  4708. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4709. ** for additional information.
  4710. **
  4711. ** These functions work very much like the [parameter binding] family of
  4712. ** functions used to bind values to host parameters in prepared statements.
  4713. ** Refer to the [SQL parameter] documentation for additional information.
  4714. **
  4715. ** ^The sqlite3_result_blob() interface sets the result from
  4716. ** an application-defined function to be the BLOB whose content is pointed
  4717. ** to by the second parameter and which is N bytes long where N is the
  4718. ** third parameter.
  4719. **
  4720. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  4721. ** interfaces set the result of the application-defined function to be
  4722. ** a BLOB containing all zero bytes and N bytes in size.
  4723. **
  4724. ** ^The sqlite3_result_double() interface sets the result from
  4725. ** an application-defined function to be a floating point value specified
  4726. ** by its 2nd argument.
  4727. **
  4728. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4729. ** cause the implemented SQL function to throw an exception.
  4730. ** ^SQLite uses the string pointed to by the
  4731. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4732. ** as the text of an error message. ^SQLite interprets the error
  4733. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4734. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4735. ** byte order. ^If the third parameter to sqlite3_result_error()
  4736. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4737. ** message all text up through the first zero character.
  4738. ** ^If the third parameter to sqlite3_result_error() or
  4739. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4740. ** bytes (not characters) from the 2nd parameter as the error message.
  4741. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4742. ** routines make a private copy of the error message text before
  4743. ** they return. Hence, the calling function can deallocate or
  4744. ** modify the text after they return without harm.
  4745. ** ^The sqlite3_result_error_code() function changes the error code
  4746. ** returned by SQLite as a result of an error in a function. ^By default,
  4747. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4748. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4749. **
  4750. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4751. ** error indicating that a string or BLOB is too long to represent.
  4752. **
  4753. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4754. ** error indicating that a memory allocation failed.
  4755. **
  4756. ** ^The sqlite3_result_int() interface sets the return value
  4757. ** of the application-defined function to be the 32-bit signed integer
  4758. ** value given in the 2nd argument.
  4759. ** ^The sqlite3_result_int64() interface sets the return value
  4760. ** of the application-defined function to be the 64-bit signed integer
  4761. ** value given in the 2nd argument.
  4762. **
  4763. ** ^The sqlite3_result_null() interface sets the return value
  4764. ** of the application-defined function to be NULL.
  4765. **
  4766. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4767. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4768. ** set the return value of the application-defined function to be
  4769. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4770. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4771. ** ^The sqlite3_result_text64() interface sets the return value of an
  4772. ** application-defined function to be a text string in an encoding
  4773. ** specified by the fifth (and last) parameter, which must be one
  4774. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4775. ** ^SQLite takes the text result from the application from
  4776. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4777. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4778. ** is negative, then SQLite takes result text from the 2nd parameter
  4779. ** through the first zero character.
  4780. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4781. ** is non-negative, then as many bytes (not characters) of the text
  4782. ** pointed to by the 2nd parameter are taken as the application-defined
  4783. ** function result. If the 3rd parameter is non-negative, then it
  4784. ** must be the byte offset into the string where the NUL terminator would
  4785. ** appear if the string where NUL terminated. If any NUL characters occur
  4786. ** in the string at a byte offset that is less than the value of the 3rd
  4787. ** parameter, then the resulting string will contain embedded NULs and the
  4788. ** result of expressions operating on strings with embedded NULs is undefined.
  4789. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4790. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4791. ** function as the destructor on the text or BLOB result when it has
  4792. ** finished using that result.
  4793. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4794. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4795. ** assumes that the text or BLOB result is in constant space and does not
  4796. ** copy the content of the parameter nor call a destructor on the content
  4797. ** when it has finished using that result.
  4798. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4799. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4800. ** then SQLite makes a copy of the result into space obtained from
  4801. ** from [sqlite3_malloc()] before it returns.
  4802. **
  4803. ** ^The sqlite3_result_value() interface sets the result of
  4804. ** the application-defined function to be a copy of the
  4805. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4806. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4807. ** so that the [sqlite3_value] specified in the parameter may change or
  4808. ** be deallocated after sqlite3_result_value() returns without harm.
  4809. ** ^A [protected sqlite3_value] object may always be used where an
  4810. ** [unprotected sqlite3_value] object is required, so either
  4811. ** kind of [sqlite3_value] object can be used with this interface.
  4812. **
  4813. ** If these routines are called from within the different thread
  4814. ** than the one containing the application-defined function that received
  4815. ** the [sqlite3_context] pointer, the results are undefined.
  4816. */
  4817. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4818. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
  4819. sqlite3_uint64,void(*)(void*));
  4820. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
  4821. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
  4822. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
  4823. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
  4824. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
  4825. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
  4826. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
  4827. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4828. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
  4829. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4830. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4831. void(*)(void*), unsigned char encoding);
  4832. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4833. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4834. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4835. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4836. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
  4837. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  4838. /*
  4839. ** CAPI3REF: Setting The Subtype Of An SQL Function
  4840. ** METHOD: sqlite3_context
  4841. **
  4842. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  4843. ** the result from the [application-defined SQL function] with
  4844. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  4845. ** of the subtype T are preserved in current versions of SQLite;
  4846. ** higher order bits are discarded.
  4847. ** The number of subtype bytes preserved by SQLite might increase
  4848. ** in future releases of SQLite.
  4849. */
  4850. SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
  4851. /*
  4852. ** CAPI3REF: Define New Collating Sequences
  4853. ** METHOD: sqlite3
  4854. **
  4855. ** ^These functions add, remove, or modify a [collation] associated
  4856. ** with the [database connection] specified as the first argument.
  4857. **
  4858. ** ^The name of the collation is a UTF-8 string
  4859. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4860. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4861. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4862. ** considered to be the same name.
  4863. **
  4864. ** ^(The third argument (eTextRep) must be one of the constants:
  4865. ** <ul>
  4866. ** <li> [SQLITE_UTF8],
  4867. ** <li> [SQLITE_UTF16LE],
  4868. ** <li> [SQLITE_UTF16BE],
  4869. ** <li> [SQLITE_UTF16], or
  4870. ** <li> [SQLITE_UTF16_ALIGNED].
  4871. ** </ul>)^
  4872. ** ^The eTextRep argument determines the encoding of strings passed
  4873. ** to the collating function callback, xCallback.
  4874. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4875. ** force strings to be UTF16 with native byte order.
  4876. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4877. ** on an even byte address.
  4878. **
  4879. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4880. ** through as the first argument to the collating function callback.
  4881. **
  4882. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4883. ** ^Multiple collating functions can be registered using the same name but
  4884. ** with different eTextRep parameters and SQLite will use whichever
  4885. ** function requires the least amount of data transformation.
  4886. ** ^If the xCallback argument is NULL then the collating function is
  4887. ** deleted. ^When all collating functions having the same name are deleted,
  4888. ** that collation is no longer usable.
  4889. **
  4890. ** ^The collating function callback is invoked with a copy of the pArg
  4891. ** application data pointer and with two strings in the encoding specified
  4892. ** by the eTextRep argument. The collating function must return an
  4893. ** integer that is negative, zero, or positive
  4894. ** if the first string is less than, equal to, or greater than the second,
  4895. ** respectively. A collating function must always return the same answer
  4896. ** given the same inputs. If two or more collating functions are registered
  4897. ** to the same collation name (using different eTextRep values) then all
  4898. ** must give an equivalent answer when invoked with equivalent strings.
  4899. ** The collating function must obey the following properties for all
  4900. ** strings A, B, and C:
  4901. **
  4902. ** <ol>
  4903. ** <li> If A==B then B==A.
  4904. ** <li> If A==B and B==C then A==C.
  4905. ** <li> If A&lt;B THEN B&gt;A.
  4906. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4907. ** </ol>
  4908. **
  4909. ** If a collating function fails any of the above constraints and that
  4910. ** collating function is registered and used, then the behavior of SQLite
  4911. ** is undefined.
  4912. **
  4913. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4914. ** with the addition that the xDestroy callback is invoked on pArg when
  4915. ** the collating function is deleted.
  4916. ** ^Collating functions are deleted when they are overridden by later
  4917. ** calls to the collation creation functions or when the
  4918. ** [database connection] is closed using [sqlite3_close()].
  4919. **
  4920. ** ^The xDestroy callback is <u>not</u> called if the
  4921. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4922. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4923. ** check the return code and dispose of the application data pointer
  4924. ** themselves rather than expecting SQLite to deal with it for them.
  4925. ** This is different from every other SQLite interface. The inconsistency
  4926. ** is unfortunate but cannot be changed without breaking backwards
  4927. ** compatibility.
  4928. **
  4929. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4930. */
  4931. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  4932. sqlite3*,
  4933. const char *zName,
  4934. int eTextRep,
  4935. void *pArg,
  4936. int(*xCompare)(void*,int,const void*,int,const void*)
  4937. );
  4938. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  4939. sqlite3*,
  4940. const char *zName,
  4941. int eTextRep,
  4942. void *pArg,
  4943. int(*xCompare)(void*,int,const void*,int,const void*),
  4944. void(*xDestroy)(void*)
  4945. );
  4946. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  4947. sqlite3*,
  4948. const void *zName,
  4949. int eTextRep,
  4950. void *pArg,
  4951. int(*xCompare)(void*,int,const void*,int,const void*)
  4952. );
  4953. /*
  4954. ** CAPI3REF: Collation Needed Callbacks
  4955. ** METHOD: sqlite3
  4956. **
  4957. ** ^To avoid having to register all collation sequences before a database
  4958. ** can be used, a single callback function may be registered with the
  4959. ** [database connection] to be invoked whenever an undefined collation
  4960. ** sequence is required.
  4961. **
  4962. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4963. ** then it is passed the names of undefined collation sequences as strings
  4964. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4965. ** the names are passed as UTF-16 in machine native byte order.
  4966. ** ^A call to either function replaces the existing collation-needed callback.
  4967. **
  4968. ** ^(When the callback is invoked, the first argument passed is a copy
  4969. ** of the second argument to sqlite3_collation_needed() or
  4970. ** sqlite3_collation_needed16(). The second argument is the database
  4971. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4972. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4973. ** sequence function required. The fourth parameter is the name of the
  4974. ** required collation sequence.)^
  4975. **
  4976. ** The callback function should register the desired collation using
  4977. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4978. ** [sqlite3_create_collation_v2()].
  4979. */
  4980. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  4981. sqlite3*,
  4982. void*,
  4983. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4984. );
  4985. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  4986. sqlite3*,
  4987. void*,
  4988. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4989. );
  4990. #ifdef SQLITE_HAS_CODEC
  4991. /*
  4992. ** Specify the key for an encrypted database. This routine should be
  4993. ** called right after sqlite3_open().
  4994. **
  4995. ** The code to implement this API is not available in the public release
  4996. ** of SQLite.
  4997. */
  4998. SQLITE_API int SQLITE_STDCALL sqlite3_key(
  4999. sqlite3 *db, /* Database to be rekeyed */
  5000. const void *pKey, int nKey /* The key */
  5001. );
  5002. SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
  5003. sqlite3 *db, /* Database to be rekeyed */
  5004. const char *zDbName, /* Name of the database */
  5005. const void *pKey, int nKey /* The key */
  5006. );
  5007. /*
  5008. ** Change the key on an open database. If the current database is not
  5009. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  5010. ** database is decrypted.
  5011. **
  5012. ** The code to implement this API is not available in the public release
  5013. ** of SQLite.
  5014. */
  5015. SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
  5016. sqlite3 *db, /* Database to be rekeyed */
  5017. const void *pKey, int nKey /* The new key */
  5018. );
  5019. SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
  5020. sqlite3 *db, /* Database to be rekeyed */
  5021. const char *zDbName, /* Name of the database */
  5022. const void *pKey, int nKey /* The new key */
  5023. );
  5024. /*
  5025. ** Specify the activation key for a SEE database. Unless
  5026. ** activated, none of the SEE routines will work.
  5027. */
  5028. SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
  5029. const char *zPassPhrase /* Activation phrase */
  5030. );
  5031. #endif
  5032. #ifdef SQLITE_ENABLE_CEROD
  5033. /*
  5034. ** Specify the activation key for a CEROD database. Unless
  5035. ** activated, none of the CEROD routines will work.
  5036. */
  5037. SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
  5038. const char *zPassPhrase /* Activation phrase */
  5039. );
  5040. #endif
  5041. /*
  5042. ** CAPI3REF: Suspend Execution For A Short Time
  5043. **
  5044. ** The sqlite3_sleep() function causes the current thread to suspend execution
  5045. ** for at least a number of milliseconds specified in its parameter.
  5046. **
  5047. ** If the operating system does not support sleep requests with
  5048. ** millisecond time resolution, then the time will be rounded up to
  5049. ** the nearest second. The number of milliseconds of sleep actually
  5050. ** requested from the operating system is returned.
  5051. **
  5052. ** ^SQLite implements this interface by calling the xSleep()
  5053. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  5054. ** of the default VFS is not implemented correctly, or not implemented at
  5055. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  5056. ** in the previous paragraphs.
  5057. */
  5058. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
  5059. /*
  5060. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  5061. **
  5062. ** ^(If this global variable is made to point to a string which is
  5063. ** the name of a folder (a.k.a. directory), then all temporary files
  5064. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  5065. ** will be placed in that directory.)^ ^If this variable
  5066. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5067. ** temporary file directory.
  5068. **
  5069. ** Applications are strongly discouraged from using this global variable.
  5070. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  5071. ** But for all other platforms, it is highly recommended that applications
  5072. ** neither read nor write this variable. This global variable is a relic
  5073. ** that exists for backwards compatibility of legacy applications and should
  5074. ** be avoided in new projects.
  5075. **
  5076. ** It is not safe to read or modify this variable in more than one
  5077. ** thread at a time. It is not safe to read or modify this variable
  5078. ** if a [database connection] is being used at the same time in a separate
  5079. ** thread.
  5080. ** It is intended that this variable be set once
  5081. ** as part of process initialization and before any SQLite interface
  5082. ** routines have been called and that this variable remain unchanged
  5083. ** thereafter.
  5084. **
  5085. ** ^The [temp_store_directory pragma] may modify this variable and cause
  5086. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5087. ** the [temp_store_directory pragma] always assumes that any string
  5088. ** that this variable points to is held in memory obtained from
  5089. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5090. ** using [sqlite3_free].
  5091. ** Hence, if this variable is modified directly, either it should be
  5092. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5093. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5094. ** Except when requested by the [temp_store_directory pragma], SQLite
  5095. ** does not free the memory that sqlite3_temp_directory points to. If
  5096. ** the application wants that memory to be freed, it must do
  5097. ** so itself, taking care to only do so after all [database connection]
  5098. ** objects have been destroyed.
  5099. **
  5100. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5101. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5102. ** features that require the use of temporary files may fail. Here is an
  5103. ** example of how to do this using C++ with the Windows Runtime:
  5104. **
  5105. ** <blockquote><pre>
  5106. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5107. ** &nbsp; TemporaryFolder->Path->Data();
  5108. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5109. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5110. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5111. ** &nbsp; NULL, NULL);
  5112. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5113. ** </pre></blockquote>
  5114. */
  5115. SQLITE_API char *sqlite3_temp_directory;
  5116. /*
  5117. ** CAPI3REF: Name Of The Folder Holding Database Files
  5118. **
  5119. ** ^(If this global variable is made to point to a string which is
  5120. ** the name of a folder (a.k.a. directory), then all database files
  5121. ** specified with a relative pathname and created or accessed by
  5122. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5123. ** to be relative to that directory.)^ ^If this variable is a NULL
  5124. ** pointer, then SQLite assumes that all database files specified
  5125. ** with a relative pathname are relative to the current directory
  5126. ** for the process. Only the windows VFS makes use of this global
  5127. ** variable; it is ignored by the unix VFS.
  5128. **
  5129. ** Changing the value of this variable while a database connection is
  5130. ** open can result in a corrupt database.
  5131. **
  5132. ** It is not safe to read or modify this variable in more than one
  5133. ** thread at a time. It is not safe to read or modify this variable
  5134. ** if a [database connection] is being used at the same time in a separate
  5135. ** thread.
  5136. ** It is intended that this variable be set once
  5137. ** as part of process initialization and before any SQLite interface
  5138. ** routines have been called and that this variable remain unchanged
  5139. ** thereafter.
  5140. **
  5141. ** ^The [data_store_directory pragma] may modify this variable and cause
  5142. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5143. ** the [data_store_directory pragma] always assumes that any string
  5144. ** that this variable points to is held in memory obtained from
  5145. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5146. ** using [sqlite3_free].
  5147. ** Hence, if this variable is modified directly, either it should be
  5148. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5149. ** or else the use of the [data_store_directory pragma] should be avoided.
  5150. */
  5151. SQLITE_API char *sqlite3_data_directory;
  5152. /*
  5153. ** CAPI3REF: Test For Auto-Commit Mode
  5154. ** KEYWORDS: {autocommit mode}
  5155. ** METHOD: sqlite3
  5156. **
  5157. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5158. ** zero if the given database connection is or is not in autocommit mode,
  5159. ** respectively. ^Autocommit mode is on by default.
  5160. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5161. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5162. **
  5163. ** If certain kinds of errors occur on a statement within a multi-statement
  5164. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5165. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5166. ** transaction might be rolled back automatically. The only way to
  5167. ** find out whether SQLite automatically rolled back the transaction after
  5168. ** an error is to use this function.
  5169. **
  5170. ** If another thread changes the autocommit status of the database
  5171. ** connection while this routine is running, then the return value
  5172. ** is undefined.
  5173. */
  5174. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
  5175. /*
  5176. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5177. ** METHOD: sqlite3_stmt
  5178. **
  5179. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5180. ** to which a [prepared statement] belongs. ^The [database connection]
  5181. ** returned by sqlite3_db_handle is the same [database connection]
  5182. ** that was the first argument
  5183. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5184. ** create the statement in the first place.
  5185. */
  5186. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
  5187. /*
  5188. ** CAPI3REF: Return The Filename For A Database Connection
  5189. ** METHOD: sqlite3
  5190. **
  5191. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5192. ** associated with database N of connection D. ^The main database file
  5193. ** has the name "main". If there is no attached database N on the database
  5194. ** connection D, or if database N is a temporary or in-memory database, then
  5195. ** a NULL pointer is returned.
  5196. **
  5197. ** ^The filename returned by this function is the output of the
  5198. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5199. ** will be an absolute pathname, even if the filename used
  5200. ** to open the database originally was a URI or relative pathname.
  5201. */
  5202. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5203. /*
  5204. ** CAPI3REF: Determine if a database is read-only
  5205. ** METHOD: sqlite3
  5206. **
  5207. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5208. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5209. ** the name of a database on connection D.
  5210. */
  5211. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5212. /*
  5213. ** CAPI3REF: Find the next prepared statement
  5214. ** METHOD: sqlite3
  5215. **
  5216. ** ^This interface returns a pointer to the next [prepared statement] after
  5217. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5218. ** then this interface returns a pointer to the first prepared statement
  5219. ** associated with the database connection pDb. ^If no prepared statement
  5220. ** satisfies the conditions of this routine, it returns NULL.
  5221. **
  5222. ** The [database connection] pointer D in a call to
  5223. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5224. ** connection and in particular must not be a NULL pointer.
  5225. */
  5226. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5227. /*
  5228. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5229. ** METHOD: sqlite3
  5230. **
  5231. ** ^The sqlite3_commit_hook() interface registers a callback
  5232. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5233. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5234. ** for the same database connection is overridden.
  5235. ** ^The sqlite3_rollback_hook() interface registers a callback
  5236. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5237. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5238. ** for the same database connection is overridden.
  5239. ** ^The pArg argument is passed through to the callback.
  5240. ** ^If the callback on a commit hook function returns non-zero,
  5241. ** then the commit is converted into a rollback.
  5242. **
  5243. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5244. ** return the P argument from the previous call of the same function
  5245. ** on the same [database connection] D, or NULL for
  5246. ** the first call for each function on D.
  5247. **
  5248. ** The commit and rollback hook callbacks are not reentrant.
  5249. ** The callback implementation must not do anything that will modify
  5250. ** the database connection that invoked the callback. Any actions
  5251. ** to modify the database connection must be deferred until after the
  5252. ** completion of the [sqlite3_step()] call that triggered the commit
  5253. ** or rollback hook in the first place.
  5254. ** Note that running any other SQL statements, including SELECT statements,
  5255. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5256. ** the database connections for the meaning of "modify" in this paragraph.
  5257. **
  5258. ** ^Registering a NULL function disables the callback.
  5259. **
  5260. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5261. ** operation is allowed to continue normally. ^If the commit hook
  5262. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5263. ** ^The rollback hook is invoked on a rollback that results from a commit
  5264. ** hook returning non-zero, just as it would be with any other rollback.
  5265. **
  5266. ** ^For the purposes of this API, a transaction is said to have been
  5267. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5268. ** an error or constraint causes an implicit rollback to occur.
  5269. ** ^The rollback callback is not invoked if a transaction is
  5270. ** automatically rolled back because the database connection is closed.
  5271. **
  5272. ** See also the [sqlite3_update_hook()] interface.
  5273. */
  5274. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5275. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5276. /*
  5277. ** CAPI3REF: Data Change Notification Callbacks
  5278. ** METHOD: sqlite3
  5279. **
  5280. ** ^The sqlite3_update_hook() interface registers a callback function
  5281. ** with the [database connection] identified by the first argument
  5282. ** to be invoked whenever a row is updated, inserted or deleted in
  5283. ** a rowid table.
  5284. ** ^Any callback set by a previous call to this function
  5285. ** for the same database connection is overridden.
  5286. **
  5287. ** ^The second argument is a pointer to the function to invoke when a
  5288. ** row is updated, inserted or deleted in a rowid table.
  5289. ** ^The first argument to the callback is a copy of the third argument
  5290. ** to sqlite3_update_hook().
  5291. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5292. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5293. ** to be invoked.
  5294. ** ^The third and fourth arguments to the callback contain pointers to the
  5295. ** database and table name containing the affected row.
  5296. ** ^The final callback parameter is the [rowid] of the row.
  5297. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5298. **
  5299. ** ^(The update hook is not invoked when internal system tables are
  5300. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5301. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5302. **
  5303. ** ^In the current implementation, the update hook
  5304. ** is not invoked when duplication rows are deleted because of an
  5305. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5306. ** invoked when rows are deleted using the [truncate optimization].
  5307. ** The exceptions defined in this paragraph might change in a future
  5308. ** release of SQLite.
  5309. **
  5310. ** The update hook implementation must not do anything that will modify
  5311. ** the database connection that invoked the update hook. Any actions
  5312. ** to modify the database connection must be deferred until after the
  5313. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5314. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5315. ** database connections for the meaning of "modify" in this paragraph.
  5316. **
  5317. ** ^The sqlite3_update_hook(D,C,P) function
  5318. ** returns the P argument from the previous call
  5319. ** on the same [database connection] D, or NULL for
  5320. ** the first call on D.
  5321. **
  5322. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5323. ** interfaces.
  5324. */
  5325. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  5326. sqlite3*,
  5327. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5328. void*
  5329. );
  5330. /*
  5331. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5332. **
  5333. ** ^(This routine enables or disables the sharing of the database cache
  5334. ** and schema data structures between [database connection | connections]
  5335. ** to the same database. Sharing is enabled if the argument is true
  5336. ** and disabled if the argument is false.)^
  5337. **
  5338. ** ^Cache sharing is enabled and disabled for an entire process.
  5339. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5340. ** sharing was enabled or disabled for each thread separately.
  5341. **
  5342. ** ^(The cache sharing mode set by this interface effects all subsequent
  5343. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5344. ** Existing database connections continue use the sharing mode
  5345. ** that was in effect at the time they were opened.)^
  5346. **
  5347. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5348. ** successfully. An [error code] is returned otherwise.)^
  5349. **
  5350. ** ^Shared cache is disabled by default. But this might change in
  5351. ** future releases of SQLite. Applications that care about shared
  5352. ** cache setting should set it explicitly.
  5353. **
  5354. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5355. ** and will always return SQLITE_MISUSE. On those systems,
  5356. ** shared cache mode should be enabled per-database connection via
  5357. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5358. **
  5359. ** This interface is threadsafe on processors where writing a
  5360. ** 32-bit integer is atomic.
  5361. **
  5362. ** See Also: [SQLite Shared-Cache Mode]
  5363. */
  5364. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
  5365. /*
  5366. ** CAPI3REF: Attempt To Free Heap Memory
  5367. **
  5368. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5369. ** of heap memory by deallocating non-essential memory allocations
  5370. ** held by the database library. Memory used to cache database
  5371. ** pages to improve performance is an example of non-essential memory.
  5372. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5373. ** which might be more or less than the amount requested.
  5374. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5375. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5376. **
  5377. ** See also: [sqlite3_db_release_memory()]
  5378. */
  5379. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
  5380. /*
  5381. ** CAPI3REF: Free Memory Used By A Database Connection
  5382. ** METHOD: sqlite3
  5383. **
  5384. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5385. ** memory as possible from database connection D. Unlike the
  5386. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5387. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5388. ** omitted.
  5389. **
  5390. ** See also: [sqlite3_release_memory()]
  5391. */
  5392. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
  5393. /*
  5394. ** CAPI3REF: Impose A Limit On Heap Size
  5395. **
  5396. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5397. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5398. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5399. ** limit by reducing the number of pages held in the page cache
  5400. ** as heap memory usages approaches the limit.
  5401. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5402. ** below the limit, it will exceed the limit rather than generate
  5403. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5404. ** is advisory only.
  5405. **
  5406. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5407. ** the soft heap limit prior to the call, or negative in the case of an
  5408. ** error. ^If the argument N is negative
  5409. ** then no change is made to the soft heap limit. Hence, the current
  5410. ** size of the soft heap limit can be determined by invoking
  5411. ** sqlite3_soft_heap_limit64() with a negative argument.
  5412. **
  5413. ** ^If the argument N is zero then the soft heap limit is disabled.
  5414. **
  5415. ** ^(The soft heap limit is not enforced in the current implementation
  5416. ** if one or more of following conditions are true:
  5417. **
  5418. ** <ul>
  5419. ** <li> The soft heap limit is set to zero.
  5420. ** <li> Memory accounting is disabled using a combination of the
  5421. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5422. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5423. ** <li> An alternative page cache implementation is specified using
  5424. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5425. ** <li> The page cache allocates from its own memory pool supplied
  5426. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5427. ** from the heap.
  5428. ** </ul>)^
  5429. **
  5430. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5431. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5432. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5433. ** the soft heap limit is enforced on every memory allocation. Without
  5434. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5435. ** when memory is allocated by the page cache. Testing suggests that because
  5436. ** the page cache is the predominate memory user in SQLite, most
  5437. ** applications will achieve adequate soft heap limit enforcement without
  5438. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5439. **
  5440. ** The circumstances under which SQLite will enforce the soft heap limit may
  5441. ** changes in future releases of SQLite.
  5442. */
  5443. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5444. /*
  5445. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5446. ** DEPRECATED
  5447. **
  5448. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5449. ** interface. This routine is provided for historical compatibility
  5450. ** only. All new applications should use the
  5451. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5452. */
  5453. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
  5454. /*
  5455. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5456. ** METHOD: sqlite3
  5457. **
  5458. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5459. ** information about column C of table T in database D
  5460. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5461. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5462. ** the final five arguments with appropriate values if the specified
  5463. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5464. ** SQLITE_ERROR and if the specified column does not exist.
  5465. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5466. ** NULL pointer, then this routine simply checks for the existance of the
  5467. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5468. ** does not.
  5469. **
  5470. ** ^The column is identified by the second, third and fourth parameters to
  5471. ** this function. ^(The second parameter is either the name of the database
  5472. ** (i.e. "main", "temp", or an attached database) containing the specified
  5473. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5474. ** for the table using the same algorithm used by the database engine to
  5475. ** resolve unqualified table references.
  5476. **
  5477. ** ^The third and fourth parameters to this function are the table and column
  5478. ** name of the desired column, respectively.
  5479. **
  5480. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5481. ** and subsequent parameters to this function. ^Any of these arguments may be
  5482. ** NULL, in which case the corresponding element of metadata is omitted.
  5483. **
  5484. ** ^(<blockquote>
  5485. ** <table border="1">
  5486. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5487. **
  5488. ** <tr><td> 5th <td> const char* <td> Data type
  5489. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5490. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5491. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5492. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5493. ** </table>
  5494. ** </blockquote>)^
  5495. **
  5496. ** ^The memory pointed to by the character pointers returned for the
  5497. ** declaration type and collation sequence is valid until the next
  5498. ** call to any SQLite API function.
  5499. **
  5500. ** ^If the specified table is actually a view, an [error code] is returned.
  5501. **
  5502. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5503. ** is not a [WITHOUT ROWID] table and an
  5504. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5505. ** parameters are set for the explicitly declared column. ^(If there is no
  5506. ** [INTEGER PRIMARY KEY] column, then the outputs
  5507. ** for the [rowid] are set as follows:
  5508. **
  5509. ** <pre>
  5510. ** data type: "INTEGER"
  5511. ** collation sequence: "BINARY"
  5512. ** not null: 0
  5513. ** primary key: 1
  5514. ** auto increment: 0
  5515. ** </pre>)^
  5516. **
  5517. ** ^This function causes all database schemas to be read from disk and
  5518. ** parsed, if that has not already been done, and returns an error if
  5519. ** any errors are encountered while loading the schema.
  5520. */
  5521. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  5522. sqlite3 *db, /* Connection handle */
  5523. const char *zDbName, /* Database name or NULL */
  5524. const char *zTableName, /* Table name */
  5525. const char *zColumnName, /* Column name */
  5526. char const **pzDataType, /* OUTPUT: Declared data type */
  5527. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5528. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5529. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5530. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5531. );
  5532. /*
  5533. ** CAPI3REF: Load An Extension
  5534. ** METHOD: sqlite3
  5535. **
  5536. ** ^This interface loads an SQLite extension library from the named file.
  5537. **
  5538. ** ^The sqlite3_load_extension() interface attempts to load an
  5539. ** [SQLite extension] library contained in the file zFile. If
  5540. ** the file cannot be loaded directly, attempts are made to load
  5541. ** with various operating-system specific extensions added.
  5542. ** So for example, if "samplelib" cannot be loaded, then names like
  5543. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5544. ** be tried also.
  5545. **
  5546. ** ^The entry point is zProc.
  5547. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5548. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5549. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5550. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5551. ** characters in the filename from the last "/" to the first following
  5552. ** "." and omitting any initial "lib".)^
  5553. ** ^The sqlite3_load_extension() interface returns
  5554. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5555. ** ^If an error occurs and pzErrMsg is not 0, then the
  5556. ** [sqlite3_load_extension()] interface shall attempt to
  5557. ** fill *pzErrMsg with error message text stored in memory
  5558. ** obtained from [sqlite3_malloc()]. The calling function
  5559. ** should free this memory by calling [sqlite3_free()].
  5560. **
  5561. ** ^Extension loading must be enabled using
  5562. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5563. ** otherwise an error will be returned.
  5564. **
  5565. ** See also the [load_extension() SQL function].
  5566. */
  5567. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  5568. sqlite3 *db, /* Load the extension into this database connection */
  5569. const char *zFile, /* Name of the shared library containing extension */
  5570. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5571. char **pzErrMsg /* Put error message here if not 0 */
  5572. );
  5573. /*
  5574. ** CAPI3REF: Enable Or Disable Extension Loading
  5575. ** METHOD: sqlite3
  5576. **
  5577. ** ^So as not to open security holes in older applications that are
  5578. ** unprepared to deal with [extension loading], and as a means of disabling
  5579. ** [extension loading] while evaluating user-entered SQL, the following API
  5580. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5581. **
  5582. ** ^Extension loading is off by default.
  5583. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5584. ** to turn extension loading on and call it with onoff==0 to turn
  5585. ** it back off again.
  5586. */
  5587. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5588. /*
  5589. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5590. **
  5591. ** ^This interface causes the xEntryPoint() function to be invoked for
  5592. ** each new [database connection] that is created. The idea here is that
  5593. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5594. ** that is to be automatically loaded into all new database connections.
  5595. **
  5596. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5597. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5598. ** arguments and expects and integer result as if the signature of the
  5599. ** entry point where as follows:
  5600. **
  5601. ** <blockquote><pre>
  5602. ** &nbsp; int xEntryPoint(
  5603. ** &nbsp; sqlite3 *db,
  5604. ** &nbsp; const char **pzErrMsg,
  5605. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5606. ** &nbsp; );
  5607. ** </pre></blockquote>)^
  5608. **
  5609. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5610. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5611. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5612. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5613. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5614. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5615. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5616. **
  5617. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5618. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5619. ** will be called more than once for each database connection that is opened.
  5620. **
  5621. ** See also: [sqlite3_reset_auto_extension()]
  5622. ** and [sqlite3_cancel_auto_extension()]
  5623. */
  5624. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
  5625. /*
  5626. ** CAPI3REF: Cancel Automatic Extension Loading
  5627. **
  5628. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5629. ** initialization routine X that was registered using a prior call to
  5630. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5631. ** routine returns 1 if initialization routine X was successfully
  5632. ** unregistered and it returns 0 if X was not on the list of initialization
  5633. ** routines.
  5634. */
  5635. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5636. /*
  5637. ** CAPI3REF: Reset Automatic Extension Loading
  5638. **
  5639. ** ^This interface disables all automatic extensions previously
  5640. ** registered using [sqlite3_auto_extension()].
  5641. */
  5642. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
  5643. /*
  5644. ** The interface to the virtual-table mechanism is currently considered
  5645. ** to be experimental. The interface might change in incompatible ways.
  5646. ** If this is a problem for you, do not use the interface at this time.
  5647. **
  5648. ** When the virtual-table mechanism stabilizes, we will declare the
  5649. ** interface fixed, support it indefinitely, and remove this comment.
  5650. */
  5651. /*
  5652. ** Structures used by the virtual table interface
  5653. */
  5654. typedef struct sqlite3_vtab sqlite3_vtab;
  5655. typedef struct sqlite3_index_info sqlite3_index_info;
  5656. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5657. typedef struct sqlite3_module sqlite3_module;
  5658. /*
  5659. ** CAPI3REF: Virtual Table Object
  5660. ** KEYWORDS: sqlite3_module {virtual table module}
  5661. **
  5662. ** This structure, sometimes called a "virtual table module",
  5663. ** defines the implementation of a [virtual tables].
  5664. ** This structure consists mostly of methods for the module.
  5665. **
  5666. ** ^A virtual table module is created by filling in a persistent
  5667. ** instance of this structure and passing a pointer to that instance
  5668. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5669. ** ^The registration remains valid until it is replaced by a different
  5670. ** module or until the [database connection] closes. The content
  5671. ** of this structure must not change while it is registered with
  5672. ** any database connection.
  5673. */
  5674. struct sqlite3_module {
  5675. int iVersion;
  5676. int (*xCreate)(sqlite3*, void *pAux,
  5677. int argc, const char *const*argv,
  5678. sqlite3_vtab **ppVTab, char**);
  5679. int (*xConnect)(sqlite3*, void *pAux,
  5680. int argc, const char *const*argv,
  5681. sqlite3_vtab **ppVTab, char**);
  5682. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5683. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5684. int (*xDestroy)(sqlite3_vtab *pVTab);
  5685. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5686. int (*xClose)(sqlite3_vtab_cursor*);
  5687. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5688. int argc, sqlite3_value **argv);
  5689. int (*xNext)(sqlite3_vtab_cursor*);
  5690. int (*xEof)(sqlite3_vtab_cursor*);
  5691. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5692. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5693. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5694. int (*xBegin)(sqlite3_vtab *pVTab);
  5695. int (*xSync)(sqlite3_vtab *pVTab);
  5696. int (*xCommit)(sqlite3_vtab *pVTab);
  5697. int (*xRollback)(sqlite3_vtab *pVTab);
  5698. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5699. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5700. void **ppArg);
  5701. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5702. /* The methods above are in version 1 of the sqlite_module object. Those
  5703. ** below are for version 2 and greater. */
  5704. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5705. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5706. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5707. };
  5708. /*
  5709. ** CAPI3REF: Virtual Table Indexing Information
  5710. ** KEYWORDS: sqlite3_index_info
  5711. **
  5712. ** The sqlite3_index_info structure and its substructures is used as part
  5713. ** of the [virtual table] interface to
  5714. ** pass information into and receive the reply from the [xBestIndex]
  5715. ** method of a [virtual table module]. The fields under **Inputs** are the
  5716. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5717. ** results into the **Outputs** fields.
  5718. **
  5719. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5720. **
  5721. ** <blockquote>column OP expr</blockquote>
  5722. **
  5723. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5724. ** stored in aConstraint[].op using one of the
  5725. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5726. ** ^(The index of the column is stored in
  5727. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5728. ** expr on the right-hand side can be evaluated (and thus the constraint
  5729. ** is usable) and false if it cannot.)^
  5730. **
  5731. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5732. ** and makes other simplifications to the WHERE clause in an attempt to
  5733. ** get as many WHERE clause terms into the form shown above as possible.
  5734. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5735. ** relevant to the particular virtual table being queried.
  5736. **
  5737. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5738. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5739. **
  5740. ** The colUsed field indicates which columns of the virtual table may be
  5741. ** required by the current scan. Virtual table columns are numbered from
  5742. ** zero in the order in which they appear within the CREATE TABLE statement
  5743. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  5744. ** the corresponding bit is set within the colUsed mask if the column may be
  5745. ** required by SQLite. If the table has at least 64 columns and any column
  5746. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  5747. ** set. In other words, column iCol may be required if the expression
  5748. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  5749. ** non-zero.
  5750. **
  5751. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5752. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5753. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5754. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5755. ** is true, then the constraint is assumed to be fully handled by the
  5756. ** virtual table and is not checked again by SQLite.)^
  5757. **
  5758. ** ^The idxNum and idxPtr values are recorded and passed into the
  5759. ** [xFilter] method.
  5760. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5761. ** needToFreeIdxPtr is true.
  5762. **
  5763. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5764. ** the correct order to satisfy the ORDER BY clause so that no separate
  5765. ** sorting step is required.
  5766. **
  5767. ** ^The estimatedCost value is an estimate of the cost of a particular
  5768. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5769. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5770. ** indicates that the expense of the operation is similar to that of a
  5771. ** binary search on a unique indexed field of an SQLite table with N rows.
  5772. **
  5773. ** ^The estimatedRows value is an estimate of the number of rows that
  5774. ** will be returned by the strategy.
  5775. **
  5776. ** The xBestIndex method may optionally populate the idxFlags field with a
  5777. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  5778. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  5779. ** assumes that the strategy may visit at most one row.
  5780. **
  5781. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  5782. ** SQLite also assumes that if a call to the xUpdate() method is made as
  5783. ** part of the same statement to delete or update a virtual table row and the
  5784. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  5785. ** any database changes. In other words, if the xUpdate() returns
  5786. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  5787. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  5788. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  5789. ** the xUpdate method are automatically rolled back by SQLite.
  5790. **
  5791. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5792. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5793. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5794. ** to read or write the estimatedRows field are undefined (but are likely
  5795. ** to included crashing the application). The estimatedRows field should
  5796. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5797. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  5798. ** was added for version 3.9.0. It may therefore only be used if
  5799. ** sqlite3_libversion_number() returns a value greater than or equal to
  5800. ** 3009000.
  5801. */
  5802. struct sqlite3_index_info {
  5803. /* Inputs */
  5804. int nConstraint; /* Number of entries in aConstraint */
  5805. struct sqlite3_index_constraint {
  5806. int iColumn; /* Column constrained. -1 for ROWID */
  5807. unsigned char op; /* Constraint operator */
  5808. unsigned char usable; /* True if this constraint is usable */
  5809. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5810. } *aConstraint; /* Table of WHERE clause constraints */
  5811. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5812. struct sqlite3_index_orderby {
  5813. int iColumn; /* Column number */
  5814. unsigned char desc; /* True for DESC. False for ASC. */
  5815. } *aOrderBy; /* The ORDER BY clause */
  5816. /* Outputs */
  5817. struct sqlite3_index_constraint_usage {
  5818. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5819. unsigned char omit; /* Do not code a test for this constraint */
  5820. } *aConstraintUsage;
  5821. int idxNum; /* Number used to identify the index */
  5822. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5823. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5824. int orderByConsumed; /* True if output is already ordered */
  5825. double estimatedCost; /* Estimated cost of using this index */
  5826. /* Fields below are only available in SQLite 3.8.2 and later */
  5827. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5828. /* Fields below are only available in SQLite 3.9.0 and later */
  5829. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  5830. /* Fields below are only available in SQLite 3.10.0 and later */
  5831. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  5832. };
  5833. /*
  5834. ** CAPI3REF: Virtual Table Scan Flags
  5835. */
  5836. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  5837. /*
  5838. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5839. **
  5840. ** These macros defined the allowed values for the
  5841. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5842. ** an operator that is part of a constraint term in the wHERE clause of
  5843. ** a query that uses a [virtual table].
  5844. */
  5845. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5846. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5847. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5848. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5849. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5850. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5851. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  5852. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  5853. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  5854. /*
  5855. ** CAPI3REF: Register A Virtual Table Implementation
  5856. ** METHOD: sqlite3
  5857. **
  5858. ** ^These routines are used to register a new [virtual table module] name.
  5859. ** ^Module names must be registered before
  5860. ** creating a new [virtual table] using the module and before using a
  5861. ** preexisting [virtual table] for the module.
  5862. **
  5863. ** ^The module name is registered on the [database connection] specified
  5864. ** by the first parameter. ^The name of the module is given by the
  5865. ** second parameter. ^The third parameter is a pointer to
  5866. ** the implementation of the [virtual table module]. ^The fourth
  5867. ** parameter is an arbitrary client data pointer that is passed through
  5868. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5869. ** when a new virtual table is be being created or reinitialized.
  5870. **
  5871. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5872. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5873. ** invoke the destructor function (if it is not NULL) when SQLite
  5874. ** no longer needs the pClientData pointer. ^The destructor will also
  5875. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5876. ** ^The sqlite3_create_module()
  5877. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5878. ** destructor.
  5879. */
  5880. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  5881. sqlite3 *db, /* SQLite connection to register module with */
  5882. const char *zName, /* Name of the module */
  5883. const sqlite3_module *p, /* Methods for the module */
  5884. void *pClientData /* Client data for xCreate/xConnect */
  5885. );
  5886. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  5887. sqlite3 *db, /* SQLite connection to register module with */
  5888. const char *zName, /* Name of the module */
  5889. const sqlite3_module *p, /* Methods for the module */
  5890. void *pClientData, /* Client data for xCreate/xConnect */
  5891. void(*xDestroy)(void*) /* Module destructor function */
  5892. );
  5893. /*
  5894. ** CAPI3REF: Virtual Table Instance Object
  5895. ** KEYWORDS: sqlite3_vtab
  5896. **
  5897. ** Every [virtual table module] implementation uses a subclass
  5898. ** of this object to describe a particular instance
  5899. ** of the [virtual table]. Each subclass will
  5900. ** be tailored to the specific needs of the module implementation.
  5901. ** The purpose of this superclass is to define certain fields that are
  5902. ** common to all module implementations.
  5903. **
  5904. ** ^Virtual tables methods can set an error message by assigning a
  5905. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5906. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5907. ** prior to assigning a new string to zErrMsg. ^After the error message
  5908. ** is delivered up to the client application, the string will be automatically
  5909. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5910. */
  5911. struct sqlite3_vtab {
  5912. const sqlite3_module *pModule; /* The module for this virtual table */
  5913. int nRef; /* Number of open cursors */
  5914. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5915. /* Virtual table implementations will typically add additional fields */
  5916. };
  5917. /*
  5918. ** CAPI3REF: Virtual Table Cursor Object
  5919. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5920. **
  5921. ** Every [virtual table module] implementation uses a subclass of the
  5922. ** following structure to describe cursors that point into the
  5923. ** [virtual table] and are used
  5924. ** to loop through the virtual table. Cursors are created using the
  5925. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5926. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5927. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5928. ** of the module. Each module implementation will define
  5929. ** the content of a cursor structure to suit its own needs.
  5930. **
  5931. ** This superclass exists in order to define fields of the cursor that
  5932. ** are common to all implementations.
  5933. */
  5934. struct sqlite3_vtab_cursor {
  5935. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5936. /* Virtual table implementations will typically add additional fields */
  5937. };
  5938. /*
  5939. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5940. **
  5941. ** ^The [xCreate] and [xConnect] methods of a
  5942. ** [virtual table module] call this interface
  5943. ** to declare the format (the names and datatypes of the columns) of
  5944. ** the virtual tables they implement.
  5945. */
  5946. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5947. /*
  5948. ** CAPI3REF: Overload A Function For A Virtual Table
  5949. ** METHOD: sqlite3
  5950. **
  5951. ** ^(Virtual tables can provide alternative implementations of functions
  5952. ** using the [xFindFunction] method of the [virtual table module].
  5953. ** But global versions of those functions
  5954. ** must exist in order to be overloaded.)^
  5955. **
  5956. ** ^(This API makes sure a global version of a function with a particular
  5957. ** name and number of parameters exists. If no such function exists
  5958. ** before this API is called, a new function is created.)^ ^The implementation
  5959. ** of the new function always causes an exception to be thrown. So
  5960. ** the new function is not good for anything by itself. Its only
  5961. ** purpose is to be a placeholder function that can be overloaded
  5962. ** by a [virtual table].
  5963. */
  5964. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5965. /*
  5966. ** The interface to the virtual-table mechanism defined above (back up
  5967. ** to a comment remarkably similar to this one) is currently considered
  5968. ** to be experimental. The interface might change in incompatible ways.
  5969. ** If this is a problem for you, do not use the interface at this time.
  5970. **
  5971. ** When the virtual-table mechanism stabilizes, we will declare the
  5972. ** interface fixed, support it indefinitely, and remove this comment.
  5973. */
  5974. /*
  5975. ** CAPI3REF: A Handle To An Open BLOB
  5976. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5977. **
  5978. ** An instance of this object represents an open BLOB on which
  5979. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5980. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5981. ** and destroyed by [sqlite3_blob_close()].
  5982. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5983. ** can be used to read or write small subsections of the BLOB.
  5984. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5985. */
  5986. typedef struct sqlite3_blob sqlite3_blob;
  5987. /*
  5988. ** CAPI3REF: Open A BLOB For Incremental I/O
  5989. ** METHOD: sqlite3
  5990. ** CONSTRUCTOR: sqlite3_blob
  5991. **
  5992. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5993. ** in row iRow, column zColumn, table zTable in database zDb;
  5994. ** in other words, the same BLOB that would be selected by:
  5995. **
  5996. ** <pre>
  5997. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5998. ** </pre>)^
  5999. **
  6000. ** ^(Parameter zDb is not the filename that contains the database, but
  6001. ** rather the symbolic name of the database. For attached databases, this is
  6002. ** the name that appears after the AS keyword in the [ATTACH] statement.
  6003. ** For the main database file, the database name is "main". For TEMP
  6004. ** tables, the database name is "temp".)^
  6005. **
  6006. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  6007. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  6008. ** read-only access.
  6009. **
  6010. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  6011. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  6012. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  6013. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  6014. ** on *ppBlob after this function it returns.
  6015. **
  6016. ** This function fails with SQLITE_ERROR if any of the following are true:
  6017. ** <ul>
  6018. ** <li> ^(Database zDb does not exist)^,
  6019. ** <li> ^(Table zTable does not exist within database zDb)^,
  6020. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  6021. ** <li> ^(Column zColumn does not exist)^,
  6022. ** <li> ^(Row iRow is not present in the table)^,
  6023. ** <li> ^(The specified column of row iRow contains a value that is not
  6024. ** a TEXT or BLOB value)^,
  6025. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  6026. ** constraint and the blob is being opened for read/write access)^,
  6027. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  6028. ** column zColumn is part of a [child key] definition and the blob is
  6029. ** being opened for read/write access)^.
  6030. ** </ul>
  6031. **
  6032. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  6033. ** [database connection] error code and message accessible via
  6034. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6035. **
  6036. **
  6037. ** ^(If the row that a BLOB handle points to is modified by an
  6038. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  6039. ** then the BLOB handle is marked as "expired".
  6040. ** This is true if any column of the row is changed, even a column
  6041. ** other than the one the BLOB handle is open on.)^
  6042. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  6043. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  6044. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  6045. ** rolled back by the expiration of the BLOB. Such changes will eventually
  6046. ** commit if the transaction continues to completion.)^
  6047. **
  6048. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  6049. ** the opened blob. ^The size of a blob may not be changed by this
  6050. ** interface. Use the [UPDATE] SQL command to change the size of a
  6051. ** blob.
  6052. **
  6053. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  6054. ** and the built-in [zeroblob] SQL function may be used to create a
  6055. ** zero-filled blob to read or write using the incremental-blob interface.
  6056. **
  6057. ** To avoid a resource leak, every open [BLOB handle] should eventually
  6058. ** be released by a call to [sqlite3_blob_close()].
  6059. */
  6060. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  6061. sqlite3*,
  6062. const char *zDb,
  6063. const char *zTable,
  6064. const char *zColumn,
  6065. sqlite3_int64 iRow,
  6066. int flags,
  6067. sqlite3_blob **ppBlob
  6068. );
  6069. /*
  6070. ** CAPI3REF: Move a BLOB Handle to a New Row
  6071. ** METHOD: sqlite3_blob
  6072. **
  6073. ** ^This function is used to move an existing blob handle so that it points
  6074. ** to a different row of the same database table. ^The new row is identified
  6075. ** by the rowid value passed as the second argument. Only the row can be
  6076. ** changed. ^The database, table and column on which the blob handle is open
  6077. ** remain the same. Moving an existing blob handle to a new row can be
  6078. ** faster than closing the existing handle and opening a new one.
  6079. **
  6080. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  6081. ** it must exist and there must be either a blob or text value stored in
  6082. ** the nominated column.)^ ^If the new row is not present in the table, or if
  6083. ** it does not contain a blob or text value, or if another error occurs, an
  6084. ** SQLite error code is returned and the blob handle is considered aborted.
  6085. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  6086. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  6087. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  6088. ** always returns zero.
  6089. **
  6090. ** ^This function sets the database handle error code and message.
  6091. */
  6092. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  6093. /*
  6094. ** CAPI3REF: Close A BLOB Handle
  6095. ** DESTRUCTOR: sqlite3_blob
  6096. **
  6097. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  6098. ** unconditionally. Even if this routine returns an error code, the
  6099. ** handle is still closed.)^
  6100. **
  6101. ** ^If the blob handle being closed was opened for read-write access, and if
  6102. ** the database is in auto-commit mode and there are no other open read-write
  6103. ** blob handles or active write statements, the current transaction is
  6104. ** committed. ^If an error occurs while committing the transaction, an error
  6105. ** code is returned and the transaction rolled back.
  6106. **
  6107. ** Calling this function with an argument that is not a NULL pointer or an
  6108. ** open blob handle results in undefined behaviour. ^Calling this routine
  6109. ** with a null pointer (such as would be returned by a failed call to
  6110. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  6111. ** is passed a valid open blob handle, the values returned by the
  6112. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  6113. */
  6114. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
  6115. /*
  6116. ** CAPI3REF: Return The Size Of An Open BLOB
  6117. ** METHOD: sqlite3_blob
  6118. **
  6119. ** ^Returns the size in bytes of the BLOB accessible via the
  6120. ** successfully opened [BLOB handle] in its only argument. ^The
  6121. ** incremental blob I/O routines can only read or overwriting existing
  6122. ** blob content; they cannot change the size of a blob.
  6123. **
  6124. ** This routine only works on a [BLOB handle] which has been created
  6125. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6126. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6127. ** to this routine results in undefined and probably undesirable behavior.
  6128. */
  6129. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
  6130. /*
  6131. ** CAPI3REF: Read Data From A BLOB Incrementally
  6132. ** METHOD: sqlite3_blob
  6133. **
  6134. ** ^(This function is used to read data from an open [BLOB handle] into a
  6135. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6136. ** from the open BLOB, starting at offset iOffset.)^
  6137. **
  6138. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6139. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  6140. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6141. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  6142. ** can be determined using the [sqlite3_blob_bytes()] interface.
  6143. **
  6144. ** ^An attempt to read from an expired [BLOB handle] fails with an
  6145. ** error code of [SQLITE_ABORT].
  6146. **
  6147. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  6148. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6149. **
  6150. ** This routine only works on a [BLOB handle] which has been created
  6151. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6152. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6153. ** to this routine results in undefined and probably undesirable behavior.
  6154. **
  6155. ** See also: [sqlite3_blob_write()].
  6156. */
  6157. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6158. /*
  6159. ** CAPI3REF: Write Data Into A BLOB Incrementally
  6160. ** METHOD: sqlite3_blob
  6161. **
  6162. ** ^(This function is used to write data into an open [BLOB handle] from a
  6163. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6164. ** into the open BLOB, starting at offset iOffset.)^
  6165. **
  6166. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6167. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6168. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6169. ** [database connection] error code and message accessible via
  6170. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6171. **
  6172. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6173. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6174. ** this function returns [SQLITE_READONLY].
  6175. **
  6176. ** This function may only modify the contents of the BLOB; it is
  6177. ** not possible to increase the size of a BLOB using this API.
  6178. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6179. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6180. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6181. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6182. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6183. **
  6184. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6185. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6186. ** before the [BLOB handle] expired are not rolled back by the
  6187. ** expiration of the handle, though of course those changes might
  6188. ** have been overwritten by the statement that expired the BLOB handle
  6189. ** or by other independent statements.
  6190. **
  6191. ** This routine only works on a [BLOB handle] which has been created
  6192. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6193. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6194. ** to this routine results in undefined and probably undesirable behavior.
  6195. **
  6196. ** See also: [sqlite3_blob_read()].
  6197. */
  6198. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6199. /*
  6200. ** CAPI3REF: Virtual File System Objects
  6201. **
  6202. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6203. ** that SQLite uses to interact
  6204. ** with the underlying operating system. Most SQLite builds come with a
  6205. ** single default VFS that is appropriate for the host computer.
  6206. ** New VFSes can be registered and existing VFSes can be unregistered.
  6207. ** The following interfaces are provided.
  6208. **
  6209. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6210. ** ^Names are case sensitive.
  6211. ** ^Names are zero-terminated UTF-8 strings.
  6212. ** ^If there is no match, a NULL pointer is returned.
  6213. ** ^If zVfsName is NULL then the default VFS is returned.
  6214. **
  6215. ** ^New VFSes are registered with sqlite3_vfs_register().
  6216. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6217. ** ^The same VFS can be registered multiple times without injury.
  6218. ** ^To make an existing VFS into the default VFS, register it again
  6219. ** with the makeDflt flag set. If two different VFSes with the
  6220. ** same name are registered, the behavior is undefined. If a
  6221. ** VFS is registered with a name that is NULL or an empty string,
  6222. ** then the behavior is undefined.
  6223. **
  6224. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6225. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6226. ** the default. The choice for the new VFS is arbitrary.)^
  6227. */
  6228. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
  6229. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6230. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
  6231. /*
  6232. ** CAPI3REF: Mutexes
  6233. **
  6234. ** The SQLite core uses these routines for thread
  6235. ** synchronization. Though they are intended for internal
  6236. ** use by SQLite, code that links against SQLite is
  6237. ** permitted to use any of these routines.
  6238. **
  6239. ** The SQLite source code contains multiple implementations
  6240. ** of these mutex routines. An appropriate implementation
  6241. ** is selected automatically at compile-time. The following
  6242. ** implementations are available in the SQLite core:
  6243. **
  6244. ** <ul>
  6245. ** <li> SQLITE_MUTEX_PTHREADS
  6246. ** <li> SQLITE_MUTEX_W32
  6247. ** <li> SQLITE_MUTEX_NOOP
  6248. ** </ul>
  6249. **
  6250. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6251. ** that does no real locking and is appropriate for use in
  6252. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6253. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6254. ** and Windows.
  6255. **
  6256. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6257. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6258. ** implementation is included with the library. In this case the
  6259. ** application must supply a custom mutex implementation using the
  6260. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6261. ** before calling sqlite3_initialize() or any other public sqlite3_
  6262. ** function that calls sqlite3_initialize().
  6263. **
  6264. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6265. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6266. ** routine returns NULL if it is unable to allocate the requested
  6267. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6268. ** integer constants:
  6269. **
  6270. ** <ul>
  6271. ** <li> SQLITE_MUTEX_FAST
  6272. ** <li> SQLITE_MUTEX_RECURSIVE
  6273. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6274. ** <li> SQLITE_MUTEX_STATIC_MEM
  6275. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6276. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6277. ** <li> SQLITE_MUTEX_STATIC_LRU
  6278. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6279. ** <li> SQLITE_MUTEX_STATIC_APP1
  6280. ** <li> SQLITE_MUTEX_STATIC_APP2
  6281. ** <li> SQLITE_MUTEX_STATIC_APP3
  6282. ** <li> SQLITE_MUTEX_STATIC_VFS1
  6283. ** <li> SQLITE_MUTEX_STATIC_VFS2
  6284. ** <li> SQLITE_MUTEX_STATIC_VFS3
  6285. ** </ul>
  6286. **
  6287. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6288. ** cause sqlite3_mutex_alloc() to create
  6289. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6290. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6291. ** The mutex implementation does not need to make a distinction
  6292. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6293. ** not want to. SQLite will only request a recursive mutex in
  6294. ** cases where it really needs one. If a faster non-recursive mutex
  6295. ** implementation is available on the host platform, the mutex subsystem
  6296. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6297. **
  6298. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6299. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6300. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6301. ** used by the current version of SQLite. Future versions of SQLite
  6302. ** may add additional static mutexes. Static mutexes are for internal
  6303. ** use by SQLite only. Applications that use SQLite mutexes should
  6304. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6305. ** SQLITE_MUTEX_RECURSIVE.
  6306. **
  6307. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6308. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6309. ** returns a different mutex on every call. ^For the static
  6310. ** mutex types, the same mutex is returned on every call that has
  6311. ** the same type number.
  6312. **
  6313. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6314. ** allocated dynamic mutex. Attempting to deallocate a static
  6315. ** mutex results in undefined behavior.
  6316. **
  6317. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6318. ** to enter a mutex. ^If another thread is already within the mutex,
  6319. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6320. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6321. ** upon successful entry. ^(Mutexes created using
  6322. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6323. ** In such cases, the
  6324. ** mutex must be exited an equal number of times before another thread
  6325. ** can enter.)^ If the same thread tries to enter any mutex other
  6326. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6327. **
  6328. ** ^(Some systems (for example, Windows 95) do not support the operation
  6329. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6330. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6331. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6332. ** behavior.)^
  6333. **
  6334. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6335. ** previously entered by the same thread. The behavior
  6336. ** is undefined if the mutex is not currently entered by the
  6337. ** calling thread or is not currently allocated.
  6338. **
  6339. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6340. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6341. ** behave as no-ops.
  6342. **
  6343. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6344. */
  6345. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
  6346. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
  6347. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
  6348. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
  6349. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
  6350. /*
  6351. ** CAPI3REF: Mutex Methods Object
  6352. **
  6353. ** An instance of this structure defines the low-level routines
  6354. ** used to allocate and use mutexes.
  6355. **
  6356. ** Usually, the default mutex implementations provided by SQLite are
  6357. ** sufficient, however the application has the option of substituting a custom
  6358. ** implementation for specialized deployments or systems for which SQLite
  6359. ** does not provide a suitable implementation. In this case, the application
  6360. ** creates and populates an instance of this structure to pass
  6361. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6362. ** Additionally, an instance of this structure can be used as an
  6363. ** output variable when querying the system for the current mutex
  6364. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6365. **
  6366. ** ^The xMutexInit method defined by this structure is invoked as
  6367. ** part of system initialization by the sqlite3_initialize() function.
  6368. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6369. ** effective call to [sqlite3_initialize()].
  6370. **
  6371. ** ^The xMutexEnd method defined by this structure is invoked as
  6372. ** part of system shutdown by the sqlite3_shutdown() function. The
  6373. ** implementation of this method is expected to release all outstanding
  6374. ** resources obtained by the mutex methods implementation, especially
  6375. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6376. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6377. **
  6378. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6379. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6380. ** xMutexNotheld) implement the following interfaces (respectively):
  6381. **
  6382. ** <ul>
  6383. ** <li> [sqlite3_mutex_alloc()] </li>
  6384. ** <li> [sqlite3_mutex_free()] </li>
  6385. ** <li> [sqlite3_mutex_enter()] </li>
  6386. ** <li> [sqlite3_mutex_try()] </li>
  6387. ** <li> [sqlite3_mutex_leave()] </li>
  6388. ** <li> [sqlite3_mutex_held()] </li>
  6389. ** <li> [sqlite3_mutex_notheld()] </li>
  6390. ** </ul>)^
  6391. **
  6392. ** The only difference is that the public sqlite3_XXX functions enumerated
  6393. ** above silently ignore any invocations that pass a NULL pointer instead
  6394. ** of a valid mutex handle. The implementations of the methods defined
  6395. ** by this structure are not required to handle this case, the results
  6396. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6397. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6398. ** it is passed a NULL pointer).
  6399. **
  6400. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6401. ** invoke xMutexInit() multiple times within the same process and without
  6402. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6403. ** xMutexInit() must be no-ops.
  6404. **
  6405. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6406. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6407. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6408. ** memory allocation for a fast or recursive mutex.
  6409. **
  6410. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6411. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6412. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6413. ** prior to returning.
  6414. */
  6415. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6416. struct sqlite3_mutex_methods {
  6417. int (*xMutexInit)(void);
  6418. int (*xMutexEnd)(void);
  6419. sqlite3_mutex *(*xMutexAlloc)(int);
  6420. void (*xMutexFree)(sqlite3_mutex *);
  6421. void (*xMutexEnter)(sqlite3_mutex *);
  6422. int (*xMutexTry)(sqlite3_mutex *);
  6423. void (*xMutexLeave)(sqlite3_mutex *);
  6424. int (*xMutexHeld)(sqlite3_mutex *);
  6425. int (*xMutexNotheld)(sqlite3_mutex *);
  6426. };
  6427. /*
  6428. ** CAPI3REF: Mutex Verification Routines
  6429. **
  6430. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6431. ** are intended for use inside assert() statements. The SQLite core
  6432. ** never uses these routines except inside an assert() and applications
  6433. ** are advised to follow the lead of the core. The SQLite core only
  6434. ** provides implementations for these routines when it is compiled
  6435. ** with the SQLITE_DEBUG flag. External mutex implementations
  6436. ** are only required to provide these routines if SQLITE_DEBUG is
  6437. ** defined and if NDEBUG is not defined.
  6438. **
  6439. ** These routines should return true if the mutex in their argument
  6440. ** is held or not held, respectively, by the calling thread.
  6441. **
  6442. ** The implementation is not required to provide versions of these
  6443. ** routines that actually work. If the implementation does not provide working
  6444. ** versions of these routines, it should at least provide stubs that always
  6445. ** return true so that one does not get spurious assertion failures.
  6446. **
  6447. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6448. ** the routine should return 1. This seems counter-intuitive since
  6449. ** clearly the mutex cannot be held if it does not exist. But
  6450. ** the reason the mutex does not exist is because the build is not
  6451. ** using mutexes. And we do not want the assert() containing the
  6452. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6453. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6454. ** interface should also return 1 when given a NULL pointer.
  6455. */
  6456. #ifndef NDEBUG
  6457. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
  6458. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
  6459. #endif
  6460. /*
  6461. ** CAPI3REF: Mutex Types
  6462. **
  6463. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6464. ** which is one of these integer constants.
  6465. **
  6466. ** The set of static mutexes may change from one SQLite release to the
  6467. ** next. Applications that override the built-in mutex logic must be
  6468. ** prepared to accommodate additional static mutexes.
  6469. */
  6470. #define SQLITE_MUTEX_FAST 0
  6471. #define SQLITE_MUTEX_RECURSIVE 1
  6472. #define SQLITE_MUTEX_STATIC_MASTER 2
  6473. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6474. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6475. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6476. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6477. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6478. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6479. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6480. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6481. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6482. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6483. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  6484. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  6485. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  6486. /*
  6487. ** CAPI3REF: Retrieve the mutex for a database connection
  6488. ** METHOD: sqlite3
  6489. **
  6490. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6491. ** serializes access to the [database connection] given in the argument
  6492. ** when the [threading mode] is Serialized.
  6493. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6494. ** routine returns a NULL pointer.
  6495. */
  6496. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
  6497. /*
  6498. ** CAPI3REF: Low-Level Control Of Database Files
  6499. ** METHOD: sqlite3
  6500. **
  6501. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6502. ** xFileControl method for the [sqlite3_io_methods] object associated
  6503. ** with a particular database identified by the second argument. ^The
  6504. ** name of the database is "main" for the main database or "temp" for the
  6505. ** TEMP database, or the name that appears after the AS keyword for
  6506. ** databases that are added using the [ATTACH] SQL command.
  6507. ** ^A NULL pointer can be used in place of "main" to refer to the
  6508. ** main database file.
  6509. ** ^The third and fourth parameters to this routine
  6510. ** are passed directly through to the second and third parameters of
  6511. ** the xFileControl method. ^The return value of the xFileControl
  6512. ** method becomes the return value of this routine.
  6513. **
  6514. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6515. ** a pointer to the underlying [sqlite3_file] object to be written into
  6516. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6517. ** case is a short-circuit path which does not actually invoke the
  6518. ** underlying sqlite3_io_methods.xFileControl method.
  6519. **
  6520. ** ^If the second parameter (zDbName) does not match the name of any
  6521. ** open database file, then SQLITE_ERROR is returned. ^This error
  6522. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6523. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6524. ** also return SQLITE_ERROR. There is no way to distinguish between
  6525. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6526. ** xFileControl method.
  6527. **
  6528. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6529. */
  6530. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6531. /*
  6532. ** CAPI3REF: Testing Interface
  6533. **
  6534. ** ^The sqlite3_test_control() interface is used to read out internal
  6535. ** state of SQLite and to inject faults into SQLite for testing
  6536. ** purposes. ^The first parameter is an operation code that determines
  6537. ** the number, meaning, and operation of all subsequent parameters.
  6538. **
  6539. ** This interface is not for use by applications. It exists solely
  6540. ** for verifying the correct operation of the SQLite library. Depending
  6541. ** on how the SQLite library is compiled, this interface might not exist.
  6542. **
  6543. ** The details of the operation codes, their meanings, the parameters
  6544. ** they take, and what they do are all subject to change without notice.
  6545. ** Unlike most of the SQLite API, this function is not guaranteed to
  6546. ** operate consistently from one release to the next.
  6547. */
  6548. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
  6549. /*
  6550. ** CAPI3REF: Testing Interface Operation Codes
  6551. **
  6552. ** These constants are the valid operation code parameters used
  6553. ** as the first argument to [sqlite3_test_control()].
  6554. **
  6555. ** These parameters and their meanings are subject to change
  6556. ** without notice. These values are for testing purposes only.
  6557. ** Applications should not use any of these parameters or the
  6558. ** [sqlite3_test_control()] interface.
  6559. */
  6560. #define SQLITE_TESTCTRL_FIRST 5
  6561. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6562. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6563. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6564. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6565. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6566. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6567. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6568. #define SQLITE_TESTCTRL_ASSERT 12
  6569. #define SQLITE_TESTCTRL_ALWAYS 13
  6570. #define SQLITE_TESTCTRL_RESERVE 14
  6571. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6572. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6573. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6574. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6575. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6576. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6577. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6578. #define SQLITE_TESTCTRL_BYTEORDER 22
  6579. #define SQLITE_TESTCTRL_ISINIT 23
  6580. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6581. #define SQLITE_TESTCTRL_IMPOSTER 25
  6582. #define SQLITE_TESTCTRL_LAST 25
  6583. /*
  6584. ** CAPI3REF: SQLite Runtime Status
  6585. **
  6586. ** ^These interfaces are used to retrieve runtime status information
  6587. ** about the performance of SQLite, and optionally to reset various
  6588. ** highwater marks. ^The first argument is an integer code for
  6589. ** the specific parameter to measure. ^(Recognized integer codes
  6590. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6591. ** ^The current value of the parameter is returned into *pCurrent.
  6592. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6593. ** resetFlag is true, then the highest record value is reset after
  6594. ** *pHighwater is written. ^(Some parameters do not record the highest
  6595. ** value. For those parameters
  6596. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6597. ** ^(Other parameters record only the highwater mark and not the current
  6598. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6599. **
  6600. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6601. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6602. **
  6603. ** If either the current value or the highwater mark is too large to
  6604. ** be represented by a 32-bit integer, then the values returned by
  6605. ** sqlite3_status() are undefined.
  6606. **
  6607. ** See also: [sqlite3_db_status()]
  6608. */
  6609. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6610. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  6611. int op,
  6612. sqlite3_int64 *pCurrent,
  6613. sqlite3_int64 *pHighwater,
  6614. int resetFlag
  6615. );
  6616. /*
  6617. ** CAPI3REF: Status Parameters
  6618. ** KEYWORDS: {status parameters}
  6619. **
  6620. ** These integer constants designate various run-time status parameters
  6621. ** that can be returned by [sqlite3_status()].
  6622. **
  6623. ** <dl>
  6624. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6625. ** <dd>This parameter is the current amount of memory checked out
  6626. ** using [sqlite3_malloc()], either directly or indirectly. The
  6627. ** figure includes calls made to [sqlite3_malloc()] by the application
  6628. ** and internal memory usage by the SQLite library. Scratch memory
  6629. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6630. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6631. ** this parameter. The amount returned is the sum of the allocation
  6632. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6633. **
  6634. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6635. ** <dd>This parameter records the largest memory allocation request
  6636. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6637. ** internal equivalents). Only the value returned in the
  6638. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6639. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6640. **
  6641. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6642. ** <dd>This parameter records the number of separate memory allocations
  6643. ** currently checked out.</dd>)^
  6644. **
  6645. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6646. ** <dd>This parameter returns the number of pages used out of the
  6647. ** [pagecache memory allocator] that was configured using
  6648. ** [SQLITE_CONFIG_PAGECACHE]. The
  6649. ** value returned is in pages, not in bytes.</dd>)^
  6650. **
  6651. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6652. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6653. ** <dd>This parameter returns the number of bytes of page cache
  6654. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6655. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6656. ** returned value includes allocations that overflowed because they
  6657. ** where too large (they were larger than the "sz" parameter to
  6658. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6659. ** no space was left in the page cache.</dd>)^
  6660. **
  6661. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6662. ** <dd>This parameter records the largest memory allocation request
  6663. ** handed to [pagecache memory allocator]. Only the value returned in the
  6664. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6665. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6666. **
  6667. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6668. ** <dd>This parameter returns the number of allocations used out of the
  6669. ** [scratch memory allocator] configured using
  6670. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6671. ** in bytes. Since a single thread may only have one scratch allocation
  6672. ** outstanding at time, this parameter also reports the number of threads
  6673. ** using scratch memory at the same time.</dd>)^
  6674. **
  6675. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6676. ** <dd>This parameter returns the number of bytes of scratch memory
  6677. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6678. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6679. ** returned include overflows because the requested allocation was too
  6680. ** larger (that is, because the requested allocation was larger than the
  6681. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6682. ** slots were available.
  6683. ** </dd>)^
  6684. **
  6685. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6686. ** <dd>This parameter records the largest memory allocation request
  6687. ** handed to [scratch memory allocator]. Only the value returned in the
  6688. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6689. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6690. **
  6691. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6692. ** <dd>The *pHighwater parameter records the deepest parser stack.
  6693. ** The *pCurrent value is undefined. The *pHighwater value is only
  6694. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6695. ** </dl>
  6696. **
  6697. ** New status parameters may be added from time to time.
  6698. */
  6699. #define SQLITE_STATUS_MEMORY_USED 0
  6700. #define SQLITE_STATUS_PAGECACHE_USED 1
  6701. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6702. #define SQLITE_STATUS_SCRATCH_USED 3
  6703. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6704. #define SQLITE_STATUS_MALLOC_SIZE 5
  6705. #define SQLITE_STATUS_PARSER_STACK 6
  6706. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6707. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6708. #define SQLITE_STATUS_MALLOC_COUNT 9
  6709. /*
  6710. ** CAPI3REF: Database Connection Status
  6711. ** METHOD: sqlite3
  6712. **
  6713. ** ^This interface is used to retrieve runtime status information
  6714. ** about a single [database connection]. ^The first argument is the
  6715. ** database connection object to be interrogated. ^The second argument
  6716. ** is an integer constant, taken from the set of
  6717. ** [SQLITE_DBSTATUS options], that
  6718. ** determines the parameter to interrogate. The set of
  6719. ** [SQLITE_DBSTATUS options] is likely
  6720. ** to grow in future releases of SQLite.
  6721. **
  6722. ** ^The current value of the requested parameter is written into *pCur
  6723. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6724. ** the resetFlg is true, then the highest instantaneous value is
  6725. ** reset back down to the current value.
  6726. **
  6727. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6728. ** non-zero [error code] on failure.
  6729. **
  6730. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6731. */
  6732. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6733. /*
  6734. ** CAPI3REF: Status Parameters for database connections
  6735. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6736. **
  6737. ** These constants are the available integer "verbs" that can be passed as
  6738. ** the second argument to the [sqlite3_db_status()] interface.
  6739. **
  6740. ** New verbs may be added in future releases of SQLite. Existing verbs
  6741. ** might be discontinued. Applications should check the return code from
  6742. ** [sqlite3_db_status()] to make sure that the call worked.
  6743. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6744. ** if a discontinued or unsupported verb is invoked.
  6745. **
  6746. ** <dl>
  6747. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6748. ** <dd>This parameter returns the number of lookaside memory slots currently
  6749. ** checked out.</dd>)^
  6750. **
  6751. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6752. ** <dd>This parameter returns the number malloc attempts that were
  6753. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6754. ** the current value is always zero.)^
  6755. **
  6756. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6757. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6758. ** <dd>This parameter returns the number malloc attempts that might have
  6759. ** been satisfied using lookaside memory but failed due to the amount of
  6760. ** memory requested being larger than the lookaside slot size.
  6761. ** Only the high-water value is meaningful;
  6762. ** the current value is always zero.)^
  6763. **
  6764. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6765. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6766. ** <dd>This parameter returns the number malloc attempts that might have
  6767. ** been satisfied using lookaside memory but failed due to all lookaside
  6768. ** memory already being in use.
  6769. ** Only the high-water value is meaningful;
  6770. ** the current value is always zero.)^
  6771. **
  6772. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6773. ** <dd>This parameter returns the approximate number of bytes of heap
  6774. ** memory used by all pager caches associated with the database connection.)^
  6775. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6776. **
  6777. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6778. ** <dd>This parameter returns the approximate number of bytes of heap
  6779. ** memory used to store the schema for all databases associated
  6780. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6781. ** ^The full amount of memory used by the schemas is reported, even if the
  6782. ** schema memory is shared with other database connections due to
  6783. ** [shared cache mode] being enabled.
  6784. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6785. **
  6786. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6787. ** <dd>This parameter returns the approximate number of bytes of heap
  6788. ** and lookaside memory used by all prepared statements associated with
  6789. ** the database connection.)^
  6790. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6791. ** </dd>
  6792. **
  6793. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6794. ** <dd>This parameter returns the number of pager cache hits that have
  6795. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6796. ** is always 0.
  6797. ** </dd>
  6798. **
  6799. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6800. ** <dd>This parameter returns the number of pager cache misses that have
  6801. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6802. ** is always 0.
  6803. ** </dd>
  6804. **
  6805. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6806. ** <dd>This parameter returns the number of dirty cache entries that have
  6807. ** been written to disk. Specifically, the number of pages written to the
  6808. ** wal file in wal mode databases, or the number of pages written to the
  6809. ** database file in rollback mode databases. Any pages written as part of
  6810. ** transaction rollback or database recovery operations are not included.
  6811. ** If an IO or other error occurs while writing a page to disk, the effect
  6812. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6813. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6814. ** </dd>
  6815. **
  6816. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6817. ** <dd>This parameter returns zero for the current value if and only if
  6818. ** all foreign key constraints (deferred or immediate) have been
  6819. ** resolved.)^ ^The highwater mark is always 0.
  6820. ** </dd>
  6821. ** </dl>
  6822. */
  6823. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6824. #define SQLITE_DBSTATUS_CACHE_USED 1
  6825. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6826. #define SQLITE_DBSTATUS_STMT_USED 3
  6827. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6828. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6829. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6830. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6831. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6832. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6833. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6834. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6835. /*
  6836. ** CAPI3REF: Prepared Statement Status
  6837. ** METHOD: sqlite3_stmt
  6838. **
  6839. ** ^(Each prepared statement maintains various
  6840. ** [SQLITE_STMTSTATUS counters] that measure the number
  6841. ** of times it has performed specific operations.)^ These counters can
  6842. ** be used to monitor the performance characteristics of the prepared
  6843. ** statements. For example, if the number of table steps greatly exceeds
  6844. ** the number of table searches or result rows, that would tend to indicate
  6845. ** that the prepared statement is using a full table scan rather than
  6846. ** an index.
  6847. **
  6848. ** ^(This interface is used to retrieve and reset counter values from
  6849. ** a [prepared statement]. The first argument is the prepared statement
  6850. ** object to be interrogated. The second argument
  6851. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6852. ** to be interrogated.)^
  6853. ** ^The current value of the requested counter is returned.
  6854. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6855. ** interface call returns.
  6856. **
  6857. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6858. */
  6859. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6860. /*
  6861. ** CAPI3REF: Status Parameters for prepared statements
  6862. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6863. **
  6864. ** These preprocessor macros define integer codes that name counter
  6865. ** values associated with the [sqlite3_stmt_status()] interface.
  6866. ** The meanings of the various counters are as follows:
  6867. **
  6868. ** <dl>
  6869. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6870. ** <dd>^This is the number of times that SQLite has stepped forward in
  6871. ** a table as part of a full table scan. Large numbers for this counter
  6872. ** may indicate opportunities for performance improvement through
  6873. ** careful use of indices.</dd>
  6874. **
  6875. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6876. ** <dd>^This is the number of sort operations that have occurred.
  6877. ** A non-zero value in this counter may indicate an opportunity to
  6878. ** improvement performance through careful use of indices.</dd>
  6879. **
  6880. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6881. ** <dd>^This is the number of rows inserted into transient indices that
  6882. ** were created automatically in order to help joins run faster.
  6883. ** A non-zero value in this counter may indicate an opportunity to
  6884. ** improvement performance by adding permanent indices that do not
  6885. ** need to be reinitialized each time the statement is run.</dd>
  6886. **
  6887. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6888. ** <dd>^This is the number of virtual machine operations executed
  6889. ** by the prepared statement if that number is less than or equal
  6890. ** to 2147483647. The number of virtual machine operations can be
  6891. ** used as a proxy for the total work done by the prepared statement.
  6892. ** If the number of virtual machine operations exceeds 2147483647
  6893. ** then the value returned by this statement status code is undefined.
  6894. ** </dd>
  6895. ** </dl>
  6896. */
  6897. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6898. #define SQLITE_STMTSTATUS_SORT 2
  6899. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6900. #define SQLITE_STMTSTATUS_VM_STEP 4
  6901. /*
  6902. ** CAPI3REF: Custom Page Cache Object
  6903. **
  6904. ** The sqlite3_pcache type is opaque. It is implemented by
  6905. ** the pluggable module. The SQLite core has no knowledge of
  6906. ** its size or internal structure and never deals with the
  6907. ** sqlite3_pcache object except by holding and passing pointers
  6908. ** to the object.
  6909. **
  6910. ** See [sqlite3_pcache_methods2] for additional information.
  6911. */
  6912. typedef struct sqlite3_pcache sqlite3_pcache;
  6913. /*
  6914. ** CAPI3REF: Custom Page Cache Object
  6915. **
  6916. ** The sqlite3_pcache_page object represents a single page in the
  6917. ** page cache. The page cache will allocate instances of this
  6918. ** object. Various methods of the page cache use pointers to instances
  6919. ** of this object as parameters or as their return value.
  6920. **
  6921. ** See [sqlite3_pcache_methods2] for additional information.
  6922. */
  6923. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6924. struct sqlite3_pcache_page {
  6925. void *pBuf; /* The content of the page */
  6926. void *pExtra; /* Extra information associated with the page */
  6927. };
  6928. /*
  6929. ** CAPI3REF: Application Defined Page Cache.
  6930. ** KEYWORDS: {page cache}
  6931. **
  6932. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6933. ** register an alternative page cache implementation by passing in an
  6934. ** instance of the sqlite3_pcache_methods2 structure.)^
  6935. ** In many applications, most of the heap memory allocated by
  6936. ** SQLite is used for the page cache.
  6937. ** By implementing a
  6938. ** custom page cache using this API, an application can better control
  6939. ** the amount of memory consumed by SQLite, the way in which
  6940. ** that memory is allocated and released, and the policies used to
  6941. ** determine exactly which parts of a database file are cached and for
  6942. ** how long.
  6943. **
  6944. ** The alternative page cache mechanism is an
  6945. ** extreme measure that is only needed by the most demanding applications.
  6946. ** The built-in page cache is recommended for most uses.
  6947. **
  6948. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6949. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6950. ** the application may discard the parameter after the call to
  6951. ** [sqlite3_config()] returns.)^
  6952. **
  6953. ** [[the xInit() page cache method]]
  6954. ** ^(The xInit() method is called once for each effective
  6955. ** call to [sqlite3_initialize()])^
  6956. ** (usually only once during the lifetime of the process). ^(The xInit()
  6957. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6958. ** The intent of the xInit() method is to set up global data structures
  6959. ** required by the custom page cache implementation.
  6960. ** ^(If the xInit() method is NULL, then the
  6961. ** built-in default page cache is used instead of the application defined
  6962. ** page cache.)^
  6963. **
  6964. ** [[the xShutdown() page cache method]]
  6965. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6966. ** It can be used to clean up
  6967. ** any outstanding resources before process shutdown, if required.
  6968. ** ^The xShutdown() method may be NULL.
  6969. **
  6970. ** ^SQLite automatically serializes calls to the xInit method,
  6971. ** so the xInit method need not be threadsafe. ^The
  6972. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6973. ** not need to be threadsafe either. All other methods must be threadsafe
  6974. ** in multithreaded applications.
  6975. **
  6976. ** ^SQLite will never invoke xInit() more than once without an intervening
  6977. ** call to xShutdown().
  6978. **
  6979. ** [[the xCreate() page cache methods]]
  6980. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6981. ** SQLite will typically create one cache instance for each open database file,
  6982. ** though this is not guaranteed. ^The
  6983. ** first parameter, szPage, is the size in bytes of the pages that must
  6984. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6985. ** second parameter szExtra is a number of bytes of extra storage
  6986. ** associated with each page cache entry. ^The szExtra parameter will
  6987. ** a number less than 250. SQLite will use the
  6988. ** extra szExtra bytes on each page to store metadata about the underlying
  6989. ** database page on disk. The value passed into szExtra depends
  6990. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6991. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6992. ** created will be used to cache database pages of a file stored on disk, or
  6993. ** false if it is used for an in-memory database. The cache implementation
  6994. ** does not have to do anything special based with the value of bPurgeable;
  6995. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6996. ** never invoke xUnpin() except to deliberately delete a page.
  6997. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6998. ** false will always have the "discard" flag set to true.
  6999. ** ^Hence, a cache created with bPurgeable false will
  7000. ** never contain any unpinned pages.
  7001. **
  7002. ** [[the xCachesize() page cache method]]
  7003. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  7004. ** suggested maximum cache-size (number of pages stored by) the cache
  7005. ** instance passed as the first argument. This is the value configured using
  7006. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  7007. ** parameter, the implementation is not required to do anything with this
  7008. ** value; it is advisory only.
  7009. **
  7010. ** [[the xPagecount() page cache methods]]
  7011. ** The xPagecount() method must return the number of pages currently
  7012. ** stored in the cache, both pinned and unpinned.
  7013. **
  7014. ** [[the xFetch() page cache methods]]
  7015. ** The xFetch() method locates a page in the cache and returns a pointer to
  7016. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  7017. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  7018. ** pointer to a buffer of szPage bytes used to store the content of a
  7019. ** single database page. The pExtra element of sqlite3_pcache_page will be
  7020. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  7021. ** for each entry in the page cache.
  7022. **
  7023. ** The page to be fetched is determined by the key. ^The minimum key value
  7024. ** is 1. After it has been retrieved using xFetch, the page is considered
  7025. ** to be "pinned".
  7026. **
  7027. ** If the requested page is already in the page cache, then the page cache
  7028. ** implementation must return a pointer to the page buffer with its content
  7029. ** intact. If the requested page is not already in the cache, then the
  7030. ** cache implementation should use the value of the createFlag
  7031. ** parameter to help it determined what action to take:
  7032. **
  7033. ** <table border=1 width=85% align=center>
  7034. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  7035. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  7036. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  7037. ** Otherwise return NULL.
  7038. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  7039. ** NULL if allocating a new page is effectively impossible.
  7040. ** </table>
  7041. **
  7042. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  7043. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  7044. ** failed.)^ In between the to xFetch() calls, SQLite may
  7045. ** attempt to unpin one or more cache pages by spilling the content of
  7046. ** pinned pages to disk and synching the operating system disk cache.
  7047. **
  7048. ** [[the xUnpin() page cache method]]
  7049. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  7050. ** as its second argument. If the third parameter, discard, is non-zero,
  7051. ** then the page must be evicted from the cache.
  7052. ** ^If the discard parameter is
  7053. ** zero, then the page may be discarded or retained at the discretion of
  7054. ** page cache implementation. ^The page cache implementation
  7055. ** may choose to evict unpinned pages at any time.
  7056. **
  7057. ** The cache must not perform any reference counting. A single
  7058. ** call to xUnpin() unpins the page regardless of the number of prior calls
  7059. ** to xFetch().
  7060. **
  7061. ** [[the xRekey() page cache methods]]
  7062. ** The xRekey() method is used to change the key value associated with the
  7063. ** page passed as the second argument. If the cache
  7064. ** previously contains an entry associated with newKey, it must be
  7065. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  7066. ** to be pinned.
  7067. **
  7068. ** When SQLite calls the xTruncate() method, the cache must discard all
  7069. ** existing cache entries with page numbers (keys) greater than or equal
  7070. ** to the value of the iLimit parameter passed to xTruncate(). If any
  7071. ** of these pages are pinned, they are implicitly unpinned, meaning that
  7072. ** they can be safely discarded.
  7073. **
  7074. ** [[the xDestroy() page cache method]]
  7075. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  7076. ** All resources associated with the specified cache should be freed. ^After
  7077. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  7078. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  7079. ** functions.
  7080. **
  7081. ** [[the xShrink() page cache method]]
  7082. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  7083. ** free up as much of heap memory as possible. The page cache implementation
  7084. ** is not obligated to free any memory, but well-behaved implementations should
  7085. ** do their best.
  7086. */
  7087. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  7088. struct sqlite3_pcache_methods2 {
  7089. int iVersion;
  7090. void *pArg;
  7091. int (*xInit)(void*);
  7092. void (*xShutdown)(void*);
  7093. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  7094. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7095. int (*xPagecount)(sqlite3_pcache*);
  7096. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7097. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  7098. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  7099. unsigned oldKey, unsigned newKey);
  7100. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7101. void (*xDestroy)(sqlite3_pcache*);
  7102. void (*xShrink)(sqlite3_pcache*);
  7103. };
  7104. /*
  7105. ** This is the obsolete pcache_methods object that has now been replaced
  7106. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  7107. ** retained in the header file for backwards compatibility only.
  7108. */
  7109. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  7110. struct sqlite3_pcache_methods {
  7111. void *pArg;
  7112. int (*xInit)(void*);
  7113. void (*xShutdown)(void*);
  7114. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  7115. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7116. int (*xPagecount)(sqlite3_pcache*);
  7117. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7118. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  7119. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  7120. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7121. void (*xDestroy)(sqlite3_pcache*);
  7122. };
  7123. /*
  7124. ** CAPI3REF: Online Backup Object
  7125. **
  7126. ** The sqlite3_backup object records state information about an ongoing
  7127. ** online backup operation. ^The sqlite3_backup object is created by
  7128. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  7129. ** [sqlite3_backup_finish()].
  7130. **
  7131. ** See Also: [Using the SQLite Online Backup API]
  7132. */
  7133. typedef struct sqlite3_backup sqlite3_backup;
  7134. /*
  7135. ** CAPI3REF: Online Backup API.
  7136. **
  7137. ** The backup API copies the content of one database into another.
  7138. ** It is useful either for creating backups of databases or
  7139. ** for copying in-memory databases to or from persistent files.
  7140. **
  7141. ** See Also: [Using the SQLite Online Backup API]
  7142. **
  7143. ** ^SQLite holds a write transaction open on the destination database file
  7144. ** for the duration of the backup operation.
  7145. ** ^The source database is read-locked only while it is being read;
  7146. ** it is not locked continuously for the entire backup operation.
  7147. ** ^Thus, the backup may be performed on a live source database without
  7148. ** preventing other database connections from
  7149. ** reading or writing to the source database while the backup is underway.
  7150. **
  7151. ** ^(To perform a backup operation:
  7152. ** <ol>
  7153. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  7154. ** backup,
  7155. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  7156. ** the data between the two databases, and finally
  7157. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  7158. ** associated with the backup operation.
  7159. ** </ol>)^
  7160. ** There should be exactly one call to sqlite3_backup_finish() for each
  7161. ** successful call to sqlite3_backup_init().
  7162. **
  7163. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  7164. **
  7165. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  7166. ** [database connection] associated with the destination database
  7167. ** and the database name, respectively.
  7168. ** ^The database name is "main" for the main database, "temp" for the
  7169. ** temporary database, or the name specified after the AS keyword in
  7170. ** an [ATTACH] statement for an attached database.
  7171. ** ^The S and M arguments passed to
  7172. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7173. ** and database name of the source database, respectively.
  7174. ** ^The source and destination [database connections] (parameters S and D)
  7175. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7176. ** an error.
  7177. **
  7178. ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
  7179. ** there is already a read or read-write transaction open on the
  7180. ** destination database.
  7181. **
  7182. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7183. ** returned and an error code and error message are stored in the
  7184. ** destination [database connection] D.
  7185. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7186. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7187. ** [sqlite3_errmsg16()] functions.
  7188. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7189. ** [sqlite3_backup] object.
  7190. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7191. ** sqlite3_backup_finish() functions to perform the specified backup
  7192. ** operation.
  7193. **
  7194. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7195. **
  7196. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7197. ** the source and destination databases specified by [sqlite3_backup] object B.
  7198. ** ^If N is negative, all remaining source pages are copied.
  7199. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7200. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7201. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7202. ** from source to destination, then it returns [SQLITE_DONE].
  7203. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7204. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7205. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7206. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7207. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7208. **
  7209. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7210. ** <ol>
  7211. ** <li> the destination database was opened read-only, or
  7212. ** <li> the destination database is using write-ahead-log journaling
  7213. ** and the destination and source page sizes differ, or
  7214. ** <li> the destination database is an in-memory database and the
  7215. ** destination and source page sizes differ.
  7216. ** </ol>)^
  7217. **
  7218. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7219. ** the [sqlite3_busy_handler | busy-handler function]
  7220. ** is invoked (if one is specified). ^If the
  7221. ** busy-handler returns non-zero before the lock is available, then
  7222. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7223. ** sqlite3_backup_step() can be retried later. ^If the source
  7224. ** [database connection]
  7225. ** is being used to write to the source database when sqlite3_backup_step()
  7226. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7227. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7228. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7229. ** [SQLITE_READONLY] is returned, then
  7230. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7231. ** errors are considered fatal.)^ The application must accept
  7232. ** that the backup operation has failed and pass the backup operation handle
  7233. ** to the sqlite3_backup_finish() to release associated resources.
  7234. **
  7235. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7236. ** on the destination file. ^The exclusive lock is not released until either
  7237. ** sqlite3_backup_finish() is called or the backup operation is complete
  7238. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7239. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7240. ** lasts for the duration of the sqlite3_backup_step() call.
  7241. ** ^Because the source database is not locked between calls to
  7242. ** sqlite3_backup_step(), the source database may be modified mid-way
  7243. ** through the backup process. ^If the source database is modified by an
  7244. ** external process or via a database connection other than the one being
  7245. ** used by the backup operation, then the backup will be automatically
  7246. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7247. ** database is modified by the using the same database connection as is used
  7248. ** by the backup operation, then the backup database is automatically
  7249. ** updated at the same time.
  7250. **
  7251. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7252. **
  7253. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7254. ** application wishes to abandon the backup operation, the application
  7255. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7256. ** ^The sqlite3_backup_finish() interfaces releases all
  7257. ** resources associated with the [sqlite3_backup] object.
  7258. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7259. ** active write-transaction on the destination database is rolled back.
  7260. ** The [sqlite3_backup] object is invalid
  7261. ** and may not be used following a call to sqlite3_backup_finish().
  7262. **
  7263. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7264. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7265. ** sqlite3_backup_step() completed.
  7266. ** ^If an out-of-memory condition or IO error occurred during any prior
  7267. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7268. ** sqlite3_backup_finish() returns the corresponding [error code].
  7269. **
  7270. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7271. ** is not a permanent error and does not affect the return value of
  7272. ** sqlite3_backup_finish().
  7273. **
  7274. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7275. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7276. **
  7277. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7278. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7279. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7280. ** in the source database at the conclusion of the most recent
  7281. ** sqlite3_backup_step().
  7282. ** ^(The values returned by these functions are only updated by
  7283. ** sqlite3_backup_step(). If the source database is modified in a way that
  7284. ** changes the size of the source database or the number of pages remaining,
  7285. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7286. ** and sqlite3_backup_remaining() until after the next
  7287. ** sqlite3_backup_step().)^
  7288. **
  7289. ** <b>Concurrent Usage of Database Handles</b>
  7290. **
  7291. ** ^The source [database connection] may be used by the application for other
  7292. ** purposes while a backup operation is underway or being initialized.
  7293. ** ^If SQLite is compiled and configured to support threadsafe database
  7294. ** connections, then the source database connection may be used concurrently
  7295. ** from within other threads.
  7296. **
  7297. ** However, the application must guarantee that the destination
  7298. ** [database connection] is not passed to any other API (by any thread) after
  7299. ** sqlite3_backup_init() is called and before the corresponding call to
  7300. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7301. ** if the application incorrectly accesses the destination [database connection]
  7302. ** and so no error code is reported, but the operations may malfunction
  7303. ** nevertheless. Use of the destination database connection while a
  7304. ** backup is in progress might also also cause a mutex deadlock.
  7305. **
  7306. ** If running in [shared cache mode], the application must
  7307. ** guarantee that the shared cache used by the destination database
  7308. ** is not accessed while the backup is running. In practice this means
  7309. ** that the application must guarantee that the disk file being
  7310. ** backed up to is not accessed by any connection within the process,
  7311. ** not just the specific connection that was passed to sqlite3_backup_init().
  7312. **
  7313. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7314. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7315. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7316. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7317. ** same time as another thread is invoking sqlite3_backup_step() it is
  7318. ** possible that they return invalid values.
  7319. */
  7320. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  7321. sqlite3 *pDest, /* Destination database handle */
  7322. const char *zDestName, /* Destination database name */
  7323. sqlite3 *pSource, /* Source database handle */
  7324. const char *zSourceName /* Source database name */
  7325. );
  7326. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7327. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
  7328. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
  7329. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
  7330. /*
  7331. ** CAPI3REF: Unlock Notification
  7332. ** METHOD: sqlite3
  7333. **
  7334. ** ^When running in shared-cache mode, a database operation may fail with
  7335. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7336. ** individual tables within the shared-cache cannot be obtained. See
  7337. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7338. ** ^This API may be used to register a callback that SQLite will invoke
  7339. ** when the connection currently holding the required lock relinquishes it.
  7340. ** ^This API is only available if the library was compiled with the
  7341. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7342. **
  7343. ** See Also: [Using the SQLite Unlock Notification Feature].
  7344. **
  7345. ** ^Shared-cache locks are released when a database connection concludes
  7346. ** its current transaction, either by committing it or rolling it back.
  7347. **
  7348. ** ^When a connection (known as the blocked connection) fails to obtain a
  7349. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7350. ** identity of the database connection (the blocking connection) that
  7351. ** has locked the required resource is stored internally. ^After an
  7352. ** application receives an SQLITE_LOCKED error, it may call the
  7353. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7354. ** the first argument to register for a callback that will be invoked
  7355. ** when the blocking connections current transaction is concluded. ^The
  7356. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7357. ** call that concludes the blocking connections transaction.
  7358. **
  7359. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7360. ** there is a chance that the blocking connection will have already
  7361. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7362. ** If this happens, then the specified callback is invoked immediately,
  7363. ** from within the call to sqlite3_unlock_notify().)^
  7364. **
  7365. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7366. ** shared-cache table, and more than one other connection currently holds
  7367. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7368. ** the other connections to use as the blocking connection.
  7369. **
  7370. ** ^(There may be at most one unlock-notify callback registered by a
  7371. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7372. ** blocked connection already has a registered unlock-notify callback,
  7373. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7374. ** called with a NULL pointer as its second argument, then any existing
  7375. ** unlock-notify callback is canceled. ^The blocked connections
  7376. ** unlock-notify callback may also be canceled by closing the blocked
  7377. ** connection using [sqlite3_close()].
  7378. **
  7379. ** The unlock-notify callback is not reentrant. If an application invokes
  7380. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7381. ** crash or deadlock may be the result.
  7382. **
  7383. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7384. ** returns SQLITE_OK.
  7385. **
  7386. ** <b>Callback Invocation Details</b>
  7387. **
  7388. ** When an unlock-notify callback is registered, the application provides a
  7389. ** single void* pointer that is passed to the callback when it is invoked.
  7390. ** However, the signature of the callback function allows SQLite to pass
  7391. ** it an array of void* context pointers. The first argument passed to
  7392. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7393. ** and the second is the number of entries in the array.
  7394. **
  7395. ** When a blocking connections transaction is concluded, there may be
  7396. ** more than one blocked connection that has registered for an unlock-notify
  7397. ** callback. ^If two or more such blocked connections have specified the
  7398. ** same callback function, then instead of invoking the callback function
  7399. ** multiple times, it is invoked once with the set of void* context pointers
  7400. ** specified by the blocked connections bundled together into an array.
  7401. ** This gives the application an opportunity to prioritize any actions
  7402. ** related to the set of unblocked database connections.
  7403. **
  7404. ** <b>Deadlock Detection</b>
  7405. **
  7406. ** Assuming that after registering for an unlock-notify callback a
  7407. ** database waits for the callback to be issued before taking any further
  7408. ** action (a reasonable assumption), then using this API may cause the
  7409. ** application to deadlock. For example, if connection X is waiting for
  7410. ** connection Y's transaction to be concluded, and similarly connection
  7411. ** Y is waiting on connection X's transaction, then neither connection
  7412. ** will proceed and the system may remain deadlocked indefinitely.
  7413. **
  7414. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7415. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7416. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7417. ** unlock-notify callback is registered. The system is said to be in
  7418. ** a deadlocked state if connection A has registered for an unlock-notify
  7419. ** callback on the conclusion of connection B's transaction, and connection
  7420. ** B has itself registered for an unlock-notify callback when connection
  7421. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7422. ** the system is also considered to be deadlocked if connection B has
  7423. ** registered for an unlock-notify callback on the conclusion of connection
  7424. ** C's transaction, where connection C is waiting on connection A. ^Any
  7425. ** number of levels of indirection are allowed.
  7426. **
  7427. ** <b>The "DROP TABLE" Exception</b>
  7428. **
  7429. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7430. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7431. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7432. ** SQLite checks if there are any currently executing SELECT statements
  7433. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7434. ** returned. In this case there is no "blocking connection", so invoking
  7435. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7436. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7437. ** or "DROP INDEX" query, an infinite loop might be the result.
  7438. **
  7439. ** One way around this problem is to check the extended error code returned
  7440. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7441. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7442. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7443. ** SQLITE_LOCKED.)^
  7444. */
  7445. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  7446. sqlite3 *pBlocked, /* Waiting connection */
  7447. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7448. void *pNotifyArg /* Argument to pass to xNotify */
  7449. );
  7450. /*
  7451. ** CAPI3REF: String Comparison
  7452. **
  7453. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7454. ** and extensions to compare the contents of two buffers containing UTF-8
  7455. ** strings in a case-independent fashion, using the same definition of "case
  7456. ** independence" that SQLite uses internally when comparing identifiers.
  7457. */
  7458. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
  7459. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
  7460. /*
  7461. ** CAPI3REF: String Globbing
  7462. *
  7463. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  7464. ** string X matches the [GLOB] pattern P.
  7465. ** ^The definition of [GLOB] pattern matching used in
  7466. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7467. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  7468. ** is case sensitive.
  7469. **
  7470. ** Note that this routine returns zero on a match and non-zero if the strings
  7471. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7472. **
  7473. ** See also: [sqlite3_strlike()].
  7474. */
  7475. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
  7476. /*
  7477. ** CAPI3REF: String LIKE Matching
  7478. *
  7479. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  7480. ** string X matches the [LIKE] pattern P with escape character E.
  7481. ** ^The definition of [LIKE] pattern matching used in
  7482. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  7483. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  7484. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  7485. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  7486. ** insensitive - equivalent upper and lower case ASCII characters match
  7487. ** one another.
  7488. **
  7489. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  7490. ** only ASCII characters are case folded.
  7491. **
  7492. ** Note that this routine returns zero on a match and non-zero if the strings
  7493. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7494. **
  7495. ** See also: [sqlite3_strglob()].
  7496. */
  7497. SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  7498. /*
  7499. ** CAPI3REF: Error Logging Interface
  7500. **
  7501. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7502. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7503. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7504. ** used with [sqlite3_snprintf()] to generate the final output string.
  7505. **
  7506. ** The sqlite3_log() interface is intended for use by extensions such as
  7507. ** virtual tables, collating functions, and SQL functions. While there is
  7508. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7509. ** is considered bad form.
  7510. **
  7511. ** The zFormat string must not be NULL.
  7512. **
  7513. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7514. ** will not use dynamically allocated memory. The log message is stored in
  7515. ** a fixed-length buffer on the stack. If the log message is longer than
  7516. ** a few hundred characters, it will be truncated to the length of the
  7517. ** buffer.
  7518. */
  7519. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
  7520. /*
  7521. ** CAPI3REF: Write-Ahead Log Commit Hook
  7522. ** METHOD: sqlite3
  7523. **
  7524. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7525. ** is invoked each time data is committed to a database in wal mode.
  7526. **
  7527. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7528. ** the associated write-lock on the database released)^, so the implementation
  7529. ** may read, write or [checkpoint] the database as required.
  7530. **
  7531. ** ^The first parameter passed to the callback function when it is invoked
  7532. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7533. ** registering the callback. ^The second is a copy of the database handle.
  7534. ** ^The third parameter is the name of the database that was written to -
  7535. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7536. ** is the number of pages currently in the write-ahead log file,
  7537. ** including those that were just committed.
  7538. **
  7539. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7540. ** code is returned, that error will propagate back up through the
  7541. ** SQLite code base to cause the statement that provoked the callback
  7542. ** to report an error, though the commit will have still occurred. If the
  7543. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7544. ** that does not correspond to any valid SQLite error code, the results
  7545. ** are undefined.
  7546. **
  7547. ** A single database handle may have at most a single write-ahead log callback
  7548. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7549. ** previously registered write-ahead log callback. ^Note that the
  7550. ** [sqlite3_wal_autocheckpoint()] interface and the
  7551. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7552. ** overwrite any prior [sqlite3_wal_hook()] settings.
  7553. */
  7554. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  7555. sqlite3*,
  7556. int(*)(void *,sqlite3*,const char*,int),
  7557. void*
  7558. );
  7559. /*
  7560. ** CAPI3REF: Configure an auto-checkpoint
  7561. ** METHOD: sqlite3
  7562. **
  7563. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7564. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7565. ** to automatically [checkpoint]
  7566. ** after committing a transaction if there are N or
  7567. ** more frames in the [write-ahead log] file. ^Passing zero or
  7568. ** a negative value as the nFrame parameter disables automatic
  7569. ** checkpoints entirely.
  7570. **
  7571. ** ^The callback registered by this function replaces any existing callback
  7572. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7573. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7574. ** configured by this function.
  7575. **
  7576. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7577. ** from SQL.
  7578. **
  7579. ** ^Checkpoints initiated by this mechanism are
  7580. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7581. **
  7582. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7583. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7584. ** pages. The use of this interface
  7585. ** is only necessary if the default setting is found to be suboptimal
  7586. ** for a particular application.
  7587. */
  7588. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7589. /*
  7590. ** CAPI3REF: Checkpoint a database
  7591. ** METHOD: sqlite3
  7592. **
  7593. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7594. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7595. **
  7596. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7597. ** [write-ahead log] for database X on [database connection] D to be
  7598. ** transferred into the database file and for the write-ahead log to
  7599. ** be reset. See the [checkpointing] documentation for addition
  7600. ** information.
  7601. **
  7602. ** This interface used to be the only way to cause a checkpoint to
  7603. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7604. ** interface was added. This interface is retained for backwards
  7605. ** compatibility and as a convenience for applications that need to manually
  7606. ** start a callback but which do not need the full power (and corresponding
  7607. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7608. */
  7609. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7610. /*
  7611. ** CAPI3REF: Checkpoint a database
  7612. ** METHOD: sqlite3
  7613. **
  7614. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7615. ** operation on database X of [database connection] D in mode M. Status
  7616. ** information is written back into integers pointed to by L and C.)^
  7617. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7618. **
  7619. ** <dl>
  7620. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7621. ** ^Checkpoint as many frames as possible without waiting for any database
  7622. ** readers or writers to finish, then sync the database file if all frames
  7623. ** in the log were checkpointed. ^The [busy-handler callback]
  7624. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7625. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7626. ** if there are concurrent readers or writers.
  7627. **
  7628. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7629. ** ^This mode blocks (it invokes the
  7630. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7631. ** database writer and all readers are reading from the most recent database
  7632. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7633. ** database file. ^This mode blocks new database writers while it is pending,
  7634. ** but new database readers are allowed to continue unimpeded.
  7635. **
  7636. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7637. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7638. ** that after checkpointing the log file it blocks (calls the
  7639. ** [busy-handler callback])
  7640. ** until all readers are reading from the database file only. ^This ensures
  7641. ** that the next writer will restart the log file from the beginning.
  7642. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7643. ** database writer attempts while it is pending, but does not impede readers.
  7644. **
  7645. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7646. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7647. ** addition that it also truncates the log file to zero bytes just prior
  7648. ** to a successful return.
  7649. ** </dl>
  7650. **
  7651. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7652. ** the log file or to -1 if the checkpoint could not run because
  7653. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7654. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7655. ** log file (including any that were already checkpointed before the function
  7656. ** was called) or to -1 if the checkpoint could not run due to an error or
  7657. ** because the database is not in WAL mode. ^Note that upon successful
  7658. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7659. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7660. **
  7661. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7662. ** any other process is running a checkpoint operation at the same time, the
  7663. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7664. ** busy-handler configured, it will not be invoked in this case.
  7665. **
  7666. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  7667. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  7668. ** obtained immediately, and a busy-handler is configured, it is invoked and
  7669. ** the writer lock retried until either the busy-handler returns 0 or the lock
  7670. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  7671. ** database readers as described above. ^If the busy-handler returns 0 before
  7672. ** the writer lock is obtained or while waiting for database readers, the
  7673. ** checkpoint operation proceeds from that point in the same way as
  7674. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7675. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  7676. **
  7677. ** ^If parameter zDb is NULL or points to a zero length string, then the
  7678. ** specified operation is attempted on all WAL databases [attached] to
  7679. ** [database connection] db. In this case the
  7680. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  7681. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7682. ** attached WAL databases, the operation is still attempted on any remaining
  7683. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  7684. ** error occurs while processing an attached database, processing is abandoned
  7685. ** and the error code is returned to the caller immediately. ^If no error
  7686. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7687. ** databases, SQLITE_OK is returned.
  7688. **
  7689. ** ^If database zDb is the name of an attached database that is not in WAL
  7690. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  7691. ** zDb is not NULL (or a zero length string) and is not the name of any
  7692. ** attached database, SQLITE_ERROR is returned to the caller.
  7693. **
  7694. ** ^Unless it returns SQLITE_MISUSE,
  7695. ** the sqlite3_wal_checkpoint_v2() interface
  7696. ** sets the error information that is queried by
  7697. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  7698. **
  7699. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  7700. ** from SQL.
  7701. */
  7702. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  7703. sqlite3 *db, /* Database handle */
  7704. const char *zDb, /* Name of attached database (or NULL) */
  7705. int eMode, /* SQLITE_CHECKPOINT_* value */
  7706. int *pnLog, /* OUT: Size of WAL log in frames */
  7707. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7708. );
  7709. /*
  7710. ** CAPI3REF: Checkpoint Mode Values
  7711. ** KEYWORDS: {checkpoint mode}
  7712. **
  7713. ** These constants define all valid values for the "checkpoint mode" passed
  7714. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  7715. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  7716. ** meaning of each of these checkpoint modes.
  7717. */
  7718. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  7719. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  7720. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  7721. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  7722. /*
  7723. ** CAPI3REF: Virtual Table Interface Configuration
  7724. **
  7725. ** This function may be called by either the [xConnect] or [xCreate] method
  7726. ** of a [virtual table] implementation to configure
  7727. ** various facets of the virtual table interface.
  7728. **
  7729. ** If this interface is invoked outside the context of an xConnect or
  7730. ** xCreate virtual table method then the behavior is undefined.
  7731. **
  7732. ** At present, there is only one option that may be configured using
  7733. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7734. ** may be added in the future.
  7735. */
  7736. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
  7737. /*
  7738. ** CAPI3REF: Virtual Table Configuration Options
  7739. **
  7740. ** These macros define the various options to the
  7741. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7742. ** can use to customize and optimize their behavior.
  7743. **
  7744. ** <dl>
  7745. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7746. ** <dd>Calls of the form
  7747. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7748. ** where X is an integer. If X is zero, then the [virtual table] whose
  7749. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7750. ** support constraints. In this configuration (which is the default) if
  7751. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7752. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7753. ** specified as part of the users SQL statement, regardless of the actual
  7754. ** ON CONFLICT mode specified.
  7755. **
  7756. ** If X is non-zero, then the virtual table implementation guarantees
  7757. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7758. ** any modifications to internal or persistent data structures have been made.
  7759. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7760. ** is able to roll back a statement or database transaction, and abandon
  7761. ** or continue processing the current SQL statement as appropriate.
  7762. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7763. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7764. ** had been ABORT.
  7765. **
  7766. ** Virtual table implementations that are required to handle OR REPLACE
  7767. ** must do so within the [xUpdate] method. If a call to the
  7768. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7769. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7770. ** silently replace the appropriate rows within the xUpdate callback and
  7771. ** return SQLITE_OK. Or, if this is not possible, it may return
  7772. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7773. ** constraint handling.
  7774. ** </dl>
  7775. */
  7776. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7777. /*
  7778. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7779. **
  7780. ** This function may only be called from within a call to the [xUpdate] method
  7781. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7782. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7783. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7784. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7785. ** [virtual table].
  7786. */
  7787. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
  7788. /*
  7789. ** CAPI3REF: Conflict resolution modes
  7790. ** KEYWORDS: {conflict resolution mode}
  7791. **
  7792. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7793. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7794. ** is for the SQL statement being evaluated.
  7795. **
  7796. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7797. ** return value from the [sqlite3_set_authorizer()] callback and that
  7798. ** [SQLITE_ABORT] is also a [result code].
  7799. */
  7800. #define SQLITE_ROLLBACK 1
  7801. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7802. #define SQLITE_FAIL 3
  7803. /* #define SQLITE_ABORT 4 // Also an error code */
  7804. #define SQLITE_REPLACE 5
  7805. /*
  7806. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  7807. ** KEYWORDS: {scanstatus options}
  7808. **
  7809. ** The following constants can be used for the T parameter to the
  7810. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  7811. ** different metric for sqlite3_stmt_scanstatus() to return.
  7812. **
  7813. ** When the value returned to V is a string, space to hold that string is
  7814. ** managed by the prepared statement S and will be automatically freed when
  7815. ** S is finalized.
  7816. **
  7817. ** <dl>
  7818. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  7819. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  7820. ** set to the total number of times that the X-th loop has run.</dd>
  7821. **
  7822. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  7823. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  7824. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  7825. **
  7826. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  7827. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  7828. ** query planner's estimate for the average number of rows output from each
  7829. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  7830. ** then this value will approximate the quotient NVISIT/NLOOP and the
  7831. ** product of this value for all prior loops with the same SELECTID will
  7832. ** be the NLOOP value for the current loop.
  7833. **
  7834. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  7835. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7836. ** to a zero-terminated UTF-8 string containing the name of the index or table
  7837. ** used for the X-th loop.
  7838. **
  7839. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  7840. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7841. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  7842. ** description for the X-th loop.
  7843. **
  7844. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  7845. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  7846. ** "select-id" for the X-th loop. The select-id identifies which query or
  7847. ** subquery the loop is part of. The main query has a select-id of zero.
  7848. ** The select-id is the same value as is output in the first column
  7849. ** of an [EXPLAIN QUERY PLAN] query.
  7850. ** </dl>
  7851. */
  7852. #define SQLITE_SCANSTAT_NLOOP 0
  7853. #define SQLITE_SCANSTAT_NVISIT 1
  7854. #define SQLITE_SCANSTAT_EST 2
  7855. #define SQLITE_SCANSTAT_NAME 3
  7856. #define SQLITE_SCANSTAT_EXPLAIN 4
  7857. #define SQLITE_SCANSTAT_SELECTID 5
  7858. /*
  7859. ** CAPI3REF: Prepared Statement Scan Status
  7860. ** METHOD: sqlite3_stmt
  7861. **
  7862. ** This interface returns information about the predicted and measured
  7863. ** performance for pStmt. Advanced applications can use this
  7864. ** interface to compare the predicted and the measured performance and
  7865. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  7866. **
  7867. ** Since this interface is expected to be rarely used, it is only
  7868. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  7869. ** compile-time option.
  7870. **
  7871. ** The "iScanStatusOp" parameter determines which status information to return.
  7872. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  7873. ** of this interface is undefined.
  7874. ** ^The requested measurement is written into a variable pointed to by
  7875. ** the "pOut" parameter.
  7876. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  7877. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  7878. ** zero or greater than or equal to the total number of loops used to implement
  7879. ** the statement - a non-zero value is returned and the variable that pOut
  7880. ** points to is unchanged.
  7881. **
  7882. ** ^Statistics might not be available for all loops in all statements. ^In cases
  7883. ** where there exist loops with no available statistics, this function behaves
  7884. ** as if the loop did not exist - it returns non-zero and leave the variable
  7885. ** that pOut points to unchanged.
  7886. **
  7887. ** See also: [sqlite3_stmt_scanstatus_reset()]
  7888. */
  7889. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  7890. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  7891. int idx, /* Index of loop to report on */
  7892. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  7893. void *pOut /* Result written here */
  7894. );
  7895. /*
  7896. ** CAPI3REF: Zero Scan-Status Counters
  7897. ** METHOD: sqlite3_stmt
  7898. **
  7899. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  7900. **
  7901. ** This API is only available if the library is built with pre-processor
  7902. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  7903. */
  7904. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  7905. /*
  7906. ** CAPI3REF: Flush caches to disk mid-transaction
  7907. **
  7908. ** ^If a write-transaction is open on [database connection] D when the
  7909. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  7910. ** pages in the pager-cache that are not currently in use are written out
  7911. ** to disk. A dirty page may be in use if a database cursor created by an
  7912. ** active SQL statement is reading from it, or if it is page 1 of a database
  7913. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  7914. ** interface flushes caches for all schemas - "main", "temp", and
  7915. ** any [attached] databases.
  7916. **
  7917. ** ^If this function needs to obtain extra database locks before dirty pages
  7918. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  7919. ** immediately and there is a busy-handler callback configured, it is invoked
  7920. ** in the usual manner. ^If the required lock still cannot be obtained, then
  7921. ** the database is skipped and an attempt made to flush any dirty pages
  7922. ** belonging to the next (if any) database. ^If any databases are skipped
  7923. ** because locks cannot be obtained, but no other error occurs, this
  7924. ** function returns SQLITE_BUSY.
  7925. **
  7926. ** ^If any other error occurs while flushing dirty pages to disk (for
  7927. ** example an IO error or out-of-memory condition), then processing is
  7928. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  7929. **
  7930. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  7931. **
  7932. ** ^This function does not set the database handle error code or message
  7933. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  7934. */
  7935. SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
  7936. /*
  7937. ** CAPI3REF: Low-level system error code
  7938. **
  7939. ** ^Attempt to return the underlying operating system error code or error
  7940. ** number that caused the most reason I/O error or failure to open a file.
  7941. ** The return value is OS-dependent. For example, on unix systems, after
  7942. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  7943. ** called to get back the underlying "errno" that caused the problem, such
  7944. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  7945. */
  7946. SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3*);
  7947. /*
  7948. ** CAPI3REF: Database Snapshot
  7949. ** KEYWORDS: {snapshot}
  7950. ** EXPERIMENTAL
  7951. **
  7952. ** An instance of the snapshot object records the state of a [WAL mode]
  7953. ** database for some specific point in history.
  7954. **
  7955. ** In [WAL mode], multiple [database connections] that are open on the
  7956. ** same database file can each be reading a different historical version
  7957. ** of the database file. When a [database connection] begins a read
  7958. ** transaction, that connection sees an unchanging copy of the database
  7959. ** as it existed for the point in time when the transaction first started.
  7960. ** Subsequent changes to the database from other connections are not seen
  7961. ** by the reader until a new read transaction is started.
  7962. **
  7963. ** The sqlite3_snapshot object records state information about an historical
  7964. ** version of the database file so that it is possible to later open a new read
  7965. ** transaction that sees that historical version of the database rather than
  7966. ** the most recent version.
  7967. **
  7968. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  7969. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  7970. ** to an historical snapshot (if possible). The destructor for
  7971. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  7972. */
  7973. typedef struct sqlite3_snapshot sqlite3_snapshot;
  7974. /*
  7975. ** CAPI3REF: Record A Database Snapshot
  7976. ** EXPERIMENTAL
  7977. **
  7978. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  7979. ** new [sqlite3_snapshot] object that records the current state of
  7980. ** schema S in database connection D. ^On success, the
  7981. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  7982. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  7983. ** ^If schema S of [database connection] D is not a [WAL mode] database
  7984. ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
  7985. ** leaves the *P value unchanged and returns an appropriate [error code].
  7986. **
  7987. ** The [sqlite3_snapshot] object returned from a successful call to
  7988. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  7989. ** to avoid a memory leak.
  7990. **
  7991. ** The [sqlite3_snapshot_get()] interface is only available when the
  7992. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  7993. */
  7994. SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_get(
  7995. sqlite3 *db,
  7996. const char *zSchema,
  7997. sqlite3_snapshot **ppSnapshot
  7998. );
  7999. /*
  8000. ** CAPI3REF: Start a read transaction on an historical snapshot
  8001. ** EXPERIMENTAL
  8002. **
  8003. ** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
  8004. ** read transaction that is currently open on schema S of
  8005. ** [database connection] D so that it refers to historical [snapshot] P.
  8006. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  8007. ** or an appropriate [error code] if it fails.
  8008. **
  8009. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  8010. ** the first operation, apart from other sqlite3_snapshot_open() calls,
  8011. ** following the [BEGIN] that starts a new read transaction.
  8012. ** ^A [snapshot] will fail to open if it has been overwritten by a
  8013. ** [checkpoint].
  8014. ** ^A [snapshot] will fail to open if the database connection D has not
  8015. ** previously completed at least one read operation against the database
  8016. ** file. (Hint: Run "[PRAGMA application_id]" against a newly opened
  8017. ** database connection in order to make it ready to use snapshots.)
  8018. **
  8019. ** The [sqlite3_snapshot_open()] interface is only available when the
  8020. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8021. */
  8022. SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(
  8023. sqlite3 *db,
  8024. const char *zSchema,
  8025. sqlite3_snapshot *pSnapshot
  8026. );
  8027. /*
  8028. ** CAPI3REF: Destroy a snapshot
  8029. ** EXPERIMENTAL
  8030. **
  8031. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  8032. ** The application must eventually free every [sqlite3_snapshot] object
  8033. ** using this routine to avoid a memory leak.
  8034. **
  8035. ** The [sqlite3_snapshot_free()] interface is only available when the
  8036. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8037. */
  8038. SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
  8039. /*
  8040. ** Undo the hack that converts floating point types to integer for
  8041. ** builds on processors without floating point support.
  8042. */
  8043. #ifdef SQLITE_OMIT_FLOATING_POINT
  8044. # undef double
  8045. #endif
  8046. #if 0
  8047. } /* End of the 'extern "C"' block */
  8048. #endif
  8049. #endif /* _SQLITE3_H_ */
  8050. /*
  8051. ** 2010 August 30
  8052. **
  8053. ** The author disclaims copyright to this source code. In place of
  8054. ** a legal notice, here is a blessing:
  8055. **
  8056. ** May you do good and not evil.
  8057. ** May you find forgiveness for yourself and forgive others.
  8058. ** May you share freely, never taking more than you give.
  8059. **
  8060. *************************************************************************
  8061. */
  8062. #ifndef _SQLITE3RTREE_H_
  8063. #define _SQLITE3RTREE_H_
  8064. #if 0
  8065. extern "C" {
  8066. #endif
  8067. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  8068. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  8069. /* The double-precision datatype used by RTree depends on the
  8070. ** SQLITE_RTREE_INT_ONLY compile-time option.
  8071. */
  8072. #ifdef SQLITE_RTREE_INT_ONLY
  8073. typedef sqlite3_int64 sqlite3_rtree_dbl;
  8074. #else
  8075. typedef double sqlite3_rtree_dbl;
  8076. #endif
  8077. /*
  8078. ** Register a geometry callback named zGeom that can be used as part of an
  8079. ** R-Tree geometry query as follows:
  8080. **
  8081. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  8082. */
  8083. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  8084. sqlite3 *db,
  8085. const char *zGeom,
  8086. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  8087. void *pContext
  8088. );
  8089. /*
  8090. ** A pointer to a structure of the following type is passed as the first
  8091. ** argument to callbacks registered using rtree_geometry_callback().
  8092. */
  8093. struct sqlite3_rtree_geometry {
  8094. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  8095. int nParam; /* Size of array aParam[] */
  8096. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  8097. void *pUser; /* Callback implementation user data */
  8098. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  8099. };
  8100. /*
  8101. ** Register a 2nd-generation geometry callback named zScore that can be
  8102. ** used as part of an R-Tree geometry query as follows:
  8103. **
  8104. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  8105. */
  8106. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  8107. sqlite3 *db,
  8108. const char *zQueryFunc,
  8109. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  8110. void *pContext,
  8111. void (*xDestructor)(void*)
  8112. );
  8113. /*
  8114. ** A pointer to a structure of the following type is passed as the
  8115. ** argument to scored geometry callback registered using
  8116. ** sqlite3_rtree_query_callback().
  8117. **
  8118. ** Note that the first 5 fields of this structure are identical to
  8119. ** sqlite3_rtree_geometry. This structure is a subclass of
  8120. ** sqlite3_rtree_geometry.
  8121. */
  8122. struct sqlite3_rtree_query_info {
  8123. void *pContext; /* pContext from when function registered */
  8124. int nParam; /* Number of function parameters */
  8125. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  8126. void *pUser; /* callback can use this, if desired */
  8127. void (*xDelUser)(void*); /* function to free pUser */
  8128. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  8129. unsigned int *anQueue; /* Number of pending entries in the queue */
  8130. int nCoord; /* Number of coordinates */
  8131. int iLevel; /* Level of current node or entry */
  8132. int mxLevel; /* The largest iLevel value in the tree */
  8133. sqlite3_int64 iRowid; /* Rowid for current entry */
  8134. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  8135. int eParentWithin; /* Visibility of parent node */
  8136. int eWithin; /* OUT: Visiblity */
  8137. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  8138. /* The following fields are only available in 3.8.11 and later */
  8139. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  8140. };
  8141. /*
  8142. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  8143. */
  8144. #define NOT_WITHIN 0 /* Object completely outside of query region */
  8145. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  8146. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  8147. #if 0
  8148. } /* end of the 'extern "C"' block */
  8149. #endif
  8150. #endif /* ifndef _SQLITE3RTREE_H_ */
  8151. /*
  8152. ** 2014 May 31
  8153. **
  8154. ** The author disclaims copyright to this source code. In place of
  8155. ** a legal notice, here is a blessing:
  8156. **
  8157. ** May you do good and not evil.
  8158. ** May you find forgiveness for yourself and forgive others.
  8159. ** May you share freely, never taking more than you give.
  8160. **
  8161. ******************************************************************************
  8162. **
  8163. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  8164. ** FTS5 may be extended with:
  8165. **
  8166. ** * custom tokenizers, and
  8167. ** * custom auxiliary functions.
  8168. */
  8169. #ifndef _FTS5_H
  8170. #define _FTS5_H
  8171. #if 0
  8172. extern "C" {
  8173. #endif
  8174. /*************************************************************************
  8175. ** CUSTOM AUXILIARY FUNCTIONS
  8176. **
  8177. ** Virtual table implementations may overload SQL functions by implementing
  8178. ** the sqlite3_module.xFindFunction() method.
  8179. */
  8180. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  8181. typedef struct Fts5Context Fts5Context;
  8182. typedef struct Fts5PhraseIter Fts5PhraseIter;
  8183. typedef void (*fts5_extension_function)(
  8184. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  8185. Fts5Context *pFts, /* First arg to pass to pApi functions */
  8186. sqlite3_context *pCtx, /* Context for returning result/error */
  8187. int nVal, /* Number of values in apVal[] array */
  8188. sqlite3_value **apVal /* Array of trailing arguments */
  8189. );
  8190. struct Fts5PhraseIter {
  8191. const unsigned char *a;
  8192. const unsigned char *b;
  8193. };
  8194. /*
  8195. ** EXTENSION API FUNCTIONS
  8196. **
  8197. ** xUserData(pFts):
  8198. ** Return a copy of the context pointer the extension function was
  8199. ** registered with.
  8200. **
  8201. ** xColumnTotalSize(pFts, iCol, pnToken):
  8202. ** If parameter iCol is less than zero, set output variable *pnToken
  8203. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  8204. ** non-negative but less than the number of columns in the table, return
  8205. ** the total number of tokens in column iCol, considering all rows in
  8206. ** the FTS5 table.
  8207. **
  8208. ** If parameter iCol is greater than or equal to the number of columns
  8209. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  8210. ** an OOM condition or IO error), an appropriate SQLite error code is
  8211. ** returned.
  8212. **
  8213. ** xColumnCount(pFts):
  8214. ** Return the number of columns in the table.
  8215. **
  8216. ** xColumnSize(pFts, iCol, pnToken):
  8217. ** If parameter iCol is less than zero, set output variable *pnToken
  8218. ** to the total number of tokens in the current row. Or, if iCol is
  8219. ** non-negative but less than the number of columns in the table, set
  8220. ** *pnToken to the number of tokens in column iCol of the current row.
  8221. **
  8222. ** If parameter iCol is greater than or equal to the number of columns
  8223. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  8224. ** an OOM condition or IO error), an appropriate SQLite error code is
  8225. ** returned.
  8226. **
  8227. ** This function may be quite inefficient if used with an FTS5 table
  8228. ** created with the "columnsize=0" option.
  8229. **
  8230. ** xColumnText:
  8231. ** This function attempts to retrieve the text of column iCol of the
  8232. ** current document. If successful, (*pz) is set to point to a buffer
  8233. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  8234. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  8235. ** if an error occurs, an SQLite error code is returned and the final values
  8236. ** of (*pz) and (*pn) are undefined.
  8237. **
  8238. ** xPhraseCount:
  8239. ** Returns the number of phrases in the current query expression.
  8240. **
  8241. ** xPhraseSize:
  8242. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  8243. ** are numbered starting from zero.
  8244. **
  8245. ** xInstCount:
  8246. ** Set *pnInst to the total number of occurrences of all phrases within
  8247. ** the query within the current row. Return SQLITE_OK if successful, or
  8248. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  8249. **
  8250. ** This API can be quite slow if used with an FTS5 table created with the
  8251. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  8252. ** with either "detail=none" or "detail=column" and "content=" option
  8253. ** (i.e. if it is a contentless table), then this API always returns 0.
  8254. **
  8255. ** xInst:
  8256. ** Query for the details of phrase match iIdx within the current row.
  8257. ** Phrase matches are numbered starting from zero, so the iIdx argument
  8258. ** should be greater than or equal to zero and smaller than the value
  8259. ** output by xInstCount().
  8260. **
  8261. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  8262. ** to the column in which it occurs and *piOff the token offset of the
  8263. ** first token of the phrase. The exception is if the table was created
  8264. ** with the offsets=0 option specified. In this case *piOff is always
  8265. ** set to -1.
  8266. **
  8267. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  8268. ** if an error occurs.
  8269. **
  8270. ** This API can be quite slow if used with an FTS5 table created with the
  8271. ** "detail=none" or "detail=column" option.
  8272. **
  8273. ** xRowid:
  8274. ** Returns the rowid of the current row.
  8275. **
  8276. ** xTokenize:
  8277. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  8278. **
  8279. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  8280. ** This API function is used to query the FTS table for phrase iPhrase
  8281. ** of the current query. Specifically, a query equivalent to:
  8282. **
  8283. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  8284. **
  8285. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  8286. ** current query is executed. For each row visited, the callback function
  8287. ** passed as the fourth argument is invoked. The context and API objects
  8288. ** passed to the callback function may be used to access the properties of
  8289. ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
  8290. ** passed as the third argument to pUserData.
  8291. **
  8292. ** If the callback function returns any value other than SQLITE_OK, the
  8293. ** query is abandoned and the xQueryPhrase function returns immediately.
  8294. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  8295. ** Otherwise, the error code is propagated upwards.
  8296. **
  8297. ** If the query runs to completion without incident, SQLITE_OK is returned.
  8298. ** Or, if some error occurs before the query completes or is aborted by
  8299. ** the callback, an SQLite error code is returned.
  8300. **
  8301. **
  8302. ** xSetAuxdata(pFts5, pAux, xDelete)
  8303. **
  8304. ** Save the pointer passed as the second argument as the extension functions
  8305. ** "auxiliary data". The pointer may then be retrieved by the current or any
  8306. ** future invocation of the same fts5 extension function made as part of
  8307. ** of the same MATCH query using the xGetAuxdata() API.
  8308. **
  8309. ** Each extension function is allocated a single auxiliary data slot for
  8310. ** each FTS query (MATCH expression). If the extension function is invoked
  8311. ** more than once for a single FTS query, then all invocations share a
  8312. ** single auxiliary data context.
  8313. **
  8314. ** If there is already an auxiliary data pointer when this function is
  8315. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  8316. ** was specified along with the original pointer, it is invoked at this
  8317. ** point.
  8318. **
  8319. ** The xDelete callback, if one is specified, is also invoked on the
  8320. ** auxiliary data pointer after the FTS5 query has finished.
  8321. **
  8322. ** If an error (e.g. an OOM condition) occurs within this function, an
  8323. ** the auxiliary data is set to NULL and an error code returned. If the
  8324. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  8325. ** pointer before returning.
  8326. **
  8327. **
  8328. ** xGetAuxdata(pFts5, bClear)
  8329. **
  8330. ** Returns the current auxiliary data pointer for the fts5 extension
  8331. ** function. See the xSetAuxdata() method for details.
  8332. **
  8333. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  8334. ** (set to NULL) before this function returns. In this case the xDelete,
  8335. ** if any, is not invoked.
  8336. **
  8337. **
  8338. ** xRowCount(pFts5, pnRow)
  8339. **
  8340. ** This function is used to retrieve the total number of rows in the table.
  8341. ** In other words, the same value that would be returned by:
  8342. **
  8343. ** SELECT count(*) FROM ftstable;
  8344. **
  8345. ** xPhraseFirst()
  8346. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  8347. ** method, to iterate through all instances of a single query phrase within
  8348. ** the current row. This is the same information as is accessible via the
  8349. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  8350. ** to use, this API may be faster under some circumstances. To iterate
  8351. ** through instances of phrase iPhrase, use the following code:
  8352. **
  8353. ** Fts5PhraseIter iter;
  8354. ** int iCol, iOff;
  8355. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  8356. ** iCol>=0;
  8357. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  8358. ** ){
  8359. ** // An instance of phrase iPhrase at offset iOff of column iCol
  8360. ** }
  8361. **
  8362. ** The Fts5PhraseIter structure is defined above. Applications should not
  8363. ** modify this structure directly - it should only be used as shown above
  8364. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  8365. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  8366. **
  8367. ** This API can be quite slow if used with an FTS5 table created with the
  8368. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  8369. ** with either "detail=none" or "detail=column" and "content=" option
  8370. ** (i.e. if it is a contentless table), then this API always iterates
  8371. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  8372. **
  8373. ** xPhraseNext()
  8374. ** See xPhraseFirst above.
  8375. **
  8376. ** xPhraseFirstColumn()
  8377. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  8378. ** and xPhraseNext() APIs described above. The difference is that instead
  8379. ** of iterating through all instances of a phrase in the current row, these
  8380. ** APIs are used to iterate through the set of columns in the current row
  8381. ** that contain one or more instances of a specified phrase. For example:
  8382. **
  8383. ** Fts5PhraseIter iter;
  8384. ** int iCol;
  8385. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  8386. ** iCol>=0;
  8387. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  8388. ** ){
  8389. ** // Column iCol contains at least one instance of phrase iPhrase
  8390. ** }
  8391. **
  8392. ** This API can be quite slow if used with an FTS5 table created with the
  8393. ** "detail=none" option. If the FTS5 table is created with either
  8394. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  8395. ** then this API always iterates through an empty set (all calls to
  8396. ** xPhraseFirstColumn() set iCol to -1).
  8397. **
  8398. ** The information accessed using this API and its companion
  8399. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  8400. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  8401. ** significantly more efficient than those alternatives when used with
  8402. ** "detail=column" tables.
  8403. **
  8404. ** xPhraseNextColumn()
  8405. ** See xPhraseFirstColumn above.
  8406. */
  8407. struct Fts5ExtensionApi {
  8408. int iVersion; /* Currently always set to 3 */
  8409. void *(*xUserData)(Fts5Context*);
  8410. int (*xColumnCount)(Fts5Context*);
  8411. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  8412. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  8413. int (*xTokenize)(Fts5Context*,
  8414. const char *pText, int nText, /* Text to tokenize */
  8415. void *pCtx, /* Context passed to xToken() */
  8416. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  8417. );
  8418. int (*xPhraseCount)(Fts5Context*);
  8419. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  8420. int (*xInstCount)(Fts5Context*, int *pnInst);
  8421. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  8422. sqlite3_int64 (*xRowid)(Fts5Context*);
  8423. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  8424. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  8425. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  8426. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  8427. );
  8428. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  8429. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  8430. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  8431. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  8432. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  8433. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  8434. };
  8435. /*
  8436. ** CUSTOM AUXILIARY FUNCTIONS
  8437. *************************************************************************/
  8438. /*************************************************************************
  8439. ** CUSTOM TOKENIZERS
  8440. **
  8441. ** Applications may also register custom tokenizer types. A tokenizer
  8442. ** is registered by providing fts5 with a populated instance of the
  8443. ** following structure. All structure methods must be defined, setting
  8444. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  8445. ** behaviour. The structure methods are expected to function as follows:
  8446. **
  8447. ** xCreate:
  8448. ** This function is used to allocate and inititalize a tokenizer instance.
  8449. ** A tokenizer instance is required to actually tokenize text.
  8450. **
  8451. ** The first argument passed to this function is a copy of the (void*)
  8452. ** pointer provided by the application when the fts5_tokenizer object
  8453. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  8454. ** The second and third arguments are an array of nul-terminated strings
  8455. ** containing the tokenizer arguments, if any, specified following the
  8456. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  8457. ** to create the FTS5 table.
  8458. **
  8459. ** The final argument is an output variable. If successful, (*ppOut)
  8460. ** should be set to point to the new tokenizer handle and SQLITE_OK
  8461. ** returned. If an error occurs, some value other than SQLITE_OK should
  8462. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  8463. ** is undefined.
  8464. **
  8465. ** xDelete:
  8466. ** This function is invoked to delete a tokenizer handle previously
  8467. ** allocated using xCreate(). Fts5 guarantees that this function will
  8468. ** be invoked exactly once for each successful call to xCreate().
  8469. **
  8470. ** xTokenize:
  8471. ** This function is expected to tokenize the nText byte string indicated
  8472. ** by argument pText. pText may or may not be nul-terminated. The first
  8473. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  8474. ** returned by an earlier call to xCreate().
  8475. **
  8476. ** The second argument indicates the reason that FTS5 is requesting
  8477. ** tokenization of the supplied text. This is always one of the following
  8478. ** four values:
  8479. **
  8480. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  8481. ** or removed from the FTS table. The tokenizer is being invoked to
  8482. ** determine the set of tokens to add to (or delete from) the
  8483. ** FTS index.
  8484. **
  8485. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  8486. ** against the FTS index. The tokenizer is being called to tokenize
  8487. ** a bareword or quoted string specified as part of the query.
  8488. **
  8489. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  8490. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  8491. ** followed by a "*" character, indicating that the last token
  8492. ** returned by the tokenizer will be treated as a token prefix.
  8493. **
  8494. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  8495. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  8496. ** function. Or an fts5_api.xColumnSize() request made by the same
  8497. ** on a columnsize=0 database.
  8498. ** </ul>
  8499. **
  8500. ** For each token in the input string, the supplied callback xToken() must
  8501. ** be invoked. The first argument to it should be a copy of the pointer
  8502. ** passed as the second argument to xTokenize(). The third and fourth
  8503. ** arguments are a pointer to a buffer containing the token text, and the
  8504. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  8505. ** of the first byte of and first byte immediately following the text from
  8506. ** which the token is derived within the input.
  8507. **
  8508. ** The second argument passed to the xToken() callback ("tflags") should
  8509. ** normally be set to 0. The exception is if the tokenizer supports
  8510. ** synonyms. In this case see the discussion below for details.
  8511. **
  8512. ** FTS5 assumes the xToken() callback is invoked for each token in the
  8513. ** order that they occur within the input text.
  8514. **
  8515. ** If an xToken() callback returns any value other than SQLITE_OK, then
  8516. ** the tokenization should be abandoned and the xTokenize() method should
  8517. ** immediately return a copy of the xToken() return value. Or, if the
  8518. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  8519. ** if an error occurs with the xTokenize() implementation itself, it
  8520. ** may abandon the tokenization and return any error code other than
  8521. ** SQLITE_OK or SQLITE_DONE.
  8522. **
  8523. ** SYNONYM SUPPORT
  8524. **
  8525. ** Custom tokenizers may also support synonyms. Consider a case in which a
  8526. ** user wishes to query for a phrase such as "first place". Using the
  8527. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  8528. ** of "first place" within the document set, but not alternative forms
  8529. ** such as "1st place". In some applications, it would be better to match
  8530. ** all instances of "first place" or "1st place" regardless of which form
  8531. ** the user specified in the MATCH query text.
  8532. **
  8533. ** There are several ways to approach this in FTS5:
  8534. **
  8535. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  8536. ** In the above example, this means that the tokenizer returns the
  8537. ** same token for inputs "first" and "1st". Say that token is in
  8538. ** fact "first", so that when the user inserts the document "I won
  8539. ** 1st place" entries are added to the index for tokens "i", "won",
  8540. ** "first" and "place". If the user then queries for '1st + place',
  8541. ** the tokenizer substitutes "first" for "1st" and the query works
  8542. ** as expected.
  8543. **
  8544. ** <li> By adding multiple synonyms for a single term to the FTS index.
  8545. ** In this case, when tokenizing query text, the tokenizer may
  8546. ** provide multiple synonyms for a single term within the document.
  8547. ** FTS5 then queries the index for each synonym individually. For
  8548. ** example, faced with the query:
  8549. **
  8550. ** <codeblock>
  8551. ** ... MATCH 'first place'</codeblock>
  8552. **
  8553. ** the tokenizer offers both "1st" and "first" as synonyms for the
  8554. ** first token in the MATCH query and FTS5 effectively runs a query
  8555. ** similar to:
  8556. **
  8557. ** <codeblock>
  8558. ** ... MATCH '(first OR 1st) place'</codeblock>
  8559. **
  8560. ** except that, for the purposes of auxiliary functions, the query
  8561. ** still appears to contain just two phrases - "(first OR 1st)"
  8562. ** being treated as a single phrase.
  8563. **
  8564. ** <li> By adding multiple synonyms for a single term to the FTS index.
  8565. ** Using this method, when tokenizing document text, the tokenizer
  8566. ** provides multiple synonyms for each token. So that when a
  8567. ** document such as "I won first place" is tokenized, entries are
  8568. ** added to the FTS index for "i", "won", "first", "1st" and
  8569. ** "place".
  8570. **
  8571. ** This way, even if the tokenizer does not provide synonyms
  8572. ** when tokenizing query text (it should not - to do would be
  8573. ** inefficient), it doesn't matter if the user queries for
  8574. ** 'first + place' or '1st + place', as there are entires in the
  8575. ** FTS index corresponding to both forms of the first token.
  8576. ** </ol>
  8577. **
  8578. ** Whether it is parsing document or query text, any call to xToken that
  8579. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  8580. ** is considered to supply a synonym for the previous token. For example,
  8581. ** when parsing the document "I won first place", a tokenizer that supports
  8582. ** synonyms would call xToken() 5 times, as follows:
  8583. **
  8584. ** <codeblock>
  8585. ** xToken(pCtx, 0, "i", 1, 0, 1);
  8586. ** xToken(pCtx, 0, "won", 3, 2, 5);
  8587. ** xToken(pCtx, 0, "first", 5, 6, 11);
  8588. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  8589. ** xToken(pCtx, 0, "place", 5, 12, 17);
  8590. **</codeblock>
  8591. **
  8592. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  8593. ** xToken() is called. Multiple synonyms may be specified for a single token
  8594. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  8595. ** There is no limit to the number of synonyms that may be provided for a
  8596. ** single token.
  8597. **
  8598. ** In many cases, method (1) above is the best approach. It does not add
  8599. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  8600. ** so it is efficient in terms of disk space and query speed. However, it
  8601. ** does not support prefix queries very well. If, as suggested above, the
  8602. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  8603. **
  8604. ** <codeblock>
  8605. ** ... MATCH '1s*'</codeblock>
  8606. **
  8607. ** will not match documents that contain the token "1st" (as the tokenizer
  8608. ** will probably not map "1s" to any prefix of "first").
  8609. **
  8610. ** For full prefix support, method (3) may be preferred. In this case,
  8611. ** because the index contains entries for both "first" and "1st", prefix
  8612. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  8613. ** extra entries are added to the FTS index, this method uses more space
  8614. ** within the database.
  8615. **
  8616. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  8617. ** a query such as '1s*' will match documents that contain the literal
  8618. ** token "1st", but not "first" (assuming the tokenizer is not able to
  8619. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  8620. ** will match against "1st" and "first". This method does not require
  8621. ** extra disk space, as no extra entries are added to the FTS index.
  8622. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  8623. ** as separate queries of the FTS index are required for each synonym.
  8624. **
  8625. ** When using methods (2) or (3), it is important that the tokenizer only
  8626. ** provide synonyms when tokenizing document text (method (2)) or query
  8627. ** text (method (3)), not both. Doing so will not cause any errors, but is
  8628. ** inefficient.
  8629. */
  8630. typedef struct Fts5Tokenizer Fts5Tokenizer;
  8631. typedef struct fts5_tokenizer fts5_tokenizer;
  8632. struct fts5_tokenizer {
  8633. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  8634. void (*xDelete)(Fts5Tokenizer*);
  8635. int (*xTokenize)(Fts5Tokenizer*,
  8636. void *pCtx,
  8637. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  8638. const char *pText, int nText,
  8639. int (*xToken)(
  8640. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  8641. int tflags, /* Mask of FTS5_TOKEN_* flags */
  8642. const char *pToken, /* Pointer to buffer containing token */
  8643. int nToken, /* Size of token in bytes */
  8644. int iStart, /* Byte offset of token within input text */
  8645. int iEnd /* Byte offset of end of token within input text */
  8646. )
  8647. );
  8648. };
  8649. /* Flags that may be passed as the third argument to xTokenize() */
  8650. #define FTS5_TOKENIZE_QUERY 0x0001
  8651. #define FTS5_TOKENIZE_PREFIX 0x0002
  8652. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  8653. #define FTS5_TOKENIZE_AUX 0x0008
  8654. /* Flags that may be passed by the tokenizer implementation back to FTS5
  8655. ** as the third argument to the supplied xToken callback. */
  8656. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  8657. /*
  8658. ** END OF CUSTOM TOKENIZERS
  8659. *************************************************************************/
  8660. /*************************************************************************
  8661. ** FTS5 EXTENSION REGISTRATION API
  8662. */
  8663. typedef struct fts5_api fts5_api;
  8664. struct fts5_api {
  8665. int iVersion; /* Currently always set to 2 */
  8666. /* Create a new tokenizer */
  8667. int (*xCreateTokenizer)(
  8668. fts5_api *pApi,
  8669. const char *zName,
  8670. void *pContext,
  8671. fts5_tokenizer *pTokenizer,
  8672. void (*xDestroy)(void*)
  8673. );
  8674. /* Find an existing tokenizer */
  8675. int (*xFindTokenizer)(
  8676. fts5_api *pApi,
  8677. const char *zName,
  8678. void **ppContext,
  8679. fts5_tokenizer *pTokenizer
  8680. );
  8681. /* Create a new auxiliary function */
  8682. int (*xCreateFunction)(
  8683. fts5_api *pApi,
  8684. const char *zName,
  8685. void *pContext,
  8686. fts5_extension_function xFunction,
  8687. void (*xDestroy)(void*)
  8688. );
  8689. };
  8690. /*
  8691. ** END OF REGISTRATION API
  8692. *************************************************************************/
  8693. #if 0
  8694. } /* end of the 'extern "C"' block */
  8695. #endif
  8696. #endif /* _FTS5_H */
  8697. /************** End of sqlite3.h *********************************************/
  8698. /************** Continuing where we left off in sqliteInt.h ******************/
  8699. /*
  8700. ** Include the configuration header output by 'configure' if we're using the
  8701. ** autoconf-based build
  8702. */
  8703. #ifdef _HAVE_SQLITE_CONFIG_H
  8704. #include "config.h"
  8705. #endif
  8706. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  8707. /************** Begin file sqliteLimit.h *************************************/
  8708. /*
  8709. ** 2007 May 7
  8710. **
  8711. ** The author disclaims copyright to this source code. In place of
  8712. ** a legal notice, here is a blessing:
  8713. **
  8714. ** May you do good and not evil.
  8715. ** May you find forgiveness for yourself and forgive others.
  8716. ** May you share freely, never taking more than you give.
  8717. **
  8718. *************************************************************************
  8719. **
  8720. ** This file defines various limits of what SQLite can process.
  8721. */
  8722. /*
  8723. ** The maximum length of a TEXT or BLOB in bytes. This also
  8724. ** limits the size of a row in a table or index.
  8725. **
  8726. ** The hard limit is the ability of a 32-bit signed integer
  8727. ** to count the size: 2^31-1 or 2147483647.
  8728. */
  8729. #ifndef SQLITE_MAX_LENGTH
  8730. # define SQLITE_MAX_LENGTH 1000000000
  8731. #endif
  8732. /*
  8733. ** This is the maximum number of
  8734. **
  8735. ** * Columns in a table
  8736. ** * Columns in an index
  8737. ** * Columns in a view
  8738. ** * Terms in the SET clause of an UPDATE statement
  8739. ** * Terms in the result set of a SELECT statement
  8740. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  8741. ** * Terms in the VALUES clause of an INSERT statement
  8742. **
  8743. ** The hard upper limit here is 32676. Most database people will
  8744. ** tell you that in a well-normalized database, you usually should
  8745. ** not have more than a dozen or so columns in any table. And if
  8746. ** that is the case, there is no point in having more than a few
  8747. ** dozen values in any of the other situations described above.
  8748. */
  8749. #ifndef SQLITE_MAX_COLUMN
  8750. # define SQLITE_MAX_COLUMN 2000
  8751. #endif
  8752. /*
  8753. ** The maximum length of a single SQL statement in bytes.
  8754. **
  8755. ** It used to be the case that setting this value to zero would
  8756. ** turn the limit off. That is no longer true. It is not possible
  8757. ** to turn this limit off.
  8758. */
  8759. #ifndef SQLITE_MAX_SQL_LENGTH
  8760. # define SQLITE_MAX_SQL_LENGTH 1000000000
  8761. #endif
  8762. /*
  8763. ** The maximum depth of an expression tree. This is limited to
  8764. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  8765. ** want to place more severe limits on the complexity of an
  8766. ** expression.
  8767. **
  8768. ** A value of 0 used to mean that the limit was not enforced.
  8769. ** But that is no longer true. The limit is now strictly enforced
  8770. ** at all times.
  8771. */
  8772. #ifndef SQLITE_MAX_EXPR_DEPTH
  8773. # define SQLITE_MAX_EXPR_DEPTH 1000
  8774. #endif
  8775. /*
  8776. ** The maximum number of terms in a compound SELECT statement.
  8777. ** The code generator for compound SELECT statements does one
  8778. ** level of recursion for each term. A stack overflow can result
  8779. ** if the number of terms is too large. In practice, most SQL
  8780. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  8781. ** any limit on the number of terms in a compount SELECT.
  8782. */
  8783. #ifndef SQLITE_MAX_COMPOUND_SELECT
  8784. # define SQLITE_MAX_COMPOUND_SELECT 500
  8785. #endif
  8786. /*
  8787. ** The maximum number of opcodes in a VDBE program.
  8788. ** Not currently enforced.
  8789. */
  8790. #ifndef SQLITE_MAX_VDBE_OP
  8791. # define SQLITE_MAX_VDBE_OP 25000
  8792. #endif
  8793. /*
  8794. ** The maximum number of arguments to an SQL function.
  8795. */
  8796. #ifndef SQLITE_MAX_FUNCTION_ARG
  8797. # define SQLITE_MAX_FUNCTION_ARG 127
  8798. #endif
  8799. /*
  8800. ** The suggested maximum number of in-memory pages to use for
  8801. ** the main database table and for temporary tables.
  8802. **
  8803. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  8804. ** which means the cache size is limited to 2048000 bytes of memory.
  8805. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  8806. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  8807. */
  8808. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  8809. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  8810. #endif
  8811. /*
  8812. ** The default number of frames to accumulate in the log file before
  8813. ** checkpointing the database in WAL mode.
  8814. */
  8815. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  8816. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  8817. #endif
  8818. /*
  8819. ** The maximum number of attached databases. This must be between 0
  8820. ** and 125. The upper bound of 125 is because the attached databases are
  8821. ** counted using a signed 8-bit integer which has a maximum value of 127
  8822. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  8823. */
  8824. #ifndef SQLITE_MAX_ATTACHED
  8825. # define SQLITE_MAX_ATTACHED 10
  8826. #endif
  8827. /*
  8828. ** The maximum value of a ?nnn wildcard that the parser will accept.
  8829. */
  8830. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  8831. # define SQLITE_MAX_VARIABLE_NUMBER 999
  8832. #endif
  8833. /* Maximum page size. The upper bound on this value is 65536. This a limit
  8834. ** imposed by the use of 16-bit offsets within each page.
  8835. **
  8836. ** Earlier versions of SQLite allowed the user to change this value at
  8837. ** compile time. This is no longer permitted, on the grounds that it creates
  8838. ** a library that is technically incompatible with an SQLite library
  8839. ** compiled with a different limit. If a process operating on a database
  8840. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  8841. ** compiled with the default page-size limit will not be able to rollback
  8842. ** the aborted transaction. This could lead to database corruption.
  8843. */
  8844. #ifdef SQLITE_MAX_PAGE_SIZE
  8845. # undef SQLITE_MAX_PAGE_SIZE
  8846. #endif
  8847. #define SQLITE_MAX_PAGE_SIZE 65536
  8848. /*
  8849. ** The default size of a database page.
  8850. */
  8851. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  8852. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  8853. #endif
  8854. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8855. # undef SQLITE_DEFAULT_PAGE_SIZE
  8856. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8857. #endif
  8858. /*
  8859. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  8860. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  8861. ** device characteristics (sector-size and atomic write() support),
  8862. ** SQLite may choose a larger value. This constant is the maximum value
  8863. ** SQLite will choose on its own.
  8864. */
  8865. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8866. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  8867. #endif
  8868. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8869. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8870. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8871. #endif
  8872. /*
  8873. ** Maximum number of pages in one database file.
  8874. **
  8875. ** This is really just the default value for the max_page_count pragma.
  8876. ** This value can be lowered (or raised) at run-time using that the
  8877. ** max_page_count macro.
  8878. */
  8879. #ifndef SQLITE_MAX_PAGE_COUNT
  8880. # define SQLITE_MAX_PAGE_COUNT 1073741823
  8881. #endif
  8882. /*
  8883. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  8884. ** operator.
  8885. */
  8886. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  8887. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  8888. #endif
  8889. /*
  8890. ** Maximum depth of recursion for triggers.
  8891. **
  8892. ** A value of 1 means that a trigger program will not be able to itself
  8893. ** fire any triggers. A value of 0 means that no trigger programs at all
  8894. ** may be executed.
  8895. */
  8896. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  8897. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  8898. #endif
  8899. /************** End of sqliteLimit.h *****************************************/
  8900. /************** Continuing where we left off in sqliteInt.h ******************/
  8901. /* Disable nuisance warnings on Borland compilers */
  8902. #if defined(__BORLANDC__)
  8903. #pragma warn -rch /* unreachable code */
  8904. #pragma warn -ccc /* Condition is always true or false */
  8905. #pragma warn -aus /* Assigned value is never used */
  8906. #pragma warn -csu /* Comparing signed and unsigned */
  8907. #pragma warn -spa /* Suspicious pointer arithmetic */
  8908. #endif
  8909. /*
  8910. ** Include standard header files as necessary
  8911. */
  8912. #ifdef HAVE_STDINT_H
  8913. #include <stdint.h>
  8914. #endif
  8915. #ifdef HAVE_INTTYPES_H
  8916. #include <inttypes.h>
  8917. #endif
  8918. /*
  8919. ** The following macros are used to cast pointers to integers and
  8920. ** integers to pointers. The way you do this varies from one compiler
  8921. ** to the next, so we have developed the following set of #if statements
  8922. ** to generate appropriate macros for a wide range of compilers.
  8923. **
  8924. ** The correct "ANSI" way to do this is to use the intptr_t type.
  8925. ** Unfortunately, that typedef is not available on all compilers, or
  8926. ** if it is available, it requires an #include of specific headers
  8927. ** that vary from one machine to the next.
  8928. **
  8929. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  8930. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  8931. ** So we have to define the macros in different ways depending on the
  8932. ** compiler.
  8933. */
  8934. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  8935. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  8936. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  8937. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  8938. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  8939. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  8940. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  8941. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  8942. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  8943. #else /* Generates a warning - but it always works */
  8944. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  8945. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  8946. #endif
  8947. /*
  8948. ** A macro to hint to the compiler that a function should not be
  8949. ** inlined.
  8950. */
  8951. #if defined(__GNUC__)
  8952. # define SQLITE_NOINLINE __attribute__((noinline))
  8953. #elif defined(_MSC_VER) && _MSC_VER>=1310
  8954. # define SQLITE_NOINLINE __declspec(noinline)
  8955. #else
  8956. # define SQLITE_NOINLINE
  8957. #endif
  8958. /*
  8959. ** Make sure that the compiler intrinsics we desire are enabled when
  8960. ** compiling with an appropriate version of MSVC unless prevented by
  8961. ** the SQLITE_DISABLE_INTRINSIC define.
  8962. */
  8963. #if !defined(SQLITE_DISABLE_INTRINSIC)
  8964. # if defined(_MSC_VER) && _MSC_VER>=1300
  8965. # if !defined(_WIN32_WCE)
  8966. # include <intrin.h>
  8967. # pragma intrinsic(_byteswap_ushort)
  8968. # pragma intrinsic(_byteswap_ulong)
  8969. # pragma intrinsic(_ReadWriteBarrier)
  8970. # else
  8971. # include <cmnintrin.h>
  8972. # endif
  8973. # endif
  8974. #endif
  8975. /*
  8976. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  8977. ** 0 means mutexes are permanently disable and the library is never
  8978. ** threadsafe. 1 means the library is serialized which is the highest
  8979. ** level of threadsafety. 2 means the library is multithreaded - multiple
  8980. ** threads can use SQLite as long as no two threads try to use the same
  8981. ** database connection at the same time.
  8982. **
  8983. ** Older versions of SQLite used an optional THREADSAFE macro.
  8984. ** We support that for legacy.
  8985. */
  8986. #if !defined(SQLITE_THREADSAFE)
  8987. # if defined(THREADSAFE)
  8988. # define SQLITE_THREADSAFE THREADSAFE
  8989. # else
  8990. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  8991. # endif
  8992. #endif
  8993. /*
  8994. ** Powersafe overwrite is on by default. But can be turned off using
  8995. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  8996. */
  8997. #ifndef SQLITE_POWERSAFE_OVERWRITE
  8998. # define SQLITE_POWERSAFE_OVERWRITE 1
  8999. #endif
  9000. /*
  9001. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  9002. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  9003. ** which case memory allocation statistics are disabled by default.
  9004. */
  9005. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  9006. # define SQLITE_DEFAULT_MEMSTATUS 1
  9007. #endif
  9008. /*
  9009. ** Exactly one of the following macros must be defined in order to
  9010. ** specify which memory allocation subsystem to use.
  9011. **
  9012. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  9013. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  9014. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  9015. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  9016. **
  9017. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  9018. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  9019. ** will cause HeapValidate to be called. If heap validation should fail, an
  9020. ** assertion will be triggered.
  9021. **
  9022. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  9023. ** the default.
  9024. */
  9025. #if defined(SQLITE_SYSTEM_MALLOC) \
  9026. + defined(SQLITE_WIN32_MALLOC) \
  9027. + defined(SQLITE_ZERO_MALLOC) \
  9028. + defined(SQLITE_MEMDEBUG)>1
  9029. # error "Two or more of the following compile-time configuration options\
  9030. are defined but at most one is allowed:\
  9031. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  9032. SQLITE_ZERO_MALLOC"
  9033. #endif
  9034. #if defined(SQLITE_SYSTEM_MALLOC) \
  9035. + defined(SQLITE_WIN32_MALLOC) \
  9036. + defined(SQLITE_ZERO_MALLOC) \
  9037. + defined(SQLITE_MEMDEBUG)==0
  9038. # define SQLITE_SYSTEM_MALLOC 1
  9039. #endif
  9040. /*
  9041. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  9042. ** sizes of memory allocations below this value where possible.
  9043. */
  9044. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  9045. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  9046. #endif
  9047. /*
  9048. ** We need to define _XOPEN_SOURCE as follows in order to enable
  9049. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  9050. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  9051. ** it.
  9052. */
  9053. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  9054. # define _XOPEN_SOURCE 600
  9055. #endif
  9056. /*
  9057. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  9058. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  9059. ** make it true by defining or undefining NDEBUG.
  9060. **
  9061. ** Setting NDEBUG makes the code smaller and faster by disabling the
  9062. ** assert() statements in the code. So we want the default action
  9063. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  9064. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  9065. ** feature.
  9066. */
  9067. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  9068. # define NDEBUG 1
  9069. #endif
  9070. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  9071. # undef NDEBUG
  9072. #endif
  9073. /*
  9074. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  9075. */
  9076. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  9077. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  9078. #endif
  9079. /*
  9080. ** The testcase() macro is used to aid in coverage testing. When
  9081. ** doing coverage testing, the condition inside the argument to
  9082. ** testcase() must be evaluated both true and false in order to
  9083. ** get full branch coverage. The testcase() macro is inserted
  9084. ** to help ensure adequate test coverage in places where simple
  9085. ** condition/decision coverage is inadequate. For example, testcase()
  9086. ** can be used to make sure boundary values are tested. For
  9087. ** bitmask tests, testcase() can be used to make sure each bit
  9088. ** is significant and used at least once. On switch statements
  9089. ** where multiple cases go to the same block of code, testcase()
  9090. ** can insure that all cases are evaluated.
  9091. **
  9092. */
  9093. #ifdef SQLITE_COVERAGE_TEST
  9094. SQLITE_PRIVATE void sqlite3Coverage(int);
  9095. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  9096. #else
  9097. # define testcase(X)
  9098. #endif
  9099. /*
  9100. ** The TESTONLY macro is used to enclose variable declarations or
  9101. ** other bits of code that are needed to support the arguments
  9102. ** within testcase() and assert() macros.
  9103. */
  9104. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  9105. # define TESTONLY(X) X
  9106. #else
  9107. # define TESTONLY(X)
  9108. #endif
  9109. /*
  9110. ** Sometimes we need a small amount of code such as a variable initialization
  9111. ** to setup for a later assert() statement. We do not want this code to
  9112. ** appear when assert() is disabled. The following macro is therefore
  9113. ** used to contain that setup code. The "VVA" acronym stands for
  9114. ** "Verification, Validation, and Accreditation". In other words, the
  9115. ** code within VVA_ONLY() will only run during verification processes.
  9116. */
  9117. #ifndef NDEBUG
  9118. # define VVA_ONLY(X) X
  9119. #else
  9120. # define VVA_ONLY(X)
  9121. #endif
  9122. /*
  9123. ** The ALWAYS and NEVER macros surround boolean expressions which
  9124. ** are intended to always be true or false, respectively. Such
  9125. ** expressions could be omitted from the code completely. But they
  9126. ** are included in a few cases in order to enhance the resilience
  9127. ** of SQLite to unexpected behavior - to make the code "self-healing"
  9128. ** or "ductile" rather than being "brittle" and crashing at the first
  9129. ** hint of unplanned behavior.
  9130. **
  9131. ** In other words, ALWAYS and NEVER are added for defensive code.
  9132. **
  9133. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  9134. ** be true and false so that the unreachable code they specify will
  9135. ** not be counted as untested code.
  9136. */
  9137. #if defined(SQLITE_COVERAGE_TEST)
  9138. # define ALWAYS(X) (1)
  9139. # define NEVER(X) (0)
  9140. #elif !defined(NDEBUG)
  9141. # define ALWAYS(X) ((X)?1:(assert(0),0))
  9142. # define NEVER(X) ((X)?(assert(0),1):0)
  9143. #else
  9144. # define ALWAYS(X) (X)
  9145. # define NEVER(X) (X)
  9146. #endif
  9147. /*
  9148. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  9149. ** defined. We need to defend against those failures when testing with
  9150. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  9151. ** during a normal build. The following macro can be used to disable tests
  9152. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  9153. */
  9154. #if defined(SQLITE_TEST_REALLOC_STRESS)
  9155. # define ONLY_IF_REALLOC_STRESS(X) (X)
  9156. #elif !defined(NDEBUG)
  9157. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  9158. #else
  9159. # define ONLY_IF_REALLOC_STRESS(X) (0)
  9160. #endif
  9161. /*
  9162. ** Declarations used for tracing the operating system interfaces.
  9163. */
  9164. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  9165. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  9166. extern int sqlite3OSTrace;
  9167. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  9168. # define SQLITE_HAVE_OS_TRACE
  9169. #else
  9170. # define OSTRACE(X)
  9171. # undef SQLITE_HAVE_OS_TRACE
  9172. #endif
  9173. /*
  9174. ** Is the sqlite3ErrName() function needed in the build? Currently,
  9175. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  9176. ** OSTRACE is enabled), and by several "test*.c" files (which are
  9177. ** compiled using SQLITE_TEST).
  9178. */
  9179. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  9180. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  9181. # define SQLITE_NEED_ERR_NAME
  9182. #else
  9183. # undef SQLITE_NEED_ERR_NAME
  9184. #endif
  9185. /*
  9186. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  9187. */
  9188. #ifdef SQLITE_OMIT_EXPLAIN
  9189. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9190. #endif
  9191. /*
  9192. ** Return true (non-zero) if the input is an integer that is too large
  9193. ** to fit in 32-bits. This macro is used inside of various testcase()
  9194. ** macros to verify that we have tested SQLite for large-file support.
  9195. */
  9196. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  9197. /*
  9198. ** The macro unlikely() is a hint that surrounds a boolean
  9199. ** expression that is usually false. Macro likely() surrounds
  9200. ** a boolean expression that is usually true. These hints could,
  9201. ** in theory, be used by the compiler to generate better code, but
  9202. ** currently they are just comments for human readers.
  9203. */
  9204. #define likely(X) (X)
  9205. #define unlikely(X) (X)
  9206. /************** Include hash.h in the middle of sqliteInt.h ******************/
  9207. /************** Begin file hash.h ********************************************/
  9208. /*
  9209. ** 2001 September 22
  9210. **
  9211. ** The author disclaims copyright to this source code. In place of
  9212. ** a legal notice, here is a blessing:
  9213. **
  9214. ** May you do good and not evil.
  9215. ** May you find forgiveness for yourself and forgive others.
  9216. ** May you share freely, never taking more than you give.
  9217. **
  9218. *************************************************************************
  9219. ** This is the header file for the generic hash-table implementation
  9220. ** used in SQLite.
  9221. */
  9222. #ifndef _SQLITE_HASH_H_
  9223. #define _SQLITE_HASH_H_
  9224. /* Forward declarations of structures. */
  9225. typedef struct Hash Hash;
  9226. typedef struct HashElem HashElem;
  9227. /* A complete hash table is an instance of the following structure.
  9228. ** The internals of this structure are intended to be opaque -- client
  9229. ** code should not attempt to access or modify the fields of this structure
  9230. ** directly. Change this structure only by using the routines below.
  9231. ** However, some of the "procedures" and "functions" for modifying and
  9232. ** accessing this structure are really macros, so we can't really make
  9233. ** this structure opaque.
  9234. **
  9235. ** All elements of the hash table are on a single doubly-linked list.
  9236. ** Hash.first points to the head of this list.
  9237. **
  9238. ** There are Hash.htsize buckets. Each bucket points to a spot in
  9239. ** the global doubly-linked list. The contents of the bucket are the
  9240. ** element pointed to plus the next _ht.count-1 elements in the list.
  9241. **
  9242. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  9243. ** by a linear search of the global list. For small tables, the
  9244. ** Hash.ht table is never allocated because if there are few elements
  9245. ** in the table, it is faster to do a linear search than to manage
  9246. ** the hash table.
  9247. */
  9248. struct Hash {
  9249. unsigned int htsize; /* Number of buckets in the hash table */
  9250. unsigned int count; /* Number of entries in this table */
  9251. HashElem *first; /* The first element of the array */
  9252. struct _ht { /* the hash table */
  9253. int count; /* Number of entries with this hash */
  9254. HashElem *chain; /* Pointer to first entry with this hash */
  9255. } *ht;
  9256. };
  9257. /* Each element in the hash table is an instance of the following
  9258. ** structure. All elements are stored on a single doubly-linked list.
  9259. **
  9260. ** Again, this structure is intended to be opaque, but it can't really
  9261. ** be opaque because it is used by macros.
  9262. */
  9263. struct HashElem {
  9264. HashElem *next, *prev; /* Next and previous elements in the table */
  9265. void *data; /* Data associated with this element */
  9266. const char *pKey; /* Key associated with this element */
  9267. };
  9268. /*
  9269. ** Access routines. To delete, insert a NULL pointer.
  9270. */
  9271. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  9272. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  9273. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  9274. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  9275. /*
  9276. ** Macros for looping over all elements of a hash table. The idiom is
  9277. ** like this:
  9278. **
  9279. ** Hash h;
  9280. ** HashElem *p;
  9281. ** ...
  9282. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  9283. ** SomeStructure *pData = sqliteHashData(p);
  9284. ** // do something with pData
  9285. ** }
  9286. */
  9287. #define sqliteHashFirst(H) ((H)->first)
  9288. #define sqliteHashNext(E) ((E)->next)
  9289. #define sqliteHashData(E) ((E)->data)
  9290. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  9291. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  9292. /*
  9293. ** Number of entries in a hash table
  9294. */
  9295. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  9296. #endif /* _SQLITE_HASH_H_ */
  9297. /************** End of hash.h ************************************************/
  9298. /************** Continuing where we left off in sqliteInt.h ******************/
  9299. /************** Include parse.h in the middle of sqliteInt.h *****************/
  9300. /************** Begin file parse.h *******************************************/
  9301. #define TK_SEMI 1
  9302. #define TK_EXPLAIN 2
  9303. #define TK_QUERY 3
  9304. #define TK_PLAN 4
  9305. #define TK_BEGIN 5
  9306. #define TK_TRANSACTION 6
  9307. #define TK_DEFERRED 7
  9308. #define TK_IMMEDIATE 8
  9309. #define TK_EXCLUSIVE 9
  9310. #define TK_COMMIT 10
  9311. #define TK_END 11
  9312. #define TK_ROLLBACK 12
  9313. #define TK_SAVEPOINT 13
  9314. #define TK_RELEASE 14
  9315. #define TK_TO 15
  9316. #define TK_TABLE 16
  9317. #define TK_CREATE 17
  9318. #define TK_IF 18
  9319. #define TK_NOT 19
  9320. #define TK_EXISTS 20
  9321. #define TK_TEMP 21
  9322. #define TK_LP 22
  9323. #define TK_RP 23
  9324. #define TK_AS 24
  9325. #define TK_WITHOUT 25
  9326. #define TK_COMMA 26
  9327. #define TK_ID 27
  9328. #define TK_INDEXED 28
  9329. #define TK_ABORT 29
  9330. #define TK_ACTION 30
  9331. #define TK_AFTER 31
  9332. #define TK_ANALYZE 32
  9333. #define TK_ASC 33
  9334. #define TK_ATTACH 34
  9335. #define TK_BEFORE 35
  9336. #define TK_BY 36
  9337. #define TK_CASCADE 37
  9338. #define TK_CAST 38
  9339. #define TK_COLUMNKW 39
  9340. #define TK_CONFLICT 40
  9341. #define TK_DATABASE 41
  9342. #define TK_DESC 42
  9343. #define TK_DETACH 43
  9344. #define TK_EACH 44
  9345. #define TK_FAIL 45
  9346. #define TK_FOR 46
  9347. #define TK_IGNORE 47
  9348. #define TK_INITIALLY 48
  9349. #define TK_INSTEAD 49
  9350. #define TK_LIKE_KW 50
  9351. #define TK_MATCH 51
  9352. #define TK_NO 52
  9353. #define TK_KEY 53
  9354. #define TK_OF 54
  9355. #define TK_OFFSET 55
  9356. #define TK_PRAGMA 56
  9357. #define TK_RAISE 57
  9358. #define TK_RECURSIVE 58
  9359. #define TK_REPLACE 59
  9360. #define TK_RESTRICT 60
  9361. #define TK_ROW 61
  9362. #define TK_TRIGGER 62
  9363. #define TK_VACUUM 63
  9364. #define TK_VIEW 64
  9365. #define TK_VIRTUAL 65
  9366. #define TK_WITH 66
  9367. #define TK_REINDEX 67
  9368. #define TK_RENAME 68
  9369. #define TK_CTIME_KW 69
  9370. #define TK_ANY 70
  9371. #define TK_OR 71
  9372. #define TK_AND 72
  9373. #define TK_IS 73
  9374. #define TK_BETWEEN 74
  9375. #define TK_IN 75
  9376. #define TK_ISNULL 76
  9377. #define TK_NOTNULL 77
  9378. #define TK_NE 78
  9379. #define TK_EQ 79
  9380. #define TK_GT 80
  9381. #define TK_LE 81
  9382. #define TK_LT 82
  9383. #define TK_GE 83
  9384. #define TK_ESCAPE 84
  9385. #define TK_BITAND 85
  9386. #define TK_BITOR 86
  9387. #define TK_LSHIFT 87
  9388. #define TK_RSHIFT 88
  9389. #define TK_PLUS 89
  9390. #define TK_MINUS 90
  9391. #define TK_STAR 91
  9392. #define TK_SLASH 92
  9393. #define TK_REM 93
  9394. #define TK_CONCAT 94
  9395. #define TK_COLLATE 95
  9396. #define TK_BITNOT 96
  9397. #define TK_STRING 97
  9398. #define TK_JOIN_KW 98
  9399. #define TK_CONSTRAINT 99
  9400. #define TK_DEFAULT 100
  9401. #define TK_NULL 101
  9402. #define TK_PRIMARY 102
  9403. #define TK_UNIQUE 103
  9404. #define TK_CHECK 104
  9405. #define TK_REFERENCES 105
  9406. #define TK_AUTOINCR 106
  9407. #define TK_ON 107
  9408. #define TK_INSERT 108
  9409. #define TK_DELETE 109
  9410. #define TK_UPDATE 110
  9411. #define TK_SET 111
  9412. #define TK_DEFERRABLE 112
  9413. #define TK_FOREIGN 113
  9414. #define TK_DROP 114
  9415. #define TK_UNION 115
  9416. #define TK_ALL 116
  9417. #define TK_EXCEPT 117
  9418. #define TK_INTERSECT 118
  9419. #define TK_SELECT 119
  9420. #define TK_VALUES 120
  9421. #define TK_DISTINCT 121
  9422. #define TK_DOT 122
  9423. #define TK_FROM 123
  9424. #define TK_JOIN 124
  9425. #define TK_USING 125
  9426. #define TK_ORDER 126
  9427. #define TK_GROUP 127
  9428. #define TK_HAVING 128
  9429. #define TK_LIMIT 129
  9430. #define TK_WHERE 130
  9431. #define TK_INTO 131
  9432. #define TK_INTEGER 132
  9433. #define TK_FLOAT 133
  9434. #define TK_BLOB 134
  9435. #define TK_VARIABLE 135
  9436. #define TK_CASE 136
  9437. #define TK_WHEN 137
  9438. #define TK_THEN 138
  9439. #define TK_ELSE 139
  9440. #define TK_INDEX 140
  9441. #define TK_ALTER 141
  9442. #define TK_ADD 142
  9443. #define TK_TO_TEXT 143
  9444. #define TK_TO_BLOB 144
  9445. #define TK_TO_NUMERIC 145
  9446. #define TK_TO_INT 146
  9447. #define TK_TO_REAL 147
  9448. #define TK_ISNOT 148
  9449. #define TK_END_OF_FILE 149
  9450. #define TK_UNCLOSED_STRING 150
  9451. #define TK_FUNCTION 151
  9452. #define TK_COLUMN 152
  9453. #define TK_AGG_FUNCTION 153
  9454. #define TK_AGG_COLUMN 154
  9455. #define TK_UMINUS 155
  9456. #define TK_UPLUS 156
  9457. #define TK_REGISTER 157
  9458. #define TK_ASTERISK 158
  9459. #define TK_SPAN 159
  9460. #define TK_SPACE 160
  9461. #define TK_ILLEGAL 161
  9462. /* The token codes above must all fit in 8 bits */
  9463. #define TKFLG_MASK 0xff
  9464. /* Flags that can be added to a token code when it is not
  9465. ** being stored in a u8: */
  9466. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  9467. /************** End of parse.h ***********************************************/
  9468. /************** Continuing where we left off in sqliteInt.h ******************/
  9469. #include <stdio.h>
  9470. #include <stdlib.h>
  9471. #include <string.h>
  9472. #include <assert.h>
  9473. #include <stddef.h>
  9474. /*
  9475. ** If compiling for a processor that lacks floating point support,
  9476. ** substitute integer for floating-point
  9477. */
  9478. #ifdef SQLITE_OMIT_FLOATING_POINT
  9479. # define double sqlite_int64
  9480. # define float sqlite_int64
  9481. # define LONGDOUBLE_TYPE sqlite_int64
  9482. # ifndef SQLITE_BIG_DBL
  9483. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  9484. # endif
  9485. # define SQLITE_OMIT_DATETIME_FUNCS 1
  9486. # define SQLITE_OMIT_TRACE 1
  9487. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  9488. # undef SQLITE_HAVE_ISNAN
  9489. #endif
  9490. #ifndef SQLITE_BIG_DBL
  9491. # define SQLITE_BIG_DBL (1e99)
  9492. #endif
  9493. /*
  9494. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  9495. ** afterward. Having this macro allows us to cause the C compiler
  9496. ** to omit code used by TEMP tables without messy #ifndef statements.
  9497. */
  9498. #ifdef SQLITE_OMIT_TEMPDB
  9499. #define OMIT_TEMPDB 1
  9500. #else
  9501. #define OMIT_TEMPDB 0
  9502. #endif
  9503. /*
  9504. ** The "file format" number is an integer that is incremented whenever
  9505. ** the VDBE-level file format changes. The following macros define the
  9506. ** the default file format for new databases and the maximum file format
  9507. ** that the library can read.
  9508. */
  9509. #define SQLITE_MAX_FILE_FORMAT 4
  9510. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  9511. # define SQLITE_DEFAULT_FILE_FORMAT 4
  9512. #endif
  9513. /*
  9514. ** Determine whether triggers are recursive by default. This can be
  9515. ** changed at run-time using a pragma.
  9516. */
  9517. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  9518. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  9519. #endif
  9520. /*
  9521. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  9522. ** on the command-line
  9523. */
  9524. #ifndef SQLITE_TEMP_STORE
  9525. # define SQLITE_TEMP_STORE 1
  9526. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  9527. #endif
  9528. /*
  9529. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  9530. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  9531. ** to zero.
  9532. */
  9533. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  9534. # undef SQLITE_MAX_WORKER_THREADS
  9535. # define SQLITE_MAX_WORKER_THREADS 0
  9536. #endif
  9537. #ifndef SQLITE_MAX_WORKER_THREADS
  9538. # define SQLITE_MAX_WORKER_THREADS 8
  9539. #endif
  9540. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  9541. # define SQLITE_DEFAULT_WORKER_THREADS 0
  9542. #endif
  9543. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  9544. # undef SQLITE_MAX_WORKER_THREADS
  9545. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  9546. #endif
  9547. /*
  9548. ** The default initial allocation for the pagecache when using separate
  9549. ** pagecaches for each database connection. A positive number is the
  9550. ** number of pages. A negative number N translations means that a buffer
  9551. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  9552. */
  9553. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  9554. # define SQLITE_DEFAULT_PCACHE_INITSZ 100
  9555. #endif
  9556. /*
  9557. ** GCC does not define the offsetof() macro so we'll have to do it
  9558. ** ourselves.
  9559. */
  9560. #ifndef offsetof
  9561. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  9562. #endif
  9563. /*
  9564. ** Macros to compute minimum and maximum of two numbers.
  9565. */
  9566. #ifndef MIN
  9567. # define MIN(A,B) ((A)<(B)?(A):(B))
  9568. #endif
  9569. #ifndef MAX
  9570. # define MAX(A,B) ((A)>(B)?(A):(B))
  9571. #endif
  9572. /*
  9573. ** Swap two objects of type TYPE.
  9574. */
  9575. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  9576. /*
  9577. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  9578. ** not, there are still machines out there that use EBCDIC.)
  9579. */
  9580. #if 'A' == '\301'
  9581. # define SQLITE_EBCDIC 1
  9582. #else
  9583. # define SQLITE_ASCII 1
  9584. #endif
  9585. /*
  9586. ** Integers of known sizes. These typedefs might change for architectures
  9587. ** where the sizes very. Preprocessor macros are available so that the
  9588. ** types can be conveniently redefined at compile-type. Like this:
  9589. **
  9590. ** cc '-DUINTPTR_TYPE=long long int' ...
  9591. */
  9592. #ifndef UINT32_TYPE
  9593. # ifdef HAVE_UINT32_T
  9594. # define UINT32_TYPE uint32_t
  9595. # else
  9596. # define UINT32_TYPE unsigned int
  9597. # endif
  9598. #endif
  9599. #ifndef UINT16_TYPE
  9600. # ifdef HAVE_UINT16_T
  9601. # define UINT16_TYPE uint16_t
  9602. # else
  9603. # define UINT16_TYPE unsigned short int
  9604. # endif
  9605. #endif
  9606. #ifndef INT16_TYPE
  9607. # ifdef HAVE_INT16_T
  9608. # define INT16_TYPE int16_t
  9609. # else
  9610. # define INT16_TYPE short int
  9611. # endif
  9612. #endif
  9613. #ifndef UINT8_TYPE
  9614. # ifdef HAVE_UINT8_T
  9615. # define UINT8_TYPE uint8_t
  9616. # else
  9617. # define UINT8_TYPE unsigned char
  9618. # endif
  9619. #endif
  9620. #ifndef INT8_TYPE
  9621. # ifdef HAVE_INT8_T
  9622. # define INT8_TYPE int8_t
  9623. # else
  9624. # define INT8_TYPE signed char
  9625. # endif
  9626. #endif
  9627. #ifndef LONGDOUBLE_TYPE
  9628. # define LONGDOUBLE_TYPE long double
  9629. #endif
  9630. typedef sqlite_int64 i64; /* 8-byte signed integer */
  9631. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  9632. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  9633. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  9634. typedef INT16_TYPE i16; /* 2-byte signed integer */
  9635. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  9636. typedef INT8_TYPE i8; /* 1-byte signed integer */
  9637. /*
  9638. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  9639. ** that can be stored in a u32 without loss of data. The value
  9640. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  9641. ** have to specify the value in the less intuitive manner shown:
  9642. */
  9643. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  9644. /*
  9645. ** The datatype used to store estimates of the number of rows in a
  9646. ** table or index. This is an unsigned integer type. For 99.9% of
  9647. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  9648. ** can be used at compile-time if desired.
  9649. */
  9650. #ifdef SQLITE_64BIT_STATS
  9651. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  9652. #else
  9653. typedef u32 tRowcnt; /* 32-bit is the default */
  9654. #endif
  9655. /*
  9656. ** Estimated quantities used for query planning are stored as 16-bit
  9657. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  9658. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  9659. ** But the allowed values are "grainy". Not every value is representable.
  9660. ** For example, quantities 16 and 17 are both represented by a LogEst
  9661. ** of 40. However, since LogEst quantities are suppose to be estimates,
  9662. ** not exact values, this imprecision is not a problem.
  9663. **
  9664. ** "LogEst" is short for "Logarithmic Estimate".
  9665. **
  9666. ** Examples:
  9667. ** 1 -> 0 20 -> 43 10000 -> 132
  9668. ** 2 -> 10 25 -> 46 25000 -> 146
  9669. ** 3 -> 16 100 -> 66 1000000 -> 199
  9670. ** 4 -> 20 1000 -> 99 1048576 -> 200
  9671. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  9672. **
  9673. ** The LogEst can be negative to indicate fractional values.
  9674. ** Examples:
  9675. **
  9676. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  9677. */
  9678. typedef INT16_TYPE LogEst;
  9679. /*
  9680. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  9681. */
  9682. #ifndef SQLITE_PTRSIZE
  9683. # if defined(__SIZEOF_POINTER__)
  9684. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  9685. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  9686. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  9687. # define SQLITE_PTRSIZE 4
  9688. # else
  9689. # define SQLITE_PTRSIZE 8
  9690. # endif
  9691. #endif
  9692. /* The uptr type is an unsigned integer large enough to hold a pointer
  9693. */
  9694. #if defined(HAVE_STDINT_H)
  9695. typedef uintptr_t uptr;
  9696. #elif SQLITE_PTRSIZE==4
  9697. typedef u32 uptr;
  9698. #else
  9699. typedef u64 uptr;
  9700. #endif
  9701. /*
  9702. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  9703. ** something between S (inclusive) and E (exclusive).
  9704. **
  9705. ** In other words, S is a buffer and E is a pointer to the first byte after
  9706. ** the end of buffer S. This macro returns true if P points to something
  9707. ** contained within the buffer S.
  9708. */
  9709. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  9710. /*
  9711. ** Macros to determine whether the machine is big or little endian,
  9712. ** and whether or not that determination is run-time or compile-time.
  9713. **
  9714. ** For best performance, an attempt is made to guess at the byte-order
  9715. ** using C-preprocessor macros. If that is unsuccessful, or if
  9716. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  9717. ** at run-time.
  9718. */
  9719. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  9720. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  9721. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  9722. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  9723. # define SQLITE_BYTEORDER 1234
  9724. # define SQLITE_BIGENDIAN 0
  9725. # define SQLITE_LITTLEENDIAN 1
  9726. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  9727. #endif
  9728. #if (defined(sparc) || defined(__ppc__)) \
  9729. && !defined(SQLITE_RUNTIME_BYTEORDER)
  9730. # define SQLITE_BYTEORDER 4321
  9731. # define SQLITE_BIGENDIAN 1
  9732. # define SQLITE_LITTLEENDIAN 0
  9733. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  9734. #endif
  9735. #if !defined(SQLITE_BYTEORDER)
  9736. # ifdef SQLITE_AMALGAMATION
  9737. const int sqlite3one = 1;
  9738. # else
  9739. extern const int sqlite3one;
  9740. # endif
  9741. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  9742. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  9743. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  9744. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  9745. #endif
  9746. /*
  9747. ** Constants for the largest and smallest possible 64-bit signed integers.
  9748. ** These macros are designed to work correctly on both 32-bit and 64-bit
  9749. ** compilers.
  9750. */
  9751. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  9752. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  9753. /*
  9754. ** Round up a number to the next larger multiple of 8. This is used
  9755. ** to force 8-byte alignment on 64-bit architectures.
  9756. */
  9757. #define ROUND8(x) (((x)+7)&~7)
  9758. /*
  9759. ** Round down to the nearest multiple of 8
  9760. */
  9761. #define ROUNDDOWN8(x) ((x)&~7)
  9762. /*
  9763. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  9764. ** macro is used only within assert() to verify that the code gets
  9765. ** all alignment restrictions correct.
  9766. **
  9767. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  9768. ** underlying malloc() implementation might return us 4-byte aligned
  9769. ** pointers. In that case, only verify 4-byte alignment.
  9770. */
  9771. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  9772. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  9773. #else
  9774. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  9775. #endif
  9776. /*
  9777. ** Disable MMAP on platforms where it is known to not work
  9778. */
  9779. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  9780. # undef SQLITE_MAX_MMAP_SIZE
  9781. # define SQLITE_MAX_MMAP_SIZE 0
  9782. #endif
  9783. /*
  9784. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  9785. */
  9786. #ifdef __APPLE__
  9787. # include <TargetConditionals.h>
  9788. #endif
  9789. #ifndef SQLITE_MAX_MMAP_SIZE
  9790. # if defined(__linux__) \
  9791. || defined(_WIN32) \
  9792. || (defined(__APPLE__) && defined(__MACH__)) \
  9793. || defined(__sun) \
  9794. || defined(__FreeBSD__) \
  9795. || defined(__DragonFly__)
  9796. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  9797. # else
  9798. # define SQLITE_MAX_MMAP_SIZE 0
  9799. # endif
  9800. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  9801. #endif
  9802. /*
  9803. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  9804. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  9805. ** not exceed the maximum mmap size.
  9806. */
  9807. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  9808. # define SQLITE_DEFAULT_MMAP_SIZE 0
  9809. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  9810. #endif
  9811. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  9812. # undef SQLITE_DEFAULT_MMAP_SIZE
  9813. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  9814. #endif
  9815. /*
  9816. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  9817. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  9818. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  9819. */
  9820. #ifdef SQLITE_ENABLE_STAT4
  9821. # undef SQLITE_ENABLE_STAT3
  9822. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  9823. #elif SQLITE_ENABLE_STAT3
  9824. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  9825. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  9826. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  9827. #endif
  9828. /*
  9829. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  9830. ** the Select query generator tracing logic is turned on.
  9831. */
  9832. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  9833. # define SELECTTRACE_ENABLED 1
  9834. #else
  9835. # define SELECTTRACE_ENABLED 0
  9836. #endif
  9837. /*
  9838. ** An instance of the following structure is used to store the busy-handler
  9839. ** callback for a given sqlite handle.
  9840. **
  9841. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  9842. ** callback for the database handle. Each pager opened via the sqlite
  9843. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  9844. ** callback is currently invoked only from within pager.c.
  9845. */
  9846. typedef struct BusyHandler BusyHandler;
  9847. struct BusyHandler {
  9848. int (*xFunc)(void *,int); /* The busy callback */
  9849. void *pArg; /* First arg to busy callback */
  9850. int nBusy; /* Incremented with each busy call */
  9851. };
  9852. /*
  9853. ** Name of the master database table. The master database table
  9854. ** is a special table that holds the names and attributes of all
  9855. ** user tables and indices.
  9856. */
  9857. #define MASTER_NAME "sqlite_master"
  9858. #define TEMP_MASTER_NAME "sqlite_temp_master"
  9859. /*
  9860. ** The root-page of the master database table.
  9861. */
  9862. #define MASTER_ROOT 1
  9863. /*
  9864. ** The name of the schema table.
  9865. */
  9866. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  9867. /*
  9868. ** A convenience macro that returns the number of elements in
  9869. ** an array.
  9870. */
  9871. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  9872. /*
  9873. ** Determine if the argument is a power of two
  9874. */
  9875. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  9876. /*
  9877. ** The following value as a destructor means to use sqlite3DbFree().
  9878. ** The sqlite3DbFree() routine requires two parameters instead of the
  9879. ** one parameter that destructors normally want. So we have to introduce
  9880. ** this magic value that the code knows to handle differently. Any
  9881. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  9882. ** and SQLITE_TRANSIENT.
  9883. */
  9884. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  9885. /*
  9886. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  9887. ** not support Writable Static Data (WSD) such as global and static variables.
  9888. ** All variables must either be on the stack or dynamically allocated from
  9889. ** the heap. When WSD is unsupported, the variable declarations scattered
  9890. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  9891. ** macro is used for this purpose. And instead of referencing the variable
  9892. ** directly, we use its constant as a key to lookup the run-time allocated
  9893. ** buffer that holds real variable. The constant is also the initializer
  9894. ** for the run-time allocated buffer.
  9895. **
  9896. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  9897. ** macros become no-ops and have zero performance impact.
  9898. */
  9899. #ifdef SQLITE_OMIT_WSD
  9900. #define SQLITE_WSD const
  9901. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  9902. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  9903. SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
  9904. SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
  9905. #else
  9906. #define SQLITE_WSD
  9907. #define GLOBAL(t,v) v
  9908. #define sqlite3GlobalConfig sqlite3Config
  9909. #endif
  9910. /*
  9911. ** The following macros are used to suppress compiler warnings and to
  9912. ** make it clear to human readers when a function parameter is deliberately
  9913. ** left unused within the body of a function. This usually happens when
  9914. ** a function is called via a function pointer. For example the
  9915. ** implementation of an SQL aggregate step callback may not use the
  9916. ** parameter indicating the number of arguments passed to the aggregate,
  9917. ** if it knows that this is enforced elsewhere.
  9918. **
  9919. ** When a function parameter is not used at all within the body of a function,
  9920. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  9921. ** However, these macros may also be used to suppress warnings related to
  9922. ** parameters that may or may not be used depending on compilation options.
  9923. ** For example those parameters only used in assert() statements. In these
  9924. ** cases the parameters are named as per the usual conventions.
  9925. */
  9926. #define UNUSED_PARAMETER(x) (void)(x)
  9927. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  9928. /*
  9929. ** Forward references to structures
  9930. */
  9931. typedef struct AggInfo AggInfo;
  9932. typedef struct AuthContext AuthContext;
  9933. typedef struct AutoincInfo AutoincInfo;
  9934. typedef struct Bitvec Bitvec;
  9935. typedef struct CollSeq CollSeq;
  9936. typedef struct Column Column;
  9937. typedef struct Db Db;
  9938. typedef struct Schema Schema;
  9939. typedef struct Expr Expr;
  9940. typedef struct ExprList ExprList;
  9941. typedef struct ExprSpan ExprSpan;
  9942. typedef struct FKey FKey;
  9943. typedef struct FuncDestructor FuncDestructor;
  9944. typedef struct FuncDef FuncDef;
  9945. typedef struct FuncDefHash FuncDefHash;
  9946. typedef struct IdList IdList;
  9947. typedef struct Index Index;
  9948. typedef struct IndexSample IndexSample;
  9949. typedef struct KeyClass KeyClass;
  9950. typedef struct KeyInfo KeyInfo;
  9951. typedef struct Lookaside Lookaside;
  9952. typedef struct LookasideSlot LookasideSlot;
  9953. typedef struct Module Module;
  9954. typedef struct NameContext NameContext;
  9955. typedef struct Parse Parse;
  9956. typedef struct PrintfArguments PrintfArguments;
  9957. typedef struct RowSet RowSet;
  9958. typedef struct Savepoint Savepoint;
  9959. typedef struct Select Select;
  9960. typedef struct SQLiteThread SQLiteThread;
  9961. typedef struct SelectDest SelectDest;
  9962. typedef struct SrcList SrcList;
  9963. typedef struct StrAccum StrAccum;
  9964. typedef struct Table Table;
  9965. typedef struct TableLock TableLock;
  9966. typedef struct Token Token;
  9967. typedef struct TreeView TreeView;
  9968. typedef struct Trigger Trigger;
  9969. typedef struct TriggerPrg TriggerPrg;
  9970. typedef struct TriggerStep TriggerStep;
  9971. typedef struct UnpackedRecord UnpackedRecord;
  9972. typedef struct VTable VTable;
  9973. typedef struct VtabCtx VtabCtx;
  9974. typedef struct Walker Walker;
  9975. typedef struct WhereInfo WhereInfo;
  9976. typedef struct With With;
  9977. /*
  9978. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  9979. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  9980. ** pointer types (i.e. FuncDef) defined above.
  9981. */
  9982. /************** Include btree.h in the middle of sqliteInt.h *****************/
  9983. /************** Begin file btree.h *******************************************/
  9984. /*
  9985. ** 2001 September 15
  9986. **
  9987. ** The author disclaims copyright to this source code. In place of
  9988. ** a legal notice, here is a blessing:
  9989. **
  9990. ** May you do good and not evil.
  9991. ** May you find forgiveness for yourself and forgive others.
  9992. ** May you share freely, never taking more than you give.
  9993. **
  9994. *************************************************************************
  9995. ** This header file defines the interface that the sqlite B-Tree file
  9996. ** subsystem. See comments in the source code for a detailed description
  9997. ** of what each interface routine does.
  9998. */
  9999. #ifndef _BTREE_H_
  10000. #define _BTREE_H_
  10001. /* TODO: This definition is just included so other modules compile. It
  10002. ** needs to be revisited.
  10003. */
  10004. #define SQLITE_N_BTREE_META 16
  10005. /*
  10006. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  10007. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  10008. */
  10009. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  10010. #define SQLITE_DEFAULT_AUTOVACUUM 0
  10011. #endif
  10012. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  10013. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  10014. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  10015. /*
  10016. ** Forward declarations of structure
  10017. */
  10018. typedef struct Btree Btree;
  10019. typedef struct BtCursor BtCursor;
  10020. typedef struct BtShared BtShared;
  10021. SQLITE_PRIVATE int sqlite3BtreeOpen(
  10022. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  10023. const char *zFilename, /* Name of database file to open */
  10024. sqlite3 *db, /* Associated database connection */
  10025. Btree **ppBtree, /* Return open Btree* here */
  10026. int flags, /* Flags */
  10027. int vfsFlags /* Flags passed through to VFS open */
  10028. );
  10029. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  10030. ** following values.
  10031. **
  10032. ** NOTE: These values must match the corresponding PAGER_ values in
  10033. ** pager.h.
  10034. */
  10035. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  10036. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  10037. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  10038. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  10039. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  10040. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  10041. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  10042. #if SQLITE_MAX_MMAP_SIZE>0
  10043. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  10044. #endif
  10045. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  10046. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  10047. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  10048. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  10049. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  10050. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  10051. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  10052. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  10053. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  10054. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  10055. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  10056. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  10057. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  10058. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  10059. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  10060. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  10061. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  10062. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  10063. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  10064. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  10065. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  10066. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  10067. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  10068. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  10069. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  10070. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  10071. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  10072. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  10073. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  10074. ** of the flags shown below.
  10075. **
  10076. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  10077. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  10078. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  10079. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  10080. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  10081. ** indices.)
  10082. */
  10083. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  10084. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  10085. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  10086. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  10087. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  10088. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  10089. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  10090. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  10091. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  10092. /*
  10093. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  10094. ** should be one of the following values. The integer values are assigned
  10095. ** to constants so that the offset of the corresponding field in an
  10096. ** SQLite database header may be found using the following formula:
  10097. **
  10098. ** offset = 36 + (idx * 4)
  10099. **
  10100. ** For example, the free-page-count field is located at byte offset 36 of
  10101. ** the database file header. The incr-vacuum-flag field is located at
  10102. ** byte offset 64 (== 36+4*7).
  10103. **
  10104. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  10105. ** It is a read-only number computed by the pager. But we merge it with
  10106. ** the header value access routines since its access pattern is the same.
  10107. ** Call it a "virtual meta value".
  10108. */
  10109. #define BTREE_FREE_PAGE_COUNT 0
  10110. #define BTREE_SCHEMA_VERSION 1
  10111. #define BTREE_FILE_FORMAT 2
  10112. #define BTREE_DEFAULT_CACHE_SIZE 3
  10113. #define BTREE_LARGEST_ROOT_PAGE 4
  10114. #define BTREE_TEXT_ENCODING 5
  10115. #define BTREE_USER_VERSION 6
  10116. #define BTREE_INCR_VACUUM 7
  10117. #define BTREE_APPLICATION_ID 8
  10118. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  10119. /*
  10120. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  10121. ** interface.
  10122. **
  10123. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  10124. **
  10125. ** The first argument is an Expr* (which is guaranteed to be constant for
  10126. ** the lifetime of the cursor) that defines constraints on which rows
  10127. ** might be fetched with this cursor. The Expr* tree may contain
  10128. ** TK_REGISTER nodes that refer to values stored in the array of registers
  10129. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  10130. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  10131. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  10132. ** column of the b-tree of the cursor. The Expr tree will not contain
  10133. ** any function calls nor subqueries nor references to b-trees other than
  10134. ** the cursor being hinted.
  10135. **
  10136. ** The design of the _RANGE hint is aid b-tree implementations that try
  10137. ** to prefetch content from remote machines - to provide those
  10138. ** implementations with limits on what needs to be prefetched and thereby
  10139. ** reduce network bandwidth.
  10140. **
  10141. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  10142. ** standard SQLite. The other hints are provided for extentions that use
  10143. ** the SQLite parser and code generator but substitute their own storage
  10144. ** engine.
  10145. */
  10146. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  10147. /*
  10148. ** Values that may be OR'd together to form the argument to the
  10149. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  10150. **
  10151. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  10152. ** to be filled with content that is already in sorted order.
  10153. **
  10154. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  10155. ** OP_SeekLE opcodes for a range search, but where the range of entries
  10156. ** selected will all have the same key. In other words, the cursor will
  10157. ** be used only for equality key searches.
  10158. **
  10159. */
  10160. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  10161. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  10162. /*
  10163. ** Flags passed as the third argument to sqlite3BtreeCursor().
  10164. **
  10165. ** For read-only cursors the wrFlag argument is always zero. For read-write
  10166. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  10167. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  10168. ** only be used by SQLite for the following:
  10169. **
  10170. ** * to seek to and then delete specific entries, and/or
  10171. **
  10172. ** * to read values that will be used to create keys that other
  10173. ** BTREE_FORDELETE cursors will seek to and delete.
  10174. **
  10175. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  10176. ** by this, the native b-tree engine of SQLite, but it is available to
  10177. ** alternative storage engines that might be substituted in place of this
  10178. ** b-tree system. For alternative storage engines in which a delete of
  10179. ** the main table row automatically deletes corresponding index rows,
  10180. ** the FORDELETE flag hint allows those alternative storage engines to
  10181. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  10182. ** and DELETE operations as no-ops, and any READ operation against a
  10183. ** FORDELETE cursor may return a null row: 0x01 0x00.
  10184. */
  10185. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  10186. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  10187. SQLITE_PRIVATE int sqlite3BtreeCursor(
  10188. Btree*, /* BTree containing table to open */
  10189. int iTable, /* Index of root page */
  10190. int wrFlag, /* 1 for writing. 0 for read-only */
  10191. struct KeyInfo*, /* First argument to compare function */
  10192. BtCursor *pCursor /* Space to write cursor structure */
  10193. );
  10194. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  10195. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  10196. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  10197. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  10198. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  10199. #endif
  10200. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  10201. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  10202. BtCursor*,
  10203. UnpackedRecord *pUnKey,
  10204. i64 intKey,
  10205. int bias,
  10206. int *pRes
  10207. );
  10208. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  10209. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  10210. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  10211. /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
  10212. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  10213. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  10214. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  10215. const void *pData, int nData,
  10216. int nZero, int bias, int seekResult);
  10217. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  10218. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  10219. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  10220. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  10221. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  10222. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  10223. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  10224. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  10225. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  10226. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  10227. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  10228. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  10229. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  10230. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  10231. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  10232. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  10233. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  10234. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  10235. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  10236. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  10237. #ifndef NDEBUG
  10238. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  10239. #endif
  10240. #ifndef SQLITE_OMIT_BTREECOUNT
  10241. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  10242. #endif
  10243. #ifdef SQLITE_TEST
  10244. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  10245. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  10246. #endif
  10247. #ifndef SQLITE_OMIT_WAL
  10248. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  10249. #endif
  10250. /*
  10251. ** If we are not using shared cache, then there is no need to
  10252. ** use mutexes to access the BtShared structures. So make the
  10253. ** Enter and Leave procedures no-ops.
  10254. */
  10255. #ifndef SQLITE_OMIT_SHARED_CACHE
  10256. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  10257. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  10258. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  10259. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  10260. #else
  10261. # define sqlite3BtreeEnter(X)
  10262. # define sqlite3BtreeEnterAll(X)
  10263. # define sqlite3BtreeSharable(X) 0
  10264. # define sqlite3BtreeEnterCursor(X)
  10265. #endif
  10266. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  10267. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  10268. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  10269. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  10270. #ifndef NDEBUG
  10271. /* These routines are used inside assert() statements only. */
  10272. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  10273. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  10274. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  10275. #endif
  10276. #else
  10277. # define sqlite3BtreeLeave(X)
  10278. # define sqlite3BtreeLeaveCursor(X)
  10279. # define sqlite3BtreeLeaveAll(X)
  10280. # define sqlite3BtreeHoldsMutex(X) 1
  10281. # define sqlite3BtreeHoldsAllMutexes(X) 1
  10282. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  10283. #endif
  10284. #endif /* _BTREE_H_ */
  10285. /************** End of btree.h ***********************************************/
  10286. /************** Continuing where we left off in sqliteInt.h ******************/
  10287. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  10288. /************** Begin file vdbe.h ********************************************/
  10289. /*
  10290. ** 2001 September 15
  10291. **
  10292. ** The author disclaims copyright to this source code. In place of
  10293. ** a legal notice, here is a blessing:
  10294. **
  10295. ** May you do good and not evil.
  10296. ** May you find forgiveness for yourself and forgive others.
  10297. ** May you share freely, never taking more than you give.
  10298. **
  10299. *************************************************************************
  10300. ** Header file for the Virtual DataBase Engine (VDBE)
  10301. **
  10302. ** This header defines the interface to the virtual database engine
  10303. ** or VDBE. The VDBE implements an abstract machine that runs a
  10304. ** simple program to access and modify the underlying database.
  10305. */
  10306. #ifndef _SQLITE_VDBE_H_
  10307. #define _SQLITE_VDBE_H_
  10308. /* #include <stdio.h> */
  10309. /*
  10310. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  10311. ** in the source file sqliteVdbe.c are allowed to see the insides
  10312. ** of this structure.
  10313. */
  10314. typedef struct Vdbe Vdbe;
  10315. /*
  10316. ** The names of the following types declared in vdbeInt.h are required
  10317. ** for the VdbeOp definition.
  10318. */
  10319. typedef struct Mem Mem;
  10320. typedef struct SubProgram SubProgram;
  10321. /*
  10322. ** A single instruction of the virtual machine has an opcode
  10323. ** and as many as three operands. The instruction is recorded
  10324. ** as an instance of the following structure:
  10325. */
  10326. struct VdbeOp {
  10327. u8 opcode; /* What operation to perform */
  10328. signed char p4type; /* One of the P4_xxx constants for p4 */
  10329. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  10330. u8 p5; /* Fifth parameter is an unsigned character */
  10331. int p1; /* First operand */
  10332. int p2; /* Second parameter (often the jump destination) */
  10333. int p3; /* The third parameter */
  10334. union p4union { /* fourth parameter */
  10335. int i; /* Integer value if p4type==P4_INT32 */
  10336. void *p; /* Generic pointer */
  10337. char *z; /* Pointer to data for string (char array) types */
  10338. i64 *pI64; /* Used when p4type is P4_INT64 */
  10339. double *pReal; /* Used when p4type is P4_REAL */
  10340. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  10341. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  10342. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  10343. Mem *pMem; /* Used when p4type is P4_MEM */
  10344. VTable *pVtab; /* Used when p4type is P4_VTAB */
  10345. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  10346. int *ai; /* Used when p4type is P4_INTARRAY */
  10347. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  10348. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  10349. Expr *pExpr; /* Used when p4type is P4_EXPR */
  10350. #endif
  10351. int (*xAdvance)(BtCursor *, int *);
  10352. } p4;
  10353. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10354. char *zComment; /* Comment to improve readability */
  10355. #endif
  10356. #ifdef VDBE_PROFILE
  10357. u32 cnt; /* Number of times this instruction was executed */
  10358. u64 cycles; /* Total time spent executing this instruction */
  10359. #endif
  10360. #ifdef SQLITE_VDBE_COVERAGE
  10361. int iSrcLine; /* Source-code line that generated this opcode */
  10362. #endif
  10363. };
  10364. typedef struct VdbeOp VdbeOp;
  10365. /*
  10366. ** A sub-routine used to implement a trigger program.
  10367. */
  10368. struct SubProgram {
  10369. VdbeOp *aOp; /* Array of opcodes for sub-program */
  10370. int nOp; /* Elements in aOp[] */
  10371. int nMem; /* Number of memory cells required */
  10372. int nCsr; /* Number of cursors required */
  10373. int nOnce; /* Number of OP_Once instructions */
  10374. void *token; /* id that may be used to recursive triggers */
  10375. SubProgram *pNext; /* Next sub-program already visited */
  10376. };
  10377. /*
  10378. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  10379. ** it takes up less space.
  10380. */
  10381. struct VdbeOpList {
  10382. u8 opcode; /* What operation to perform */
  10383. signed char p1; /* First operand */
  10384. signed char p2; /* Second parameter (often the jump destination) */
  10385. signed char p3; /* Third parameter */
  10386. };
  10387. typedef struct VdbeOpList VdbeOpList;
  10388. /*
  10389. ** Allowed values of VdbeOp.p4type
  10390. */
  10391. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  10392. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  10393. #define P4_STATIC (-2) /* Pointer to a static string */
  10394. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  10395. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  10396. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  10397. #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
  10398. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  10399. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  10400. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  10401. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  10402. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  10403. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  10404. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  10405. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  10406. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  10407. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  10408. #define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
  10409. /* Error message codes for OP_Halt */
  10410. #define P5_ConstraintNotNull 1
  10411. #define P5_ConstraintUnique 2
  10412. #define P5_ConstraintCheck 3
  10413. #define P5_ConstraintFK 4
  10414. /*
  10415. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  10416. ** number of columns of data returned by the statement.
  10417. */
  10418. #define COLNAME_NAME 0
  10419. #define COLNAME_DECLTYPE 1
  10420. #define COLNAME_DATABASE 2
  10421. #define COLNAME_TABLE 3
  10422. #define COLNAME_COLUMN 4
  10423. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  10424. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  10425. #else
  10426. # ifdef SQLITE_OMIT_DECLTYPE
  10427. # define COLNAME_N 1 /* Store only the name */
  10428. # else
  10429. # define COLNAME_N 2 /* Store the name and decltype */
  10430. # endif
  10431. #endif
  10432. /*
  10433. ** The following macro converts a relative address in the p2 field
  10434. ** of a VdbeOp structure into a negative number so that
  10435. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  10436. ** the macro again restores the address.
  10437. */
  10438. #define ADDR(X) (-1-(X))
  10439. /*
  10440. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  10441. ** header file that defines a number for each opcode used by the VDBE.
  10442. */
  10443. /************** Include opcodes.h in the middle of vdbe.h ********************/
  10444. /************** Begin file opcodes.h *****************************************/
  10445. /* Automatically generated. Do not edit */
  10446. /* See the tool/mkopcodeh.tcl script for details */
  10447. #define OP_Savepoint 0
  10448. #define OP_AutoCommit 1
  10449. #define OP_Transaction 2
  10450. #define OP_SorterNext 3
  10451. #define OP_PrevIfOpen 4
  10452. #define OP_NextIfOpen 5
  10453. #define OP_Prev 6
  10454. #define OP_Next 7
  10455. #define OP_Checkpoint 8
  10456. #define OP_JournalMode 9
  10457. #define OP_Vacuum 10
  10458. #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
  10459. #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
  10460. #define OP_Goto 13
  10461. #define OP_Gosub 14
  10462. #define OP_Return 15
  10463. #define OP_InitCoroutine 16
  10464. #define OP_EndCoroutine 17
  10465. #define OP_Yield 18
  10466. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  10467. #define OP_HaltIfNull 20 /* synopsis: if r[P3]=null halt */
  10468. #define OP_Halt 21
  10469. #define OP_Integer 22 /* synopsis: r[P2]=P1 */
  10470. #define OP_Int64 23 /* synopsis: r[P2]=P4 */
  10471. #define OP_String 24 /* synopsis: r[P2]='P4' (len=P1) */
  10472. #define OP_Null 25 /* synopsis: r[P2..P3]=NULL */
  10473. #define OP_SoftNull 26 /* synopsis: r[P1]=NULL */
  10474. #define OP_Blob 27 /* synopsis: r[P2]=P4 (len=P1) */
  10475. #define OP_Variable 28 /* synopsis: r[P2]=parameter(P1,P4) */
  10476. #define OP_Move 29 /* synopsis: r[P2@P3]=r[P1@P3] */
  10477. #define OP_Copy 30 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  10478. #define OP_SCopy 31 /* synopsis: r[P2]=r[P1] */
  10479. #define OP_IntCopy 32 /* synopsis: r[P2]=r[P1] */
  10480. #define OP_ResultRow 33 /* synopsis: output=r[P1@P2] */
  10481. #define OP_CollSeq 34
  10482. #define OP_Function0 35 /* synopsis: r[P3]=func(r[P2@P5]) */
  10483. #define OP_Function 36 /* synopsis: r[P3]=func(r[P2@P5]) */
  10484. #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
  10485. #define OP_MustBeInt 38
  10486. #define OP_RealAffinity 39
  10487. #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
  10488. #define OP_Permutation 41
  10489. #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  10490. #define OP_Jump 43
  10491. #define OP_Once 44
  10492. #define OP_If 45
  10493. #define OP_IfNot 46
  10494. #define OP_Column 47 /* synopsis: r[P3]=PX */
  10495. #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
  10496. #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  10497. #define OP_Count 50 /* synopsis: r[P2]=count() */
  10498. #define OP_ReadCookie 51
  10499. #define OP_SetCookie 52
  10500. #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
  10501. #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
  10502. #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
  10503. #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
  10504. #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
  10505. #define OP_SorterOpen 58
  10506. #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  10507. #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
  10508. #define OP_Close 61
  10509. #define OP_ColumnsUsed 62
  10510. #define OP_SeekLT 63 /* synopsis: key=r[P3@P4] */
  10511. #define OP_SeekLE 64 /* synopsis: key=r[P3@P4] */
  10512. #define OP_SeekGE 65 /* synopsis: key=r[P3@P4] */
  10513. #define OP_SeekGT 66 /* synopsis: key=r[P3@P4] */
  10514. #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
  10515. #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
  10516. #define OP_Found 69 /* synopsis: key=r[P3@P4] */
  10517. #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
  10518. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  10519. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  10520. #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
  10521. #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
  10522. #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
  10523. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  10524. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  10525. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  10526. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  10527. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  10528. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  10529. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  10530. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  10531. #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
  10532. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  10533. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  10534. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  10535. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  10536. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  10537. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  10538. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  10539. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  10540. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  10541. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  10542. #define OP_Delete 95
  10543. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  10544. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  10545. #define OP_ResetCount 98
  10546. #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  10547. #define OP_SorterData 100 /* synopsis: r[P2]=data */
  10548. #define OP_RowKey 101 /* synopsis: r[P2]=key */
  10549. #define OP_RowData 102 /* synopsis: r[P2]=data */
  10550. #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
  10551. #define OP_NullRow 104
  10552. #define OP_Last 105
  10553. #define OP_SorterSort 106
  10554. #define OP_Sort 107
  10555. #define OP_Rewind 108
  10556. #define OP_SorterInsert 109
  10557. #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
  10558. #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
  10559. #define OP_Seek 112 /* synopsis: Move P3 to P1.rowid */
  10560. #define OP_IdxRowid 113 /* synopsis: r[P2]=rowid */
  10561. #define OP_IdxLE 114 /* synopsis: key=r[P3@P4] */
  10562. #define OP_IdxGT 115 /* synopsis: key=r[P3@P4] */
  10563. #define OP_IdxLT 116 /* synopsis: key=r[P3@P4] */
  10564. #define OP_IdxGE 117 /* synopsis: key=r[P3@P4] */
  10565. #define OP_Destroy 118
  10566. #define OP_Clear 119
  10567. #define OP_ResetSorter 120
  10568. #define OP_CreateIndex 121 /* synopsis: r[P2]=root iDb=P1 */
  10569. #define OP_CreateTable 122 /* synopsis: r[P2]=root iDb=P1 */
  10570. #define OP_ParseSchema 123
  10571. #define OP_LoadAnalysis 124
  10572. #define OP_DropTable 125
  10573. #define OP_DropIndex 126
  10574. #define OP_DropTrigger 127
  10575. #define OP_IntegrityCk 128
  10576. #define OP_RowSetAdd 129 /* synopsis: rowset(P1)=r[P2] */
  10577. #define OP_RowSetRead 130 /* synopsis: r[P3]=rowset(P1) */
  10578. #define OP_RowSetTest 131 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  10579. #define OP_Program 132
  10580. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  10581. #define OP_Param 134
  10582. #define OP_FkCounter 135 /* synopsis: fkctr[P1]+=P2 */
  10583. #define OP_FkIfZero 136 /* synopsis: if fkctr[P1]==0 goto P2 */
  10584. #define OP_MemMax 137 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  10585. #define OP_IfPos 138 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  10586. #define OP_OffsetLimit 139 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  10587. #define OP_IfNotZero 140 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
  10588. #define OP_DecrJumpZero 141 /* synopsis: if (--r[P1])==0 goto P2 */
  10589. #define OP_JumpZeroIncr 142 /* synopsis: if (r[P1]++)==0 ) goto P2 */
  10590. #define OP_AggStep0 143 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  10591. #define OP_AggStep 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  10592. #define OP_AggFinal 145 /* synopsis: accum=r[P1] N=P2 */
  10593. #define OP_IncrVacuum 146
  10594. #define OP_Expire 147
  10595. #define OP_TableLock 148 /* synopsis: iDb=P1 root=P2 write=P3 */
  10596. #define OP_VBegin 149
  10597. #define OP_VCreate 150
  10598. #define OP_VDestroy 151
  10599. #define OP_VOpen 152
  10600. #define OP_VColumn 153 /* synopsis: r[P3]=vcolumn(P2) */
  10601. #define OP_VNext 154
  10602. #define OP_VRename 155
  10603. #define OP_Pagecount 156
  10604. #define OP_MaxPgcnt 157
  10605. #define OP_Init 158 /* synopsis: Start at P2 */
  10606. #define OP_CursorHint 159
  10607. #define OP_Noop 160
  10608. #define OP_Explain 161
  10609. /* Properties such as "out2" or "jump" that are specified in
  10610. ** comments following the "case" for each opcode in the vdbe.c
  10611. ** are encoded into bitvectors as follows:
  10612. */
  10613. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  10614. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  10615. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  10616. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  10617. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  10618. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  10619. #define OPFLG_INITIALIZER {\
  10620. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
  10621. /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x02,\
  10622. /* 16 */ 0x01, 0x02, 0x03, 0x12, 0x08, 0x00, 0x10, 0x10,\
  10623. /* 24 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
  10624. /* 32 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x02,\
  10625. /* 40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
  10626. /* 48 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
  10627. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09,\
  10628. /* 64 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x26,\
  10629. /* 72 */ 0x26, 0x10, 0x10, 0x00, 0x03, 0x03, 0x0b, 0x0b,\
  10630. /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
  10631. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
  10632. /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
  10633. /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04, 0x00,\
  10634. /* 112 */ 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00,\
  10635. /* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10636. /* 128 */ 0x00, 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00,\
  10637. /* 136 */ 0x01, 0x04, 0x03, 0x1a, 0x03, 0x03, 0x03, 0x00,\
  10638. /* 144 */ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10639. /* 152 */ 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01, 0x00,\
  10640. /* 160 */ 0x00, 0x00,}
  10641. /************** End of opcodes.h *********************************************/
  10642. /************** Continuing where we left off in vdbe.h ***********************/
  10643. /*
  10644. ** Prototypes for the VDBE interface. See comments on the implementation
  10645. ** for a description of what each of these routines does.
  10646. */
  10647. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  10648. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  10649. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  10650. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  10651. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  10652. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  10653. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  10654. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  10655. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  10656. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  10657. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  10658. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  10659. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  10660. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  10661. #else
  10662. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  10663. #endif
  10664. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  10665. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  10666. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  10667. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  10668. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  10669. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  10670. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  10671. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  10672. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  10673. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  10674. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  10675. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  10676. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  10677. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  10678. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  10679. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  10680. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  10681. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  10682. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  10683. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  10684. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  10685. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  10686. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  10687. #ifdef SQLITE_DEBUG
  10688. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  10689. #endif
  10690. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  10691. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  10692. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  10693. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  10694. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  10695. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  10696. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  10697. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  10698. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  10699. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  10700. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  10701. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  10702. #ifndef SQLITE_OMIT_TRACE
  10703. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  10704. #endif
  10705. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  10706. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  10707. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  10708. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  10709. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  10710. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  10711. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  10712. #ifndef SQLITE_OMIT_TRIGGER
  10713. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  10714. #endif
  10715. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  10716. ** each VDBE opcode.
  10717. **
  10718. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  10719. ** comments in VDBE programs that show key decision points in the code
  10720. ** generator.
  10721. */
  10722. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10723. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  10724. # define VdbeComment(X) sqlite3VdbeComment X
  10725. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  10726. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  10727. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  10728. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  10729. # else
  10730. # define VdbeModuleComment(X)
  10731. # endif
  10732. #else
  10733. # define VdbeComment(X)
  10734. # define VdbeNoopComment(X)
  10735. # define VdbeModuleComment(X)
  10736. #endif
  10737. /*
  10738. ** The VdbeCoverage macros are used to set a coverage testing point
  10739. ** for VDBE branch instructions. The coverage testing points are line
  10740. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  10741. ** only works with an amalagmation build. That's ok since a VDBE branch
  10742. ** coverage build designed for testing the test suite only. No application
  10743. ** should ever ship with VDBE branch coverage measuring turned on.
  10744. **
  10745. ** VdbeCoverage(v) // Mark the previously coded instruction
  10746. ** // as a branch
  10747. **
  10748. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  10749. **
  10750. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  10751. **
  10752. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  10753. **
  10754. ** Every VDBE branch operation must be tagged with one of the macros above.
  10755. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  10756. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  10757. ** routine in vdbe.c, alerting the developer to the missed tag.
  10758. */
  10759. #ifdef SQLITE_VDBE_COVERAGE
  10760. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  10761. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  10762. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  10763. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  10764. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  10765. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  10766. #else
  10767. # define VdbeCoverage(v)
  10768. # define VdbeCoverageIf(v,x)
  10769. # define VdbeCoverageAlwaysTaken(v)
  10770. # define VdbeCoverageNeverTaken(v)
  10771. # define VDBE_OFFSET_LINENO(x) 0
  10772. #endif
  10773. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  10774. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  10775. #else
  10776. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  10777. #endif
  10778. #endif
  10779. /************** End of vdbe.h ************************************************/
  10780. /************** Continuing where we left off in sqliteInt.h ******************/
  10781. /************** Include pager.h in the middle of sqliteInt.h *****************/
  10782. /************** Begin file pager.h *******************************************/
  10783. /*
  10784. ** 2001 September 15
  10785. **
  10786. ** The author disclaims copyright to this source code. In place of
  10787. ** a legal notice, here is a blessing:
  10788. **
  10789. ** May you do good and not evil.
  10790. ** May you find forgiveness for yourself and forgive others.
  10791. ** May you share freely, never taking more than you give.
  10792. **
  10793. *************************************************************************
  10794. ** This header file defines the interface that the sqlite page cache
  10795. ** subsystem. The page cache subsystem reads and writes a file a page
  10796. ** at a time and provides a journal for rollback.
  10797. */
  10798. #ifndef _PAGER_H_
  10799. #define _PAGER_H_
  10800. /*
  10801. ** Default maximum size for persistent journal files. A negative
  10802. ** value means no limit. This value may be overridden using the
  10803. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  10804. */
  10805. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  10806. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  10807. #endif
  10808. /*
  10809. ** The type used to represent a page number. The first page in a file
  10810. ** is called page 1. 0 is used to represent "not a page".
  10811. */
  10812. typedef u32 Pgno;
  10813. /*
  10814. ** Each open file is managed by a separate instance of the "Pager" structure.
  10815. */
  10816. typedef struct Pager Pager;
  10817. /*
  10818. ** Handle type for pages.
  10819. */
  10820. typedef struct PgHdr DbPage;
  10821. /*
  10822. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  10823. ** reserved for working around a windows/posix incompatibility). It is
  10824. ** used in the journal to signify that the remainder of the journal file
  10825. ** is devoted to storing a master journal name - there are no more pages to
  10826. ** roll back. See comments for function writeMasterJournal() in pager.c
  10827. ** for details.
  10828. */
  10829. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  10830. /*
  10831. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  10832. **
  10833. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  10834. */
  10835. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  10836. #define PAGER_MEMORY 0x0002 /* In-memory database */
  10837. /*
  10838. ** Valid values for the second argument to sqlite3PagerLockingMode().
  10839. */
  10840. #define PAGER_LOCKINGMODE_QUERY -1
  10841. #define PAGER_LOCKINGMODE_NORMAL 0
  10842. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  10843. /*
  10844. ** Numeric constants that encode the journalmode.
  10845. */
  10846. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  10847. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  10848. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  10849. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  10850. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  10851. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  10852. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  10853. /*
  10854. ** Flags that make up the mask passed to sqlite3PagerGet().
  10855. */
  10856. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  10857. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  10858. /*
  10859. ** Flags for sqlite3PagerSetFlags()
  10860. */
  10861. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  10862. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  10863. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  10864. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  10865. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  10866. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  10867. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  10868. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  10869. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  10870. /*
  10871. ** The remainder of this file contains the declarations of the functions
  10872. ** that make up the Pager sub-system API. See source code comments for
  10873. ** a detailed description of each routine.
  10874. */
  10875. /* Open and close a Pager connection. */
  10876. SQLITE_PRIVATE int sqlite3PagerOpen(
  10877. sqlite3_vfs*,
  10878. Pager **ppPager,
  10879. const char*,
  10880. int,
  10881. int,
  10882. int,
  10883. void(*)(DbPage*)
  10884. );
  10885. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  10886. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  10887. /* Functions used to configure a Pager object. */
  10888. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  10889. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  10890. #ifdef SQLITE_HAS_CODEC
  10891. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  10892. #endif
  10893. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  10894. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  10895. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  10896. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  10897. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  10898. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  10899. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  10900. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  10901. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  10902. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  10903. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  10904. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  10905. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  10906. /* Functions used to obtain and release page references. */
  10907. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  10908. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  10909. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  10910. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  10911. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  10912. /* Operations on page references. */
  10913. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  10914. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  10915. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  10916. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  10917. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  10918. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  10919. /* Functions used to manage pager transactions and savepoints. */
  10920. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  10921. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  10922. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  10923. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  10924. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  10925. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  10926. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  10927. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  10928. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  10929. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  10930. #ifndef SQLITE_OMIT_WAL
  10931. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  10932. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  10933. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  10934. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  10935. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  10936. # ifdef SQLITE_ENABLE_SNAPSHOT
  10937. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  10938. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  10939. # endif
  10940. #endif
  10941. #ifdef SQLITE_ENABLE_ZIPVFS
  10942. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  10943. #endif
  10944. /* Functions used to query pager state and configuration. */
  10945. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  10946. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  10947. #ifdef SQLITE_DEBUG
  10948. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  10949. #endif
  10950. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  10951. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  10952. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  10953. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  10954. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  10955. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  10956. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  10957. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  10958. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  10959. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  10960. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  10961. /* Functions used to truncate the database file. */
  10962. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  10963. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  10964. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  10965. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  10966. #endif
  10967. /* Functions to support testing and debugging. */
  10968. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  10969. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  10970. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  10971. #endif
  10972. #ifdef SQLITE_TEST
  10973. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  10974. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  10975. void disable_simulated_io_errors(void);
  10976. void enable_simulated_io_errors(void);
  10977. #else
  10978. # define disable_simulated_io_errors()
  10979. # define enable_simulated_io_errors()
  10980. #endif
  10981. #endif /* _PAGER_H_ */
  10982. /************** End of pager.h ***********************************************/
  10983. /************** Continuing where we left off in sqliteInt.h ******************/
  10984. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  10985. /************** Begin file pcache.h ******************************************/
  10986. /*
  10987. ** 2008 August 05
  10988. **
  10989. ** The author disclaims copyright to this source code. In place of
  10990. ** a legal notice, here is a blessing:
  10991. **
  10992. ** May you do good and not evil.
  10993. ** May you find forgiveness for yourself and forgive others.
  10994. ** May you share freely, never taking more than you give.
  10995. **
  10996. *************************************************************************
  10997. ** This header file defines the interface that the sqlite page cache
  10998. ** subsystem.
  10999. */
  11000. #ifndef _PCACHE_H_
  11001. typedef struct PgHdr PgHdr;
  11002. typedef struct PCache PCache;
  11003. /*
  11004. ** Every page in the cache is controlled by an instance of the following
  11005. ** structure.
  11006. */
  11007. struct PgHdr {
  11008. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  11009. void *pData; /* Page data */
  11010. void *pExtra; /* Extra content */
  11011. PgHdr *pDirty; /* Transient list of dirty pages */
  11012. Pager *pPager; /* The pager this page is part of */
  11013. Pgno pgno; /* Page number for this page */
  11014. #ifdef SQLITE_CHECK_PAGES
  11015. u32 pageHash; /* Hash of page content */
  11016. #endif
  11017. u16 flags; /* PGHDR flags defined below */
  11018. /**********************************************************************
  11019. ** Elements above are public. All that follows is private to pcache.c
  11020. ** and should not be accessed by other modules.
  11021. */
  11022. i16 nRef; /* Number of users of this page */
  11023. PCache *pCache; /* Cache that owns this page */
  11024. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  11025. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  11026. };
  11027. /* Bit values for PgHdr.flags */
  11028. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  11029. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  11030. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  11031. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  11032. ** writing this page to the database */
  11033. #define PGHDR_NEED_READ 0x010 /* Content is unread */
  11034. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  11035. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  11036. #define PGHDR_WAL_APPEND 0x080 /* Appended to wal file */
  11037. /* Initialize and shutdown the page cache subsystem */
  11038. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  11039. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  11040. /* Page cache buffer management:
  11041. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  11042. */
  11043. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  11044. /* Create a new pager cache.
  11045. ** Under memory stress, invoke xStress to try to make pages clean.
  11046. ** Only clean and unpinned pages can be reclaimed.
  11047. */
  11048. SQLITE_PRIVATE int sqlite3PcacheOpen(
  11049. int szPage, /* Size of every page */
  11050. int szExtra, /* Extra space associated with each page */
  11051. int bPurgeable, /* True if pages are on backing store */
  11052. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  11053. void *pStress, /* Argument to xStress */
  11054. PCache *pToInit /* Preallocated space for the PCache */
  11055. );
  11056. /* Modify the page-size after the cache has been created. */
  11057. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  11058. /* Return the size in bytes of a PCache object. Used to preallocate
  11059. ** storage space.
  11060. */
  11061. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  11062. /* One release per successful fetch. Page is pinned until released.
  11063. ** Reference counted.
  11064. */
  11065. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  11066. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  11067. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  11068. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  11069. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  11070. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  11071. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  11072. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  11073. /* Change a page number. Used by incr-vacuum. */
  11074. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  11075. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  11076. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  11077. /* Get a list of all dirty pages in the cache, sorted by page number */
  11078. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  11079. /* Reset and close the cache object */
  11080. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  11081. /* Clear flags from pages of the page cache */
  11082. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  11083. /* Discard the contents of the cache */
  11084. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  11085. /* Return the total number of outstanding page references */
  11086. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  11087. /* Increment the reference count of an existing page */
  11088. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  11089. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  11090. /* Return the total number of pages stored in the cache */
  11091. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  11092. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  11093. /* Iterate through all dirty pages currently stored in the cache. This
  11094. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  11095. ** library is built.
  11096. */
  11097. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  11098. #endif
  11099. /* Set and get the suggested cache-size for the specified pager-cache.
  11100. **
  11101. ** If no global maximum is configured, then the system attempts to limit
  11102. ** the total number of pages cached by purgeable pager-caches to the sum
  11103. ** of the suggested cache-sizes.
  11104. */
  11105. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  11106. #ifdef SQLITE_TEST
  11107. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  11108. #endif
  11109. /* Set or get the suggested spill-size for the specified pager-cache.
  11110. **
  11111. ** The spill-size is the minimum number of pages in cache before the cache
  11112. ** will attempt to spill dirty pages by calling xStress.
  11113. */
  11114. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  11115. /* Free up as much memory as possible from the page cache */
  11116. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  11117. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  11118. /* Try to return memory used by the pcache module to the main memory heap */
  11119. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  11120. #endif
  11121. #ifdef SQLITE_TEST
  11122. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  11123. #endif
  11124. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  11125. /* Return the header size */
  11126. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  11127. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  11128. #endif /* _PCACHE_H_ */
  11129. /************** End of pcache.h **********************************************/
  11130. /************** Continuing where we left off in sqliteInt.h ******************/
  11131. /************** Include os.h in the middle of sqliteInt.h ********************/
  11132. /************** Begin file os.h **********************************************/
  11133. /*
  11134. ** 2001 September 16
  11135. **
  11136. ** The author disclaims copyright to this source code. In place of
  11137. ** a legal notice, here is a blessing:
  11138. **
  11139. ** May you do good and not evil.
  11140. ** May you find forgiveness for yourself and forgive others.
  11141. ** May you share freely, never taking more than you give.
  11142. **
  11143. ******************************************************************************
  11144. **
  11145. ** This header file (together with is companion C source-code file
  11146. ** "os.c") attempt to abstract the underlying operating system so that
  11147. ** the SQLite library will work on both POSIX and windows systems.
  11148. **
  11149. ** This header file is #include-ed by sqliteInt.h and thus ends up
  11150. ** being included by every source file.
  11151. */
  11152. #ifndef _SQLITE_OS_H_
  11153. #define _SQLITE_OS_H_
  11154. /*
  11155. ** Attempt to automatically detect the operating system and setup the
  11156. ** necessary pre-processor macros for it.
  11157. */
  11158. /************** Include os_setup.h in the middle of os.h *********************/
  11159. /************** Begin file os_setup.h ****************************************/
  11160. /*
  11161. ** 2013 November 25
  11162. **
  11163. ** The author disclaims copyright to this source code. In place of
  11164. ** a legal notice, here is a blessing:
  11165. **
  11166. ** May you do good and not evil.
  11167. ** May you find forgiveness for yourself and forgive others.
  11168. ** May you share freely, never taking more than you give.
  11169. **
  11170. ******************************************************************************
  11171. **
  11172. ** This file contains pre-processor directives related to operating system
  11173. ** detection and/or setup.
  11174. */
  11175. #ifndef _OS_SETUP_H_
  11176. #define _OS_SETUP_H_
  11177. /*
  11178. ** Figure out if we are dealing with Unix, Windows, or some other operating
  11179. ** system.
  11180. **
  11181. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  11182. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  11183. ** the three will be 1. The other two will be 0.
  11184. */
  11185. #if defined(SQLITE_OS_OTHER)
  11186. # if SQLITE_OS_OTHER==1
  11187. # undef SQLITE_OS_UNIX
  11188. # define SQLITE_OS_UNIX 0
  11189. # undef SQLITE_OS_WIN
  11190. # define SQLITE_OS_WIN 0
  11191. # else
  11192. # undef SQLITE_OS_OTHER
  11193. # endif
  11194. #endif
  11195. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  11196. # define SQLITE_OS_OTHER 0
  11197. # ifndef SQLITE_OS_WIN
  11198. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  11199. defined(__MINGW32__) || defined(__BORLANDC__)
  11200. # define SQLITE_OS_WIN 1
  11201. # define SQLITE_OS_UNIX 0
  11202. # else
  11203. # define SQLITE_OS_WIN 0
  11204. # define SQLITE_OS_UNIX 1
  11205. # endif
  11206. # else
  11207. # define SQLITE_OS_UNIX 0
  11208. # endif
  11209. #else
  11210. # ifndef SQLITE_OS_WIN
  11211. # define SQLITE_OS_WIN 0
  11212. # endif
  11213. #endif
  11214. #endif /* _OS_SETUP_H_ */
  11215. /************** End of os_setup.h ********************************************/
  11216. /************** Continuing where we left off in os.h *************************/
  11217. /* If the SET_FULLSYNC macro is not defined above, then make it
  11218. ** a no-op
  11219. */
  11220. #ifndef SET_FULLSYNC
  11221. # define SET_FULLSYNC(x,y)
  11222. #endif
  11223. /*
  11224. ** The default size of a disk sector
  11225. */
  11226. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  11227. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  11228. #endif
  11229. /*
  11230. ** Temporary files are named starting with this prefix followed by 16 random
  11231. ** alphanumeric characters, and no file extension. They are stored in the
  11232. ** OS's standard temporary file directory, and are deleted prior to exit.
  11233. ** If sqlite is being embedded in another program, you may wish to change the
  11234. ** prefix to reflect your program's name, so that if your program exits
  11235. ** prematurely, old temporary files can be easily identified. This can be done
  11236. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  11237. **
  11238. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  11239. ** Mcafee started using SQLite in their anti-virus product and it
  11240. ** started putting files with the "sqlite" name in the c:/temp folder.
  11241. ** This annoyed many windows users. Those users would then do a
  11242. ** Google search for "sqlite", find the telephone numbers of the
  11243. ** developers and call to wake them up at night and complain.
  11244. ** For this reason, the default name prefix is changed to be "sqlite"
  11245. ** spelled backwards. So the temp files are still identified, but
  11246. ** anybody smart enough to figure out the code is also likely smart
  11247. ** enough to know that calling the developer will not help get rid
  11248. ** of the file.
  11249. */
  11250. #ifndef SQLITE_TEMP_FILE_PREFIX
  11251. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  11252. #endif
  11253. /*
  11254. ** The following values may be passed as the second argument to
  11255. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  11256. **
  11257. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  11258. ** RESERVED: A single process may hold a RESERVED lock on a file at
  11259. ** any time. Other processes may hold and obtain new SHARED locks.
  11260. ** PENDING: A single process may hold a PENDING lock on a file at
  11261. ** any one time. Existing SHARED locks may persist, but no new
  11262. ** SHARED locks may be obtained by other processes.
  11263. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  11264. **
  11265. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  11266. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  11267. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  11268. ** sqlite3OsLock().
  11269. */
  11270. #define NO_LOCK 0
  11271. #define SHARED_LOCK 1
  11272. #define RESERVED_LOCK 2
  11273. #define PENDING_LOCK 3
  11274. #define EXCLUSIVE_LOCK 4
  11275. /*
  11276. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  11277. **
  11278. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  11279. ** those functions are not available. So we use only LockFile() and
  11280. ** UnlockFile().
  11281. **
  11282. ** LockFile() prevents not just writing but also reading by other processes.
  11283. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  11284. ** byte out of a specific range of bytes. The lock byte is obtained at
  11285. ** random so two separate readers can probably access the file at the
  11286. ** same time, unless they are unlucky and choose the same lock byte.
  11287. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  11288. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  11289. ** a single byte of the file that is designated as the reserved lock byte.
  11290. ** A PENDING_LOCK is obtained by locking a designated byte different from
  11291. ** the RESERVED_LOCK byte.
  11292. **
  11293. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  11294. ** which means we can use reader/writer locks. When reader/writer locks
  11295. ** are used, the lock is placed on the same range of bytes that is used
  11296. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  11297. ** will support two or more Win95 readers or two or more WinNT readers.
  11298. ** But a single Win95 reader will lock out all WinNT readers and a single
  11299. ** WinNT reader will lock out all other Win95 readers.
  11300. **
  11301. ** The following #defines specify the range of bytes used for locking.
  11302. ** SHARED_SIZE is the number of bytes available in the pool from which
  11303. ** a random byte is selected for a shared lock. The pool of bytes for
  11304. ** shared locks begins at SHARED_FIRST.
  11305. **
  11306. ** The same locking strategy and
  11307. ** byte ranges are used for Unix. This leaves open the possibility of having
  11308. ** clients on win95, winNT, and unix all talking to the same shared file
  11309. ** and all locking correctly. To do so would require that samba (or whatever
  11310. ** tool is being used for file sharing) implements locks correctly between
  11311. ** windows and unix. I'm guessing that isn't likely to happen, but by
  11312. ** using the same locking range we are at least open to the possibility.
  11313. **
  11314. ** Locking in windows is manditory. For this reason, we cannot store
  11315. ** actual data in the bytes used for locking. The pager never allocates
  11316. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  11317. ** that all locks will fit on a single page even at the minimum page size.
  11318. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  11319. ** is set high so that we don't have to allocate an unused page except
  11320. ** for very large databases. But one should test the page skipping logic
  11321. ** by setting PENDING_BYTE low and running the entire regression suite.
  11322. **
  11323. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  11324. ** file format. Depending on how it is changed, you might not notice
  11325. ** the incompatibility right away, even running a full regression test.
  11326. ** The default location of PENDING_BYTE is the first byte past the
  11327. ** 1GB boundary.
  11328. **
  11329. */
  11330. #ifdef SQLITE_OMIT_WSD
  11331. # define PENDING_BYTE (0x40000000)
  11332. #else
  11333. # define PENDING_BYTE sqlite3PendingByte
  11334. #endif
  11335. #define RESERVED_BYTE (PENDING_BYTE+1)
  11336. #define SHARED_FIRST (PENDING_BYTE+2)
  11337. #define SHARED_SIZE 510
  11338. /*
  11339. ** Wrapper around OS specific sqlite3_os_init() function.
  11340. */
  11341. SQLITE_PRIVATE int sqlite3OsInit(void);
  11342. /*
  11343. ** Functions for accessing sqlite3_file methods
  11344. */
  11345. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  11346. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  11347. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  11348. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  11349. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  11350. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  11351. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  11352. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  11353. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  11354. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  11355. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  11356. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  11357. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  11358. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  11359. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  11360. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  11361. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  11362. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  11363. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  11364. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  11365. /*
  11366. ** Functions for accessing sqlite3_vfs methods
  11367. */
  11368. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  11369. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  11370. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  11371. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  11372. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11373. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  11374. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  11375. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  11376. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  11377. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  11378. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  11379. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  11380. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  11381. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  11382. /*
  11383. ** Convenience functions for opening and closing files using
  11384. ** sqlite3_malloc() to obtain space for the file-handle structure.
  11385. */
  11386. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  11387. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  11388. #endif /* _SQLITE_OS_H_ */
  11389. /************** End of os.h **************************************************/
  11390. /************** Continuing where we left off in sqliteInt.h ******************/
  11391. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  11392. /************** Begin file mutex.h *******************************************/
  11393. /*
  11394. ** 2007 August 28
  11395. **
  11396. ** The author disclaims copyright to this source code. In place of
  11397. ** a legal notice, here is a blessing:
  11398. **
  11399. ** May you do good and not evil.
  11400. ** May you find forgiveness for yourself and forgive others.
  11401. ** May you share freely, never taking more than you give.
  11402. **
  11403. *************************************************************************
  11404. **
  11405. ** This file contains the common header for all mutex implementations.
  11406. ** The sqliteInt.h header #includes this file so that it is available
  11407. ** to all source files. We break it out in an effort to keep the code
  11408. ** better organized.
  11409. **
  11410. ** NOTE: source files should *not* #include this header file directly.
  11411. ** Source files should #include the sqliteInt.h file and let that file
  11412. ** include this one indirectly.
  11413. */
  11414. /*
  11415. ** Figure out what version of the code to use. The choices are
  11416. **
  11417. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  11418. ** mutexes implementation cannot be overridden
  11419. ** at start-time.
  11420. **
  11421. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  11422. ** mutual exclusion is provided. But this
  11423. ** implementation can be overridden at
  11424. ** start-time.
  11425. **
  11426. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  11427. **
  11428. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  11429. */
  11430. #if !SQLITE_THREADSAFE
  11431. # define SQLITE_MUTEX_OMIT
  11432. #endif
  11433. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  11434. # if SQLITE_OS_UNIX
  11435. # define SQLITE_MUTEX_PTHREADS
  11436. # elif SQLITE_OS_WIN
  11437. # define SQLITE_MUTEX_W32
  11438. # else
  11439. # define SQLITE_MUTEX_NOOP
  11440. # endif
  11441. #endif
  11442. #ifdef SQLITE_MUTEX_OMIT
  11443. /*
  11444. ** If this is a no-op implementation, implement everything as macros.
  11445. */
  11446. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  11447. #define sqlite3_mutex_free(X)
  11448. #define sqlite3_mutex_enter(X)
  11449. #define sqlite3_mutex_try(X) SQLITE_OK
  11450. #define sqlite3_mutex_leave(X)
  11451. #define sqlite3_mutex_held(X) ((void)(X),1)
  11452. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  11453. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  11454. #define sqlite3MutexInit() SQLITE_OK
  11455. #define sqlite3MutexEnd()
  11456. #define MUTEX_LOGIC(X)
  11457. #else
  11458. #define MUTEX_LOGIC(X) X
  11459. #endif /* defined(SQLITE_MUTEX_OMIT) */
  11460. /************** End of mutex.h ***********************************************/
  11461. /************** Continuing where we left off in sqliteInt.h ******************/
  11462. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  11463. ** synchronous setting to EXTRA. It is no longer supported.
  11464. */
  11465. #ifdef SQLITE_EXTRA_DURABLE
  11466. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  11467. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  11468. #endif
  11469. /*
  11470. ** Default synchronous levels.
  11471. **
  11472. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  11473. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  11474. **
  11475. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  11476. ** OFF 1 0
  11477. ** NORMAL 2 1
  11478. ** FULL 3 2
  11479. ** EXTRA 4 3
  11480. **
  11481. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  11482. ** In other words, the zero-based numbers are used for all external interfaces
  11483. ** and the one-based values are used internally.
  11484. */
  11485. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  11486. # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
  11487. #endif
  11488. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  11489. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  11490. #endif
  11491. /*
  11492. ** Each database file to be accessed by the system is an instance
  11493. ** of the following structure. There are normally two of these structures
  11494. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  11495. ** aDb[1] is the database file used to hold temporary tables. Additional
  11496. ** databases may be attached.
  11497. */
  11498. struct Db {
  11499. char *zName; /* Name of this database */
  11500. Btree *pBt; /* The B*Tree structure for this database file */
  11501. u8 safety_level; /* How aggressive at syncing data to disk */
  11502. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  11503. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  11504. };
  11505. /*
  11506. ** An instance of the following structure stores a database schema.
  11507. **
  11508. ** Most Schema objects are associated with a Btree. The exception is
  11509. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  11510. ** In shared cache mode, a single Schema object can be shared by multiple
  11511. ** Btrees that refer to the same underlying BtShared object.
  11512. **
  11513. ** Schema objects are automatically deallocated when the last Btree that
  11514. ** references them is destroyed. The TEMP Schema is manually freed by
  11515. ** sqlite3_close().
  11516. *
  11517. ** A thread must be holding a mutex on the corresponding Btree in order
  11518. ** to access Schema content. This implies that the thread must also be
  11519. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  11520. ** For a TEMP Schema, only the connection mutex is required.
  11521. */
  11522. struct Schema {
  11523. int schema_cookie; /* Database schema version number for this file */
  11524. int iGeneration; /* Generation counter. Incremented with each change */
  11525. Hash tblHash; /* All tables indexed by name */
  11526. Hash idxHash; /* All (named) indices indexed by name */
  11527. Hash trigHash; /* All triggers indexed by name */
  11528. Hash fkeyHash; /* All foreign keys by referenced table name */
  11529. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  11530. u8 file_format; /* Schema format version for this file */
  11531. u8 enc; /* Text encoding used by this database */
  11532. u16 schemaFlags; /* Flags associated with this schema */
  11533. int cache_size; /* Number of pages to use in the cache */
  11534. };
  11535. /*
  11536. ** These macros can be used to test, set, or clear bits in the
  11537. ** Db.pSchema->flags field.
  11538. */
  11539. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  11540. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  11541. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  11542. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  11543. /*
  11544. ** Allowed values for the DB.pSchema->flags field.
  11545. **
  11546. ** The DB_SchemaLoaded flag is set after the database schema has been
  11547. ** read into internal hash tables.
  11548. **
  11549. ** DB_UnresetViews means that one or more views have column names that
  11550. ** have been filled out. If the schema changes, these column names might
  11551. ** changes and so the view will need to be reset.
  11552. */
  11553. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  11554. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  11555. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  11556. /*
  11557. ** The number of different kinds of things that can be limited
  11558. ** using the sqlite3_limit() interface.
  11559. */
  11560. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  11561. /*
  11562. ** Lookaside malloc is a set of fixed-size buffers that can be used
  11563. ** to satisfy small transient memory allocation requests for objects
  11564. ** associated with a particular database connection. The use of
  11565. ** lookaside malloc provides a significant performance enhancement
  11566. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  11567. ** SQL statements.
  11568. **
  11569. ** The Lookaside structure holds configuration information about the
  11570. ** lookaside malloc subsystem. Each available memory allocation in
  11571. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  11572. ** objects.
  11573. **
  11574. ** Lookaside allocations are only allowed for objects that are associated
  11575. ** with a particular database connection. Hence, schema information cannot
  11576. ** be stored in lookaside because in shared cache mode the schema information
  11577. ** is shared by multiple database connections. Therefore, while parsing
  11578. ** schema information, the Lookaside.bEnabled flag is cleared so that
  11579. ** lookaside allocations are not used to construct the schema objects.
  11580. */
  11581. struct Lookaside {
  11582. u32 bDisable; /* Only operate the lookaside when zero */
  11583. u16 sz; /* Size of each buffer in bytes */
  11584. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  11585. int nOut; /* Number of buffers currently checked out */
  11586. int mxOut; /* Highwater mark for nOut */
  11587. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  11588. LookasideSlot *pFree; /* List of available buffers */
  11589. void *pStart; /* First byte of available memory space */
  11590. void *pEnd; /* First byte past end of available space */
  11591. };
  11592. struct LookasideSlot {
  11593. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  11594. };
  11595. /*
  11596. ** A hash table for built-in function definitions. (Application-defined
  11597. ** functions use a regular table table from hash.h.)
  11598. **
  11599. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  11600. ** Collisions are on the FuncDef.u.pHash chain.
  11601. */
  11602. #define SQLITE_FUNC_HASH_SZ 23
  11603. struct FuncDefHash {
  11604. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  11605. };
  11606. #ifdef SQLITE_USER_AUTHENTICATION
  11607. /*
  11608. ** Information held in the "sqlite3" database connection object and used
  11609. ** to manage user authentication.
  11610. */
  11611. typedef struct sqlite3_userauth sqlite3_userauth;
  11612. struct sqlite3_userauth {
  11613. u8 authLevel; /* Current authentication level */
  11614. int nAuthPW; /* Size of the zAuthPW in bytes */
  11615. char *zAuthPW; /* Password used to authenticate */
  11616. char *zAuthUser; /* User name used to authenticate */
  11617. };
  11618. /* Allowed values for sqlite3_userauth.authLevel */
  11619. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  11620. #define UAUTH_Fail 1 /* User authentication failed */
  11621. #define UAUTH_User 2 /* Authenticated as a normal user */
  11622. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  11623. /* Functions used only by user authorization logic */
  11624. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  11625. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  11626. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  11627. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  11628. #endif /* SQLITE_USER_AUTHENTICATION */
  11629. /*
  11630. ** typedef for the authorization callback function.
  11631. */
  11632. #ifdef SQLITE_USER_AUTHENTICATION
  11633. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  11634. const char*, const char*);
  11635. #else
  11636. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  11637. const char*);
  11638. #endif
  11639. /*
  11640. ** Each database connection is an instance of the following structure.
  11641. */
  11642. struct sqlite3 {
  11643. sqlite3_vfs *pVfs; /* OS Interface */
  11644. struct Vdbe *pVdbe; /* List of active virtual machines */
  11645. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  11646. sqlite3_mutex *mutex; /* Connection mutex */
  11647. Db *aDb; /* All backends */
  11648. int nDb; /* Number of backends currently in use */
  11649. int flags; /* Miscellaneous flags. See below */
  11650. i64 lastRowid; /* ROWID of most recent insert (see above) */
  11651. i64 szMmap; /* Default mmap_size setting */
  11652. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  11653. int errCode; /* Most recent error code (SQLITE_*) */
  11654. int errMask; /* & result codes with this before returning */
  11655. int iSysErrno; /* Errno value from last system error */
  11656. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  11657. u8 enc; /* Text encoding */
  11658. u8 autoCommit; /* The auto-commit flag. */
  11659. u8 temp_store; /* 1: file 2: memory 0: default */
  11660. u8 mallocFailed; /* True if we have seen a malloc failure */
  11661. u8 bBenignMalloc; /* Do not require OOMs if true */
  11662. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  11663. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  11664. u8 suppressErr; /* Do not issue error messages if true */
  11665. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  11666. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  11667. int nextPagesize; /* Pagesize after VACUUM if >0 */
  11668. u32 magic; /* Magic number for detect library misuse */
  11669. int nChange; /* Value returned by sqlite3_changes() */
  11670. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  11671. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  11672. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  11673. struct sqlite3InitInfo { /* Information used during initialization */
  11674. int newTnum; /* Rootpage of table being initialized */
  11675. u8 iDb; /* Which db file is being initialized */
  11676. u8 busy; /* TRUE if currently initializing */
  11677. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  11678. u8 imposterTable; /* Building an imposter table */
  11679. } init;
  11680. int nVdbeActive; /* Number of VDBEs currently running */
  11681. int nVdbeRead; /* Number of active VDBEs that read or write */
  11682. int nVdbeWrite; /* Number of active VDBEs that read and write */
  11683. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  11684. int nVDestroy; /* Number of active OP_VDestroy operations */
  11685. int nExtension; /* Number of loaded extensions */
  11686. void **aExtension; /* Array of shared library handles */
  11687. void (*xTrace)(void*,const char*); /* Trace function */
  11688. void *pTraceArg; /* Argument to the trace function */
  11689. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  11690. void *pProfileArg; /* Argument to profile function */
  11691. void *pCommitArg; /* Argument to xCommitCallback() */
  11692. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  11693. void *pRollbackArg; /* Argument to xRollbackCallback() */
  11694. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  11695. void *pUpdateArg;
  11696. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  11697. #ifndef SQLITE_OMIT_WAL
  11698. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  11699. void *pWalArg;
  11700. #endif
  11701. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  11702. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  11703. void *pCollNeededArg;
  11704. sqlite3_value *pErr; /* Most recent error message */
  11705. union {
  11706. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  11707. double notUsed1; /* Spacer */
  11708. } u1;
  11709. Lookaside lookaside; /* Lookaside malloc configuration */
  11710. #ifndef SQLITE_OMIT_AUTHORIZATION
  11711. sqlite3_xauth xAuth; /* Access authorization function */
  11712. void *pAuthArg; /* 1st argument to the access auth function */
  11713. #endif
  11714. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  11715. int (*xProgress)(void *); /* The progress callback */
  11716. void *pProgressArg; /* Argument to the progress callback */
  11717. unsigned nProgressOps; /* Number of opcodes for progress callback */
  11718. #endif
  11719. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11720. int nVTrans; /* Allocated size of aVTrans */
  11721. Hash aModule; /* populated by sqlite3_create_module() */
  11722. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  11723. VTable **aVTrans; /* Virtual tables with open transactions */
  11724. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  11725. #endif
  11726. Hash aFunc; /* Hash table of connection functions */
  11727. Hash aCollSeq; /* All collating sequences */
  11728. BusyHandler busyHandler; /* Busy callback */
  11729. Db aDbStatic[2]; /* Static space for the 2 default backends */
  11730. Savepoint *pSavepoint; /* List of active savepoints */
  11731. int busyTimeout; /* Busy handler timeout, in msec */
  11732. int nSavepoint; /* Number of non-transaction savepoints */
  11733. int nStatement; /* Number of nested statement-transactions */
  11734. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  11735. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  11736. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  11737. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11738. /* The following variables are all protected by the STATIC_MASTER
  11739. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  11740. **
  11741. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  11742. ** unlock so that it can proceed.
  11743. **
  11744. ** When X.pBlockingConnection==Y, that means that something that X tried
  11745. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  11746. ** held by Y.
  11747. */
  11748. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  11749. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  11750. void *pUnlockArg; /* Argument to xUnlockNotify */
  11751. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  11752. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  11753. #endif
  11754. #ifdef SQLITE_USER_AUTHENTICATION
  11755. sqlite3_userauth auth; /* User authentication information */
  11756. #endif
  11757. };
  11758. /*
  11759. ** A macro to discover the encoding of a database.
  11760. */
  11761. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  11762. #define ENC(db) ((db)->enc)
  11763. /*
  11764. ** Possible values for the sqlite3.flags.
  11765. */
  11766. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  11767. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  11768. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  11769. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  11770. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  11771. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  11772. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  11773. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  11774. /* DELETE, or UPDATE and return */
  11775. /* the count using a callback. */
  11776. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  11777. /* result set is empty */
  11778. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  11779. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  11780. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  11781. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  11782. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  11783. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  11784. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  11785. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  11786. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  11787. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  11788. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  11789. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  11790. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  11791. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  11792. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  11793. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  11794. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  11795. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  11796. #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
  11797. #define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
  11798. #define SQLITE_Fts3Tokenizer 0x20000000 /* Enable fts3_tokenizer(2) */
  11799. /*
  11800. ** Bits of the sqlite3.dbOptFlags field that are used by the
  11801. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  11802. ** selectively disable various optimizations.
  11803. */
  11804. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  11805. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  11806. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  11807. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  11808. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  11809. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  11810. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  11811. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  11812. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  11813. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  11814. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  11815. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  11816. #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
  11817. #define SQLITE_AllOpts 0xffff /* All optimizations */
  11818. /*
  11819. ** Macros for testing whether or not optimizations are enabled or disabled.
  11820. */
  11821. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11822. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  11823. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  11824. #else
  11825. #define OptimizationDisabled(db, mask) 0
  11826. #define OptimizationEnabled(db, mask) 1
  11827. #endif
  11828. /*
  11829. ** Return true if it OK to factor constant expressions into the initialization
  11830. ** code. The argument is a Parse object for the code generator.
  11831. */
  11832. #define ConstFactorOk(P) ((P)->okConstFactor)
  11833. /*
  11834. ** Possible values for the sqlite.magic field.
  11835. ** The numbers are obtained at random and have no special meaning, other
  11836. ** than being distinct from one another.
  11837. */
  11838. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  11839. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  11840. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  11841. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  11842. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  11843. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  11844. /*
  11845. ** Each SQL function is defined by an instance of the following
  11846. ** structure. For global built-in functions (ex: substr(), max(), count())
  11847. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  11848. ** For per-connection application-defined functions, a pointer to this
  11849. ** structure is held in the db->aHash hash table.
  11850. **
  11851. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  11852. ** field is used by per-connection app-def functions.
  11853. */
  11854. struct FuncDef {
  11855. i8 nArg; /* Number of arguments. -1 means unlimited */
  11856. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  11857. void *pUserData; /* User data parameter */
  11858. FuncDef *pNext; /* Next function with same name */
  11859. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  11860. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  11861. const char *zName; /* SQL name of the function. */
  11862. union {
  11863. FuncDef *pHash; /* Next with a different name but the same hash */
  11864. FuncDestructor *pDestructor; /* Reference counted destructor function */
  11865. } u;
  11866. };
  11867. /*
  11868. ** This structure encapsulates a user-function destructor callback (as
  11869. ** configured using create_function_v2()) and a reference counter. When
  11870. ** create_function_v2() is called to create a function with a destructor,
  11871. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  11872. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  11873. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  11874. ** member of each of the new FuncDef objects is set to point to the allocated
  11875. ** FuncDestructor.
  11876. **
  11877. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  11878. ** count on this object is decremented. When it reaches 0, the destructor
  11879. ** is invoked and the FuncDestructor structure freed.
  11880. */
  11881. struct FuncDestructor {
  11882. int nRef;
  11883. void (*xDestroy)(void *);
  11884. void *pUserData;
  11885. };
  11886. /*
  11887. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  11888. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  11889. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  11890. ** are assert() statements in the code to verify this.
  11891. */
  11892. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  11893. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  11894. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  11895. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  11896. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  11897. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  11898. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  11899. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  11900. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  11901. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  11902. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  11903. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  11904. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  11905. ** single query - might change over time */
  11906. /*
  11907. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  11908. ** used to create the initializers for the FuncDef structures.
  11909. **
  11910. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  11911. ** Used to create a scalar function definition of a function zName
  11912. ** implemented by C function xFunc that accepts nArg arguments. The
  11913. ** value passed as iArg is cast to a (void*) and made available
  11914. ** as the user-data (sqlite3_user_data()) for the function. If
  11915. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  11916. **
  11917. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  11918. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  11919. **
  11920. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  11921. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  11922. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  11923. ** and functions like sqlite_version() that can change, but not during
  11924. ** a single query.
  11925. **
  11926. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  11927. ** Used to create an aggregate function definition implemented by
  11928. ** the C functions xStep and xFinal. The first four parameters
  11929. ** are interpreted in the same way as the first 4 parameters to
  11930. ** FUNCTION().
  11931. **
  11932. ** LIKEFUNC(zName, nArg, pArg, flags)
  11933. ** Used to create a scalar function definition of a function zName
  11934. ** that accepts nArg arguments and is implemented by a call to C
  11935. ** function likeFunc. Argument pArg is cast to a (void *) and made
  11936. ** available as the function user-data (sqlite3_user_data()). The
  11937. ** FuncDef.flags variable is set to the value passed as the flags
  11938. ** parameter.
  11939. */
  11940. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11941. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11942. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  11943. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11944. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11945. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  11946. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11947. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11948. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  11949. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  11950. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  11951. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  11952. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  11953. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11954. pArg, 0, xFunc, 0, #zName, }
  11955. #define LIKEFUNC(zName, nArg, arg, flags) \
  11956. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  11957. (void *)arg, 0, likeFunc, 0, #zName, {0} }
  11958. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  11959. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  11960. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  11961. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  11962. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  11963. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  11964. /*
  11965. ** All current savepoints are stored in a linked list starting at
  11966. ** sqlite3.pSavepoint. The first element in the list is the most recently
  11967. ** opened savepoint. Savepoints are added to the list by the vdbe
  11968. ** OP_Savepoint instruction.
  11969. */
  11970. struct Savepoint {
  11971. char *zName; /* Savepoint name (nul-terminated) */
  11972. i64 nDeferredCons; /* Number of deferred fk violations */
  11973. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  11974. Savepoint *pNext; /* Parent savepoint (if any) */
  11975. };
  11976. /*
  11977. ** The following are used as the second parameter to sqlite3Savepoint(),
  11978. ** and as the P1 argument to the OP_Savepoint instruction.
  11979. */
  11980. #define SAVEPOINT_BEGIN 0
  11981. #define SAVEPOINT_RELEASE 1
  11982. #define SAVEPOINT_ROLLBACK 2
  11983. /*
  11984. ** Each SQLite module (virtual table definition) is defined by an
  11985. ** instance of the following structure, stored in the sqlite3.aModule
  11986. ** hash table.
  11987. */
  11988. struct Module {
  11989. const sqlite3_module *pModule; /* Callback pointers */
  11990. const char *zName; /* Name passed to create_module() */
  11991. void *pAux; /* pAux passed to create_module() */
  11992. void (*xDestroy)(void *); /* Module destructor function */
  11993. Table *pEpoTab; /* Eponymous table for this module */
  11994. };
  11995. /*
  11996. ** information about each column of an SQL table is held in an instance
  11997. ** of this structure.
  11998. */
  11999. struct Column {
  12000. char *zName; /* Name of this column, \000, then the type */
  12001. Expr *pDflt; /* Default value of this column */
  12002. char *zColl; /* Collating sequence. If NULL, use the default */
  12003. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  12004. char affinity; /* One of the SQLITE_AFF_... values */
  12005. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  12006. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  12007. };
  12008. /* Allowed values for Column.colFlags:
  12009. */
  12010. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  12011. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  12012. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  12013. /*
  12014. ** A "Collating Sequence" is defined by an instance of the following
  12015. ** structure. Conceptually, a collating sequence consists of a name and
  12016. ** a comparison routine that defines the order of that sequence.
  12017. **
  12018. ** If CollSeq.xCmp is NULL, it means that the
  12019. ** collating sequence is undefined. Indices built on an undefined
  12020. ** collating sequence may not be read or written.
  12021. */
  12022. struct CollSeq {
  12023. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  12024. u8 enc; /* Text encoding handled by xCmp() */
  12025. void *pUser; /* First argument to xCmp() */
  12026. int (*xCmp)(void*,int, const void*, int, const void*);
  12027. void (*xDel)(void*); /* Destructor for pUser */
  12028. };
  12029. /*
  12030. ** A sort order can be either ASC or DESC.
  12031. */
  12032. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  12033. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  12034. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  12035. /*
  12036. ** Column affinity types.
  12037. **
  12038. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  12039. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  12040. ** the speed a little by numbering the values consecutively.
  12041. **
  12042. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  12043. ** when multiple affinity types are concatenated into a string and
  12044. ** used as the P4 operand, they will be more readable.
  12045. **
  12046. ** Note also that the numeric types are grouped together so that testing
  12047. ** for a numeric type is a single comparison. And the BLOB type is first.
  12048. */
  12049. #define SQLITE_AFF_BLOB 'A'
  12050. #define SQLITE_AFF_TEXT 'B'
  12051. #define SQLITE_AFF_NUMERIC 'C'
  12052. #define SQLITE_AFF_INTEGER 'D'
  12053. #define SQLITE_AFF_REAL 'E'
  12054. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  12055. /*
  12056. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  12057. ** affinity value.
  12058. */
  12059. #define SQLITE_AFF_MASK 0x47
  12060. /*
  12061. ** Additional bit values that can be ORed with an affinity without
  12062. ** changing the affinity.
  12063. **
  12064. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  12065. ** It causes an assert() to fire if either operand to a comparison
  12066. ** operator is NULL. It is added to certain comparison operators to
  12067. ** prove that the operands are always NOT NULL.
  12068. */
  12069. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  12070. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  12071. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  12072. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  12073. /*
  12074. ** An object of this type is created for each virtual table present in
  12075. ** the database schema.
  12076. **
  12077. ** If the database schema is shared, then there is one instance of this
  12078. ** structure for each database connection (sqlite3*) that uses the shared
  12079. ** schema. This is because each database connection requires its own unique
  12080. ** instance of the sqlite3_vtab* handle used to access the virtual table
  12081. ** implementation. sqlite3_vtab* handles can not be shared between
  12082. ** database connections, even when the rest of the in-memory database
  12083. ** schema is shared, as the implementation often stores the database
  12084. ** connection handle passed to it via the xConnect() or xCreate() method
  12085. ** during initialization internally. This database connection handle may
  12086. ** then be used by the virtual table implementation to access real tables
  12087. ** within the database. So that they appear as part of the callers
  12088. ** transaction, these accesses need to be made via the same database
  12089. ** connection as that used to execute SQL operations on the virtual table.
  12090. **
  12091. ** All VTable objects that correspond to a single table in a shared
  12092. ** database schema are initially stored in a linked-list pointed to by
  12093. ** the Table.pVTable member variable of the corresponding Table object.
  12094. ** When an sqlite3_prepare() operation is required to access the virtual
  12095. ** table, it searches the list for the VTable that corresponds to the
  12096. ** database connection doing the preparing so as to use the correct
  12097. ** sqlite3_vtab* handle in the compiled query.
  12098. **
  12099. ** When an in-memory Table object is deleted (for example when the
  12100. ** schema is being reloaded for some reason), the VTable objects are not
  12101. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  12102. ** immediately. Instead, they are moved from the Table.pVTable list to
  12103. ** another linked list headed by the sqlite3.pDisconnect member of the
  12104. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  12105. ** next time a statement is prepared using said sqlite3*. This is done
  12106. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  12107. ** Refer to comments above function sqlite3VtabUnlockList() for an
  12108. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  12109. ** list without holding the corresponding sqlite3.mutex mutex.
  12110. **
  12111. ** The memory for objects of this type is always allocated by
  12112. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  12113. ** the first argument.
  12114. */
  12115. struct VTable {
  12116. sqlite3 *db; /* Database connection associated with this table */
  12117. Module *pMod; /* Pointer to module implementation */
  12118. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  12119. int nRef; /* Number of pointers to this structure */
  12120. u8 bConstraint; /* True if constraints are supported */
  12121. int iSavepoint; /* Depth of the SAVEPOINT stack */
  12122. VTable *pNext; /* Next in linked list (see above) */
  12123. };
  12124. /*
  12125. ** The schema for each SQL table and view is represented in memory
  12126. ** by an instance of the following structure.
  12127. */
  12128. struct Table {
  12129. char *zName; /* Name of the table or view */
  12130. Column *aCol; /* Information about each column */
  12131. Index *pIndex; /* List of SQL indexes on this table. */
  12132. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  12133. FKey *pFKey; /* Linked list of all foreign keys in this table */
  12134. char *zColAff; /* String defining the affinity of each column */
  12135. ExprList *pCheck; /* All CHECK constraints */
  12136. /* ... also used as column name list in a VIEW */
  12137. int tnum; /* Root BTree page for this table */
  12138. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  12139. i16 nCol; /* Number of columns in this table */
  12140. u16 nRef; /* Number of pointers to this Table */
  12141. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  12142. LogEst szTabRow; /* Estimated size of each table row in bytes */
  12143. #ifdef SQLITE_ENABLE_COSTMULT
  12144. LogEst costMult; /* Cost multiplier for using this table */
  12145. #endif
  12146. u8 tabFlags; /* Mask of TF_* values */
  12147. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  12148. #ifndef SQLITE_OMIT_ALTERTABLE
  12149. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  12150. #endif
  12151. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12152. int nModuleArg; /* Number of arguments to the module */
  12153. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  12154. VTable *pVTable; /* List of VTable objects. */
  12155. #endif
  12156. Trigger *pTrigger; /* List of triggers stored in pSchema */
  12157. Schema *pSchema; /* Schema that contains this table */
  12158. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  12159. };
  12160. /*
  12161. ** Allowed values for Table.tabFlags.
  12162. **
  12163. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  12164. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  12165. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  12166. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  12167. ** special handling during INSERT processing.
  12168. */
  12169. #define TF_Readonly 0x01 /* Read-only system table */
  12170. #define TF_Ephemeral 0x02 /* An ephemeral table */
  12171. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  12172. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  12173. #define TF_Virtual 0x10 /* Is a virtual table */
  12174. #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
  12175. #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
  12176. #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
  12177. /*
  12178. ** Test to see whether or not a table is a virtual table. This is
  12179. ** done as a macro so that it will be optimized out when virtual
  12180. ** table support is omitted from the build.
  12181. */
  12182. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12183. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  12184. #else
  12185. # define IsVirtual(X) 0
  12186. #endif
  12187. /*
  12188. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  12189. ** only works for non-virtual tables (ordinary tables and views) and is
  12190. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  12191. ** IsHiddenColumn() macro is general purpose.
  12192. */
  12193. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  12194. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  12195. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  12196. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  12197. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  12198. # define IsOrdinaryHiddenColumn(X) 0
  12199. #else
  12200. # define IsHiddenColumn(X) 0
  12201. # define IsOrdinaryHiddenColumn(X) 0
  12202. #endif
  12203. /* Does the table have a rowid */
  12204. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  12205. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  12206. /*
  12207. ** Each foreign key constraint is an instance of the following structure.
  12208. **
  12209. ** A foreign key is associated with two tables. The "from" table is
  12210. ** the table that contains the REFERENCES clause that creates the foreign
  12211. ** key. The "to" table is the table that is named in the REFERENCES clause.
  12212. ** Consider this example:
  12213. **
  12214. ** CREATE TABLE ex1(
  12215. ** a INTEGER PRIMARY KEY,
  12216. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  12217. ** );
  12218. **
  12219. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  12220. ** Equivalent names:
  12221. **
  12222. ** from-table == child-table
  12223. ** to-table == parent-table
  12224. **
  12225. ** Each REFERENCES clause generates an instance of the following structure
  12226. ** which is attached to the from-table. The to-table need not exist when
  12227. ** the from-table is created. The existence of the to-table is not checked.
  12228. **
  12229. ** The list of all parents for child Table X is held at X.pFKey.
  12230. **
  12231. ** A list of all children for a table named Z (which might not even exist)
  12232. ** is held in Schema.fkeyHash with a hash key of Z.
  12233. */
  12234. struct FKey {
  12235. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  12236. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  12237. char *zTo; /* Name of table that the key points to (aka: Parent) */
  12238. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  12239. FKey *pPrevTo; /* Previous with the same zTo */
  12240. int nCol; /* Number of columns in this key */
  12241. /* EV: R-30323-21917 */
  12242. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  12243. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  12244. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  12245. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  12246. int iFrom; /* Index of column in pFrom */
  12247. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  12248. } aCol[1]; /* One entry for each of nCol columns */
  12249. };
  12250. /*
  12251. ** SQLite supports many different ways to resolve a constraint
  12252. ** error. ROLLBACK processing means that a constraint violation
  12253. ** causes the operation in process to fail and for the current transaction
  12254. ** to be rolled back. ABORT processing means the operation in process
  12255. ** fails and any prior changes from that one operation are backed out,
  12256. ** but the transaction is not rolled back. FAIL processing means that
  12257. ** the operation in progress stops and returns an error code. But prior
  12258. ** changes due to the same operation are not backed out and no rollback
  12259. ** occurs. IGNORE means that the particular row that caused the constraint
  12260. ** error is not inserted or updated. Processing continues and no error
  12261. ** is returned. REPLACE means that preexisting database rows that caused
  12262. ** a UNIQUE constraint violation are removed so that the new insert or
  12263. ** update can proceed. Processing continues and no error is reported.
  12264. **
  12265. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  12266. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  12267. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  12268. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  12269. ** referenced table row is propagated into the row that holds the
  12270. ** foreign key.
  12271. **
  12272. ** The following symbolic values are used to record which type
  12273. ** of action to take.
  12274. */
  12275. #define OE_None 0 /* There is no constraint to check */
  12276. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  12277. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  12278. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  12279. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  12280. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  12281. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  12282. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  12283. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  12284. #define OE_Cascade 9 /* Cascade the changes */
  12285. #define OE_Default 10 /* Do whatever the default action is */
  12286. /*
  12287. ** An instance of the following structure is passed as the first
  12288. ** argument to sqlite3VdbeKeyCompare and is used to control the
  12289. ** comparison of the two index keys.
  12290. **
  12291. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  12292. ** are nField slots for the columns of an index then one extra slot
  12293. ** for the rowid at the end.
  12294. */
  12295. struct KeyInfo {
  12296. u32 nRef; /* Number of references to this KeyInfo object */
  12297. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  12298. u16 nField; /* Number of key columns in the index */
  12299. u16 nXField; /* Number of columns beyond the key columns */
  12300. sqlite3 *db; /* The database connection */
  12301. u8 *aSortOrder; /* Sort order for each column. */
  12302. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  12303. };
  12304. /*
  12305. ** This object holds a record which has been parsed out into individual
  12306. ** fields, for the purposes of doing a comparison.
  12307. **
  12308. ** A record is an object that contains one or more fields of data.
  12309. ** Records are used to store the content of a table row and to store
  12310. ** the key of an index. A blob encoding of a record is created by
  12311. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  12312. ** OP_Column opcode.
  12313. **
  12314. ** An instance of this object serves as a "key" for doing a search on
  12315. ** an index b+tree. The goal of the search is to find the entry that
  12316. ** is closed to the key described by this object. This object might hold
  12317. ** just a prefix of the key. The number of fields is given by
  12318. ** pKeyInfo->nField.
  12319. **
  12320. ** The r1 and r2 fields are the values to return if this key is less than
  12321. ** or greater than a key in the btree, respectively. These are normally
  12322. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  12323. ** is in DESC order.
  12324. **
  12325. ** The key comparison functions actually return default_rc when they find
  12326. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  12327. ** multiple entries in the b-tree with the same key (when only looking
  12328. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  12329. ** cause the search to find the last match, or +1 to cause the search to
  12330. ** find the first match.
  12331. **
  12332. ** The key comparison functions will set eqSeen to true if they ever
  12333. ** get and equal results when comparing this structure to a b-tree record.
  12334. ** When default_rc!=0, the search might end up on the record immediately
  12335. ** before the first match or immediately after the last match. The
  12336. ** eqSeen field will indicate whether or not an exact match exists in the
  12337. ** b-tree.
  12338. */
  12339. struct UnpackedRecord {
  12340. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  12341. Mem *aMem; /* Values */
  12342. u16 nField; /* Number of entries in apMem[] */
  12343. i8 default_rc; /* Comparison result if keys are equal */
  12344. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  12345. i8 r1; /* Value to return if (lhs > rhs) */
  12346. i8 r2; /* Value to return if (rhs < lhs) */
  12347. u8 eqSeen; /* True if an equality comparison has been seen */
  12348. };
  12349. /*
  12350. ** Each SQL index is represented in memory by an
  12351. ** instance of the following structure.
  12352. **
  12353. ** The columns of the table that are to be indexed are described
  12354. ** by the aiColumn[] field of this structure. For example, suppose
  12355. ** we have the following table and index:
  12356. **
  12357. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  12358. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  12359. **
  12360. ** In the Table structure describing Ex1, nCol==3 because there are
  12361. ** three columns in the table. In the Index structure describing
  12362. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  12363. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  12364. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  12365. ** The second column to be indexed (c1) has an index of 0 in
  12366. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  12367. **
  12368. ** The Index.onError field determines whether or not the indexed columns
  12369. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  12370. ** it means this is not a unique index. Otherwise it is a unique index
  12371. ** and the value of Index.onError indicate the which conflict resolution
  12372. ** algorithm to employ whenever an attempt is made to insert a non-unique
  12373. ** element.
  12374. **
  12375. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  12376. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  12377. ** table as part of parsing an existing database schema), transient instances
  12378. ** of this structure may be created. In this case the Index.tnum variable is
  12379. ** used to store the address of a VDBE instruction, not a database page
  12380. ** number (it cannot - the database page is not allocated until the VDBE
  12381. ** program is executed). See convertToWithoutRowidTable() for details.
  12382. */
  12383. struct Index {
  12384. char *zName; /* Name of this index */
  12385. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  12386. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  12387. Table *pTable; /* The SQL table being indexed */
  12388. char *zColAff; /* String defining the affinity of each column */
  12389. Index *pNext; /* The next index associated with the same table */
  12390. Schema *pSchema; /* Schema containing this index */
  12391. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  12392. const char **azColl; /* Array of collation sequence names for index */
  12393. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  12394. ExprList *aColExpr; /* Column expressions */
  12395. int tnum; /* DB Page containing root of this index */
  12396. LogEst szIdxRow; /* Estimated average row size in bytes */
  12397. u16 nKeyCol; /* Number of columns forming the key */
  12398. u16 nColumn; /* Number of columns stored in the index */
  12399. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  12400. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  12401. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  12402. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  12403. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  12404. unsigned isCovering:1; /* True if this is a covering index */
  12405. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  12406. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  12407. int nSample; /* Number of elements in aSample[] */
  12408. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  12409. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  12410. IndexSample *aSample; /* Samples of the left-most key */
  12411. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  12412. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  12413. #endif
  12414. };
  12415. /*
  12416. ** Allowed values for Index.idxType
  12417. */
  12418. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  12419. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  12420. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  12421. /* Return true if index X is a PRIMARY KEY index */
  12422. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  12423. /* Return true if index X is a UNIQUE index */
  12424. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  12425. /* The Index.aiColumn[] values are normally positive integer. But
  12426. ** there are some negative values that have special meaning:
  12427. */
  12428. #define XN_ROWID (-1) /* Indexed column is the rowid */
  12429. #define XN_EXPR (-2) /* Indexed column is an expression */
  12430. /*
  12431. ** Each sample stored in the sqlite_stat3 table is represented in memory
  12432. ** using a structure of this type. See documentation at the top of the
  12433. ** analyze.c source file for additional information.
  12434. */
  12435. struct IndexSample {
  12436. void *p; /* Pointer to sampled record */
  12437. int n; /* Size of record in bytes */
  12438. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  12439. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  12440. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  12441. };
  12442. /*
  12443. ** Each token coming out of the lexer is an instance of
  12444. ** this structure. Tokens are also used as part of an expression.
  12445. **
  12446. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  12447. ** may contain random values. Do not make any assumptions about Token.dyn
  12448. ** and Token.n when Token.z==0.
  12449. */
  12450. struct Token {
  12451. const char *z; /* Text of the token. Not NULL-terminated! */
  12452. unsigned int n; /* Number of characters in this token */
  12453. };
  12454. /*
  12455. ** An instance of this structure contains information needed to generate
  12456. ** code for a SELECT that contains aggregate functions.
  12457. **
  12458. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  12459. ** pointer to this structure. The Expr.iColumn field is the index in
  12460. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  12461. ** code for that node.
  12462. **
  12463. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  12464. ** original Select structure that describes the SELECT statement. These
  12465. ** fields do not need to be freed when deallocating the AggInfo structure.
  12466. */
  12467. struct AggInfo {
  12468. u8 directMode; /* Direct rendering mode means take data directly
  12469. ** from source tables rather than from accumulators */
  12470. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  12471. ** than the source table */
  12472. int sortingIdx; /* Cursor number of the sorting index */
  12473. int sortingIdxPTab; /* Cursor number of pseudo-table */
  12474. int nSortingColumn; /* Number of columns in the sorting index */
  12475. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  12476. ExprList *pGroupBy; /* The group by clause */
  12477. struct AggInfo_col { /* For each column used in source tables */
  12478. Table *pTab; /* Source table */
  12479. int iTable; /* Cursor number of the source table */
  12480. int iColumn; /* Column number within the source table */
  12481. int iSorterColumn; /* Column number in the sorting index */
  12482. int iMem; /* Memory location that acts as accumulator */
  12483. Expr *pExpr; /* The original expression */
  12484. } *aCol;
  12485. int nColumn; /* Number of used entries in aCol[] */
  12486. int nAccumulator; /* Number of columns that show through to the output.
  12487. ** Additional columns are used only as parameters to
  12488. ** aggregate functions */
  12489. struct AggInfo_func { /* For each aggregate function */
  12490. Expr *pExpr; /* Expression encoding the function */
  12491. FuncDef *pFunc; /* The aggregate function implementation */
  12492. int iMem; /* Memory location that acts as accumulator */
  12493. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  12494. } *aFunc;
  12495. int nFunc; /* Number of entries in aFunc[] */
  12496. };
  12497. /*
  12498. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  12499. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  12500. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  12501. ** it uses less memory in the Expr object, which is a big memory user
  12502. ** in systems with lots of prepared statements. And few applications
  12503. ** need more than about 10 or 20 variables. But some extreme users want
  12504. ** to have prepared statements with over 32767 variables, and for them
  12505. ** the option is available (at compile-time).
  12506. */
  12507. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  12508. typedef i16 ynVar;
  12509. #else
  12510. typedef int ynVar;
  12511. #endif
  12512. /*
  12513. ** Each node of an expression in the parse tree is an instance
  12514. ** of this structure.
  12515. **
  12516. ** Expr.op is the opcode. The integer parser token codes are reused
  12517. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  12518. ** code representing the ">=" operator. This same integer code is reused
  12519. ** to represent the greater-than-or-equal-to operator in the expression
  12520. ** tree.
  12521. **
  12522. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  12523. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  12524. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  12525. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  12526. ** then Expr.token contains the name of the function.
  12527. **
  12528. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  12529. ** binary operator. Either or both may be NULL.
  12530. **
  12531. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  12532. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  12533. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  12534. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  12535. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  12536. ** valid.
  12537. **
  12538. ** An expression of the form ID or ID.ID refers to a column in a table.
  12539. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  12540. ** the integer cursor number of a VDBE cursor pointing to that table and
  12541. ** Expr.iColumn is the column number for the specific column. If the
  12542. ** expression is used as a result in an aggregate SELECT, then the
  12543. ** value is also stored in the Expr.iAgg column in the aggregate so that
  12544. ** it can be accessed after all aggregates are computed.
  12545. **
  12546. ** If the expression is an unbound variable marker (a question mark
  12547. ** character '?' in the original SQL) then the Expr.iTable holds the index
  12548. ** number for that variable.
  12549. **
  12550. ** If the expression is a subquery then Expr.iColumn holds an integer
  12551. ** register number containing the result of the subquery. If the
  12552. ** subquery gives a constant result, then iTable is -1. If the subquery
  12553. ** gives a different answer at different times during statement processing
  12554. ** then iTable is the address of a subroutine that computes the subquery.
  12555. **
  12556. ** If the Expr is of type OP_Column, and the table it is selecting from
  12557. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  12558. ** corresponding table definition.
  12559. **
  12560. ** ALLOCATION NOTES:
  12561. **
  12562. ** Expr objects can use a lot of memory space in database schema. To
  12563. ** help reduce memory requirements, sometimes an Expr object will be
  12564. ** truncated. And to reduce the number of memory allocations, sometimes
  12565. ** two or more Expr objects will be stored in a single memory allocation,
  12566. ** together with Expr.zToken strings.
  12567. **
  12568. ** If the EP_Reduced and EP_TokenOnly flags are set when
  12569. ** an Expr object is truncated. When EP_Reduced is set, then all
  12570. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  12571. ** are contained within the same memory allocation. Note, however, that
  12572. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  12573. ** allocated, regardless of whether or not EP_Reduced is set.
  12574. */
  12575. struct Expr {
  12576. u8 op; /* Operation performed by this node */
  12577. char affinity; /* The affinity of the column or 0 if not a column */
  12578. u32 flags; /* Various flags. EP_* See below */
  12579. union {
  12580. char *zToken; /* Token value. Zero terminated and dequoted */
  12581. int iValue; /* Non-negative integer value if EP_IntValue */
  12582. } u;
  12583. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  12584. ** space is allocated for the fields below this point. An attempt to
  12585. ** access them will result in a segfault or malfunction.
  12586. *********************************************************************/
  12587. Expr *pLeft; /* Left subnode */
  12588. Expr *pRight; /* Right subnode */
  12589. union {
  12590. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  12591. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  12592. } x;
  12593. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  12594. ** space is allocated for the fields below this point. An attempt to
  12595. ** access them will result in a segfault or malfunction.
  12596. *********************************************************************/
  12597. #if SQLITE_MAX_EXPR_DEPTH>0
  12598. int nHeight; /* Height of the tree headed by this node */
  12599. #endif
  12600. int iTable; /* TK_COLUMN: cursor number of table holding column
  12601. ** TK_REGISTER: register number
  12602. ** TK_TRIGGER: 1 -> new, 0 -> old
  12603. ** EP_Unlikely: 134217728 times likelihood */
  12604. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  12605. ** TK_VARIABLE: variable number (always >= 1). */
  12606. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  12607. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  12608. u8 op2; /* TK_REGISTER: original value of Expr.op
  12609. ** TK_COLUMN: the value of p5 for OP_Column
  12610. ** TK_AGG_FUNCTION: nesting depth */
  12611. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  12612. Table *pTab; /* Table for TK_COLUMN expressions. */
  12613. };
  12614. /*
  12615. ** The following are the meanings of bits in the Expr.flags field.
  12616. */
  12617. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  12618. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  12619. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  12620. #define EP_Error 0x000008 /* Expression contains one or more errors */
  12621. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  12622. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  12623. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  12624. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  12625. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  12626. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  12627. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  12628. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  12629. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  12630. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  12631. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  12632. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  12633. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  12634. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  12635. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  12636. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  12637. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  12638. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  12639. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  12640. /*
  12641. ** Combinations of two or more EP_* flags
  12642. */
  12643. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  12644. /*
  12645. ** These macros can be used to test, set, or clear bits in the
  12646. ** Expr.flags field.
  12647. */
  12648. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  12649. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  12650. #define ExprSetProperty(E,P) (E)->flags|=(P)
  12651. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  12652. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  12653. ** and Accreditation only. It works like ExprSetProperty() during VVA
  12654. ** processes but is a no-op for delivery.
  12655. */
  12656. #ifdef SQLITE_DEBUG
  12657. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  12658. #else
  12659. # define ExprSetVVAProperty(E,P)
  12660. #endif
  12661. /*
  12662. ** Macros to determine the number of bytes required by a normal Expr
  12663. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  12664. ** and an Expr struct with the EP_TokenOnly flag set.
  12665. */
  12666. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  12667. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  12668. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  12669. /*
  12670. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  12671. ** above sqlite3ExprDup() for details.
  12672. */
  12673. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  12674. /*
  12675. ** A list of expressions. Each expression may optionally have a
  12676. ** name. An expr/name combination can be used in several ways, such
  12677. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  12678. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  12679. ** also be used as the argument to a function, in which case the a.zName
  12680. ** field is not used.
  12681. **
  12682. ** By default the Expr.zSpan field holds a human-readable description of
  12683. ** the expression that is used in the generation of error messages and
  12684. ** column labels. In this case, Expr.zSpan is typically the text of a
  12685. ** column expression as it exists in a SELECT statement. However, if
  12686. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  12687. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  12688. ** form is used for name resolution with nested FROM clauses.
  12689. */
  12690. struct ExprList {
  12691. int nExpr; /* Number of expressions on the list */
  12692. struct ExprList_item { /* For each expression in the list */
  12693. Expr *pExpr; /* The list of expressions */
  12694. char *zName; /* Token associated with this expression */
  12695. char *zSpan; /* Original text of the expression */
  12696. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  12697. unsigned done :1; /* A flag to indicate when processing is finished */
  12698. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  12699. unsigned reusable :1; /* Constant expression is reusable */
  12700. union {
  12701. struct {
  12702. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  12703. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  12704. } x;
  12705. int iConstExprReg; /* Register in which Expr value is cached */
  12706. } u;
  12707. } *a; /* Alloc a power of two greater or equal to nExpr */
  12708. };
  12709. /*
  12710. ** An instance of this structure is used by the parser to record both
  12711. ** the parse tree for an expression and the span of input text for an
  12712. ** expression.
  12713. */
  12714. struct ExprSpan {
  12715. Expr *pExpr; /* The expression parse tree */
  12716. const char *zStart; /* First character of input text */
  12717. const char *zEnd; /* One character past the end of input text */
  12718. };
  12719. /*
  12720. ** An instance of this structure can hold a simple list of identifiers,
  12721. ** such as the list "a,b,c" in the following statements:
  12722. **
  12723. ** INSERT INTO t(a,b,c) VALUES ...;
  12724. ** CREATE INDEX idx ON t(a,b,c);
  12725. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  12726. **
  12727. ** The IdList.a.idx field is used when the IdList represents the list of
  12728. ** column names after a table name in an INSERT statement. In the statement
  12729. **
  12730. ** INSERT INTO t(a,b,c) ...
  12731. **
  12732. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  12733. */
  12734. struct IdList {
  12735. struct IdList_item {
  12736. char *zName; /* Name of the identifier */
  12737. int idx; /* Index in some Table.aCol[] of a column named zName */
  12738. } *a;
  12739. int nId; /* Number of identifiers on the list */
  12740. };
  12741. /*
  12742. ** The bitmask datatype defined below is used for various optimizations.
  12743. **
  12744. ** Changing this from a 64-bit to a 32-bit type limits the number of
  12745. ** tables in a join to 32 instead of 64. But it also reduces the size
  12746. ** of the library by 738 bytes on ix86.
  12747. */
  12748. #ifdef SQLITE_BITMASK_TYPE
  12749. typedef SQLITE_BITMASK_TYPE Bitmask;
  12750. #else
  12751. typedef u64 Bitmask;
  12752. #endif
  12753. /*
  12754. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  12755. */
  12756. #define BMS ((int)(sizeof(Bitmask)*8))
  12757. /*
  12758. ** A bit in a Bitmask
  12759. */
  12760. #define MASKBIT(n) (((Bitmask)1)<<(n))
  12761. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  12762. #define ALLBITS ((Bitmask)-1)
  12763. /*
  12764. ** The following structure describes the FROM clause of a SELECT statement.
  12765. ** Each table or subquery in the FROM clause is a separate element of
  12766. ** the SrcList.a[] array.
  12767. **
  12768. ** With the addition of multiple database support, the following structure
  12769. ** can also be used to describe a particular table such as the table that
  12770. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  12771. ** such a table must be a simple name: ID. But in SQLite, the table can
  12772. ** now be identified by a database name, a dot, then the table name: ID.ID.
  12773. **
  12774. ** The jointype starts out showing the join type between the current table
  12775. ** and the next table on the list. The parser builds the list this way.
  12776. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  12777. ** jointype expresses the join between the table and the previous table.
  12778. **
  12779. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  12780. ** contains more than 63 columns and the 64-th or later column is used.
  12781. */
  12782. struct SrcList {
  12783. int nSrc; /* Number of tables or subqueries in the FROM clause */
  12784. u32 nAlloc; /* Number of entries allocated in a[] below */
  12785. struct SrcList_item {
  12786. Schema *pSchema; /* Schema to which this item is fixed */
  12787. char *zDatabase; /* Name of database holding this table */
  12788. char *zName; /* Name of the table */
  12789. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  12790. Table *pTab; /* An SQL table corresponding to zName */
  12791. Select *pSelect; /* A SELECT statement used in place of a table name */
  12792. int addrFillSub; /* Address of subroutine to manifest a subquery */
  12793. int regReturn; /* Register holding return address of addrFillSub */
  12794. int regResult; /* Registers holding results of a co-routine */
  12795. struct {
  12796. u8 jointype; /* Type of join between this able and the previous */
  12797. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  12798. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  12799. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  12800. unsigned isCorrelated :1; /* True if sub-query is correlated */
  12801. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  12802. unsigned isRecursive :1; /* True for recursive reference in WITH */
  12803. } fg;
  12804. #ifndef SQLITE_OMIT_EXPLAIN
  12805. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  12806. #endif
  12807. int iCursor; /* The VDBE cursor number used to access this table */
  12808. Expr *pOn; /* The ON clause of a join */
  12809. IdList *pUsing; /* The USING clause of a join */
  12810. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  12811. union {
  12812. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  12813. ExprList *pFuncArg; /* Arguments to table-valued-function */
  12814. } u1;
  12815. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  12816. } a[1]; /* One entry for each identifier on the list */
  12817. };
  12818. /*
  12819. ** Permitted values of the SrcList.a.jointype field
  12820. */
  12821. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  12822. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  12823. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  12824. #define JT_LEFT 0x0008 /* Left outer join */
  12825. #define JT_RIGHT 0x0010 /* Right outer join */
  12826. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  12827. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  12828. /*
  12829. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  12830. ** and the WhereInfo.wctrlFlags member.
  12831. */
  12832. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  12833. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  12834. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  12835. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  12836. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  12837. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  12838. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  12839. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  12840. #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
  12841. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  12842. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  12843. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  12844. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  12845. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  12846. #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
  12847. #define WHERE_USE_LIMIT 0x4000 /* There is a constant LIMIT clause */
  12848. /* Allowed return values from sqlite3WhereIsDistinct()
  12849. */
  12850. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  12851. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  12852. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  12853. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  12854. /*
  12855. ** A NameContext defines a context in which to resolve table and column
  12856. ** names. The context consists of a list of tables (the pSrcList) field and
  12857. ** a list of named expression (pEList). The named expression list may
  12858. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  12859. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  12860. ** pEList corresponds to the result set of a SELECT and is NULL for
  12861. ** other statements.
  12862. **
  12863. ** NameContexts can be nested. When resolving names, the inner-most
  12864. ** context is searched first. If no match is found, the next outer
  12865. ** context is checked. If there is still no match, the next context
  12866. ** is checked. This process continues until either a match is found
  12867. ** or all contexts are check. When a match is found, the nRef member of
  12868. ** the context containing the match is incremented.
  12869. **
  12870. ** Each subquery gets a new NameContext. The pNext field points to the
  12871. ** NameContext in the parent query. Thus the process of scanning the
  12872. ** NameContext list corresponds to searching through successively outer
  12873. ** subqueries looking for a match.
  12874. */
  12875. struct NameContext {
  12876. Parse *pParse; /* The parser */
  12877. SrcList *pSrcList; /* One or more tables used to resolve names */
  12878. ExprList *pEList; /* Optional list of result-set columns */
  12879. AggInfo *pAggInfo; /* Information about aggregates at this level */
  12880. NameContext *pNext; /* Next outer name context. NULL for outermost */
  12881. int nRef; /* Number of names resolved by this context */
  12882. int nErr; /* Number of errors encountered while resolving names */
  12883. u16 ncFlags; /* Zero or more NC_* flags defined below */
  12884. };
  12885. /*
  12886. ** Allowed values for the NameContext, ncFlags field.
  12887. **
  12888. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  12889. ** SQLITE_FUNC_MINMAX.
  12890. **
  12891. */
  12892. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  12893. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  12894. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  12895. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  12896. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  12897. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  12898. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  12899. /*
  12900. ** An instance of the following structure contains all information
  12901. ** needed to generate code for a single SELECT statement.
  12902. **
  12903. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  12904. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  12905. ** limit and nOffset to the value of the offset (or 0 if there is not
  12906. ** offset). But later on, nLimit and nOffset become the memory locations
  12907. ** in the VDBE that record the limit and offset counters.
  12908. **
  12909. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  12910. ** These addresses must be stored so that we can go back and fill in
  12911. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  12912. ** the number of columns in P2 can be computed at the same time
  12913. ** as the OP_OpenEphm instruction is coded because not
  12914. ** enough information about the compound query is known at that point.
  12915. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  12916. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  12917. ** sequences for the ORDER BY clause.
  12918. */
  12919. struct Select {
  12920. ExprList *pEList; /* The fields of the result */
  12921. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  12922. LogEst nSelectRow; /* Estimated number of result rows */
  12923. u32 selFlags; /* Various SF_* values */
  12924. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  12925. #if SELECTTRACE_ENABLED
  12926. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  12927. #endif
  12928. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  12929. SrcList *pSrc; /* The FROM clause */
  12930. Expr *pWhere; /* The WHERE clause */
  12931. ExprList *pGroupBy; /* The GROUP BY clause */
  12932. Expr *pHaving; /* The HAVING clause */
  12933. ExprList *pOrderBy; /* The ORDER BY clause */
  12934. Select *pPrior; /* Prior select in a compound select statement */
  12935. Select *pNext; /* Next select to the left in a compound */
  12936. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  12937. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  12938. With *pWith; /* WITH clause attached to this select. Or NULL. */
  12939. };
  12940. /*
  12941. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  12942. ** "Select Flag".
  12943. */
  12944. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  12945. #define SF_All 0x00002 /* Includes the ALL keyword */
  12946. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  12947. #define SF_Aggregate 0x00008 /* Contains aggregate functions */
  12948. #define SF_UsesEphemeral 0x00010 /* Uses the OpenEphemeral opcode */
  12949. #define SF_Expanded 0x00020 /* sqlite3SelectExpand() called on this */
  12950. #define SF_HasTypeInfo 0x00040 /* FROM subqueries have Table metadata */
  12951. #define SF_Compound 0x00080 /* Part of a compound query */
  12952. #define SF_Values 0x00100 /* Synthesized from VALUES clause */
  12953. #define SF_MultiValue 0x00200 /* Single VALUES term with multiple rows */
  12954. #define SF_NestedFrom 0x00400 /* Part of a parenthesized FROM clause */
  12955. #define SF_MaybeConvert 0x00800 /* Need convertCompoundSelectToSubquery() */
  12956. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  12957. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  12958. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  12959. #define SF_Converted 0x08000 /* By convertCompoundSelectToSubquery() */
  12960. #define SF_IncludeHidden 0x10000 /* Include hidden columns in output */
  12961. /*
  12962. ** The results of a SELECT can be distributed in several ways, as defined
  12963. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  12964. ** Type".
  12965. **
  12966. ** SRT_Union Store results as a key in a temporary index
  12967. ** identified by pDest->iSDParm.
  12968. **
  12969. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  12970. **
  12971. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  12972. ** set is not empty.
  12973. **
  12974. ** SRT_Discard Throw the results away. This is used by SELECT
  12975. ** statements within triggers whose only purpose is
  12976. ** the side-effects of functions.
  12977. **
  12978. ** All of the above are free to ignore their ORDER BY clause. Those that
  12979. ** follow must honor the ORDER BY clause.
  12980. **
  12981. ** SRT_Output Generate a row of output (using the OP_ResultRow
  12982. ** opcode) for each row in the result set.
  12983. **
  12984. ** SRT_Mem Only valid if the result is a single column.
  12985. ** Store the first column of the first result row
  12986. ** in register pDest->iSDParm then abandon the rest
  12987. ** of the query. This destination implies "LIMIT 1".
  12988. **
  12989. ** SRT_Set The result must be a single column. Store each
  12990. ** row of result as the key in table pDest->iSDParm.
  12991. ** Apply the affinity pDest->affSdst before storing
  12992. ** results. Used to implement "IN (SELECT ...)".
  12993. **
  12994. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  12995. ** the result there. The cursor is left open after
  12996. ** returning. This is like SRT_Table except that
  12997. ** this destination uses OP_OpenEphemeral to create
  12998. ** the table first.
  12999. **
  13000. ** SRT_Coroutine Generate a co-routine that returns a new row of
  13001. ** results each time it is invoked. The entry point
  13002. ** of the co-routine is stored in register pDest->iSDParm
  13003. ** and the result row is stored in pDest->nDest registers
  13004. ** starting with pDest->iSdst.
  13005. **
  13006. ** SRT_Table Store results in temporary table pDest->iSDParm.
  13007. ** SRT_Fifo This is like SRT_EphemTab except that the table
  13008. ** is assumed to already be open. SRT_Fifo has
  13009. ** the additional property of being able to ignore
  13010. ** the ORDER BY clause.
  13011. **
  13012. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  13013. ** But also use temporary table pDest->iSDParm+1 as
  13014. ** a record of all prior results and ignore any duplicate
  13015. ** rows. Name means: "Distinct Fifo".
  13016. **
  13017. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  13018. ** an index). Append a sequence number so that all entries
  13019. ** are distinct.
  13020. **
  13021. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  13022. ** the same record has never been stored before. The
  13023. ** index at pDest->iSDParm+1 hold all prior stores.
  13024. */
  13025. #define SRT_Union 1 /* Store result as keys in an index */
  13026. #define SRT_Except 2 /* Remove result from a UNION index */
  13027. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  13028. #define SRT_Discard 4 /* Do not save the results anywhere */
  13029. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  13030. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  13031. #define SRT_Queue 7 /* Store result in an queue */
  13032. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  13033. /* The ORDER BY clause is ignored for all of the above */
  13034. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  13035. #define SRT_Output 9 /* Output each row of result */
  13036. #define SRT_Mem 10 /* Store result in a memory cell */
  13037. #define SRT_Set 11 /* Store results as keys in an index */
  13038. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  13039. #define SRT_Coroutine 13 /* Generate a single row of result */
  13040. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  13041. /*
  13042. ** An instance of this object describes where to put of the results of
  13043. ** a SELECT statement.
  13044. */
  13045. struct SelectDest {
  13046. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  13047. char affSdst; /* Affinity used when eDest==SRT_Set */
  13048. int iSDParm; /* A parameter used by the eDest disposal method */
  13049. int iSdst; /* Base register where results are written */
  13050. int nSdst; /* Number of registers allocated */
  13051. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  13052. };
  13053. /*
  13054. ** During code generation of statements that do inserts into AUTOINCREMENT
  13055. ** tables, the following information is attached to the Table.u.autoInc.p
  13056. ** pointer of each autoincrement table to record some side information that
  13057. ** the code generator needs. We have to keep per-table autoincrement
  13058. ** information in case inserts are done within triggers. Triggers do not
  13059. ** normally coordinate their activities, but we do need to coordinate the
  13060. ** loading and saving of autoincrement information.
  13061. */
  13062. struct AutoincInfo {
  13063. AutoincInfo *pNext; /* Next info block in a list of them all */
  13064. Table *pTab; /* Table this info block refers to */
  13065. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  13066. int regCtr; /* Memory register holding the rowid counter */
  13067. };
  13068. /*
  13069. ** Size of the column cache
  13070. */
  13071. #ifndef SQLITE_N_COLCACHE
  13072. # define SQLITE_N_COLCACHE 10
  13073. #endif
  13074. /*
  13075. ** At least one instance of the following structure is created for each
  13076. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  13077. ** statement. All such objects are stored in the linked list headed at
  13078. ** Parse.pTriggerPrg and deleted once statement compilation has been
  13079. ** completed.
  13080. **
  13081. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  13082. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  13083. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  13084. ** The Parse.pTriggerPrg list never contains two entries with the same
  13085. ** values for both pTrigger and orconf.
  13086. **
  13087. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  13088. ** accessed (or set to 0 for triggers fired as a result of INSERT
  13089. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  13090. ** a mask of new.* columns used by the program.
  13091. */
  13092. struct TriggerPrg {
  13093. Trigger *pTrigger; /* Trigger this program was coded from */
  13094. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  13095. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  13096. int orconf; /* Default ON CONFLICT policy */
  13097. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  13098. };
  13099. /*
  13100. ** The yDbMask datatype for the bitmask of all attached databases.
  13101. */
  13102. #if SQLITE_MAX_ATTACHED>30
  13103. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  13104. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  13105. # define DbMaskZero(M) memset((M),0,sizeof(M))
  13106. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  13107. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  13108. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  13109. #else
  13110. typedef unsigned int yDbMask;
  13111. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  13112. # define DbMaskZero(M) (M)=0
  13113. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  13114. # define DbMaskAllZero(M) (M)==0
  13115. # define DbMaskNonZero(M) (M)!=0
  13116. #endif
  13117. /*
  13118. ** An SQL parser context. A copy of this structure is passed through
  13119. ** the parser and down into all the parser action routine in order to
  13120. ** carry around information that is global to the entire parse.
  13121. **
  13122. ** The structure is divided into two parts. When the parser and code
  13123. ** generate call themselves recursively, the first part of the structure
  13124. ** is constant but the second part is reset at the beginning and end of
  13125. ** each recursion.
  13126. **
  13127. ** The nTableLock and aTableLock variables are only used if the shared-cache
  13128. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  13129. ** used to store the set of table-locks required by the statement being
  13130. ** compiled. Function sqlite3TableLock() is used to add entries to the
  13131. ** list.
  13132. */
  13133. struct Parse {
  13134. sqlite3 *db; /* The main database structure */
  13135. char *zErrMsg; /* An error message */
  13136. Vdbe *pVdbe; /* An engine for executing database bytecode */
  13137. int rc; /* Return code from execution */
  13138. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  13139. u8 checkSchema; /* Causes schema cookie check after an error */
  13140. u8 nested; /* Number of nested calls to the parser/code generator */
  13141. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  13142. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  13143. u8 mayAbort; /* True if statement may throw an ABORT exception */
  13144. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  13145. u8 okConstFactor; /* OK to factor out constants */
  13146. u8 disableLookaside; /* Number of times lookaside has been disabled */
  13147. int aTempReg[8]; /* Holding area for temporary registers */
  13148. int nRangeReg; /* Size of the temporary register block */
  13149. int iRangeReg; /* First register in temporary register block */
  13150. int nErr; /* Number of errors seen */
  13151. int nTab; /* Number of previously allocated VDBE cursors */
  13152. int nMem; /* Number of memory cells used so far */
  13153. int nSet; /* Number of sets used so far */
  13154. int nOnce; /* Number of OP_Once instructions so far */
  13155. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  13156. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  13157. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  13158. int ckBase; /* Base register of data during check constraints */
  13159. int iSelfTab; /* Table of an index whose exprs are being coded */
  13160. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  13161. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  13162. int nLabel; /* Number of labels used */
  13163. int *aLabel; /* Space to hold the labels */
  13164. struct yColCache {
  13165. int iTable; /* Table cursor number */
  13166. i16 iColumn; /* Table column number */
  13167. u8 tempReg; /* iReg is a temp register that needs to be freed */
  13168. int iLevel; /* Nesting level */
  13169. int iReg; /* Reg with value of this column. 0 means none. */
  13170. int lru; /* Least recently used entry has the smallest value */
  13171. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  13172. ExprList *pConstExpr;/* Constant expressions */
  13173. Token constraintName;/* Name of the constraint currently being parsed */
  13174. yDbMask writeMask; /* Start a write transaction on these databases */
  13175. yDbMask cookieMask; /* Bitmask of schema verified databases */
  13176. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  13177. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  13178. int regRoot; /* Register holding root page number for new objects */
  13179. int nMaxArg; /* Max args passed to user function by sub-program */
  13180. #if SELECTTRACE_ENABLED
  13181. int nSelect; /* Number of SELECT statements seen */
  13182. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  13183. #endif
  13184. #ifndef SQLITE_OMIT_SHARED_CACHE
  13185. int nTableLock; /* Number of locks in aTableLock */
  13186. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  13187. #endif
  13188. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  13189. /* Information used while coding trigger programs. */
  13190. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  13191. Table *pTriggerTab; /* Table triggers are being coded for */
  13192. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  13193. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  13194. u32 oldmask; /* Mask of old.* columns referenced */
  13195. u32 newmask; /* Mask of new.* columns referenced */
  13196. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  13197. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  13198. u8 disableTriggers; /* True to disable triggers */
  13199. /************************************************************************
  13200. ** Above is constant between recursions. Below is reset before and after
  13201. ** each recursion. The boundary between these two regions is determined
  13202. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  13203. ** in the recursive region.
  13204. ************************************************************************/
  13205. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  13206. int nzVar; /* Number of available slots in azVar[] */
  13207. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  13208. u8 explain; /* True if the EXPLAIN flag is found on the query */
  13209. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13210. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  13211. int nVtabLock; /* Number of virtual tables to lock */
  13212. #endif
  13213. int nAlias; /* Number of aliased result set columns */
  13214. int nHeight; /* Expression tree height of current sub-select */
  13215. #ifndef SQLITE_OMIT_EXPLAIN
  13216. int iSelectId; /* ID of current select for EXPLAIN output */
  13217. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  13218. #endif
  13219. char **azVar; /* Pointers to names of parameters */
  13220. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  13221. const char *zTail; /* All SQL text past the last semicolon parsed */
  13222. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  13223. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  13224. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  13225. Token sNameToken; /* Token with unqualified schema object name */
  13226. Token sLastToken; /* The last token parsed */
  13227. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13228. Token sArg; /* Complete text of a module argument */
  13229. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  13230. #endif
  13231. Table *pZombieTab; /* List of Table objects to delete after code gen */
  13232. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  13233. With *pWith; /* Current WITH clause, or NULL */
  13234. With *pWithToFree; /* Free this WITH object at the end of the parse */
  13235. };
  13236. /*
  13237. ** Return true if currently inside an sqlite3_declare_vtab() call.
  13238. */
  13239. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13240. #define IN_DECLARE_VTAB 0
  13241. #else
  13242. #define IN_DECLARE_VTAB (pParse->declareVtab)
  13243. #endif
  13244. /*
  13245. ** An instance of the following structure can be declared on a stack and used
  13246. ** to save the Parse.zAuthContext value so that it can be restored later.
  13247. */
  13248. struct AuthContext {
  13249. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  13250. Parse *pParse; /* The Parse structure */
  13251. };
  13252. /*
  13253. ** Bitfield flags for P5 value in various opcodes.
  13254. */
  13255. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  13256. /* Also used in P2 (not P5) of OP_Delete */
  13257. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  13258. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  13259. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  13260. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  13261. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  13262. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  13263. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  13264. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  13265. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  13266. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  13267. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  13268. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  13269. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */
  13270. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  13271. /*
  13272. * Each trigger present in the database schema is stored as an instance of
  13273. * struct Trigger.
  13274. *
  13275. * Pointers to instances of struct Trigger are stored in two ways.
  13276. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  13277. * database). This allows Trigger structures to be retrieved by name.
  13278. * 2. All triggers associated with a single table form a linked list, using the
  13279. * pNext member of struct Trigger. A pointer to the first element of the
  13280. * linked list is stored as the "pTrigger" member of the associated
  13281. * struct Table.
  13282. *
  13283. * The "step_list" member points to the first element of a linked list
  13284. * containing the SQL statements specified as the trigger program.
  13285. */
  13286. struct Trigger {
  13287. char *zName; /* The name of the trigger */
  13288. char *table; /* The table or view to which the trigger applies */
  13289. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  13290. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  13291. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  13292. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  13293. the <column-list> is stored here */
  13294. Schema *pSchema; /* Schema containing the trigger */
  13295. Schema *pTabSchema; /* Schema containing the table */
  13296. TriggerStep *step_list; /* Link list of trigger program steps */
  13297. Trigger *pNext; /* Next trigger associated with the table */
  13298. };
  13299. /*
  13300. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  13301. ** determine which.
  13302. **
  13303. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  13304. ** In that cases, the constants below can be ORed together.
  13305. */
  13306. #define TRIGGER_BEFORE 1
  13307. #define TRIGGER_AFTER 2
  13308. /*
  13309. * An instance of struct TriggerStep is used to store a single SQL statement
  13310. * that is a part of a trigger-program.
  13311. *
  13312. * Instances of struct TriggerStep are stored in a singly linked list (linked
  13313. * using the "pNext" member) referenced by the "step_list" member of the
  13314. * associated struct Trigger instance. The first element of the linked list is
  13315. * the first step of the trigger-program.
  13316. *
  13317. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  13318. * "SELECT" statement. The meanings of the other members is determined by the
  13319. * value of "op" as follows:
  13320. *
  13321. * (op == TK_INSERT)
  13322. * orconf -> stores the ON CONFLICT algorithm
  13323. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  13324. * this stores a pointer to the SELECT statement. Otherwise NULL.
  13325. * zTarget -> Dequoted name of the table to insert into.
  13326. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  13327. * this stores values to be inserted. Otherwise NULL.
  13328. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  13329. * statement, then this stores the column-names to be
  13330. * inserted into.
  13331. *
  13332. * (op == TK_DELETE)
  13333. * zTarget -> Dequoted name of the table to delete from.
  13334. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  13335. * Otherwise NULL.
  13336. *
  13337. * (op == TK_UPDATE)
  13338. * zTarget -> Dequoted name of the table to update.
  13339. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  13340. * Otherwise NULL.
  13341. * pExprList -> A list of the columns to update and the expressions to update
  13342. * them to. See sqlite3Update() documentation of "pChanges"
  13343. * argument.
  13344. *
  13345. */
  13346. struct TriggerStep {
  13347. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  13348. u8 orconf; /* OE_Rollback etc. */
  13349. Trigger *pTrig; /* The trigger that this step is a part of */
  13350. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  13351. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  13352. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  13353. ExprList *pExprList; /* SET clause for UPDATE. */
  13354. IdList *pIdList; /* Column names for INSERT */
  13355. TriggerStep *pNext; /* Next in the link-list */
  13356. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  13357. };
  13358. /*
  13359. ** The following structure contains information used by the sqliteFix...
  13360. ** routines as they walk the parse tree to make database references
  13361. ** explicit.
  13362. */
  13363. typedef struct DbFixer DbFixer;
  13364. struct DbFixer {
  13365. Parse *pParse; /* The parsing context. Error messages written here */
  13366. Schema *pSchema; /* Fix items to this schema */
  13367. int bVarOnly; /* Check for variable references only */
  13368. const char *zDb; /* Make sure all objects are contained in this database */
  13369. const char *zType; /* Type of the container - used for error messages */
  13370. const Token *pName; /* Name of the container - used for error messages */
  13371. };
  13372. /*
  13373. ** An objected used to accumulate the text of a string where we
  13374. ** do not necessarily know how big the string will be in the end.
  13375. */
  13376. struct StrAccum {
  13377. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  13378. char *zBase; /* A base allocation. Not from malloc. */
  13379. char *zText; /* The string collected so far */
  13380. u32 nChar; /* Length of the string so far */
  13381. u32 nAlloc; /* Amount of space allocated in zText */
  13382. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  13383. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  13384. u8 printfFlags; /* SQLITE_PRINTF flags below */
  13385. };
  13386. #define STRACCUM_NOMEM 1
  13387. #define STRACCUM_TOOBIG 2
  13388. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  13389. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  13390. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  13391. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  13392. /*
  13393. ** A pointer to this structure is used to communicate information
  13394. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  13395. */
  13396. typedef struct {
  13397. sqlite3 *db; /* The database being initialized */
  13398. char **pzErrMsg; /* Error message stored here */
  13399. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  13400. int rc; /* Result code stored here */
  13401. } InitData;
  13402. /*
  13403. ** Structure containing global configuration data for the SQLite library.
  13404. **
  13405. ** This structure also contains some state information.
  13406. */
  13407. struct Sqlite3Config {
  13408. int bMemstat; /* True to enable memory status */
  13409. int bCoreMutex; /* True to enable core mutexing */
  13410. int bFullMutex; /* True to enable full mutexing */
  13411. int bOpenUri; /* True to interpret filenames as URIs */
  13412. int bUseCis; /* Use covering indices for full-scans */
  13413. int mxStrlen; /* Maximum string length */
  13414. int neverCorrupt; /* Database is always well-formed */
  13415. int szLookaside; /* Default lookaside buffer size */
  13416. int nLookaside; /* Default lookaside buffer count */
  13417. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  13418. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  13419. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  13420. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  13421. void *pHeap; /* Heap storage space */
  13422. int nHeap; /* Size of pHeap[] */
  13423. int mnReq, mxReq; /* Min and max heap requests sizes */
  13424. sqlite3_int64 szMmap; /* mmap() space per open file */
  13425. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  13426. void *pScratch; /* Scratch memory */
  13427. int szScratch; /* Size of each scratch buffer */
  13428. int nScratch; /* Number of scratch buffers */
  13429. void *pPage; /* Page cache memory */
  13430. int szPage; /* Size of each page in pPage[] */
  13431. int nPage; /* Number of pages in pPage[] */
  13432. int mxParserStack; /* maximum depth of the parser stack */
  13433. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  13434. u32 szPma; /* Maximum Sorter PMA size */
  13435. /* The above might be initialized to non-zero. The following need to always
  13436. ** initially be zero, however. */
  13437. int isInit; /* True after initialization has finished */
  13438. int inProgress; /* True while initialization in progress */
  13439. int isMutexInit; /* True after mutexes are initialized */
  13440. int isMallocInit; /* True after malloc is initialized */
  13441. int isPCacheInit; /* True after malloc is initialized */
  13442. int nRefInitMutex; /* Number of users of pInitMutex */
  13443. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  13444. void (*xLog)(void*,int,const char*); /* Function for logging */
  13445. void *pLogArg; /* First argument to xLog() */
  13446. #ifdef SQLITE_ENABLE_SQLLOG
  13447. void(*xSqllog)(void*,sqlite3*,const char*, int);
  13448. void *pSqllogArg;
  13449. #endif
  13450. #ifdef SQLITE_VDBE_COVERAGE
  13451. /* The following callback (if not NULL) is invoked on every VDBE branch
  13452. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  13453. */
  13454. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  13455. void *pVdbeBranchArg; /* 1st argument */
  13456. #endif
  13457. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13458. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  13459. #endif
  13460. int bLocaltimeFault; /* True to fail localtime() calls */
  13461. };
  13462. /*
  13463. ** This macro is used inside of assert() statements to indicate that
  13464. ** the assert is only valid on a well-formed database. Instead of:
  13465. **
  13466. ** assert( X );
  13467. **
  13468. ** One writes:
  13469. **
  13470. ** assert( X || CORRUPT_DB );
  13471. **
  13472. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  13473. ** that the database is definitely corrupt, only that it might be corrupt.
  13474. ** For most test cases, CORRUPT_DB is set to false using a special
  13475. ** sqlite3_test_control(). This enables assert() statements to prove
  13476. ** things that are always true for well-formed databases.
  13477. */
  13478. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  13479. /*
  13480. ** Context pointer passed down through the tree-walk.
  13481. */
  13482. struct Walker {
  13483. Parse *pParse; /* Parser context. */
  13484. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  13485. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  13486. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  13487. int walkerDepth; /* Number of subqueries */
  13488. u8 eCode; /* A small processing code */
  13489. union { /* Extra data for callback */
  13490. NameContext *pNC; /* Naming context */
  13491. int n; /* A counter */
  13492. int iCur; /* A cursor number */
  13493. SrcList *pSrcList; /* FROM clause */
  13494. struct SrcCount *pSrcCount; /* Counting column references */
  13495. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  13496. int *aiCol; /* array of column indexes */
  13497. } u;
  13498. };
  13499. /* Forward declarations */
  13500. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  13501. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  13502. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  13503. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  13504. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  13505. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  13506. /*
  13507. ** Return code from the parse-tree walking primitives and their
  13508. ** callbacks.
  13509. */
  13510. #define WRC_Continue 0 /* Continue down into children */
  13511. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  13512. #define WRC_Abort 2 /* Abandon the tree walk */
  13513. /*
  13514. ** An instance of this structure represents a set of one or more CTEs
  13515. ** (common table expressions) created by a single WITH clause.
  13516. */
  13517. struct With {
  13518. int nCte; /* Number of CTEs in the WITH clause */
  13519. With *pOuter; /* Containing WITH clause, or NULL */
  13520. struct Cte { /* For each CTE in the WITH clause.... */
  13521. char *zName; /* Name of this CTE */
  13522. ExprList *pCols; /* List of explicit column names, or NULL */
  13523. Select *pSelect; /* The definition of this CTE */
  13524. const char *zCteErr; /* Error message for circular references */
  13525. } a[1];
  13526. };
  13527. #ifdef SQLITE_DEBUG
  13528. /*
  13529. ** An instance of the TreeView object is used for printing the content of
  13530. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  13531. */
  13532. struct TreeView {
  13533. int iLevel; /* Which level of the tree we are on */
  13534. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  13535. };
  13536. #endif /* SQLITE_DEBUG */
  13537. /*
  13538. ** Assuming zIn points to the first byte of a UTF-8 character,
  13539. ** advance zIn to point to the first byte of the next UTF-8 character.
  13540. */
  13541. #define SQLITE_SKIP_UTF8(zIn) { \
  13542. if( (*(zIn++))>=0xc0 ){ \
  13543. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  13544. } \
  13545. }
  13546. /*
  13547. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  13548. ** the same name but without the _BKPT suffix. These macros invoke
  13549. ** routines that report the line-number on which the error originated
  13550. ** using sqlite3_log(). The routines also provide a convenient place
  13551. ** to set a debugger breakpoint.
  13552. */
  13553. SQLITE_PRIVATE int sqlite3CorruptError(int);
  13554. SQLITE_PRIVATE int sqlite3MisuseError(int);
  13555. SQLITE_PRIVATE int sqlite3CantopenError(int);
  13556. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  13557. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  13558. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  13559. #ifdef SQLITE_DEBUG
  13560. SQLITE_PRIVATE int sqlite3NomemError(int);
  13561. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  13562. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  13563. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  13564. #else
  13565. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  13566. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  13567. #endif
  13568. /*
  13569. ** FTS3 and FTS4 both require virtual table support
  13570. */
  13571. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  13572. # undef SQLITE_ENABLE_FTS3
  13573. # undef SQLITE_ENABLE_FTS4
  13574. #endif
  13575. /*
  13576. ** FTS4 is really an extension for FTS3. It is enabled using the
  13577. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  13578. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  13579. */
  13580. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  13581. # define SQLITE_ENABLE_FTS3 1
  13582. #endif
  13583. /*
  13584. ** The ctype.h header is needed for non-ASCII systems. It is also
  13585. ** needed by FTS3 when FTS3 is included in the amalgamation.
  13586. */
  13587. #if !defined(SQLITE_ASCII) || \
  13588. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  13589. # include <ctype.h>
  13590. #endif
  13591. /*
  13592. ** The following macros mimic the standard library functions toupper(),
  13593. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  13594. ** sqlite versions only work for ASCII characters, regardless of locale.
  13595. */
  13596. #ifdef SQLITE_ASCII
  13597. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  13598. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  13599. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  13600. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  13601. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  13602. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  13603. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  13604. #else
  13605. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  13606. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  13607. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  13608. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  13609. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  13610. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  13611. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  13612. #endif
  13613. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  13614. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  13615. #endif
  13616. /*
  13617. ** Internal function prototypes
  13618. */
  13619. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  13620. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  13621. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  13622. #define sqlite3StrNICmp sqlite3_strnicmp
  13623. SQLITE_PRIVATE int sqlite3MallocInit(void);
  13624. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  13625. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  13626. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  13627. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  13628. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  13629. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  13630. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  13631. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  13632. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  13633. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  13634. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  13635. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  13636. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  13637. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  13638. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  13639. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  13640. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  13641. SQLITE_PRIVATE void sqlite3PageFree(void*);
  13642. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  13643. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13644. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  13645. #endif
  13646. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  13647. /*
  13648. ** On systems with ample stack space and that support alloca(), make
  13649. ** use of alloca() to obtain space for large automatic objects. By default,
  13650. ** obtain space from malloc().
  13651. **
  13652. ** The alloca() routine never returns NULL. This will cause code paths
  13653. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  13654. */
  13655. #ifdef SQLITE_USE_ALLOCA
  13656. # define sqlite3StackAllocRaw(D,N) alloca(N)
  13657. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  13658. # define sqlite3StackFree(D,P)
  13659. #else
  13660. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  13661. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  13662. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  13663. #endif
  13664. #ifdef SQLITE_ENABLE_MEMSYS3
  13665. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  13666. #endif
  13667. #ifdef SQLITE_ENABLE_MEMSYS5
  13668. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  13669. #endif
  13670. #ifndef SQLITE_MUTEX_OMIT
  13671. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  13672. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  13673. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  13674. SQLITE_PRIVATE int sqlite3MutexInit(void);
  13675. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  13676. #endif
  13677. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  13678. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  13679. #else
  13680. # define sqlite3MemoryBarrier()
  13681. #endif
  13682. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  13683. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  13684. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  13685. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  13686. /* Access to mutexes used by sqlite3_status() */
  13687. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  13688. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  13689. #ifndef SQLITE_OMIT_FLOATING_POINT
  13690. SQLITE_PRIVATE int sqlite3IsNaN(double);
  13691. #else
  13692. # define sqlite3IsNaN(X) 0
  13693. #endif
  13694. /*
  13695. ** An instance of the following structure holds information about SQL
  13696. ** functions arguments that are the parameters to the printf() function.
  13697. */
  13698. struct PrintfArguments {
  13699. int nArg; /* Total number of arguments */
  13700. int nUsed; /* Number of arguments used so far */
  13701. sqlite3_value **apArg; /* The argument values */
  13702. };
  13703. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
  13704. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  13705. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  13706. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  13707. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  13708. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  13709. #endif
  13710. #if defined(SQLITE_TEST)
  13711. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  13712. #endif
  13713. #if defined(SQLITE_DEBUG)
  13714. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  13715. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  13716. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  13717. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  13718. #endif
  13719. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  13720. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  13721. SQLITE_PRIVATE int sqlite3Dequote(char*);
  13722. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  13723. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  13724. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  13725. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  13726. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  13727. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  13728. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  13729. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  13730. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  13731. #ifdef SQLITE_DEBUG
  13732. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  13733. #endif
  13734. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  13735. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  13736. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  13737. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  13738. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  13739. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  13740. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  13741. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  13742. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  13743. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  13744. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  13745. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  13746. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  13747. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  13748. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  13749. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  13750. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  13751. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  13752. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  13753. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  13754. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  13755. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  13756. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  13757. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  13758. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  13759. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  13760. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  13761. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  13762. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  13763. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  13764. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  13765. #else
  13766. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  13767. #endif
  13768. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  13769. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  13770. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  13771. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  13772. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  13773. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  13774. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  13775. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  13776. sqlite3_vfs**,char**,char **);
  13777. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  13778. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  13779. #ifdef SQLITE_OMIT_BUILTIN_TEST
  13780. # define sqlite3FaultSim(X) SQLITE_OK
  13781. #else
  13782. SQLITE_PRIVATE int sqlite3FaultSim(int);
  13783. #endif
  13784. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  13785. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  13786. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  13787. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  13788. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  13789. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  13790. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  13791. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13792. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  13793. #endif
  13794. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  13795. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  13796. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  13797. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  13798. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  13799. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  13800. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  13801. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  13802. #else
  13803. # define sqlite3ViewGetColumnNames(A,B) 0
  13804. #endif
  13805. #if SQLITE_MAX_ATTACHED>30
  13806. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  13807. #endif
  13808. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  13809. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  13810. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  13811. #ifndef SQLITE_OMIT_AUTOINCREMENT
  13812. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  13813. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  13814. #else
  13815. # define sqlite3AutoincrementBegin(X)
  13816. # define sqlite3AutoincrementEnd(X)
  13817. #endif
  13818. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  13819. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  13820. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  13821. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  13822. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  13823. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  13824. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  13825. Token*, Select*, Expr*, IdList*);
  13826. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  13827. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  13828. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  13829. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  13830. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  13831. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  13832. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  13833. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  13834. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  13835. Expr*, int, int);
  13836. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  13837. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  13838. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  13839. Expr*,ExprList*,u32,Expr*,Expr*);
  13840. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  13841. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  13842. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  13843. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  13844. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  13845. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  13846. #endif
  13847. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  13848. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  13849. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  13850. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  13851. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  13852. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  13853. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  13854. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  13855. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  13856. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  13857. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  13858. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  13859. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  13860. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  13861. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  13862. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  13863. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  13864. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  13865. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  13866. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  13867. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  13868. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  13869. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  13870. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  13871. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  13872. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  13873. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  13874. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  13875. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  13876. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  13877. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  13878. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  13879. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  13880. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  13881. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  13882. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  13883. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  13884. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  13885. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  13886. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  13887. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  13888. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  13889. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  13890. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  13891. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  13892. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  13893. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  13894. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  13895. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  13896. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  13897. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  13898. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  13899. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  13900. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  13901. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  13902. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13903. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  13904. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  13905. #endif
  13906. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  13907. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  13908. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  13909. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  13910. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  13911. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  13912. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  13913. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  13914. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  13915. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  13916. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  13917. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  13918. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  13919. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13920. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  13921. #endif
  13922. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  13923. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  13924. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  13925. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  13926. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  13927. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  13928. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  13929. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  13930. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  13931. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  13932. u8,u8,int,int*,int*);
  13933. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  13934. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  13935. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  13936. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  13937. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  13938. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  13939. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  13940. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  13941. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  13942. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  13943. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  13944. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  13945. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  13946. #if SELECTTRACE_ENABLED
  13947. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  13948. #else
  13949. # define sqlite3SelectSetName(A,B)
  13950. #endif
  13951. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  13952. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  13953. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  13954. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  13955. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  13956. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  13957. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  13958. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  13959. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  13960. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  13961. #endif
  13962. #ifndef SQLITE_OMIT_TRIGGER
  13963. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  13964. Expr*,int, int);
  13965. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  13966. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  13967. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  13968. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  13969. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  13970. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  13971. int, int, int);
  13972. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  13973. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  13974. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  13975. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  13976. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  13977. Select*,u8);
  13978. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  13979. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  13980. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  13981. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  13982. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  13983. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  13984. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  13985. #else
  13986. # define sqlite3TriggersExist(B,C,D,E,F) 0
  13987. # define sqlite3DeleteTrigger(A,B)
  13988. # define sqlite3DropTriggerPtr(A,B)
  13989. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  13990. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  13991. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  13992. # define sqlite3TriggerList(X, Y) 0
  13993. # define sqlite3ParseToplevel(p) p
  13994. # define sqlite3IsToplevel(p) 1
  13995. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  13996. #endif
  13997. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  13998. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  13999. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  14000. #ifndef SQLITE_OMIT_AUTHORIZATION
  14001. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  14002. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  14003. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  14004. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  14005. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  14006. #else
  14007. # define sqlite3AuthRead(a,b,c,d)
  14008. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  14009. # define sqlite3AuthContextPush(a,b,c)
  14010. # define sqlite3AuthContextPop(a) ((void)(a))
  14011. #endif
  14012. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  14013. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  14014. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  14015. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  14016. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  14017. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  14018. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  14019. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  14020. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  14021. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  14022. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  14023. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  14024. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  14025. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  14026. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  14027. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  14028. #ifndef SQLITE_OMIT_VIRTUALTABLE
  14029. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  14030. #endif
  14031. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  14032. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  14033. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  14034. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  14035. #endif
  14036. /*
  14037. ** Routines to read and write variable-length integers. These used to
  14038. ** be defined locally, but now we use the varint routines in the util.c
  14039. ** file.
  14040. */
  14041. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  14042. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  14043. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  14044. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  14045. /*
  14046. ** The common case is for a varint to be a single byte. They following
  14047. ** macros handle the common case without a procedure call, but then call
  14048. ** the procedure for larger varints.
  14049. */
  14050. #define getVarint32(A,B) \
  14051. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  14052. #define putVarint32(A,B) \
  14053. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  14054. sqlite3PutVarint((A),(B)))
  14055. #define getVarint sqlite3GetVarint
  14056. #define putVarint sqlite3PutVarint
  14057. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  14058. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  14059. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  14060. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  14061. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  14062. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  14063. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  14064. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  14065. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  14066. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  14067. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  14068. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  14069. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  14070. #if defined(SQLITE_NEED_ERR_NAME)
  14071. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  14072. #endif
  14073. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  14074. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  14075. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  14076. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  14077. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  14078. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  14079. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  14080. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  14081. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  14082. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  14083. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  14084. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  14085. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  14086. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  14087. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  14088. #ifdef SQLITE_ENABLE_8_3_NAMES
  14089. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  14090. #else
  14091. # define sqlite3FileSuffix3(X,Y)
  14092. #endif
  14093. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  14094. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  14095. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  14096. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  14097. void(*)(void*));
  14098. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  14099. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  14100. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  14101. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  14102. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  14103. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  14104. #ifndef SQLITE_AMALGAMATION
  14105. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  14106. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  14107. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  14108. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  14109. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  14110. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  14111. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  14112. #ifndef SQLITE_OMIT_WSD
  14113. SQLITE_PRIVATE int sqlite3PendingByte;
  14114. #endif
  14115. #endif
  14116. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  14117. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  14118. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  14119. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  14120. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  14121. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  14122. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  14123. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  14124. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  14125. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  14126. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  14127. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  14128. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  14129. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  14130. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  14131. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  14132. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  14133. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  14134. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  14135. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  14136. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  14137. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  14138. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  14139. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  14140. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  14141. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  14142. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  14143. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  14144. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  14145. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  14146. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  14147. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  14148. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  14149. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  14150. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  14151. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  14152. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  14153. #ifdef SQLITE_DEBUG
  14154. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  14155. #endif
  14156. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  14157. void (*)(sqlite3_context*,int,sqlite3_value **),
  14158. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  14159. FuncDestructor *pDestructor
  14160. );
  14161. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  14162. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  14163. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  14164. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  14165. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  14166. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  14167. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  14168. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  14169. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  14170. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  14171. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  14172. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  14173. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  14174. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  14175. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  14176. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  14177. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  14178. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  14179. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  14180. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  14181. #endif
  14182. /*
  14183. ** The interface to the LEMON-generated parser
  14184. */
  14185. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  14186. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  14187. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  14188. #ifdef YYTRACKMAXSTACKDEPTH
  14189. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  14190. #endif
  14191. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  14192. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14193. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  14194. #else
  14195. # define sqlite3CloseExtensions(X)
  14196. #endif
  14197. #ifndef SQLITE_OMIT_SHARED_CACHE
  14198. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  14199. #else
  14200. #define sqlite3TableLock(v,w,x,y,z)
  14201. #endif
  14202. #ifdef SQLITE_TEST
  14203. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  14204. #endif
  14205. #ifdef SQLITE_OMIT_VIRTUALTABLE
  14206. # define sqlite3VtabClear(Y)
  14207. # define sqlite3VtabSync(X,Y) SQLITE_OK
  14208. # define sqlite3VtabRollback(X)
  14209. # define sqlite3VtabCommit(X)
  14210. # define sqlite3VtabInSync(db) 0
  14211. # define sqlite3VtabLock(X)
  14212. # define sqlite3VtabUnlock(X)
  14213. # define sqlite3VtabUnlockList(X)
  14214. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  14215. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  14216. #else
  14217. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  14218. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  14219. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  14220. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  14221. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  14222. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  14223. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  14224. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  14225. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  14226. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  14227. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  14228. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  14229. #endif
  14230. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  14231. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  14232. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  14233. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  14234. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  14235. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  14236. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  14237. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  14238. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  14239. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  14240. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  14241. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  14242. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  14243. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  14244. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  14245. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  14246. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  14247. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  14248. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  14249. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  14250. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  14251. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  14252. #ifndef SQLITE_OMIT_WAL
  14253. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  14254. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  14255. #endif
  14256. #ifndef SQLITE_OMIT_CTE
  14257. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  14258. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  14259. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  14260. #else
  14261. #define sqlite3WithPush(x,y,z)
  14262. #define sqlite3WithDelete(x,y)
  14263. #endif
  14264. /* Declarations for functions in fkey.c. All of these are replaced by
  14265. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  14266. ** key functionality is available. If OMIT_TRIGGER is defined but
  14267. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  14268. ** this case foreign keys are parsed, but no other functionality is
  14269. ** provided (enforcement of FK constraints requires the triggers sub-system).
  14270. */
  14271. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  14272. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  14273. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  14274. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  14275. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  14276. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  14277. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  14278. #else
  14279. #define sqlite3FkActions(a,b,c,d,e,f)
  14280. #define sqlite3FkCheck(a,b,c,d,e,f)
  14281. #define sqlite3FkDropTable(a,b,c)
  14282. #define sqlite3FkOldmask(a,b) 0
  14283. #define sqlite3FkRequired(a,b,c,d) 0
  14284. #endif
  14285. #ifndef SQLITE_OMIT_FOREIGN_KEY
  14286. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  14287. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  14288. #else
  14289. #define sqlite3FkDelete(a,b)
  14290. #define sqlite3FkLocateIndex(a,b,c,d,e)
  14291. #endif
  14292. /*
  14293. ** Available fault injectors. Should be numbered beginning with 0.
  14294. */
  14295. #define SQLITE_FAULTINJECTOR_MALLOC 0
  14296. #define SQLITE_FAULTINJECTOR_COUNT 1
  14297. /*
  14298. ** The interface to the code in fault.c used for identifying "benign"
  14299. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  14300. ** is not defined.
  14301. */
  14302. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14303. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  14304. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  14305. #else
  14306. #define sqlite3BeginBenignMalloc()
  14307. #define sqlite3EndBenignMalloc()
  14308. #endif
  14309. /*
  14310. ** Allowed return values from sqlite3FindInIndex()
  14311. */
  14312. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  14313. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  14314. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  14315. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  14316. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  14317. /*
  14318. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  14319. */
  14320. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  14321. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  14322. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  14323. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  14324. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  14325. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  14326. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  14327. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  14328. #endif
  14329. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  14330. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  14331. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  14332. #if SQLITE_MAX_EXPR_DEPTH>0
  14333. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  14334. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  14335. #else
  14336. #define sqlite3SelectExprHeight(x) 0
  14337. #define sqlite3ExprCheckHeight(x,y)
  14338. #endif
  14339. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  14340. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  14341. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  14342. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  14343. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  14344. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  14345. #else
  14346. #define sqlite3ConnectionBlocked(x,y)
  14347. #define sqlite3ConnectionUnlocked(x)
  14348. #define sqlite3ConnectionClosed(x)
  14349. #endif
  14350. #ifdef SQLITE_DEBUG
  14351. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  14352. #endif
  14353. /*
  14354. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  14355. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  14356. ** print I/O tracing messages.
  14357. */
  14358. #ifdef SQLITE_ENABLE_IOTRACE
  14359. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  14360. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  14361. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  14362. #else
  14363. # define IOTRACE(A)
  14364. # define sqlite3VdbeIOTraceSql(X)
  14365. #endif
  14366. /*
  14367. ** These routines are available for the mem2.c debugging memory allocator
  14368. ** only. They are used to verify that different "types" of memory
  14369. ** allocations are properly tracked by the system.
  14370. **
  14371. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  14372. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  14373. ** a single bit set.
  14374. **
  14375. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  14376. ** argument match the type set by the previous sqlite3MemdebugSetType().
  14377. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  14378. **
  14379. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  14380. ** argument match the type set by the previous sqlite3MemdebugSetType().
  14381. **
  14382. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  14383. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  14384. ** it might have been allocated by lookaside, except the allocation was
  14385. ** too large or lookaside was already full. It is important to verify
  14386. ** that allocations that might have been satisfied by lookaside are not
  14387. ** passed back to non-lookaside free() routines. Asserts such as the
  14388. ** example above are placed on the non-lookaside free() routines to verify
  14389. ** this constraint.
  14390. **
  14391. ** All of this is no-op for a production build. It only comes into
  14392. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  14393. */
  14394. #ifdef SQLITE_MEMDEBUG
  14395. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  14396. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  14397. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  14398. #else
  14399. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  14400. # define sqlite3MemdebugHasType(X,Y) 1
  14401. # define sqlite3MemdebugNoType(X,Y) 1
  14402. #endif
  14403. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  14404. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  14405. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  14406. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  14407. /*
  14408. ** Threading interface
  14409. */
  14410. #if SQLITE_MAX_WORKER_THREADS>0
  14411. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  14412. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  14413. #endif
  14414. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  14415. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  14416. #endif
  14417. #endif /* _SQLITEINT_H_ */
  14418. /************** End of sqliteInt.h *******************************************/
  14419. /************** Begin file global.c ******************************************/
  14420. /*
  14421. ** 2008 June 13
  14422. **
  14423. ** The author disclaims copyright to this source code. In place of
  14424. ** a legal notice, here is a blessing:
  14425. **
  14426. ** May you do good and not evil.
  14427. ** May you find forgiveness for yourself and forgive others.
  14428. ** May you share freely, never taking more than you give.
  14429. **
  14430. *************************************************************************
  14431. **
  14432. ** This file contains definitions of global variables and constants.
  14433. */
  14434. /* #include "sqliteInt.h" */
  14435. /* An array to map all upper-case characters into their corresponding
  14436. ** lower-case character.
  14437. **
  14438. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  14439. ** handle case conversions for the UTF character set since the tables
  14440. ** involved are nearly as big or bigger than SQLite itself.
  14441. */
  14442. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  14443. #ifdef SQLITE_ASCII
  14444. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  14445. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  14446. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  14447. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  14448. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  14449. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  14450. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  14451. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  14452. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  14453. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  14454. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  14455. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  14456. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  14457. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  14458. 252,253,254,255
  14459. #endif
  14460. #ifdef SQLITE_EBCDIC
  14461. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  14462. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  14463. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  14464. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  14465. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  14466. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  14467. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  14468. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  14469. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  14470. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  14471. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  14472. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  14473. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  14474. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  14475. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  14476. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  14477. #endif
  14478. };
  14479. /*
  14480. ** The following 256 byte lookup table is used to support SQLites built-in
  14481. ** equivalents to the following standard library functions:
  14482. **
  14483. ** isspace() 0x01
  14484. ** isalpha() 0x02
  14485. ** isdigit() 0x04
  14486. ** isalnum() 0x06
  14487. ** isxdigit() 0x08
  14488. ** toupper() 0x20
  14489. ** SQLite identifier character 0x40
  14490. **
  14491. ** Bit 0x20 is set if the mapped character requires translation to upper
  14492. ** case. i.e. if the character is a lower-case ASCII character.
  14493. ** If x is a lower-case ASCII character, then its upper-case equivalent
  14494. ** is (x - 0x20). Therefore toupper() can be implemented as:
  14495. **
  14496. ** (x & ~(map[x]&0x20))
  14497. **
  14498. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  14499. ** array. tolower() is used more often than toupper() by SQLite.
  14500. **
  14501. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  14502. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  14503. ** non-ASCII UTF character. Hence the test for whether or not a character is
  14504. ** part of an identifier is 0x46.
  14505. **
  14506. ** SQLite's versions are identical to the standard versions assuming a
  14507. ** locale of "C". They are implemented as macros in sqliteInt.h.
  14508. */
  14509. #ifdef SQLITE_ASCII
  14510. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  14511. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  14512. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  14513. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  14514. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  14515. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  14516. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  14517. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  14518. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  14519. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  14520. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  14521. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  14522. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  14523. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  14524. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  14525. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  14526. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  14527. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  14528. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  14529. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  14530. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  14531. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  14532. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  14533. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  14534. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  14535. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  14536. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  14537. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  14538. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  14539. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  14540. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  14541. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  14542. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  14543. };
  14544. #endif
  14545. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  14546. ** compatibility for legacy applications, the URI filename capability is
  14547. ** disabled by default.
  14548. **
  14549. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  14550. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  14551. **
  14552. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  14553. ** disabled. The default value may be changed by compiling with the
  14554. ** SQLITE_USE_URI symbol defined.
  14555. */
  14556. #ifndef SQLITE_USE_URI
  14557. # define SQLITE_USE_URI 0
  14558. #endif
  14559. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  14560. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  14561. ** that compile-time option is omitted.
  14562. */
  14563. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  14564. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  14565. #endif
  14566. /* The minimum PMA size is set to this value multiplied by the database
  14567. ** page size in bytes.
  14568. */
  14569. #ifndef SQLITE_SORTER_PMASZ
  14570. # define SQLITE_SORTER_PMASZ 250
  14571. #endif
  14572. /* Statement journals spill to disk when their size exceeds the following
  14573. ** threashold (in bytes). 0 means that statement journals are created and
  14574. ** written to disk immediately (the default behavior for SQLite versions
  14575. ** before 3.12.0). -1 means always keep the entire statement journal in
  14576. ** memory. (The statement journal is also always held entirely in memory
  14577. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  14578. ** setting.)
  14579. */
  14580. #ifndef SQLITE_STMTJRNL_SPILL
  14581. # define SQLITE_STMTJRNL_SPILL (64*1024)
  14582. #endif
  14583. /*
  14584. ** The following singleton contains the global configuration for
  14585. ** the SQLite library.
  14586. */
  14587. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  14588. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  14589. 1, /* bCoreMutex */
  14590. SQLITE_THREADSAFE==1, /* bFullMutex */
  14591. SQLITE_USE_URI, /* bOpenUri */
  14592. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  14593. 0x7ffffffe, /* mxStrlen */
  14594. 0, /* neverCorrupt */
  14595. 128, /* szLookaside */
  14596. 500, /* nLookaside */
  14597. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  14598. {0,0,0,0,0,0,0,0}, /* m */
  14599. {0,0,0,0,0,0,0,0,0}, /* mutex */
  14600. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  14601. (void*)0, /* pHeap */
  14602. 0, /* nHeap */
  14603. 0, 0, /* mnHeap, mxHeap */
  14604. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  14605. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  14606. (void*)0, /* pScratch */
  14607. 0, /* szScratch */
  14608. 0, /* nScratch */
  14609. (void*)0, /* pPage */
  14610. 0, /* szPage */
  14611. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  14612. 0, /* mxParserStack */
  14613. 0, /* sharedCacheEnabled */
  14614. SQLITE_SORTER_PMASZ, /* szPma */
  14615. /* All the rest should always be initialized to zero */
  14616. 0, /* isInit */
  14617. 0, /* inProgress */
  14618. 0, /* isMutexInit */
  14619. 0, /* isMallocInit */
  14620. 0, /* isPCacheInit */
  14621. 0, /* nRefInitMutex */
  14622. 0, /* pInitMutex */
  14623. 0, /* xLog */
  14624. 0, /* pLogArg */
  14625. #ifdef SQLITE_ENABLE_SQLLOG
  14626. 0, /* xSqllog */
  14627. 0, /* pSqllogArg */
  14628. #endif
  14629. #ifdef SQLITE_VDBE_COVERAGE
  14630. 0, /* xVdbeBranch */
  14631. 0, /* pVbeBranchArg */
  14632. #endif
  14633. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14634. 0, /* xTestCallback */
  14635. #endif
  14636. 0 /* bLocaltimeFault */
  14637. };
  14638. /*
  14639. ** Hash table for global functions - functions common to all
  14640. ** database connections. After initialization, this table is
  14641. ** read-only.
  14642. */
  14643. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  14644. /*
  14645. ** Constant tokens for values 0 and 1.
  14646. */
  14647. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  14648. { "0", 1 },
  14649. { "1", 1 }
  14650. };
  14651. /*
  14652. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  14653. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  14654. ** the database page that contains the pending byte. It never attempts
  14655. ** to read or write that page. The pending byte page is set assign
  14656. ** for use by the VFS layers as space for managing file locks.
  14657. **
  14658. ** During testing, it is often desirable to move the pending byte to
  14659. ** a different position in the file. This allows code that has to
  14660. ** deal with the pending byte to run on files that are much smaller
  14661. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  14662. ** move the pending byte.
  14663. **
  14664. ** IMPORTANT: Changing the pending byte to any value other than
  14665. ** 0x40000000 results in an incompatible database file format!
  14666. ** Changing the pending byte during operation will result in undefined
  14667. ** and incorrect behavior.
  14668. */
  14669. #ifndef SQLITE_OMIT_WSD
  14670. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  14671. #endif
  14672. /* #include "opcodes.h" */
  14673. /*
  14674. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  14675. ** created by mkopcodeh.awk during compilation. Data is obtained
  14676. ** from the comments following the "case OP_xxxx:" statements in
  14677. ** the vdbe.c file.
  14678. */
  14679. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  14680. /*
  14681. ** Name of the default collating sequence
  14682. */
  14683. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  14684. /************** End of global.c **********************************************/
  14685. /************** Begin file ctime.c *******************************************/
  14686. /*
  14687. ** 2010 February 23
  14688. **
  14689. ** The author disclaims copyright to this source code. In place of
  14690. ** a legal notice, here is a blessing:
  14691. **
  14692. ** May you do good and not evil.
  14693. ** May you find forgiveness for yourself and forgive others.
  14694. ** May you share freely, never taking more than you give.
  14695. **
  14696. *************************************************************************
  14697. **
  14698. ** This file implements routines used to report what compile-time options
  14699. ** SQLite was built with.
  14700. */
  14701. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  14702. /* #include "sqliteInt.h" */
  14703. /*
  14704. ** An array of names of all compile-time options. This array should
  14705. ** be sorted A-Z.
  14706. **
  14707. ** This array looks large, but in a typical installation actually uses
  14708. ** only a handful of compile-time options, so most times this array is usually
  14709. ** rather short and uses little memory space.
  14710. */
  14711. static const char * const azCompileOpt[] = {
  14712. /* These macros are provided to "stringify" the value of the define
  14713. ** for those options in which the value is meaningful. */
  14714. #define CTIMEOPT_VAL_(opt) #opt
  14715. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  14716. #if SQLITE_32BIT_ROWID
  14717. "32BIT_ROWID",
  14718. #endif
  14719. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  14720. "4_BYTE_ALIGNED_MALLOC",
  14721. #endif
  14722. #if SQLITE_CASE_SENSITIVE_LIKE
  14723. "CASE_SENSITIVE_LIKE",
  14724. #endif
  14725. #if SQLITE_CHECK_PAGES
  14726. "CHECK_PAGES",
  14727. #endif
  14728. #if SQLITE_COVERAGE_TEST
  14729. "COVERAGE_TEST",
  14730. #endif
  14731. #if SQLITE_DEBUG
  14732. "DEBUG",
  14733. #endif
  14734. #if SQLITE_DEFAULT_LOCKING_MODE
  14735. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  14736. #endif
  14737. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  14738. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  14739. #endif
  14740. #if SQLITE_DISABLE_DIRSYNC
  14741. "DISABLE_DIRSYNC",
  14742. #endif
  14743. #if SQLITE_DISABLE_LFS
  14744. "DISABLE_LFS",
  14745. #endif
  14746. #if SQLITE_ENABLE_8_3_NAMES
  14747. "ENABLE_8_3_NAMES",
  14748. #endif
  14749. #if SQLITE_ENABLE_API_ARMOR
  14750. "ENABLE_API_ARMOR",
  14751. #endif
  14752. #if SQLITE_ENABLE_ATOMIC_WRITE
  14753. "ENABLE_ATOMIC_WRITE",
  14754. #endif
  14755. #if SQLITE_ENABLE_CEROD
  14756. "ENABLE_CEROD",
  14757. #endif
  14758. #if SQLITE_ENABLE_COLUMN_METADATA
  14759. "ENABLE_COLUMN_METADATA",
  14760. #endif
  14761. #if SQLITE_ENABLE_DBSTAT_VTAB
  14762. "ENABLE_DBSTAT_VTAB",
  14763. #endif
  14764. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  14765. "ENABLE_EXPENSIVE_ASSERT",
  14766. #endif
  14767. #if SQLITE_ENABLE_FTS1
  14768. "ENABLE_FTS1",
  14769. #endif
  14770. #if SQLITE_ENABLE_FTS2
  14771. "ENABLE_FTS2",
  14772. #endif
  14773. #if SQLITE_ENABLE_FTS3
  14774. "ENABLE_FTS3",
  14775. #endif
  14776. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  14777. "ENABLE_FTS3_PARENTHESIS",
  14778. #endif
  14779. #if SQLITE_ENABLE_FTS4
  14780. "ENABLE_FTS4",
  14781. #endif
  14782. #if SQLITE_ENABLE_FTS5
  14783. "ENABLE_FTS5",
  14784. #endif
  14785. #if SQLITE_ENABLE_ICU
  14786. "ENABLE_ICU",
  14787. #endif
  14788. #if SQLITE_ENABLE_IOTRACE
  14789. "ENABLE_IOTRACE",
  14790. #endif
  14791. #if SQLITE_ENABLE_JSON1
  14792. "ENABLE_JSON1",
  14793. #endif
  14794. #if SQLITE_ENABLE_LOAD_EXTENSION
  14795. "ENABLE_LOAD_EXTENSION",
  14796. #endif
  14797. #if SQLITE_ENABLE_LOCKING_STYLE
  14798. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  14799. #endif
  14800. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  14801. "ENABLE_MEMORY_MANAGEMENT",
  14802. #endif
  14803. #if SQLITE_ENABLE_MEMSYS3
  14804. "ENABLE_MEMSYS3",
  14805. #endif
  14806. #if SQLITE_ENABLE_MEMSYS5
  14807. "ENABLE_MEMSYS5",
  14808. #endif
  14809. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  14810. "ENABLE_OVERSIZE_CELL_CHECK",
  14811. #endif
  14812. #if SQLITE_ENABLE_RTREE
  14813. "ENABLE_RTREE",
  14814. #endif
  14815. #if defined(SQLITE_ENABLE_STAT4)
  14816. "ENABLE_STAT4",
  14817. #elif defined(SQLITE_ENABLE_STAT3)
  14818. "ENABLE_STAT3",
  14819. #endif
  14820. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  14821. "ENABLE_UNLOCK_NOTIFY",
  14822. #endif
  14823. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  14824. "ENABLE_UPDATE_DELETE_LIMIT",
  14825. #endif
  14826. #if SQLITE_HAS_CODEC
  14827. "HAS_CODEC",
  14828. #endif
  14829. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  14830. "HAVE_ISNAN",
  14831. #endif
  14832. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14833. "HOMEGROWN_RECURSIVE_MUTEX",
  14834. #endif
  14835. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  14836. "IGNORE_AFP_LOCK_ERRORS",
  14837. #endif
  14838. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  14839. "IGNORE_FLOCK_LOCK_ERRORS",
  14840. #endif
  14841. #ifdef SQLITE_INT64_TYPE
  14842. "INT64_TYPE",
  14843. #endif
  14844. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  14845. "LIKE_DOESNT_MATCH_BLOBS",
  14846. #endif
  14847. #if SQLITE_LOCK_TRACE
  14848. "LOCK_TRACE",
  14849. #endif
  14850. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  14851. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  14852. #endif
  14853. #ifdef SQLITE_MAX_SCHEMA_RETRY
  14854. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  14855. #endif
  14856. #if SQLITE_MEMDEBUG
  14857. "MEMDEBUG",
  14858. #endif
  14859. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  14860. "MIXED_ENDIAN_64BIT_FLOAT",
  14861. #endif
  14862. #if SQLITE_NO_SYNC
  14863. "NO_SYNC",
  14864. #endif
  14865. #if SQLITE_OMIT_ALTERTABLE
  14866. "OMIT_ALTERTABLE",
  14867. #endif
  14868. #if SQLITE_OMIT_ANALYZE
  14869. "OMIT_ANALYZE",
  14870. #endif
  14871. #if SQLITE_OMIT_ATTACH
  14872. "OMIT_ATTACH",
  14873. #endif
  14874. #if SQLITE_OMIT_AUTHORIZATION
  14875. "OMIT_AUTHORIZATION",
  14876. #endif
  14877. #if SQLITE_OMIT_AUTOINCREMENT
  14878. "OMIT_AUTOINCREMENT",
  14879. #endif
  14880. #if SQLITE_OMIT_AUTOINIT
  14881. "OMIT_AUTOINIT",
  14882. #endif
  14883. #if SQLITE_OMIT_AUTOMATIC_INDEX
  14884. "OMIT_AUTOMATIC_INDEX",
  14885. #endif
  14886. #if SQLITE_OMIT_AUTORESET
  14887. "OMIT_AUTORESET",
  14888. #endif
  14889. #if SQLITE_OMIT_AUTOVACUUM
  14890. "OMIT_AUTOVACUUM",
  14891. #endif
  14892. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  14893. "OMIT_BETWEEN_OPTIMIZATION",
  14894. #endif
  14895. #if SQLITE_OMIT_BLOB_LITERAL
  14896. "OMIT_BLOB_LITERAL",
  14897. #endif
  14898. #if SQLITE_OMIT_BTREECOUNT
  14899. "OMIT_BTREECOUNT",
  14900. #endif
  14901. #if SQLITE_OMIT_BUILTIN_TEST
  14902. "OMIT_BUILTIN_TEST",
  14903. #endif
  14904. #if SQLITE_OMIT_CAST
  14905. "OMIT_CAST",
  14906. #endif
  14907. #if SQLITE_OMIT_CHECK
  14908. "OMIT_CHECK",
  14909. #endif
  14910. #if SQLITE_OMIT_COMPLETE
  14911. "OMIT_COMPLETE",
  14912. #endif
  14913. #if SQLITE_OMIT_COMPOUND_SELECT
  14914. "OMIT_COMPOUND_SELECT",
  14915. #endif
  14916. #if SQLITE_OMIT_CTE
  14917. "OMIT_CTE",
  14918. #endif
  14919. #if SQLITE_OMIT_DATETIME_FUNCS
  14920. "OMIT_DATETIME_FUNCS",
  14921. #endif
  14922. #if SQLITE_OMIT_DECLTYPE
  14923. "OMIT_DECLTYPE",
  14924. #endif
  14925. #if SQLITE_OMIT_DEPRECATED
  14926. "OMIT_DEPRECATED",
  14927. #endif
  14928. #if SQLITE_OMIT_DISKIO
  14929. "OMIT_DISKIO",
  14930. #endif
  14931. #if SQLITE_OMIT_EXPLAIN
  14932. "OMIT_EXPLAIN",
  14933. #endif
  14934. #if SQLITE_OMIT_FLAG_PRAGMAS
  14935. "OMIT_FLAG_PRAGMAS",
  14936. #endif
  14937. #if SQLITE_OMIT_FLOATING_POINT
  14938. "OMIT_FLOATING_POINT",
  14939. #endif
  14940. #if SQLITE_OMIT_FOREIGN_KEY
  14941. "OMIT_FOREIGN_KEY",
  14942. #endif
  14943. #if SQLITE_OMIT_GET_TABLE
  14944. "OMIT_GET_TABLE",
  14945. #endif
  14946. #if SQLITE_OMIT_INCRBLOB
  14947. "OMIT_INCRBLOB",
  14948. #endif
  14949. #if SQLITE_OMIT_INTEGRITY_CHECK
  14950. "OMIT_INTEGRITY_CHECK",
  14951. #endif
  14952. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  14953. "OMIT_LIKE_OPTIMIZATION",
  14954. #endif
  14955. #if SQLITE_OMIT_LOAD_EXTENSION
  14956. "OMIT_LOAD_EXTENSION",
  14957. #endif
  14958. #if SQLITE_OMIT_LOCALTIME
  14959. "OMIT_LOCALTIME",
  14960. #endif
  14961. #if SQLITE_OMIT_LOOKASIDE
  14962. "OMIT_LOOKASIDE",
  14963. #endif
  14964. #if SQLITE_OMIT_MEMORYDB
  14965. "OMIT_MEMORYDB",
  14966. #endif
  14967. #if SQLITE_OMIT_OR_OPTIMIZATION
  14968. "OMIT_OR_OPTIMIZATION",
  14969. #endif
  14970. #if SQLITE_OMIT_PAGER_PRAGMAS
  14971. "OMIT_PAGER_PRAGMAS",
  14972. #endif
  14973. #if SQLITE_OMIT_PRAGMA
  14974. "OMIT_PRAGMA",
  14975. #endif
  14976. #if SQLITE_OMIT_PROGRESS_CALLBACK
  14977. "OMIT_PROGRESS_CALLBACK",
  14978. #endif
  14979. #if SQLITE_OMIT_QUICKBALANCE
  14980. "OMIT_QUICKBALANCE",
  14981. #endif
  14982. #if SQLITE_OMIT_REINDEX
  14983. "OMIT_REINDEX",
  14984. #endif
  14985. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  14986. "OMIT_SCHEMA_PRAGMAS",
  14987. #endif
  14988. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  14989. "OMIT_SCHEMA_VERSION_PRAGMAS",
  14990. #endif
  14991. #if SQLITE_OMIT_SHARED_CACHE
  14992. "OMIT_SHARED_CACHE",
  14993. #endif
  14994. #if SQLITE_OMIT_SUBQUERY
  14995. "OMIT_SUBQUERY",
  14996. #endif
  14997. #if SQLITE_OMIT_TCL_VARIABLE
  14998. "OMIT_TCL_VARIABLE",
  14999. #endif
  15000. #if SQLITE_OMIT_TEMPDB
  15001. "OMIT_TEMPDB",
  15002. #endif
  15003. #if SQLITE_OMIT_TRACE
  15004. "OMIT_TRACE",
  15005. #endif
  15006. #if SQLITE_OMIT_TRIGGER
  15007. "OMIT_TRIGGER",
  15008. #endif
  15009. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  15010. "OMIT_TRUNCATE_OPTIMIZATION",
  15011. #endif
  15012. #if SQLITE_OMIT_UTF16
  15013. "OMIT_UTF16",
  15014. #endif
  15015. #if SQLITE_OMIT_VACUUM
  15016. "OMIT_VACUUM",
  15017. #endif
  15018. #if SQLITE_OMIT_VIEW
  15019. "OMIT_VIEW",
  15020. #endif
  15021. #if SQLITE_OMIT_VIRTUALTABLE
  15022. "OMIT_VIRTUALTABLE",
  15023. #endif
  15024. #if SQLITE_OMIT_WAL
  15025. "OMIT_WAL",
  15026. #endif
  15027. #if SQLITE_OMIT_WSD
  15028. "OMIT_WSD",
  15029. #endif
  15030. #if SQLITE_OMIT_XFER_OPT
  15031. "OMIT_XFER_OPT",
  15032. #endif
  15033. #if SQLITE_PERFORMANCE_TRACE
  15034. "PERFORMANCE_TRACE",
  15035. #endif
  15036. #if SQLITE_PROXY_DEBUG
  15037. "PROXY_DEBUG",
  15038. #endif
  15039. #if SQLITE_RTREE_INT_ONLY
  15040. "RTREE_INT_ONLY",
  15041. #endif
  15042. #if SQLITE_SECURE_DELETE
  15043. "SECURE_DELETE",
  15044. #endif
  15045. #if SQLITE_SMALL_STACK
  15046. "SMALL_STACK",
  15047. #endif
  15048. #if SQLITE_SOUNDEX
  15049. "SOUNDEX",
  15050. #endif
  15051. #if SQLITE_SYSTEM_MALLOC
  15052. "SYSTEM_MALLOC",
  15053. #endif
  15054. #if SQLITE_TCL
  15055. "TCL",
  15056. #endif
  15057. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  15058. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  15059. #endif
  15060. #if SQLITE_TEST
  15061. "TEST",
  15062. #endif
  15063. #if defined(SQLITE_THREADSAFE)
  15064. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  15065. #endif
  15066. #if SQLITE_USE_ALLOCA
  15067. "USE_ALLOCA",
  15068. #endif
  15069. #if SQLITE_USER_AUTHENTICATION
  15070. "USER_AUTHENTICATION",
  15071. #endif
  15072. #if SQLITE_WIN32_MALLOC
  15073. "WIN32_MALLOC",
  15074. #endif
  15075. #if SQLITE_ZERO_MALLOC
  15076. "ZERO_MALLOC"
  15077. #endif
  15078. };
  15079. /*
  15080. ** Given the name of a compile-time option, return true if that option
  15081. ** was used and false if not.
  15082. **
  15083. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  15084. ** is not required for a match.
  15085. */
  15086. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
  15087. int i, n;
  15088. #if SQLITE_ENABLE_API_ARMOR
  15089. if( zOptName==0 ){
  15090. (void)SQLITE_MISUSE_BKPT;
  15091. return 0;
  15092. }
  15093. #endif
  15094. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  15095. n = sqlite3Strlen30(zOptName);
  15096. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  15097. ** linear search is adequate. No need for a binary search. */
  15098. for(i=0; i<ArraySize(azCompileOpt); i++){
  15099. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  15100. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  15101. ){
  15102. return 1;
  15103. }
  15104. }
  15105. return 0;
  15106. }
  15107. /*
  15108. ** Return the N-th compile-time option string. If N is out of range,
  15109. ** return a NULL pointer.
  15110. */
  15111. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
  15112. if( N>=0 && N<ArraySize(azCompileOpt) ){
  15113. return azCompileOpt[N];
  15114. }
  15115. return 0;
  15116. }
  15117. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  15118. /************** End of ctime.c ***********************************************/
  15119. /************** Begin file status.c ******************************************/
  15120. /*
  15121. ** 2008 June 18
  15122. **
  15123. ** The author disclaims copyright to this source code. In place of
  15124. ** a legal notice, here is a blessing:
  15125. **
  15126. ** May you do good and not evil.
  15127. ** May you find forgiveness for yourself and forgive others.
  15128. ** May you share freely, never taking more than you give.
  15129. **
  15130. *************************************************************************
  15131. **
  15132. ** This module implements the sqlite3_status() interface and related
  15133. ** functionality.
  15134. */
  15135. /* #include "sqliteInt.h" */
  15136. /************** Include vdbeInt.h in the middle of status.c ******************/
  15137. /************** Begin file vdbeInt.h *****************************************/
  15138. /*
  15139. ** 2003 September 6
  15140. **
  15141. ** The author disclaims copyright to this source code. In place of
  15142. ** a legal notice, here is a blessing:
  15143. **
  15144. ** May you do good and not evil.
  15145. ** May you find forgiveness for yourself and forgive others.
  15146. ** May you share freely, never taking more than you give.
  15147. **
  15148. *************************************************************************
  15149. ** This is the header file for information that is private to the
  15150. ** VDBE. This information used to all be at the top of the single
  15151. ** source code file "vdbe.c". When that file became too big (over
  15152. ** 6000 lines long) it was split up into several smaller files and
  15153. ** this header information was factored out.
  15154. */
  15155. #ifndef _VDBEINT_H_
  15156. #define _VDBEINT_H_
  15157. /*
  15158. ** The maximum number of times that a statement will try to reparse
  15159. ** itself before giving up and returning SQLITE_SCHEMA.
  15160. */
  15161. #ifndef SQLITE_MAX_SCHEMA_RETRY
  15162. # define SQLITE_MAX_SCHEMA_RETRY 50
  15163. #endif
  15164. /*
  15165. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  15166. ** "explain" P4 display logic is enabled.
  15167. */
  15168. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  15169. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  15170. # define VDBE_DISPLAY_P4 1
  15171. #else
  15172. # define VDBE_DISPLAY_P4 0
  15173. #endif
  15174. /*
  15175. ** SQL is translated into a sequence of instructions to be
  15176. ** executed by a virtual machine. Each instruction is an instance
  15177. ** of the following structure.
  15178. */
  15179. typedef struct VdbeOp Op;
  15180. /*
  15181. ** Boolean values
  15182. */
  15183. typedef unsigned Bool;
  15184. /* Opaque type used by code in vdbesort.c */
  15185. typedef struct VdbeSorter VdbeSorter;
  15186. /* Opaque type used by the explainer */
  15187. typedef struct Explain Explain;
  15188. /* Elements of the linked list at Vdbe.pAuxData */
  15189. typedef struct AuxData AuxData;
  15190. /* Types of VDBE cursors */
  15191. #define CURTYPE_BTREE 0
  15192. #define CURTYPE_SORTER 1
  15193. #define CURTYPE_VTAB 2
  15194. #define CURTYPE_PSEUDO 3
  15195. /*
  15196. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  15197. **
  15198. ** * A b-tree cursor
  15199. ** - In the main database or in an ephemeral database
  15200. ** - On either an index or a table
  15201. ** * A sorter
  15202. ** * A virtual table
  15203. ** * A one-row "pseudotable" stored in a single register
  15204. */
  15205. typedef struct VdbeCursor VdbeCursor;
  15206. struct VdbeCursor {
  15207. u8 eCurType; /* One of the CURTYPE_* values above */
  15208. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  15209. u8 nullRow; /* True if pointing to a row with no data */
  15210. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  15211. u8 isTable; /* True for rowid tables. False for indexes */
  15212. #ifdef SQLITE_DEBUG
  15213. u8 seekOp; /* Most recent seek operation on this cursor */
  15214. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  15215. #endif
  15216. Bool isEphemeral:1; /* True for an ephemeral table */
  15217. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  15218. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  15219. Pgno pgnoRoot; /* Root page of the open btree cursor */
  15220. i16 nField; /* Number of fields in the header */
  15221. u16 nHdrParsed; /* Number of header fields parsed so far */
  15222. union {
  15223. BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
  15224. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  15225. int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
  15226. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  15227. } uc;
  15228. Btree *pBt; /* Separate file holding temporary table */
  15229. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  15230. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  15231. i64 seqCount; /* Sequence counter */
  15232. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  15233. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  15234. int *aAltMap; /* Mapping from table to index column numbers */
  15235. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  15236. u64 maskUsed; /* Mask of columns used by this cursor */
  15237. #endif
  15238. /* Cached information about the header for the data record that the
  15239. ** cursor is currently pointing to. Only valid if cacheStatus matches
  15240. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  15241. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  15242. ** the cache is out of date.
  15243. **
  15244. ** aRow might point to (ephemeral) data for the current row, or it might
  15245. ** be NULL.
  15246. */
  15247. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  15248. u32 payloadSize; /* Total number of bytes in the record */
  15249. u32 szRow; /* Byte available in aRow */
  15250. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  15251. const u8 *aRow; /* Data for the current row, if all on one page */
  15252. u32 *aOffset; /* Pointer to aType[nField] */
  15253. u32 aType[1]; /* Type values for all entries in the record */
  15254. /* 2*nField extra array elements allocated for aType[], beyond the one
  15255. ** static element declared in the structure. nField total array slots for
  15256. ** aType[] and nField+1 array slots for aOffset[] */
  15257. };
  15258. /*
  15259. ** When a sub-program is executed (OP_Program), a structure of this type
  15260. ** is allocated to store the current value of the program counter, as
  15261. ** well as the current memory cell array and various other frame specific
  15262. ** values stored in the Vdbe struct. When the sub-program is finished,
  15263. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  15264. ** restoring the state of the VM to as it was before the sub-program
  15265. ** began executing.
  15266. **
  15267. ** The memory for a VdbeFrame object is allocated and managed by a memory
  15268. ** cell in the parent (calling) frame. When the memory cell is deleted or
  15269. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  15270. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  15271. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  15272. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  15273. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  15274. ** child frame are released.
  15275. **
  15276. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  15277. ** set to NULL if the currently executing frame is the main program.
  15278. */
  15279. typedef struct VdbeFrame VdbeFrame;
  15280. struct VdbeFrame {
  15281. Vdbe *v; /* VM this frame belongs to */
  15282. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  15283. Op *aOp; /* Program instructions for parent frame */
  15284. i64 *anExec; /* Event counters from parent frame */
  15285. Mem *aMem; /* Array of memory cells for parent frame */
  15286. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  15287. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  15288. void *token; /* Copy of SubProgram.token */
  15289. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  15290. AuxData *pAuxData; /* Linked list of auxdata allocations */
  15291. int nCursor; /* Number of entries in apCsr */
  15292. int pc; /* Program Counter in parent (calling) frame */
  15293. int nOp; /* Size of aOp array */
  15294. int nMem; /* Number of entries in aMem */
  15295. int nOnceFlag; /* Number of entries in aOnceFlag */
  15296. int nChildMem; /* Number of memory cells for child frame */
  15297. int nChildCsr; /* Number of cursors for child frame */
  15298. int nChange; /* Statement changes (Vdbe.nChange) */
  15299. int nDbChange; /* Value of db->nChange */
  15300. };
  15301. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  15302. /*
  15303. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  15304. */
  15305. #define CACHE_STALE 0
  15306. /*
  15307. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  15308. ** structures. Each Mem struct may cache multiple representations (string,
  15309. ** integer etc.) of the same value.
  15310. */
  15311. struct Mem {
  15312. union MemValue {
  15313. double r; /* Real value used when MEM_Real is set in flags */
  15314. i64 i; /* Integer value used when MEM_Int is set in flags */
  15315. int nZero; /* Used when bit MEM_Zero is set in flags */
  15316. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  15317. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  15318. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  15319. } u;
  15320. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  15321. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  15322. u8 eSubtype; /* Subtype for this value */
  15323. int n; /* Number of characters in string value, excluding '\0' */
  15324. char *z; /* String or BLOB value */
  15325. /* ShallowCopy only needs to copy the information above */
  15326. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  15327. int szMalloc; /* Size of the zMalloc allocation */
  15328. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  15329. sqlite3 *db; /* The associated database connection */
  15330. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  15331. #ifdef SQLITE_DEBUG
  15332. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  15333. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  15334. #endif
  15335. };
  15336. /*
  15337. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  15338. ** follows.
  15339. */
  15340. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  15341. /* One or more of the following flags are set to indicate the validOK
  15342. ** representations of the value stored in the Mem struct.
  15343. **
  15344. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  15345. ** No other flags may be set in this case.
  15346. **
  15347. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  15348. ** Usually this is encoded in the same unicode encoding as the main
  15349. ** database (see below for exceptions). If the MEM_Term flag is also
  15350. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  15351. ** flags may coexist with the MEM_Str flag.
  15352. */
  15353. #define MEM_Null 0x0001 /* Value is NULL */
  15354. #define MEM_Str 0x0002 /* Value is a string */
  15355. #define MEM_Int 0x0004 /* Value is an integer */
  15356. #define MEM_Real 0x0008 /* Value is a real number */
  15357. #define MEM_Blob 0x0010 /* Value is a BLOB */
  15358. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  15359. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  15360. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  15361. #define MEM_Undefined 0x0080 /* Value is undefined */
  15362. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  15363. #define MEM_TypeMask 0x81ff /* Mask of type bits */
  15364. /* Whenever Mem contains a valid string or blob representation, one of
  15365. ** the following flags must be set to determine the memory management
  15366. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  15367. ** string is \000 or \u0000 terminated
  15368. */
  15369. #define MEM_Term 0x0200 /* String rep is nul terminated */
  15370. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  15371. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  15372. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  15373. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  15374. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  15375. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  15376. #ifdef SQLITE_OMIT_INCRBLOB
  15377. #undef MEM_Zero
  15378. #define MEM_Zero 0x0000
  15379. #endif
  15380. /* Return TRUE if Mem X contains dynamically allocated content - anything
  15381. ** that needs to be deallocated to avoid a leak.
  15382. */
  15383. #define VdbeMemDynamic(X) \
  15384. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  15385. /*
  15386. ** Clear any existing type flags from a Mem and replace them with f
  15387. */
  15388. #define MemSetTypeFlag(p, f) \
  15389. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  15390. /*
  15391. ** Return true if a memory cell is not marked as invalid. This macro
  15392. ** is for use inside assert() statements only.
  15393. */
  15394. #ifdef SQLITE_DEBUG
  15395. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  15396. #endif
  15397. /*
  15398. ** Each auxiliary data pointer stored by a user defined function
  15399. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  15400. ** of this structure. All such structures associated with a single VM
  15401. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  15402. ** when the VM is halted (if not before).
  15403. */
  15404. struct AuxData {
  15405. int iOp; /* Instruction number of OP_Function opcode */
  15406. int iArg; /* Index of function argument. */
  15407. void *pAux; /* Aux data pointer */
  15408. void (*xDelete)(void *); /* Destructor for the aux data */
  15409. AuxData *pNext; /* Next element in list */
  15410. };
  15411. /*
  15412. ** The "context" argument for an installable function. A pointer to an
  15413. ** instance of this structure is the first argument to the routines used
  15414. ** implement the SQL functions.
  15415. **
  15416. ** There is a typedef for this structure in sqlite.h. So all routines,
  15417. ** even the public interface to SQLite, can use a pointer to this structure.
  15418. ** But this file is the only place where the internal details of this
  15419. ** structure are known.
  15420. **
  15421. ** This structure is defined inside of vdbeInt.h because it uses substructures
  15422. ** (Mem) which are only defined there.
  15423. */
  15424. struct sqlite3_context {
  15425. Mem *pOut; /* The return value is stored here */
  15426. FuncDef *pFunc; /* Pointer to function information */
  15427. Mem *pMem; /* Memory cell used to store aggregate context */
  15428. Vdbe *pVdbe; /* The VM that owns this context */
  15429. int iOp; /* Instruction number of OP_Function */
  15430. int isError; /* Error code returned by the function. */
  15431. u8 skipFlag; /* Skip accumulator loading if true */
  15432. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  15433. u8 argc; /* Number of arguments */
  15434. sqlite3_value *argv[1]; /* Argument set */
  15435. };
  15436. /*
  15437. ** An Explain object accumulates indented output which is helpful
  15438. ** in describing recursive data structures.
  15439. */
  15440. struct Explain {
  15441. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  15442. StrAccum str; /* The string being accumulated */
  15443. int nIndent; /* Number of elements in aIndent */
  15444. u16 aIndent[100]; /* Levels of indentation */
  15445. char zBase[100]; /* Initial space */
  15446. };
  15447. /* A bitfield type for use inside of structures. Always follow with :N where
  15448. ** N is the number of bits.
  15449. */
  15450. typedef unsigned bft; /* Bit Field Type */
  15451. typedef struct ScanStatus ScanStatus;
  15452. struct ScanStatus {
  15453. int addrExplain; /* OP_Explain for loop */
  15454. int addrLoop; /* Address of "loops" counter */
  15455. int addrVisit; /* Address of "rows visited" counter */
  15456. int iSelectID; /* The "Select-ID" for this loop */
  15457. LogEst nEst; /* Estimated output rows per loop */
  15458. char *zName; /* Name of table or index */
  15459. };
  15460. /*
  15461. ** An instance of the virtual machine. This structure contains the complete
  15462. ** state of the virtual machine.
  15463. **
  15464. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  15465. ** is really a pointer to an instance of this structure.
  15466. */
  15467. struct Vdbe {
  15468. sqlite3 *db; /* The database connection that owns this statement */
  15469. Op *aOp; /* Space to hold the virtual machine's program */
  15470. Mem *aMem; /* The memory locations */
  15471. Mem **apArg; /* Arguments to currently executing user function */
  15472. Mem *aColName; /* Column names to return */
  15473. Mem *pResultSet; /* Pointer to an array of results */
  15474. Parse *pParse; /* Parsing context used to create this Vdbe */
  15475. int nMem; /* Number of memory locations currently allocated */
  15476. int nOp; /* Number of instructions in the program */
  15477. int nCursor; /* Number of slots in apCsr[] */
  15478. u32 magic; /* Magic number for sanity checking */
  15479. char *zErrMsg; /* Error message written here */
  15480. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  15481. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  15482. Mem *aVar; /* Values for the OP_Variable opcode. */
  15483. char **azVar; /* Name of variables */
  15484. ynVar nVar; /* Number of entries in aVar[] */
  15485. ynVar nzVar; /* Number of entries in azVar[] */
  15486. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  15487. int pc; /* The program counter */
  15488. int rc; /* Value to return */
  15489. #ifdef SQLITE_DEBUG
  15490. int rcApp; /* errcode set by sqlite3_result_error_code() */
  15491. #endif
  15492. u16 nResColumn; /* Number of columns in one row of the result set */
  15493. u8 errorAction; /* Recovery action to do in case of an error */
  15494. bft expired:1; /* True if the VM needs to be recompiled */
  15495. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  15496. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  15497. bft explain:2; /* True if EXPLAIN present on SQL command */
  15498. bft changeCntOn:1; /* True to update the change-counter */
  15499. bft runOnlyOnce:1; /* Automatically expire on reset */
  15500. bft usesStmtJournal:1; /* True if uses a statement journal */
  15501. bft readOnly:1; /* True for statements that do not write */
  15502. bft bIsReader:1; /* True for statements that read */
  15503. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  15504. int nChange; /* Number of db changes made since last reset */
  15505. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  15506. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  15507. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  15508. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  15509. #ifndef SQLITE_OMIT_TRACE
  15510. i64 startTime; /* Time when query started - used for profiling */
  15511. #endif
  15512. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  15513. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  15514. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  15515. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  15516. char *zSql; /* Text of the SQL statement that generated this */
  15517. void *pFree; /* Free this when deleting the vdbe */
  15518. VdbeFrame *pFrame; /* Parent frame */
  15519. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  15520. int nFrame; /* Number of frames in pFrame list */
  15521. u32 expmask; /* Binding to these vars invalidates VM */
  15522. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  15523. int nOnceFlag; /* Size of array aOnceFlag[] */
  15524. u8 *aOnceFlag; /* Flags for OP_Once */
  15525. AuxData *pAuxData; /* Linked list of auxdata allocations */
  15526. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  15527. i64 *anExec; /* Number of times each op has been executed */
  15528. int nScan; /* Entries in aScan[] */
  15529. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  15530. #endif
  15531. };
  15532. /*
  15533. ** The following are allowed values for Vdbe.magic
  15534. */
  15535. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  15536. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  15537. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  15538. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  15539. /*
  15540. ** Function prototypes
  15541. */
  15542. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  15543. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  15544. void sqliteVdbePopStack(Vdbe*,int);
  15545. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  15546. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  15547. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  15548. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  15549. #endif
  15550. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  15551. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  15552. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  15553. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  15554. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  15555. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  15556. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  15557. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  15558. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  15559. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  15560. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  15561. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  15562. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  15563. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  15564. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  15565. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  15566. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  15567. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  15568. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  15569. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  15570. #ifdef SQLITE_OMIT_FLOATING_POINT
  15571. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  15572. #else
  15573. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  15574. #endif
  15575. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  15576. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  15577. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  15578. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  15579. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  15580. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  15581. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  15582. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  15583. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  15584. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  15585. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  15586. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  15587. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  15588. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  15589. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  15590. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  15591. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  15592. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  15593. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  15594. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  15595. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  15596. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  15597. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  15598. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  15599. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  15600. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  15601. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  15602. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  15603. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  15604. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  15605. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  15606. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  15607. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  15608. #else
  15609. # define sqlite3VdbeEnter(X)
  15610. #endif
  15611. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  15612. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  15613. #else
  15614. # define sqlite3VdbeLeave(X)
  15615. #endif
  15616. #ifdef SQLITE_DEBUG
  15617. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  15618. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  15619. #endif
  15620. #ifndef SQLITE_OMIT_FOREIGN_KEY
  15621. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  15622. #else
  15623. # define sqlite3VdbeCheckFk(p,i) 0
  15624. #endif
  15625. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  15626. #ifdef SQLITE_DEBUG
  15627. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  15628. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  15629. #endif
  15630. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  15631. #ifndef SQLITE_OMIT_INCRBLOB
  15632. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  15633. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  15634. #else
  15635. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  15636. #define ExpandBlob(P) SQLITE_OK
  15637. #endif
  15638. #endif /* !defined(_VDBEINT_H_) */
  15639. /************** End of vdbeInt.h *********************************************/
  15640. /************** Continuing where we left off in status.c *********************/
  15641. /*
  15642. ** Variables in which to record status information.
  15643. */
  15644. #if SQLITE_PTRSIZE>4
  15645. typedef sqlite3_int64 sqlite3StatValueType;
  15646. #else
  15647. typedef u32 sqlite3StatValueType;
  15648. #endif
  15649. typedef struct sqlite3StatType sqlite3StatType;
  15650. static SQLITE_WSD struct sqlite3StatType {
  15651. sqlite3StatValueType nowValue[10]; /* Current value */
  15652. sqlite3StatValueType mxValue[10]; /* Maximum value */
  15653. } sqlite3Stat = { {0,}, {0,} };
  15654. /*
  15655. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  15656. ** mutex, or by the pcache1 mutex. The following array determines which.
  15657. */
  15658. static const char statMutex[] = {
  15659. 0, /* SQLITE_STATUS_MEMORY_USED */
  15660. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  15661. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  15662. 0, /* SQLITE_STATUS_SCRATCH_USED */
  15663. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  15664. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  15665. 0, /* SQLITE_STATUS_PARSER_STACK */
  15666. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  15667. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  15668. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  15669. };
  15670. /* The "wsdStat" macro will resolve to the status information
  15671. ** state vector. If writable static data is unsupported on the target,
  15672. ** we have to locate the state vector at run-time. In the more common
  15673. ** case where writable static data is supported, wsdStat can refer directly
  15674. ** to the "sqlite3Stat" state vector declared above.
  15675. */
  15676. #ifdef SQLITE_OMIT_WSD
  15677. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  15678. # define wsdStat x[0]
  15679. #else
  15680. # define wsdStatInit
  15681. # define wsdStat sqlite3Stat
  15682. #endif
  15683. /*
  15684. ** Return the current value of a status parameter. The caller must
  15685. ** be holding the appropriate mutex.
  15686. */
  15687. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  15688. wsdStatInit;
  15689. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15690. assert( op>=0 && op<ArraySize(statMutex) );
  15691. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15692. : sqlite3MallocMutex()) );
  15693. return wsdStat.nowValue[op];
  15694. }
  15695. /*
  15696. ** Add N to the value of a status record. The caller must hold the
  15697. ** appropriate mutex. (Locking is checked by assert()).
  15698. **
  15699. ** The StatusUp() routine can accept positive or negative values for N.
  15700. ** The value of N is added to the current status value and the high-water
  15701. ** mark is adjusted if necessary.
  15702. **
  15703. ** The StatusDown() routine lowers the current value by N. The highwater
  15704. ** mark is unchanged. N must be non-negative for StatusDown().
  15705. */
  15706. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  15707. wsdStatInit;
  15708. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15709. assert( op>=0 && op<ArraySize(statMutex) );
  15710. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15711. : sqlite3MallocMutex()) );
  15712. wsdStat.nowValue[op] += N;
  15713. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  15714. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15715. }
  15716. }
  15717. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  15718. wsdStatInit;
  15719. assert( N>=0 );
  15720. assert( op>=0 && op<ArraySize(statMutex) );
  15721. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15722. : sqlite3MallocMutex()) );
  15723. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15724. wsdStat.nowValue[op] -= N;
  15725. }
  15726. /*
  15727. ** Adjust the highwater mark if necessary.
  15728. ** The caller must hold the appropriate mutex.
  15729. */
  15730. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  15731. sqlite3StatValueType newValue;
  15732. wsdStatInit;
  15733. assert( X>=0 );
  15734. newValue = (sqlite3StatValueType)X;
  15735. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15736. assert( op>=0 && op<ArraySize(statMutex) );
  15737. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15738. : sqlite3MallocMutex()) );
  15739. assert( op==SQLITE_STATUS_MALLOC_SIZE
  15740. || op==SQLITE_STATUS_PAGECACHE_SIZE
  15741. || op==SQLITE_STATUS_SCRATCH_SIZE
  15742. || op==SQLITE_STATUS_PARSER_STACK );
  15743. if( newValue>wsdStat.mxValue[op] ){
  15744. wsdStat.mxValue[op] = newValue;
  15745. }
  15746. }
  15747. /*
  15748. ** Query status information.
  15749. */
  15750. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  15751. int op,
  15752. sqlite3_int64 *pCurrent,
  15753. sqlite3_int64 *pHighwater,
  15754. int resetFlag
  15755. ){
  15756. sqlite3_mutex *pMutex;
  15757. wsdStatInit;
  15758. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  15759. return SQLITE_MISUSE_BKPT;
  15760. }
  15761. #ifdef SQLITE_ENABLE_API_ARMOR
  15762. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  15763. #endif
  15764. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  15765. sqlite3_mutex_enter(pMutex);
  15766. *pCurrent = wsdStat.nowValue[op];
  15767. *pHighwater = wsdStat.mxValue[op];
  15768. if( resetFlag ){
  15769. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15770. }
  15771. sqlite3_mutex_leave(pMutex);
  15772. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  15773. return SQLITE_OK;
  15774. }
  15775. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  15776. sqlite3_int64 iCur, iHwtr;
  15777. int rc;
  15778. #ifdef SQLITE_ENABLE_API_ARMOR
  15779. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  15780. #endif
  15781. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  15782. if( rc==0 ){
  15783. *pCurrent = (int)iCur;
  15784. *pHighwater = (int)iHwtr;
  15785. }
  15786. return rc;
  15787. }
  15788. /*
  15789. ** Query status information for a single database connection
  15790. */
  15791. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
  15792. sqlite3 *db, /* The database connection whose status is desired */
  15793. int op, /* Status verb */
  15794. int *pCurrent, /* Write current value here */
  15795. int *pHighwater, /* Write high-water mark here */
  15796. int resetFlag /* Reset high-water mark if true */
  15797. ){
  15798. int rc = SQLITE_OK; /* Return code */
  15799. #ifdef SQLITE_ENABLE_API_ARMOR
  15800. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  15801. return SQLITE_MISUSE_BKPT;
  15802. }
  15803. #endif
  15804. sqlite3_mutex_enter(db->mutex);
  15805. switch( op ){
  15806. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  15807. *pCurrent = db->lookaside.nOut;
  15808. *pHighwater = db->lookaside.mxOut;
  15809. if( resetFlag ){
  15810. db->lookaside.mxOut = db->lookaside.nOut;
  15811. }
  15812. break;
  15813. }
  15814. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  15815. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  15816. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  15817. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  15818. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  15819. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  15820. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  15821. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  15822. *pCurrent = 0;
  15823. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  15824. if( resetFlag ){
  15825. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  15826. }
  15827. break;
  15828. }
  15829. /*
  15830. ** Return an approximation for the amount of memory currently used
  15831. ** by all pagers associated with the given database connection. The
  15832. ** highwater mark is meaningless and is returned as zero.
  15833. */
  15834. case SQLITE_DBSTATUS_CACHE_USED: {
  15835. int totalUsed = 0;
  15836. int i;
  15837. sqlite3BtreeEnterAll(db);
  15838. for(i=0; i<db->nDb; i++){
  15839. Btree *pBt = db->aDb[i].pBt;
  15840. if( pBt ){
  15841. Pager *pPager = sqlite3BtreePager(pBt);
  15842. totalUsed += sqlite3PagerMemUsed(pPager);
  15843. }
  15844. }
  15845. sqlite3BtreeLeaveAll(db);
  15846. *pCurrent = totalUsed;
  15847. *pHighwater = 0;
  15848. break;
  15849. }
  15850. /*
  15851. ** *pCurrent gets an accurate estimate of the amount of memory used
  15852. ** to store the schema for all databases (main, temp, and any ATTACHed
  15853. ** databases. *pHighwater is set to zero.
  15854. */
  15855. case SQLITE_DBSTATUS_SCHEMA_USED: {
  15856. int i; /* Used to iterate through schemas */
  15857. int nByte = 0; /* Used to accumulate return value */
  15858. sqlite3BtreeEnterAll(db);
  15859. db->pnBytesFreed = &nByte;
  15860. for(i=0; i<db->nDb; i++){
  15861. Schema *pSchema = db->aDb[i].pSchema;
  15862. if( ALWAYS(pSchema!=0) ){
  15863. HashElem *p;
  15864. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  15865. pSchema->tblHash.count
  15866. + pSchema->trigHash.count
  15867. + pSchema->idxHash.count
  15868. + pSchema->fkeyHash.count
  15869. );
  15870. nByte += sqlite3_msize(pSchema->tblHash.ht);
  15871. nByte += sqlite3_msize(pSchema->trigHash.ht);
  15872. nByte += sqlite3_msize(pSchema->idxHash.ht);
  15873. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  15874. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  15875. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  15876. }
  15877. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  15878. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  15879. }
  15880. }
  15881. }
  15882. db->pnBytesFreed = 0;
  15883. sqlite3BtreeLeaveAll(db);
  15884. *pHighwater = 0;
  15885. *pCurrent = nByte;
  15886. break;
  15887. }
  15888. /*
  15889. ** *pCurrent gets an accurate estimate of the amount of memory used
  15890. ** to store all prepared statements.
  15891. ** *pHighwater is set to zero.
  15892. */
  15893. case SQLITE_DBSTATUS_STMT_USED: {
  15894. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  15895. int nByte = 0; /* Used to accumulate return value */
  15896. db->pnBytesFreed = &nByte;
  15897. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  15898. sqlite3VdbeClearObject(db, pVdbe);
  15899. sqlite3DbFree(db, pVdbe);
  15900. }
  15901. db->pnBytesFreed = 0;
  15902. *pHighwater = 0; /* IMP: R-64479-57858 */
  15903. *pCurrent = nByte;
  15904. break;
  15905. }
  15906. /*
  15907. ** Set *pCurrent to the total cache hits or misses encountered by all
  15908. ** pagers the database handle is connected to. *pHighwater is always set
  15909. ** to zero.
  15910. */
  15911. case SQLITE_DBSTATUS_CACHE_HIT:
  15912. case SQLITE_DBSTATUS_CACHE_MISS:
  15913. case SQLITE_DBSTATUS_CACHE_WRITE:{
  15914. int i;
  15915. int nRet = 0;
  15916. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  15917. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  15918. for(i=0; i<db->nDb; i++){
  15919. if( db->aDb[i].pBt ){
  15920. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  15921. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  15922. }
  15923. }
  15924. *pHighwater = 0; /* IMP: R-42420-56072 */
  15925. /* IMP: R-54100-20147 */
  15926. /* IMP: R-29431-39229 */
  15927. *pCurrent = nRet;
  15928. break;
  15929. }
  15930. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  15931. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  15932. ** have been satisfied. The *pHighwater is always set to zero.
  15933. */
  15934. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  15935. *pHighwater = 0; /* IMP: R-11967-56545 */
  15936. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  15937. break;
  15938. }
  15939. default: {
  15940. rc = SQLITE_ERROR;
  15941. }
  15942. }
  15943. sqlite3_mutex_leave(db->mutex);
  15944. return rc;
  15945. }
  15946. /************** End of status.c **********************************************/
  15947. /************** Begin file date.c ********************************************/
  15948. /*
  15949. ** 2003 October 31
  15950. **
  15951. ** The author disclaims copyright to this source code. In place of
  15952. ** a legal notice, here is a blessing:
  15953. **
  15954. ** May you do good and not evil.
  15955. ** May you find forgiveness for yourself and forgive others.
  15956. ** May you share freely, never taking more than you give.
  15957. **
  15958. *************************************************************************
  15959. ** This file contains the C functions that implement date and time
  15960. ** functions for SQLite.
  15961. **
  15962. ** There is only one exported symbol in this file - the function
  15963. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  15964. ** All other code has file scope.
  15965. **
  15966. ** SQLite processes all times and dates as julian day numbers. The
  15967. ** dates and times are stored as the number of days since noon
  15968. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  15969. ** calendar system.
  15970. **
  15971. ** 1970-01-01 00:00:00 is JD 2440587.5
  15972. ** 2000-01-01 00:00:00 is JD 2451544.5
  15973. **
  15974. ** This implementation requires years to be expressed as a 4-digit number
  15975. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  15976. ** be represented, even though julian day numbers allow a much wider
  15977. ** range of dates.
  15978. **
  15979. ** The Gregorian calendar system is used for all dates and times,
  15980. ** even those that predate the Gregorian calendar. Historians usually
  15981. ** use the julian calendar for dates prior to 1582-10-15 and for some
  15982. ** dates afterwards, depending on locale. Beware of this difference.
  15983. **
  15984. ** The conversion algorithms are implemented based on descriptions
  15985. ** in the following text:
  15986. **
  15987. ** Jean Meeus
  15988. ** Astronomical Algorithms, 2nd Edition, 1998
  15989. ** ISBM 0-943396-61-1
  15990. ** Willmann-Bell, Inc
  15991. ** Richmond, Virginia (USA)
  15992. */
  15993. /* #include "sqliteInt.h" */
  15994. /* #include <stdlib.h> */
  15995. /* #include <assert.h> */
  15996. #include <time.h>
  15997. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15998. /*
  15999. ** A structure for holding a single date and time.
  16000. */
  16001. typedef struct DateTime DateTime;
  16002. struct DateTime {
  16003. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  16004. int Y, M, D; /* Year, month, and day */
  16005. int h, m; /* Hour and minutes */
  16006. int tz; /* Timezone offset in minutes */
  16007. double s; /* Seconds */
  16008. char validYMD; /* True (1) if Y,M,D are valid */
  16009. char validHMS; /* True (1) if h,m,s are valid */
  16010. char validJD; /* True (1) if iJD is valid */
  16011. char validTZ; /* True (1) if tz is valid */
  16012. char tzSet; /* Timezone was set explicitly */
  16013. };
  16014. /*
  16015. ** Convert zDate into one or more integers according to the conversion
  16016. ** specifier zFormat.
  16017. **
  16018. ** zFormat[] contains 4 characters for each integer converted, except for
  16019. ** the last integer which is specified by three characters. The meaning
  16020. ** of a four-character format specifiers ABCD is:
  16021. **
  16022. ** A: number of digits to convert. Always "2" or "4".
  16023. ** B: minimum value. Always "0" or "1".
  16024. ** C: maximum value, decoded as:
  16025. ** a: 12
  16026. ** b: 14
  16027. ** c: 24
  16028. ** d: 31
  16029. ** e: 59
  16030. ** f: 9999
  16031. ** D: the separator character, or \000 to indicate this is the
  16032. ** last number to convert.
  16033. **
  16034. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  16035. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  16036. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  16037. ** the 2-digit day which is the last integer in the set.
  16038. **
  16039. ** The function returns the number of successful conversions.
  16040. */
  16041. static int getDigits(const char *zDate, const char *zFormat, ...){
  16042. /* The aMx[] array translates the 3rd character of each format
  16043. ** spec into a max size: a b c d e f */
  16044. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  16045. va_list ap;
  16046. int cnt = 0;
  16047. char nextC;
  16048. va_start(ap, zFormat);
  16049. do{
  16050. char N = zFormat[0] - '0';
  16051. char min = zFormat[1] - '0';
  16052. int val = 0;
  16053. u16 max;
  16054. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  16055. max = aMx[zFormat[2] - 'a'];
  16056. nextC = zFormat[3];
  16057. val = 0;
  16058. while( N-- ){
  16059. if( !sqlite3Isdigit(*zDate) ){
  16060. goto end_getDigits;
  16061. }
  16062. val = val*10 + *zDate - '0';
  16063. zDate++;
  16064. }
  16065. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  16066. goto end_getDigits;
  16067. }
  16068. *va_arg(ap,int*) = val;
  16069. zDate++;
  16070. cnt++;
  16071. zFormat += 4;
  16072. }while( nextC );
  16073. end_getDigits:
  16074. va_end(ap);
  16075. return cnt;
  16076. }
  16077. /*
  16078. ** Parse a timezone extension on the end of a date-time.
  16079. ** The extension is of the form:
  16080. **
  16081. ** (+/-)HH:MM
  16082. **
  16083. ** Or the "zulu" notation:
  16084. **
  16085. ** Z
  16086. **
  16087. ** If the parse is successful, write the number of minutes
  16088. ** of change in p->tz and return 0. If a parser error occurs,
  16089. ** return non-zero.
  16090. **
  16091. ** A missing specifier is not considered an error.
  16092. */
  16093. static int parseTimezone(const char *zDate, DateTime *p){
  16094. int sgn = 0;
  16095. int nHr, nMn;
  16096. int c;
  16097. while( sqlite3Isspace(*zDate) ){ zDate++; }
  16098. p->tz = 0;
  16099. c = *zDate;
  16100. if( c=='-' ){
  16101. sgn = -1;
  16102. }else if( c=='+' ){
  16103. sgn = +1;
  16104. }else if( c=='Z' || c=='z' ){
  16105. zDate++;
  16106. goto zulu_time;
  16107. }else{
  16108. return c!=0;
  16109. }
  16110. zDate++;
  16111. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  16112. return 1;
  16113. }
  16114. zDate += 5;
  16115. p->tz = sgn*(nMn + nHr*60);
  16116. zulu_time:
  16117. while( sqlite3Isspace(*zDate) ){ zDate++; }
  16118. p->tzSet = 1;
  16119. return *zDate!=0;
  16120. }
  16121. /*
  16122. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  16123. ** The HH, MM, and SS must each be exactly 2 digits. The
  16124. ** fractional seconds FFFF can be one or more digits.
  16125. **
  16126. ** Return 1 if there is a parsing error and 0 on success.
  16127. */
  16128. static int parseHhMmSs(const char *zDate, DateTime *p){
  16129. int h, m, s;
  16130. double ms = 0.0;
  16131. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  16132. return 1;
  16133. }
  16134. zDate += 5;
  16135. if( *zDate==':' ){
  16136. zDate++;
  16137. if( getDigits(zDate, "20e", &s)!=1 ){
  16138. return 1;
  16139. }
  16140. zDate += 2;
  16141. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  16142. double rScale = 1.0;
  16143. zDate++;
  16144. while( sqlite3Isdigit(*zDate) ){
  16145. ms = ms*10.0 + *zDate - '0';
  16146. rScale *= 10.0;
  16147. zDate++;
  16148. }
  16149. ms /= rScale;
  16150. }
  16151. }else{
  16152. s = 0;
  16153. }
  16154. p->validJD = 0;
  16155. p->validHMS = 1;
  16156. p->h = h;
  16157. p->m = m;
  16158. p->s = s + ms;
  16159. if( parseTimezone(zDate, p) ) return 1;
  16160. p->validTZ = (p->tz!=0)?1:0;
  16161. return 0;
  16162. }
  16163. /*
  16164. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  16165. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  16166. **
  16167. ** Reference: Meeus page 61
  16168. */
  16169. static void computeJD(DateTime *p){
  16170. int Y, M, D, A, B, X1, X2;
  16171. if( p->validJD ) return;
  16172. if( p->validYMD ){
  16173. Y = p->Y;
  16174. M = p->M;
  16175. D = p->D;
  16176. }else{
  16177. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  16178. M = 1;
  16179. D = 1;
  16180. }
  16181. if( M<=2 ){
  16182. Y--;
  16183. M += 12;
  16184. }
  16185. A = Y/100;
  16186. B = 2 - A + (A/4);
  16187. X1 = 36525*(Y+4716)/100;
  16188. X2 = 306001*(M+1)/10000;
  16189. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  16190. p->validJD = 1;
  16191. if( p->validHMS ){
  16192. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  16193. if( p->validTZ ){
  16194. p->iJD -= p->tz*60000;
  16195. p->validYMD = 0;
  16196. p->validHMS = 0;
  16197. p->validTZ = 0;
  16198. }
  16199. }
  16200. }
  16201. /*
  16202. ** Parse dates of the form
  16203. **
  16204. ** YYYY-MM-DD HH:MM:SS.FFF
  16205. ** YYYY-MM-DD HH:MM:SS
  16206. ** YYYY-MM-DD HH:MM
  16207. ** YYYY-MM-DD
  16208. **
  16209. ** Write the result into the DateTime structure and return 0
  16210. ** on success and 1 if the input string is not a well-formed
  16211. ** date.
  16212. */
  16213. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  16214. int Y, M, D, neg;
  16215. if( zDate[0]=='-' ){
  16216. zDate++;
  16217. neg = 1;
  16218. }else{
  16219. neg = 0;
  16220. }
  16221. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  16222. return 1;
  16223. }
  16224. zDate += 10;
  16225. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  16226. if( parseHhMmSs(zDate, p)==0 ){
  16227. /* We got the time */
  16228. }else if( *zDate==0 ){
  16229. p->validHMS = 0;
  16230. }else{
  16231. return 1;
  16232. }
  16233. p->validJD = 0;
  16234. p->validYMD = 1;
  16235. p->Y = neg ? -Y : Y;
  16236. p->M = M;
  16237. p->D = D;
  16238. if( p->validTZ ){
  16239. computeJD(p);
  16240. }
  16241. return 0;
  16242. }
  16243. /*
  16244. ** Set the time to the current time reported by the VFS.
  16245. **
  16246. ** Return the number of errors.
  16247. */
  16248. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  16249. p->iJD = sqlite3StmtCurrentTime(context);
  16250. if( p->iJD>0 ){
  16251. p->validJD = 1;
  16252. return 0;
  16253. }else{
  16254. return 1;
  16255. }
  16256. }
  16257. /*
  16258. ** Attempt to parse the given string into a julian day number. Return
  16259. ** the number of errors.
  16260. **
  16261. ** The following are acceptable forms for the input string:
  16262. **
  16263. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  16264. ** DDDD.DD
  16265. ** now
  16266. **
  16267. ** In the first form, the +/-HH:MM is always optional. The fractional
  16268. ** seconds extension (the ".FFF") is optional. The seconds portion
  16269. ** (":SS.FFF") is option. The year and date can be omitted as long
  16270. ** as there is a time string. The time string can be omitted as long
  16271. ** as there is a year and date.
  16272. */
  16273. static int parseDateOrTime(
  16274. sqlite3_context *context,
  16275. const char *zDate,
  16276. DateTime *p
  16277. ){
  16278. double r;
  16279. if( parseYyyyMmDd(zDate,p)==0 ){
  16280. return 0;
  16281. }else if( parseHhMmSs(zDate, p)==0 ){
  16282. return 0;
  16283. }else if( sqlite3StrICmp(zDate,"now")==0){
  16284. return setDateTimeToCurrent(context, p);
  16285. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  16286. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  16287. p->validJD = 1;
  16288. return 0;
  16289. }
  16290. return 1;
  16291. }
  16292. /*
  16293. ** Compute the Year, Month, and Day from the julian day number.
  16294. */
  16295. static void computeYMD(DateTime *p){
  16296. int Z, A, B, C, D, E, X1;
  16297. if( p->validYMD ) return;
  16298. if( !p->validJD ){
  16299. p->Y = 2000;
  16300. p->M = 1;
  16301. p->D = 1;
  16302. }else{
  16303. Z = (int)((p->iJD + 43200000)/86400000);
  16304. A = (int)((Z - 1867216.25)/36524.25);
  16305. A = Z + 1 + A - (A/4);
  16306. B = A + 1524;
  16307. C = (int)((B - 122.1)/365.25);
  16308. D = (36525*(C&32767))/100;
  16309. E = (int)((B-D)/30.6001);
  16310. X1 = (int)(30.6001*E);
  16311. p->D = B - D - X1;
  16312. p->M = E<14 ? E-1 : E-13;
  16313. p->Y = p->M>2 ? C - 4716 : C - 4715;
  16314. }
  16315. p->validYMD = 1;
  16316. }
  16317. /*
  16318. ** Compute the Hour, Minute, and Seconds from the julian day number.
  16319. */
  16320. static void computeHMS(DateTime *p){
  16321. int s;
  16322. if( p->validHMS ) return;
  16323. computeJD(p);
  16324. s = (int)((p->iJD + 43200000) % 86400000);
  16325. p->s = s/1000.0;
  16326. s = (int)p->s;
  16327. p->s -= s;
  16328. p->h = s/3600;
  16329. s -= p->h*3600;
  16330. p->m = s/60;
  16331. p->s += s - p->m*60;
  16332. p->validHMS = 1;
  16333. }
  16334. /*
  16335. ** Compute both YMD and HMS
  16336. */
  16337. static void computeYMD_HMS(DateTime *p){
  16338. computeYMD(p);
  16339. computeHMS(p);
  16340. }
  16341. /*
  16342. ** Clear the YMD and HMS and the TZ
  16343. */
  16344. static void clearYMD_HMS_TZ(DateTime *p){
  16345. p->validYMD = 0;
  16346. p->validHMS = 0;
  16347. p->validTZ = 0;
  16348. }
  16349. /*
  16350. ** On recent Windows platforms, the localtime_s() function is available
  16351. ** as part of the "Secure CRT". It is essentially equivalent to
  16352. ** localtime_r() available under most POSIX platforms, except that the
  16353. ** order of the parameters is reversed.
  16354. **
  16355. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  16356. **
  16357. ** If the user has not indicated to use localtime_r() or localtime_s()
  16358. ** already, check for an MSVC build environment that provides
  16359. ** localtime_s().
  16360. */
  16361. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  16362. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  16363. #undef HAVE_LOCALTIME_S
  16364. #define HAVE_LOCALTIME_S 1
  16365. #endif
  16366. #ifndef SQLITE_OMIT_LOCALTIME
  16367. /*
  16368. ** The following routine implements the rough equivalent of localtime_r()
  16369. ** using whatever operating-system specific localtime facility that
  16370. ** is available. This routine returns 0 on success and
  16371. ** non-zero on any kind of error.
  16372. **
  16373. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  16374. ** routine will always fail.
  16375. **
  16376. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  16377. ** library function localtime_r() is used to assist in the calculation of
  16378. ** local time.
  16379. */
  16380. static int osLocaltime(time_t *t, struct tm *pTm){
  16381. int rc;
  16382. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  16383. struct tm *pX;
  16384. #if SQLITE_THREADSAFE>0
  16385. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16386. #endif
  16387. sqlite3_mutex_enter(mutex);
  16388. pX = localtime(t);
  16389. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16390. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  16391. #endif
  16392. if( pX ) *pTm = *pX;
  16393. sqlite3_mutex_leave(mutex);
  16394. rc = pX==0;
  16395. #else
  16396. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16397. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  16398. #endif
  16399. #if HAVE_LOCALTIME_R
  16400. rc = localtime_r(t, pTm)==0;
  16401. #else
  16402. rc = localtime_s(pTm, t);
  16403. #endif /* HAVE_LOCALTIME_R */
  16404. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  16405. return rc;
  16406. }
  16407. #endif /* SQLITE_OMIT_LOCALTIME */
  16408. #ifndef SQLITE_OMIT_LOCALTIME
  16409. /*
  16410. ** Compute the difference (in milliseconds) between localtime and UTC
  16411. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  16412. ** return this value and set *pRc to SQLITE_OK.
  16413. **
  16414. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  16415. ** is undefined in this case.
  16416. */
  16417. static sqlite3_int64 localtimeOffset(
  16418. DateTime *p, /* Date at which to calculate offset */
  16419. sqlite3_context *pCtx, /* Write error here if one occurs */
  16420. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  16421. ){
  16422. DateTime x, y;
  16423. time_t t;
  16424. struct tm sLocal;
  16425. /* Initialize the contents of sLocal to avoid a compiler warning. */
  16426. memset(&sLocal, 0, sizeof(sLocal));
  16427. x = *p;
  16428. computeYMD_HMS(&x);
  16429. if( x.Y<1971 || x.Y>=2038 ){
  16430. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  16431. ** works for years between 1970 and 2037. For dates outside this range,
  16432. ** SQLite attempts to map the year into an equivalent year within this
  16433. ** range, do the calculation, then map the year back.
  16434. */
  16435. x.Y = 2000;
  16436. x.M = 1;
  16437. x.D = 1;
  16438. x.h = 0;
  16439. x.m = 0;
  16440. x.s = 0.0;
  16441. } else {
  16442. int s = (int)(x.s + 0.5);
  16443. x.s = s;
  16444. }
  16445. x.tz = 0;
  16446. x.validJD = 0;
  16447. computeJD(&x);
  16448. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  16449. if( osLocaltime(&t, &sLocal) ){
  16450. sqlite3_result_error(pCtx, "local time unavailable", -1);
  16451. *pRc = SQLITE_ERROR;
  16452. return 0;
  16453. }
  16454. y.Y = sLocal.tm_year + 1900;
  16455. y.M = sLocal.tm_mon + 1;
  16456. y.D = sLocal.tm_mday;
  16457. y.h = sLocal.tm_hour;
  16458. y.m = sLocal.tm_min;
  16459. y.s = sLocal.tm_sec;
  16460. y.validYMD = 1;
  16461. y.validHMS = 1;
  16462. y.validJD = 0;
  16463. y.validTZ = 0;
  16464. computeJD(&y);
  16465. *pRc = SQLITE_OK;
  16466. return y.iJD - x.iJD;
  16467. }
  16468. #endif /* SQLITE_OMIT_LOCALTIME */
  16469. /*
  16470. ** Process a modifier to a date-time stamp. The modifiers are
  16471. ** as follows:
  16472. **
  16473. ** NNN days
  16474. ** NNN hours
  16475. ** NNN minutes
  16476. ** NNN.NNNN seconds
  16477. ** NNN months
  16478. ** NNN years
  16479. ** start of month
  16480. ** start of year
  16481. ** start of week
  16482. ** start of day
  16483. ** weekday N
  16484. ** unixepoch
  16485. ** localtime
  16486. ** utc
  16487. **
  16488. ** Return 0 on success and 1 if there is any kind of error. If the error
  16489. ** is in a system call (i.e. localtime()), then an error message is written
  16490. ** to context pCtx. If the error is an unrecognized modifier, no error is
  16491. ** written to pCtx.
  16492. */
  16493. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  16494. int rc = 1;
  16495. int n;
  16496. double r;
  16497. char *z, zBuf[30];
  16498. z = zBuf;
  16499. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  16500. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  16501. }
  16502. z[n] = 0;
  16503. switch( z[0] ){
  16504. #ifndef SQLITE_OMIT_LOCALTIME
  16505. case 'l': {
  16506. /* localtime
  16507. **
  16508. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  16509. ** show local time.
  16510. */
  16511. if( strcmp(z, "localtime")==0 ){
  16512. computeJD(p);
  16513. p->iJD += localtimeOffset(p, pCtx, &rc);
  16514. clearYMD_HMS_TZ(p);
  16515. }
  16516. break;
  16517. }
  16518. #endif
  16519. case 'u': {
  16520. /*
  16521. ** unixepoch
  16522. **
  16523. ** Treat the current value of p->iJD as the number of
  16524. ** seconds since 1970. Convert to a real julian day number.
  16525. */
  16526. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  16527. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  16528. clearYMD_HMS_TZ(p);
  16529. rc = 0;
  16530. }
  16531. #ifndef SQLITE_OMIT_LOCALTIME
  16532. else if( strcmp(z, "utc")==0 ){
  16533. if( p->tzSet==0 ){
  16534. sqlite3_int64 c1;
  16535. computeJD(p);
  16536. c1 = localtimeOffset(p, pCtx, &rc);
  16537. if( rc==SQLITE_OK ){
  16538. p->iJD -= c1;
  16539. clearYMD_HMS_TZ(p);
  16540. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  16541. }
  16542. p->tzSet = 1;
  16543. }else{
  16544. rc = SQLITE_OK;
  16545. }
  16546. }
  16547. #endif
  16548. break;
  16549. }
  16550. case 'w': {
  16551. /*
  16552. ** weekday N
  16553. **
  16554. ** Move the date to the same time on the next occurrence of
  16555. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  16556. ** date is already on the appropriate weekday, this is a no-op.
  16557. */
  16558. if( strncmp(z, "weekday ", 8)==0
  16559. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  16560. && (n=(int)r)==r && n>=0 && r<7 ){
  16561. sqlite3_int64 Z;
  16562. computeYMD_HMS(p);
  16563. p->validTZ = 0;
  16564. p->validJD = 0;
  16565. computeJD(p);
  16566. Z = ((p->iJD + 129600000)/86400000) % 7;
  16567. if( Z>n ) Z -= 7;
  16568. p->iJD += (n - Z)*86400000;
  16569. clearYMD_HMS_TZ(p);
  16570. rc = 0;
  16571. }
  16572. break;
  16573. }
  16574. case 's': {
  16575. /*
  16576. ** start of TTTTT
  16577. **
  16578. ** Move the date backwards to the beginning of the current day,
  16579. ** or month or year.
  16580. */
  16581. if( strncmp(z, "start of ", 9)!=0 ) break;
  16582. z += 9;
  16583. computeYMD(p);
  16584. p->validHMS = 1;
  16585. p->h = p->m = 0;
  16586. p->s = 0.0;
  16587. p->validTZ = 0;
  16588. p->validJD = 0;
  16589. if( strcmp(z,"month")==0 ){
  16590. p->D = 1;
  16591. rc = 0;
  16592. }else if( strcmp(z,"year")==0 ){
  16593. computeYMD(p);
  16594. p->M = 1;
  16595. p->D = 1;
  16596. rc = 0;
  16597. }else if( strcmp(z,"day")==0 ){
  16598. rc = 0;
  16599. }
  16600. break;
  16601. }
  16602. case '+':
  16603. case '-':
  16604. case '0':
  16605. case '1':
  16606. case '2':
  16607. case '3':
  16608. case '4':
  16609. case '5':
  16610. case '6':
  16611. case '7':
  16612. case '8':
  16613. case '9': {
  16614. double rRounder;
  16615. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  16616. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  16617. rc = 1;
  16618. break;
  16619. }
  16620. if( z[n]==':' ){
  16621. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  16622. ** specified number of hours, minutes, seconds, and fractional seconds
  16623. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  16624. ** omitted.
  16625. */
  16626. const char *z2 = z;
  16627. DateTime tx;
  16628. sqlite3_int64 day;
  16629. if( !sqlite3Isdigit(*z2) ) z2++;
  16630. memset(&tx, 0, sizeof(tx));
  16631. if( parseHhMmSs(z2, &tx) ) break;
  16632. computeJD(&tx);
  16633. tx.iJD -= 43200000;
  16634. day = tx.iJD/86400000;
  16635. tx.iJD -= day*86400000;
  16636. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  16637. computeJD(p);
  16638. clearYMD_HMS_TZ(p);
  16639. p->iJD += tx.iJD;
  16640. rc = 0;
  16641. break;
  16642. }
  16643. z += n;
  16644. while( sqlite3Isspace(*z) ) z++;
  16645. n = sqlite3Strlen30(z);
  16646. if( n>10 || n<3 ) break;
  16647. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  16648. computeJD(p);
  16649. rc = 0;
  16650. rRounder = r<0 ? -0.5 : +0.5;
  16651. if( n==3 && strcmp(z,"day")==0 ){
  16652. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  16653. }else if( n==4 && strcmp(z,"hour")==0 ){
  16654. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  16655. }else if( n==6 && strcmp(z,"minute")==0 ){
  16656. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  16657. }else if( n==6 && strcmp(z,"second")==0 ){
  16658. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  16659. }else if( n==5 && strcmp(z,"month")==0 ){
  16660. int x, y;
  16661. computeYMD_HMS(p);
  16662. p->M += (int)r;
  16663. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  16664. p->Y += x;
  16665. p->M -= x*12;
  16666. p->validJD = 0;
  16667. computeJD(p);
  16668. y = (int)r;
  16669. if( y!=r ){
  16670. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  16671. }
  16672. }else if( n==4 && strcmp(z,"year")==0 ){
  16673. int y = (int)r;
  16674. computeYMD_HMS(p);
  16675. p->Y += y;
  16676. p->validJD = 0;
  16677. computeJD(p);
  16678. if( y!=r ){
  16679. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  16680. }
  16681. }else{
  16682. rc = 1;
  16683. }
  16684. clearYMD_HMS_TZ(p);
  16685. break;
  16686. }
  16687. default: {
  16688. break;
  16689. }
  16690. }
  16691. return rc;
  16692. }
  16693. /*
  16694. ** Process time function arguments. argv[0] is a date-time stamp.
  16695. ** argv[1] and following are modifiers. Parse them all and write
  16696. ** the resulting time into the DateTime structure p. Return 0
  16697. ** on success and 1 if there are any errors.
  16698. **
  16699. ** If there are zero parameters (if even argv[0] is undefined)
  16700. ** then assume a default value of "now" for argv[0].
  16701. */
  16702. static int isDate(
  16703. sqlite3_context *context,
  16704. int argc,
  16705. sqlite3_value **argv,
  16706. DateTime *p
  16707. ){
  16708. int i;
  16709. const unsigned char *z;
  16710. int eType;
  16711. memset(p, 0, sizeof(*p));
  16712. if( argc==0 ){
  16713. return setDateTimeToCurrent(context, p);
  16714. }
  16715. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  16716. || eType==SQLITE_INTEGER ){
  16717. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  16718. p->validJD = 1;
  16719. }else{
  16720. z = sqlite3_value_text(argv[0]);
  16721. if( !z || parseDateOrTime(context, (char*)z, p) ){
  16722. return 1;
  16723. }
  16724. }
  16725. for(i=1; i<argc; i++){
  16726. z = sqlite3_value_text(argv[i]);
  16727. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  16728. }
  16729. return 0;
  16730. }
  16731. /*
  16732. ** The following routines implement the various date and time functions
  16733. ** of SQLite.
  16734. */
  16735. /*
  16736. ** julianday( TIMESTRING, MOD, MOD, ...)
  16737. **
  16738. ** Return the julian day number of the date specified in the arguments
  16739. */
  16740. static void juliandayFunc(
  16741. sqlite3_context *context,
  16742. int argc,
  16743. sqlite3_value **argv
  16744. ){
  16745. DateTime x;
  16746. if( isDate(context, argc, argv, &x)==0 ){
  16747. computeJD(&x);
  16748. sqlite3_result_double(context, x.iJD/86400000.0);
  16749. }
  16750. }
  16751. /*
  16752. ** datetime( TIMESTRING, MOD, MOD, ...)
  16753. **
  16754. ** Return YYYY-MM-DD HH:MM:SS
  16755. */
  16756. static void datetimeFunc(
  16757. sqlite3_context *context,
  16758. int argc,
  16759. sqlite3_value **argv
  16760. ){
  16761. DateTime x;
  16762. if( isDate(context, argc, argv, &x)==0 ){
  16763. char zBuf[100];
  16764. computeYMD_HMS(&x);
  16765. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  16766. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  16767. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16768. }
  16769. }
  16770. /*
  16771. ** time( TIMESTRING, MOD, MOD, ...)
  16772. **
  16773. ** Return HH:MM:SS
  16774. */
  16775. static void timeFunc(
  16776. sqlite3_context *context,
  16777. int argc,
  16778. sqlite3_value **argv
  16779. ){
  16780. DateTime x;
  16781. if( isDate(context, argc, argv, &x)==0 ){
  16782. char zBuf[100];
  16783. computeHMS(&x);
  16784. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  16785. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16786. }
  16787. }
  16788. /*
  16789. ** date( TIMESTRING, MOD, MOD, ...)
  16790. **
  16791. ** Return YYYY-MM-DD
  16792. */
  16793. static void dateFunc(
  16794. sqlite3_context *context,
  16795. int argc,
  16796. sqlite3_value **argv
  16797. ){
  16798. DateTime x;
  16799. if( isDate(context, argc, argv, &x)==0 ){
  16800. char zBuf[100];
  16801. computeYMD(&x);
  16802. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  16803. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16804. }
  16805. }
  16806. /*
  16807. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  16808. **
  16809. ** Return a string described by FORMAT. Conversions as follows:
  16810. **
  16811. ** %d day of month
  16812. ** %f ** fractional seconds SS.SSS
  16813. ** %H hour 00-24
  16814. ** %j day of year 000-366
  16815. ** %J ** julian day number
  16816. ** %m month 01-12
  16817. ** %M minute 00-59
  16818. ** %s seconds since 1970-01-01
  16819. ** %S seconds 00-59
  16820. ** %w day of week 0-6 sunday==0
  16821. ** %W week of year 00-53
  16822. ** %Y year 0000-9999
  16823. ** %% %
  16824. */
  16825. static void strftimeFunc(
  16826. sqlite3_context *context,
  16827. int argc,
  16828. sqlite3_value **argv
  16829. ){
  16830. DateTime x;
  16831. u64 n;
  16832. size_t i,j;
  16833. char *z;
  16834. sqlite3 *db;
  16835. const char *zFmt;
  16836. char zBuf[100];
  16837. if( argc==0 ) return;
  16838. zFmt = (const char*)sqlite3_value_text(argv[0]);
  16839. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  16840. db = sqlite3_context_db_handle(context);
  16841. for(i=0, n=1; zFmt[i]; i++, n++){
  16842. if( zFmt[i]=='%' ){
  16843. switch( zFmt[i+1] ){
  16844. case 'd':
  16845. case 'H':
  16846. case 'm':
  16847. case 'M':
  16848. case 'S':
  16849. case 'W':
  16850. n++;
  16851. /* fall thru */
  16852. case 'w':
  16853. case '%':
  16854. break;
  16855. case 'f':
  16856. n += 8;
  16857. break;
  16858. case 'j':
  16859. n += 3;
  16860. break;
  16861. case 'Y':
  16862. n += 8;
  16863. break;
  16864. case 's':
  16865. case 'J':
  16866. n += 50;
  16867. break;
  16868. default:
  16869. return; /* ERROR. return a NULL */
  16870. }
  16871. i++;
  16872. }
  16873. }
  16874. testcase( n==sizeof(zBuf)-1 );
  16875. testcase( n==sizeof(zBuf) );
  16876. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  16877. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  16878. if( n<sizeof(zBuf) ){
  16879. z = zBuf;
  16880. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  16881. sqlite3_result_error_toobig(context);
  16882. return;
  16883. }else{
  16884. z = sqlite3DbMallocRawNN(db, (int)n);
  16885. if( z==0 ){
  16886. sqlite3_result_error_nomem(context);
  16887. return;
  16888. }
  16889. }
  16890. computeJD(&x);
  16891. computeYMD_HMS(&x);
  16892. for(i=j=0; zFmt[i]; i++){
  16893. if( zFmt[i]!='%' ){
  16894. z[j++] = zFmt[i];
  16895. }else{
  16896. i++;
  16897. switch( zFmt[i] ){
  16898. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  16899. case 'f': {
  16900. double s = x.s;
  16901. if( s>59.999 ) s = 59.999;
  16902. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  16903. j += sqlite3Strlen30(&z[j]);
  16904. break;
  16905. }
  16906. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  16907. case 'W': /* Fall thru */
  16908. case 'j': {
  16909. int nDay; /* Number of days since 1st day of year */
  16910. DateTime y = x;
  16911. y.validJD = 0;
  16912. y.M = 1;
  16913. y.D = 1;
  16914. computeJD(&y);
  16915. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  16916. if( zFmt[i]=='W' ){
  16917. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  16918. wd = (int)(((x.iJD+43200000)/86400000)%7);
  16919. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  16920. j += 2;
  16921. }else{
  16922. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  16923. j += 3;
  16924. }
  16925. break;
  16926. }
  16927. case 'J': {
  16928. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  16929. j+=sqlite3Strlen30(&z[j]);
  16930. break;
  16931. }
  16932. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  16933. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  16934. case 's': {
  16935. sqlite3_snprintf(30,&z[j],"%lld",
  16936. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  16937. j += sqlite3Strlen30(&z[j]);
  16938. break;
  16939. }
  16940. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  16941. case 'w': {
  16942. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  16943. break;
  16944. }
  16945. case 'Y': {
  16946. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  16947. break;
  16948. }
  16949. default: z[j++] = '%'; break;
  16950. }
  16951. }
  16952. }
  16953. z[j] = 0;
  16954. sqlite3_result_text(context, z, -1,
  16955. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  16956. }
  16957. /*
  16958. ** current_time()
  16959. **
  16960. ** This function returns the same value as time('now').
  16961. */
  16962. static void ctimeFunc(
  16963. sqlite3_context *context,
  16964. int NotUsed,
  16965. sqlite3_value **NotUsed2
  16966. ){
  16967. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16968. timeFunc(context, 0, 0);
  16969. }
  16970. /*
  16971. ** current_date()
  16972. **
  16973. ** This function returns the same value as date('now').
  16974. */
  16975. static void cdateFunc(
  16976. sqlite3_context *context,
  16977. int NotUsed,
  16978. sqlite3_value **NotUsed2
  16979. ){
  16980. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16981. dateFunc(context, 0, 0);
  16982. }
  16983. /*
  16984. ** current_timestamp()
  16985. **
  16986. ** This function returns the same value as datetime('now').
  16987. */
  16988. static void ctimestampFunc(
  16989. sqlite3_context *context,
  16990. int NotUsed,
  16991. sqlite3_value **NotUsed2
  16992. ){
  16993. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16994. datetimeFunc(context, 0, 0);
  16995. }
  16996. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  16997. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  16998. /*
  16999. ** If the library is compiled to omit the full-scale date and time
  17000. ** handling (to get a smaller binary), the following minimal version
  17001. ** of the functions current_time(), current_date() and current_timestamp()
  17002. ** are included instead. This is to support column declarations that
  17003. ** include "DEFAULT CURRENT_TIME" etc.
  17004. **
  17005. ** This function uses the C-library functions time(), gmtime()
  17006. ** and strftime(). The format string to pass to strftime() is supplied
  17007. ** as the user-data for the function.
  17008. */
  17009. static void currentTimeFunc(
  17010. sqlite3_context *context,
  17011. int argc,
  17012. sqlite3_value **argv
  17013. ){
  17014. time_t t;
  17015. char *zFormat = (char *)sqlite3_user_data(context);
  17016. sqlite3 *db;
  17017. sqlite3_int64 iT;
  17018. struct tm *pTm;
  17019. struct tm sNow;
  17020. char zBuf[20];
  17021. UNUSED_PARAMETER(argc);
  17022. UNUSED_PARAMETER(argv);
  17023. iT = sqlite3StmtCurrentTime(context);
  17024. if( iT<=0 ) return;
  17025. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  17026. #if HAVE_GMTIME_R
  17027. pTm = gmtime_r(&t, &sNow);
  17028. #else
  17029. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  17030. pTm = gmtime(&t);
  17031. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  17032. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  17033. #endif
  17034. if( pTm ){
  17035. strftime(zBuf, 20, zFormat, &sNow);
  17036. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  17037. }
  17038. }
  17039. #endif
  17040. /*
  17041. ** This function registered all of the above C functions as SQL
  17042. ** functions. This should be the only routine in this file with
  17043. ** external linkage.
  17044. */
  17045. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  17046. static FuncDef aDateTimeFuncs[] = {
  17047. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  17048. DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  17049. DFUNCTION(date, -1, 0, 0, dateFunc ),
  17050. DFUNCTION(time, -1, 0, 0, timeFunc ),
  17051. DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  17052. DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  17053. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  17054. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  17055. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  17056. #else
  17057. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  17058. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  17059. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  17060. #endif
  17061. };
  17062. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  17063. }
  17064. /************** End of date.c ************************************************/
  17065. /************** Begin file os.c **********************************************/
  17066. /*
  17067. ** 2005 November 29
  17068. **
  17069. ** The author disclaims copyright to this source code. In place of
  17070. ** a legal notice, here is a blessing:
  17071. **
  17072. ** May you do good and not evil.
  17073. ** May you find forgiveness for yourself and forgive others.
  17074. ** May you share freely, never taking more than you give.
  17075. **
  17076. ******************************************************************************
  17077. **
  17078. ** This file contains OS interface code that is common to all
  17079. ** architectures.
  17080. */
  17081. #define _SQLITE_OS_C_ 1
  17082. /* #include "sqliteInt.h" */
  17083. #undef _SQLITE_OS_C_
  17084. /*
  17085. ** If we compile with the SQLITE_TEST macro set, then the following block
  17086. ** of code will give us the ability to simulate a disk I/O error. This
  17087. ** is used for testing the I/O recovery logic.
  17088. */
  17089. #if defined(SQLITE_TEST)
  17090. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  17091. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  17092. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  17093. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  17094. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  17095. SQLITE_API int sqlite3_diskfull_pending = 0;
  17096. SQLITE_API int sqlite3_diskfull = 0;
  17097. #endif /* defined(SQLITE_TEST) */
  17098. /*
  17099. ** When testing, also keep a count of the number of open files.
  17100. */
  17101. #if defined(SQLITE_TEST)
  17102. SQLITE_API int sqlite3_open_file_count = 0;
  17103. #endif /* defined(SQLITE_TEST) */
  17104. /*
  17105. ** The default SQLite sqlite3_vfs implementations do not allocate
  17106. ** memory (actually, os_unix.c allocates a small amount of memory
  17107. ** from within OsOpen()), but some third-party implementations may.
  17108. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  17109. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  17110. **
  17111. ** The following functions are instrumented for malloc() failure
  17112. ** testing:
  17113. **
  17114. ** sqlite3OsRead()
  17115. ** sqlite3OsWrite()
  17116. ** sqlite3OsSync()
  17117. ** sqlite3OsFileSize()
  17118. ** sqlite3OsLock()
  17119. ** sqlite3OsCheckReservedLock()
  17120. ** sqlite3OsFileControl()
  17121. ** sqlite3OsShmMap()
  17122. ** sqlite3OsOpen()
  17123. ** sqlite3OsDelete()
  17124. ** sqlite3OsAccess()
  17125. ** sqlite3OsFullPathname()
  17126. **
  17127. */
  17128. #if defined(SQLITE_TEST)
  17129. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  17130. #define DO_OS_MALLOC_TEST(x) \
  17131. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  17132. void *pTstAlloc = sqlite3Malloc(10); \
  17133. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  17134. sqlite3_free(pTstAlloc); \
  17135. }
  17136. #else
  17137. #define DO_OS_MALLOC_TEST(x)
  17138. #endif
  17139. /*
  17140. ** The following routines are convenience wrappers around methods
  17141. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  17142. ** of this would be completely automatic if SQLite were coded using
  17143. ** C++ instead of plain old C.
  17144. */
  17145. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  17146. int rc = SQLITE_OK;
  17147. if( pId->pMethods ){
  17148. rc = pId->pMethods->xClose(pId);
  17149. pId->pMethods = 0;
  17150. }
  17151. return rc;
  17152. }
  17153. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  17154. DO_OS_MALLOC_TEST(id);
  17155. return id->pMethods->xRead(id, pBuf, amt, offset);
  17156. }
  17157. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  17158. DO_OS_MALLOC_TEST(id);
  17159. return id->pMethods->xWrite(id, pBuf, amt, offset);
  17160. }
  17161. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  17162. return id->pMethods->xTruncate(id, size);
  17163. }
  17164. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  17165. DO_OS_MALLOC_TEST(id);
  17166. return id->pMethods->xSync(id, flags);
  17167. }
  17168. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  17169. DO_OS_MALLOC_TEST(id);
  17170. return id->pMethods->xFileSize(id, pSize);
  17171. }
  17172. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  17173. DO_OS_MALLOC_TEST(id);
  17174. return id->pMethods->xLock(id, lockType);
  17175. }
  17176. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  17177. return id->pMethods->xUnlock(id, lockType);
  17178. }
  17179. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  17180. DO_OS_MALLOC_TEST(id);
  17181. return id->pMethods->xCheckReservedLock(id, pResOut);
  17182. }
  17183. /*
  17184. ** Use sqlite3OsFileControl() when we are doing something that might fail
  17185. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  17186. ** when simply tossing information over the wall to the VFS and we do not
  17187. ** really care if the VFS receives and understands the information since it
  17188. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  17189. ** routine has no return value since the return value would be meaningless.
  17190. */
  17191. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  17192. #ifdef SQLITE_TEST
  17193. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  17194. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  17195. ** is using a regular VFS, it is called after the corresponding
  17196. ** transaction has been committed. Injecting a fault at this point
  17197. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  17198. ** but the transaction is committed anyway.
  17199. **
  17200. ** The core must call OsFileControl() though, not OsFileControlHint(),
  17201. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  17202. ** means the commit really has failed and an error should be returned
  17203. ** to the user. */
  17204. DO_OS_MALLOC_TEST(id);
  17205. }
  17206. #endif
  17207. return id->pMethods->xFileControl(id, op, pArg);
  17208. }
  17209. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  17210. (void)id->pMethods->xFileControl(id, op, pArg);
  17211. }
  17212. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  17213. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  17214. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  17215. }
  17216. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  17217. return id->pMethods->xDeviceCharacteristics(id);
  17218. }
  17219. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  17220. return id->pMethods->xShmLock(id, offset, n, flags);
  17221. }
  17222. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  17223. id->pMethods->xShmBarrier(id);
  17224. }
  17225. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  17226. return id->pMethods->xShmUnmap(id, deleteFlag);
  17227. }
  17228. SQLITE_PRIVATE int sqlite3OsShmMap(
  17229. sqlite3_file *id, /* Database file handle */
  17230. int iPage,
  17231. int pgsz,
  17232. int bExtend, /* True to extend file if necessary */
  17233. void volatile **pp /* OUT: Pointer to mapping */
  17234. ){
  17235. DO_OS_MALLOC_TEST(id);
  17236. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  17237. }
  17238. #if SQLITE_MAX_MMAP_SIZE>0
  17239. /* The real implementation of xFetch and xUnfetch */
  17240. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  17241. DO_OS_MALLOC_TEST(id);
  17242. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  17243. }
  17244. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  17245. return id->pMethods->xUnfetch(id, iOff, p);
  17246. }
  17247. #else
  17248. /* No-op stubs to use when memory-mapped I/O is disabled */
  17249. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  17250. *pp = 0;
  17251. return SQLITE_OK;
  17252. }
  17253. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  17254. return SQLITE_OK;
  17255. }
  17256. #endif
  17257. /*
  17258. ** The next group of routines are convenience wrappers around the
  17259. ** VFS methods.
  17260. */
  17261. SQLITE_PRIVATE int sqlite3OsOpen(
  17262. sqlite3_vfs *pVfs,
  17263. const char *zPath,
  17264. sqlite3_file *pFile,
  17265. int flags,
  17266. int *pFlagsOut
  17267. ){
  17268. int rc;
  17269. DO_OS_MALLOC_TEST(0);
  17270. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  17271. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  17272. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  17273. ** reaching the VFS. */
  17274. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  17275. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  17276. return rc;
  17277. }
  17278. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  17279. DO_OS_MALLOC_TEST(0);
  17280. assert( dirSync==0 || dirSync==1 );
  17281. return pVfs->xDelete(pVfs, zPath, dirSync);
  17282. }
  17283. SQLITE_PRIVATE int sqlite3OsAccess(
  17284. sqlite3_vfs *pVfs,
  17285. const char *zPath,
  17286. int flags,
  17287. int *pResOut
  17288. ){
  17289. DO_OS_MALLOC_TEST(0);
  17290. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  17291. }
  17292. SQLITE_PRIVATE int sqlite3OsFullPathname(
  17293. sqlite3_vfs *pVfs,
  17294. const char *zPath,
  17295. int nPathOut,
  17296. char *zPathOut
  17297. ){
  17298. DO_OS_MALLOC_TEST(0);
  17299. zPathOut[0] = 0;
  17300. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  17301. }
  17302. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  17303. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  17304. return pVfs->xDlOpen(pVfs, zPath);
  17305. }
  17306. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  17307. pVfs->xDlError(pVfs, nByte, zBufOut);
  17308. }
  17309. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  17310. return pVfs->xDlSym(pVfs, pHdle, zSym);
  17311. }
  17312. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  17313. pVfs->xDlClose(pVfs, pHandle);
  17314. }
  17315. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  17316. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  17317. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  17318. }
  17319. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  17320. return pVfs->xSleep(pVfs, nMicro);
  17321. }
  17322. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  17323. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  17324. }
  17325. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  17326. int rc;
  17327. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  17328. ** method to get the current date and time if that method is available
  17329. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  17330. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  17331. ** unavailable.
  17332. */
  17333. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  17334. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  17335. }else{
  17336. double r;
  17337. rc = pVfs->xCurrentTime(pVfs, &r);
  17338. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  17339. }
  17340. return rc;
  17341. }
  17342. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  17343. sqlite3_vfs *pVfs,
  17344. const char *zFile,
  17345. sqlite3_file **ppFile,
  17346. int flags,
  17347. int *pOutFlags
  17348. ){
  17349. int rc;
  17350. sqlite3_file *pFile;
  17351. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  17352. if( pFile ){
  17353. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  17354. if( rc!=SQLITE_OK ){
  17355. sqlite3_free(pFile);
  17356. }else{
  17357. *ppFile = pFile;
  17358. }
  17359. }else{
  17360. rc = SQLITE_NOMEM_BKPT;
  17361. }
  17362. return rc;
  17363. }
  17364. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  17365. int rc = SQLITE_OK;
  17366. assert( pFile );
  17367. rc = sqlite3OsClose(pFile);
  17368. sqlite3_free(pFile);
  17369. return rc;
  17370. }
  17371. /*
  17372. ** This function is a wrapper around the OS specific implementation of
  17373. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  17374. ** ability to simulate a malloc failure, so that the handling of an
  17375. ** error in sqlite3_os_init() by the upper layers can be tested.
  17376. */
  17377. SQLITE_PRIVATE int sqlite3OsInit(void){
  17378. void *p = sqlite3_malloc(10);
  17379. if( p==0 ) return SQLITE_NOMEM_BKPT;
  17380. sqlite3_free(p);
  17381. return sqlite3_os_init();
  17382. }
  17383. /*
  17384. ** The list of all registered VFS implementations.
  17385. */
  17386. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  17387. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  17388. /*
  17389. ** Locate a VFS by name. If no name is given, simply return the
  17390. ** first VFS on the list.
  17391. */
  17392. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
  17393. sqlite3_vfs *pVfs = 0;
  17394. #if SQLITE_THREADSAFE
  17395. sqlite3_mutex *mutex;
  17396. #endif
  17397. #ifndef SQLITE_OMIT_AUTOINIT
  17398. int rc = sqlite3_initialize();
  17399. if( rc ) return 0;
  17400. #endif
  17401. #if SQLITE_THREADSAFE
  17402. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  17403. #endif
  17404. sqlite3_mutex_enter(mutex);
  17405. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  17406. if( zVfs==0 ) break;
  17407. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  17408. }
  17409. sqlite3_mutex_leave(mutex);
  17410. return pVfs;
  17411. }
  17412. /*
  17413. ** Unlink a VFS from the linked list
  17414. */
  17415. static void vfsUnlink(sqlite3_vfs *pVfs){
  17416. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  17417. if( pVfs==0 ){
  17418. /* No-op */
  17419. }else if( vfsList==pVfs ){
  17420. vfsList = pVfs->pNext;
  17421. }else if( vfsList ){
  17422. sqlite3_vfs *p = vfsList;
  17423. while( p->pNext && p->pNext!=pVfs ){
  17424. p = p->pNext;
  17425. }
  17426. if( p->pNext==pVfs ){
  17427. p->pNext = pVfs->pNext;
  17428. }
  17429. }
  17430. }
  17431. /*
  17432. ** Register a VFS with the system. It is harmless to register the same
  17433. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  17434. ** true.
  17435. */
  17436. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  17437. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  17438. #ifndef SQLITE_OMIT_AUTOINIT
  17439. int rc = sqlite3_initialize();
  17440. if( rc ) return rc;
  17441. #endif
  17442. #ifdef SQLITE_ENABLE_API_ARMOR
  17443. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  17444. #endif
  17445. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  17446. sqlite3_mutex_enter(mutex);
  17447. vfsUnlink(pVfs);
  17448. if( makeDflt || vfsList==0 ){
  17449. pVfs->pNext = vfsList;
  17450. vfsList = pVfs;
  17451. }else{
  17452. pVfs->pNext = vfsList->pNext;
  17453. vfsList->pNext = pVfs;
  17454. }
  17455. assert(vfsList);
  17456. sqlite3_mutex_leave(mutex);
  17457. return SQLITE_OK;
  17458. }
  17459. /*
  17460. ** Unregister a VFS so that it is no longer accessible.
  17461. */
  17462. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  17463. #if SQLITE_THREADSAFE
  17464. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  17465. #endif
  17466. sqlite3_mutex_enter(mutex);
  17467. vfsUnlink(pVfs);
  17468. sqlite3_mutex_leave(mutex);
  17469. return SQLITE_OK;
  17470. }
  17471. /************** End of os.c **************************************************/
  17472. /************** Begin file fault.c *******************************************/
  17473. /*
  17474. ** 2008 Jan 22
  17475. **
  17476. ** The author disclaims copyright to this source code. In place of
  17477. ** a legal notice, here is a blessing:
  17478. **
  17479. ** May you do good and not evil.
  17480. ** May you find forgiveness for yourself and forgive others.
  17481. ** May you share freely, never taking more than you give.
  17482. **
  17483. *************************************************************************
  17484. **
  17485. ** This file contains code to support the concept of "benign"
  17486. ** malloc failures (when the xMalloc() or xRealloc() method of the
  17487. ** sqlite3_mem_methods structure fails to allocate a block of memory
  17488. ** and returns 0).
  17489. **
  17490. ** Most malloc failures are non-benign. After they occur, SQLite
  17491. ** abandons the current operation and returns an error code (usually
  17492. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  17493. ** fatal. For example, if a malloc fails while resizing a hash table, this
  17494. ** is completely recoverable simply by not carrying out the resize. The
  17495. ** hash table will continue to function normally. So a malloc failure
  17496. ** during a hash table resize is a benign fault.
  17497. */
  17498. /* #include "sqliteInt.h" */
  17499. #ifndef SQLITE_OMIT_BUILTIN_TEST
  17500. /*
  17501. ** Global variables.
  17502. */
  17503. typedef struct BenignMallocHooks BenignMallocHooks;
  17504. static SQLITE_WSD struct BenignMallocHooks {
  17505. void (*xBenignBegin)(void);
  17506. void (*xBenignEnd)(void);
  17507. } sqlite3Hooks = { 0, 0 };
  17508. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  17509. ** structure. If writable static data is unsupported on the target,
  17510. ** we have to locate the state vector at run-time. In the more common
  17511. ** case where writable static data is supported, wsdHooks can refer directly
  17512. ** to the "sqlite3Hooks" state vector declared above.
  17513. */
  17514. #ifdef SQLITE_OMIT_WSD
  17515. # define wsdHooksInit \
  17516. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  17517. # define wsdHooks x[0]
  17518. #else
  17519. # define wsdHooksInit
  17520. # define wsdHooks sqlite3Hooks
  17521. #endif
  17522. /*
  17523. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  17524. ** sqlite3EndBenignMalloc() are called, respectively.
  17525. */
  17526. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  17527. void (*xBenignBegin)(void),
  17528. void (*xBenignEnd)(void)
  17529. ){
  17530. wsdHooksInit;
  17531. wsdHooks.xBenignBegin = xBenignBegin;
  17532. wsdHooks.xBenignEnd = xBenignEnd;
  17533. }
  17534. /*
  17535. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  17536. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  17537. ** indicates that subsequent malloc failures are non-benign.
  17538. */
  17539. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  17540. wsdHooksInit;
  17541. if( wsdHooks.xBenignBegin ){
  17542. wsdHooks.xBenignBegin();
  17543. }
  17544. }
  17545. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  17546. wsdHooksInit;
  17547. if( wsdHooks.xBenignEnd ){
  17548. wsdHooks.xBenignEnd();
  17549. }
  17550. }
  17551. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  17552. /************** End of fault.c ***********************************************/
  17553. /************** Begin file mem0.c ********************************************/
  17554. /*
  17555. ** 2008 October 28
  17556. **
  17557. ** The author disclaims copyright to this source code. In place of
  17558. ** a legal notice, here is a blessing:
  17559. **
  17560. ** May you do good and not evil.
  17561. ** May you find forgiveness for yourself and forgive others.
  17562. ** May you share freely, never taking more than you give.
  17563. **
  17564. *************************************************************************
  17565. **
  17566. ** This file contains a no-op memory allocation drivers for use when
  17567. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  17568. ** here always fail. SQLite will not operate with these drivers. These
  17569. ** are merely placeholders. Real drivers must be substituted using
  17570. ** sqlite3_config() before SQLite will operate.
  17571. */
  17572. /* #include "sqliteInt.h" */
  17573. /*
  17574. ** This version of the memory allocator is the default. It is
  17575. ** used when no other memory allocator is specified using compile-time
  17576. ** macros.
  17577. */
  17578. #ifdef SQLITE_ZERO_MALLOC
  17579. /*
  17580. ** No-op versions of all memory allocation routines
  17581. */
  17582. static void *sqlite3MemMalloc(int nByte){ return 0; }
  17583. static void sqlite3MemFree(void *pPrior){ return; }
  17584. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  17585. static int sqlite3MemSize(void *pPrior){ return 0; }
  17586. static int sqlite3MemRoundup(int n){ return n; }
  17587. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  17588. static void sqlite3MemShutdown(void *NotUsed){ return; }
  17589. /*
  17590. ** This routine is the only routine in this file with external linkage.
  17591. **
  17592. ** Populate the low-level memory allocation function pointers in
  17593. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17594. */
  17595. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17596. static const sqlite3_mem_methods defaultMethods = {
  17597. sqlite3MemMalloc,
  17598. sqlite3MemFree,
  17599. sqlite3MemRealloc,
  17600. sqlite3MemSize,
  17601. sqlite3MemRoundup,
  17602. sqlite3MemInit,
  17603. sqlite3MemShutdown,
  17604. 0
  17605. };
  17606. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17607. }
  17608. #endif /* SQLITE_ZERO_MALLOC */
  17609. /************** End of mem0.c ************************************************/
  17610. /************** Begin file mem1.c ********************************************/
  17611. /*
  17612. ** 2007 August 14
  17613. **
  17614. ** The author disclaims copyright to this source code. In place of
  17615. ** a legal notice, here is a blessing:
  17616. **
  17617. ** May you do good and not evil.
  17618. ** May you find forgiveness for yourself and forgive others.
  17619. ** May you share freely, never taking more than you give.
  17620. **
  17621. *************************************************************************
  17622. **
  17623. ** This file contains low-level memory allocation drivers for when
  17624. ** SQLite will use the standard C-library malloc/realloc/free interface
  17625. ** to obtain the memory it needs.
  17626. **
  17627. ** This file contains implementations of the low-level memory allocation
  17628. ** routines specified in the sqlite3_mem_methods object. The content of
  17629. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  17630. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  17631. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  17632. ** default configuration is to use memory allocation routines in this
  17633. ** file.
  17634. **
  17635. ** C-preprocessor macro summary:
  17636. **
  17637. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  17638. ** the malloc_usable_size() interface exists
  17639. ** on the target platform. Or, this symbol
  17640. ** can be set manually, if desired.
  17641. ** If an equivalent interface exists by
  17642. ** a different name, using a separate -D
  17643. ** option to rename it.
  17644. **
  17645. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  17646. ** memory allocator. Set this symbol to enable
  17647. ** building on older macs.
  17648. **
  17649. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  17650. ** _msize() on windows systems. This might
  17651. ** be necessary when compiling for Delphi,
  17652. ** for example.
  17653. */
  17654. /* #include "sqliteInt.h" */
  17655. /*
  17656. ** This version of the memory allocator is the default. It is
  17657. ** used when no other memory allocator is specified using compile-time
  17658. ** macros.
  17659. */
  17660. #ifdef SQLITE_SYSTEM_MALLOC
  17661. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  17662. /*
  17663. ** Use the zone allocator available on apple products unless the
  17664. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  17665. */
  17666. #include <sys/sysctl.h>
  17667. #include <malloc/malloc.h>
  17668. #include <libkern/OSAtomic.h>
  17669. static malloc_zone_t* _sqliteZone_;
  17670. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  17671. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  17672. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  17673. #define SQLITE_MALLOCSIZE(x) \
  17674. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  17675. #else /* if not __APPLE__ */
  17676. /*
  17677. ** Use standard C library malloc and free on non-Apple systems.
  17678. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  17679. */
  17680. #define SQLITE_MALLOC(x) malloc(x)
  17681. #define SQLITE_FREE(x) free(x)
  17682. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  17683. /*
  17684. ** The malloc.h header file is needed for malloc_usable_size() function
  17685. ** on some systems (e.g. Linux).
  17686. */
  17687. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  17688. # define SQLITE_USE_MALLOC_H 1
  17689. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  17690. /*
  17691. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  17692. ** use of _msize() is automatic, but can be disabled by compiling with
  17693. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  17694. ** the malloc.h header file.
  17695. */
  17696. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  17697. # define SQLITE_USE_MALLOC_H
  17698. # define SQLITE_USE_MSIZE
  17699. #endif
  17700. /*
  17701. ** Include the malloc.h header file, if necessary. Also set define macro
  17702. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  17703. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  17704. ** The memory size function can always be overridden manually by defining
  17705. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  17706. */
  17707. #if defined(SQLITE_USE_MALLOC_H)
  17708. # include <malloc.h>
  17709. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  17710. # if !defined(SQLITE_MALLOCSIZE)
  17711. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  17712. # endif
  17713. # elif defined(SQLITE_USE_MSIZE)
  17714. # if !defined(SQLITE_MALLOCSIZE)
  17715. # define SQLITE_MALLOCSIZE _msize
  17716. # endif
  17717. # endif
  17718. #endif /* defined(SQLITE_USE_MALLOC_H) */
  17719. #endif /* __APPLE__ or not __APPLE__ */
  17720. /*
  17721. ** Like malloc(), but remember the size of the allocation
  17722. ** so that we can find it later using sqlite3MemSize().
  17723. **
  17724. ** For this low-level routine, we are guaranteed that nByte>0 because
  17725. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  17726. ** routines.
  17727. */
  17728. static void *sqlite3MemMalloc(int nByte){
  17729. #ifdef SQLITE_MALLOCSIZE
  17730. void *p = SQLITE_MALLOC( nByte );
  17731. if( p==0 ){
  17732. testcase( sqlite3GlobalConfig.xLog!=0 );
  17733. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  17734. }
  17735. return p;
  17736. #else
  17737. sqlite3_int64 *p;
  17738. assert( nByte>0 );
  17739. nByte = ROUND8(nByte);
  17740. p = SQLITE_MALLOC( nByte+8 );
  17741. if( p ){
  17742. p[0] = nByte;
  17743. p++;
  17744. }else{
  17745. testcase( sqlite3GlobalConfig.xLog!=0 );
  17746. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  17747. }
  17748. return (void *)p;
  17749. #endif
  17750. }
  17751. /*
  17752. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  17753. ** or sqlite3MemRealloc().
  17754. **
  17755. ** For this low-level routine, we already know that pPrior!=0 since
  17756. ** cases where pPrior==0 will have been intecepted and dealt with
  17757. ** by higher-level routines.
  17758. */
  17759. static void sqlite3MemFree(void *pPrior){
  17760. #ifdef SQLITE_MALLOCSIZE
  17761. SQLITE_FREE(pPrior);
  17762. #else
  17763. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  17764. assert( pPrior!=0 );
  17765. p--;
  17766. SQLITE_FREE(p);
  17767. #endif
  17768. }
  17769. /*
  17770. ** Report the allocated size of a prior return from xMalloc()
  17771. ** or xRealloc().
  17772. */
  17773. static int sqlite3MemSize(void *pPrior){
  17774. #ifdef SQLITE_MALLOCSIZE
  17775. assert( pPrior!=0 );
  17776. return (int)SQLITE_MALLOCSIZE(pPrior);
  17777. #else
  17778. sqlite3_int64 *p;
  17779. assert( pPrior!=0 );
  17780. p = (sqlite3_int64*)pPrior;
  17781. p--;
  17782. return (int)p[0];
  17783. #endif
  17784. }
  17785. /*
  17786. ** Like realloc(). Resize an allocation previously obtained from
  17787. ** sqlite3MemMalloc().
  17788. **
  17789. ** For this low-level interface, we know that pPrior!=0. Cases where
  17790. ** pPrior==0 while have been intercepted by higher-level routine and
  17791. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  17792. ** cases where nByte<=0 will have been intercepted by higher-level
  17793. ** routines and redirected to xFree.
  17794. */
  17795. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  17796. #ifdef SQLITE_MALLOCSIZE
  17797. void *p = SQLITE_REALLOC(pPrior, nByte);
  17798. if( p==0 ){
  17799. testcase( sqlite3GlobalConfig.xLog!=0 );
  17800. sqlite3_log(SQLITE_NOMEM,
  17801. "failed memory resize %u to %u bytes",
  17802. SQLITE_MALLOCSIZE(pPrior), nByte);
  17803. }
  17804. return p;
  17805. #else
  17806. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  17807. assert( pPrior!=0 && nByte>0 );
  17808. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  17809. p--;
  17810. p = SQLITE_REALLOC(p, nByte+8 );
  17811. if( p ){
  17812. p[0] = nByte;
  17813. p++;
  17814. }else{
  17815. testcase( sqlite3GlobalConfig.xLog!=0 );
  17816. sqlite3_log(SQLITE_NOMEM,
  17817. "failed memory resize %u to %u bytes",
  17818. sqlite3MemSize(pPrior), nByte);
  17819. }
  17820. return (void*)p;
  17821. #endif
  17822. }
  17823. /*
  17824. ** Round up a request size to the next valid allocation size.
  17825. */
  17826. static int sqlite3MemRoundup(int n){
  17827. return ROUND8(n);
  17828. }
  17829. /*
  17830. ** Initialize this module.
  17831. */
  17832. static int sqlite3MemInit(void *NotUsed){
  17833. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  17834. int cpuCount;
  17835. size_t len;
  17836. if( _sqliteZone_ ){
  17837. return SQLITE_OK;
  17838. }
  17839. len = sizeof(cpuCount);
  17840. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  17841. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  17842. if( cpuCount>1 ){
  17843. /* defer MT decisions to system malloc */
  17844. _sqliteZone_ = malloc_default_zone();
  17845. }else{
  17846. /* only 1 core, use our own zone to contention over global locks,
  17847. ** e.g. we have our own dedicated locks */
  17848. bool success;
  17849. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  17850. malloc_set_zone_name(newzone, "Sqlite_Heap");
  17851. do{
  17852. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  17853. (void * volatile *)&_sqliteZone_);
  17854. }while(!_sqliteZone_);
  17855. if( !success ){
  17856. /* somebody registered a zone first */
  17857. malloc_destroy_zone(newzone);
  17858. }
  17859. }
  17860. #endif
  17861. UNUSED_PARAMETER(NotUsed);
  17862. return SQLITE_OK;
  17863. }
  17864. /*
  17865. ** Deinitialize this module.
  17866. */
  17867. static void sqlite3MemShutdown(void *NotUsed){
  17868. UNUSED_PARAMETER(NotUsed);
  17869. return;
  17870. }
  17871. /*
  17872. ** This routine is the only routine in this file with external linkage.
  17873. **
  17874. ** Populate the low-level memory allocation function pointers in
  17875. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17876. */
  17877. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17878. static const sqlite3_mem_methods defaultMethods = {
  17879. sqlite3MemMalloc,
  17880. sqlite3MemFree,
  17881. sqlite3MemRealloc,
  17882. sqlite3MemSize,
  17883. sqlite3MemRoundup,
  17884. sqlite3MemInit,
  17885. sqlite3MemShutdown,
  17886. 0
  17887. };
  17888. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17889. }
  17890. #endif /* SQLITE_SYSTEM_MALLOC */
  17891. /************** End of mem1.c ************************************************/
  17892. /************** Begin file mem2.c ********************************************/
  17893. /*
  17894. ** 2007 August 15
  17895. **
  17896. ** The author disclaims copyright to this source code. In place of
  17897. ** a legal notice, here is a blessing:
  17898. **
  17899. ** May you do good and not evil.
  17900. ** May you find forgiveness for yourself and forgive others.
  17901. ** May you share freely, never taking more than you give.
  17902. **
  17903. *************************************************************************
  17904. **
  17905. ** This file contains low-level memory allocation drivers for when
  17906. ** SQLite will use the standard C-library malloc/realloc/free interface
  17907. ** to obtain the memory it needs while adding lots of additional debugging
  17908. ** information to each allocation in order to help detect and fix memory
  17909. ** leaks and memory usage errors.
  17910. **
  17911. ** This file contains implementations of the low-level memory allocation
  17912. ** routines specified in the sqlite3_mem_methods object.
  17913. */
  17914. /* #include "sqliteInt.h" */
  17915. /*
  17916. ** This version of the memory allocator is used only if the
  17917. ** SQLITE_MEMDEBUG macro is defined
  17918. */
  17919. #ifdef SQLITE_MEMDEBUG
  17920. /*
  17921. ** The backtrace functionality is only available with GLIBC
  17922. */
  17923. #ifdef __GLIBC__
  17924. extern int backtrace(void**,int);
  17925. extern void backtrace_symbols_fd(void*const*,int,int);
  17926. #else
  17927. # define backtrace(A,B) 1
  17928. # define backtrace_symbols_fd(A,B,C)
  17929. #endif
  17930. /* #include <stdio.h> */
  17931. /*
  17932. ** Each memory allocation looks like this:
  17933. **
  17934. ** ------------------------------------------------------------------------
  17935. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  17936. ** ------------------------------------------------------------------------
  17937. **
  17938. ** The application code sees only a pointer to the allocation. We have
  17939. ** to back up from the allocation pointer to find the MemBlockHdr. The
  17940. ** MemBlockHdr tells us the size of the allocation and the number of
  17941. ** backtrace pointers. There is also a guard word at the end of the
  17942. ** MemBlockHdr.
  17943. */
  17944. struct MemBlockHdr {
  17945. i64 iSize; /* Size of this allocation */
  17946. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  17947. char nBacktrace; /* Number of backtraces on this alloc */
  17948. char nBacktraceSlots; /* Available backtrace slots */
  17949. u8 nTitle; /* Bytes of title; includes '\0' */
  17950. u8 eType; /* Allocation type code */
  17951. int iForeGuard; /* Guard word for sanity */
  17952. };
  17953. /*
  17954. ** Guard words
  17955. */
  17956. #define FOREGUARD 0x80F5E153
  17957. #define REARGUARD 0xE4676B53
  17958. /*
  17959. ** Number of malloc size increments to track.
  17960. */
  17961. #define NCSIZE 1000
  17962. /*
  17963. ** All of the static variables used by this module are collected
  17964. ** into a single structure named "mem". This is to keep the
  17965. ** static variables organized and to reduce namespace pollution
  17966. ** when this module is combined with other in the amalgamation.
  17967. */
  17968. static struct {
  17969. /*
  17970. ** Mutex to control access to the memory allocation subsystem.
  17971. */
  17972. sqlite3_mutex *mutex;
  17973. /*
  17974. ** Head and tail of a linked list of all outstanding allocations
  17975. */
  17976. struct MemBlockHdr *pFirst;
  17977. struct MemBlockHdr *pLast;
  17978. /*
  17979. ** The number of levels of backtrace to save in new allocations.
  17980. */
  17981. int nBacktrace;
  17982. void (*xBacktrace)(int, int, void **);
  17983. /*
  17984. ** Title text to insert in front of each block
  17985. */
  17986. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  17987. char zTitle[100]; /* The title text */
  17988. /*
  17989. ** sqlite3MallocDisallow() increments the following counter.
  17990. ** sqlite3MallocAllow() decrements it.
  17991. */
  17992. int disallow; /* Do not allow memory allocation */
  17993. /*
  17994. ** Gather statistics on the sizes of memory allocations.
  17995. ** nAlloc[i] is the number of allocation attempts of i*8
  17996. ** bytes. i==NCSIZE is the number of allocation attempts for
  17997. ** sizes more than NCSIZE*8 bytes.
  17998. */
  17999. int nAlloc[NCSIZE]; /* Total number of allocations */
  18000. int nCurrent[NCSIZE]; /* Current number of allocations */
  18001. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  18002. } mem;
  18003. /*
  18004. ** Adjust memory usage statistics
  18005. */
  18006. static void adjustStats(int iSize, int increment){
  18007. int i = ROUND8(iSize)/8;
  18008. if( i>NCSIZE-1 ){
  18009. i = NCSIZE - 1;
  18010. }
  18011. if( increment>0 ){
  18012. mem.nAlloc[i]++;
  18013. mem.nCurrent[i]++;
  18014. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  18015. mem.mxCurrent[i] = mem.nCurrent[i];
  18016. }
  18017. }else{
  18018. mem.nCurrent[i]--;
  18019. assert( mem.nCurrent[i]>=0 );
  18020. }
  18021. }
  18022. /*
  18023. ** Given an allocation, find the MemBlockHdr for that allocation.
  18024. **
  18025. ** This routine checks the guards at either end of the allocation and
  18026. ** if they are incorrect it asserts.
  18027. */
  18028. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  18029. struct MemBlockHdr *p;
  18030. int *pInt;
  18031. u8 *pU8;
  18032. int nReserve;
  18033. p = (struct MemBlockHdr*)pAllocation;
  18034. p--;
  18035. assert( p->iForeGuard==(int)FOREGUARD );
  18036. nReserve = ROUND8(p->iSize);
  18037. pInt = (int*)pAllocation;
  18038. pU8 = (u8*)pAllocation;
  18039. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  18040. /* This checks any of the "extra" bytes allocated due
  18041. ** to rounding up to an 8 byte boundary to ensure
  18042. ** they haven't been overwritten.
  18043. */
  18044. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  18045. return p;
  18046. }
  18047. /*
  18048. ** Return the number of bytes currently allocated at address p.
  18049. */
  18050. static int sqlite3MemSize(void *p){
  18051. struct MemBlockHdr *pHdr;
  18052. if( !p ){
  18053. return 0;
  18054. }
  18055. pHdr = sqlite3MemsysGetHeader(p);
  18056. return (int)pHdr->iSize;
  18057. }
  18058. /*
  18059. ** Initialize the memory allocation subsystem.
  18060. */
  18061. static int sqlite3MemInit(void *NotUsed){
  18062. UNUSED_PARAMETER(NotUsed);
  18063. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  18064. if( !sqlite3GlobalConfig.bMemstat ){
  18065. /* If memory status is enabled, then the malloc.c wrapper will already
  18066. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  18067. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18068. }
  18069. return SQLITE_OK;
  18070. }
  18071. /*
  18072. ** Deinitialize the memory allocation subsystem.
  18073. */
  18074. static void sqlite3MemShutdown(void *NotUsed){
  18075. UNUSED_PARAMETER(NotUsed);
  18076. mem.mutex = 0;
  18077. }
  18078. /*
  18079. ** Round up a request size to the next valid allocation size.
  18080. */
  18081. static int sqlite3MemRoundup(int n){
  18082. return ROUND8(n);
  18083. }
  18084. /*
  18085. ** Fill a buffer with pseudo-random bytes. This is used to preset
  18086. ** the content of a new memory allocation to unpredictable values and
  18087. ** to clear the content of a freed allocation to unpredictable values.
  18088. */
  18089. static void randomFill(char *pBuf, int nByte){
  18090. unsigned int x, y, r;
  18091. x = SQLITE_PTR_TO_INT(pBuf);
  18092. y = nByte | 1;
  18093. while( nByte >= 4 ){
  18094. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  18095. y = y*1103515245 + 12345;
  18096. r = x ^ y;
  18097. *(int*)pBuf = r;
  18098. pBuf += 4;
  18099. nByte -= 4;
  18100. }
  18101. while( nByte-- > 0 ){
  18102. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  18103. y = y*1103515245 + 12345;
  18104. r = x ^ y;
  18105. *(pBuf++) = r & 0xff;
  18106. }
  18107. }
  18108. /*
  18109. ** Allocate nByte bytes of memory.
  18110. */
  18111. static void *sqlite3MemMalloc(int nByte){
  18112. struct MemBlockHdr *pHdr;
  18113. void **pBt;
  18114. char *z;
  18115. int *pInt;
  18116. void *p = 0;
  18117. int totalSize;
  18118. int nReserve;
  18119. sqlite3_mutex_enter(mem.mutex);
  18120. assert( mem.disallow==0 );
  18121. nReserve = ROUND8(nByte);
  18122. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  18123. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  18124. p = malloc(totalSize);
  18125. if( p ){
  18126. z = p;
  18127. pBt = (void**)&z[mem.nTitle];
  18128. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  18129. pHdr->pNext = 0;
  18130. pHdr->pPrev = mem.pLast;
  18131. if( mem.pLast ){
  18132. mem.pLast->pNext = pHdr;
  18133. }else{
  18134. mem.pFirst = pHdr;
  18135. }
  18136. mem.pLast = pHdr;
  18137. pHdr->iForeGuard = FOREGUARD;
  18138. pHdr->eType = MEMTYPE_HEAP;
  18139. pHdr->nBacktraceSlots = mem.nBacktrace;
  18140. pHdr->nTitle = mem.nTitle;
  18141. if( mem.nBacktrace ){
  18142. void *aAddr[40];
  18143. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  18144. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  18145. assert(pBt[0]);
  18146. if( mem.xBacktrace ){
  18147. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  18148. }
  18149. }else{
  18150. pHdr->nBacktrace = 0;
  18151. }
  18152. if( mem.nTitle ){
  18153. memcpy(z, mem.zTitle, mem.nTitle);
  18154. }
  18155. pHdr->iSize = nByte;
  18156. adjustStats(nByte, +1);
  18157. pInt = (int*)&pHdr[1];
  18158. pInt[nReserve/sizeof(int)] = REARGUARD;
  18159. randomFill((char*)pInt, nByte);
  18160. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  18161. p = (void*)pInt;
  18162. }
  18163. sqlite3_mutex_leave(mem.mutex);
  18164. return p;
  18165. }
  18166. /*
  18167. ** Free memory.
  18168. */
  18169. static void sqlite3MemFree(void *pPrior){
  18170. struct MemBlockHdr *pHdr;
  18171. void **pBt;
  18172. char *z;
  18173. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  18174. || mem.mutex!=0 );
  18175. pHdr = sqlite3MemsysGetHeader(pPrior);
  18176. pBt = (void**)pHdr;
  18177. pBt -= pHdr->nBacktraceSlots;
  18178. sqlite3_mutex_enter(mem.mutex);
  18179. if( pHdr->pPrev ){
  18180. assert( pHdr->pPrev->pNext==pHdr );
  18181. pHdr->pPrev->pNext = pHdr->pNext;
  18182. }else{
  18183. assert( mem.pFirst==pHdr );
  18184. mem.pFirst = pHdr->pNext;
  18185. }
  18186. if( pHdr->pNext ){
  18187. assert( pHdr->pNext->pPrev==pHdr );
  18188. pHdr->pNext->pPrev = pHdr->pPrev;
  18189. }else{
  18190. assert( mem.pLast==pHdr );
  18191. mem.pLast = pHdr->pPrev;
  18192. }
  18193. z = (char*)pBt;
  18194. z -= pHdr->nTitle;
  18195. adjustStats((int)pHdr->iSize, -1);
  18196. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  18197. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  18198. free(z);
  18199. sqlite3_mutex_leave(mem.mutex);
  18200. }
  18201. /*
  18202. ** Change the size of an existing memory allocation.
  18203. **
  18204. ** For this debugging implementation, we *always* make a copy of the
  18205. ** allocation into a new place in memory. In this way, if the
  18206. ** higher level code is using pointer to the old allocation, it is
  18207. ** much more likely to break and we are much more liking to find
  18208. ** the error.
  18209. */
  18210. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  18211. struct MemBlockHdr *pOldHdr;
  18212. void *pNew;
  18213. assert( mem.disallow==0 );
  18214. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  18215. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  18216. pNew = sqlite3MemMalloc(nByte);
  18217. if( pNew ){
  18218. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  18219. if( nByte>pOldHdr->iSize ){
  18220. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  18221. }
  18222. sqlite3MemFree(pPrior);
  18223. }
  18224. return pNew;
  18225. }
  18226. /*
  18227. ** Populate the low-level memory allocation function pointers in
  18228. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  18229. */
  18230. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  18231. static const sqlite3_mem_methods defaultMethods = {
  18232. sqlite3MemMalloc,
  18233. sqlite3MemFree,
  18234. sqlite3MemRealloc,
  18235. sqlite3MemSize,
  18236. sqlite3MemRoundup,
  18237. sqlite3MemInit,
  18238. sqlite3MemShutdown,
  18239. 0
  18240. };
  18241. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  18242. }
  18243. /*
  18244. ** Set the "type" of an allocation.
  18245. */
  18246. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  18247. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  18248. struct MemBlockHdr *pHdr;
  18249. pHdr = sqlite3MemsysGetHeader(p);
  18250. assert( pHdr->iForeGuard==FOREGUARD );
  18251. pHdr->eType = eType;
  18252. }
  18253. }
  18254. /*
  18255. ** Return TRUE if the mask of type in eType matches the type of the
  18256. ** allocation p. Also return true if p==NULL.
  18257. **
  18258. ** This routine is designed for use within an assert() statement, to
  18259. ** verify the type of an allocation. For example:
  18260. **
  18261. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18262. */
  18263. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  18264. int rc = 1;
  18265. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  18266. struct MemBlockHdr *pHdr;
  18267. pHdr = sqlite3MemsysGetHeader(p);
  18268. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  18269. if( (pHdr->eType&eType)==0 ){
  18270. rc = 0;
  18271. }
  18272. }
  18273. return rc;
  18274. }
  18275. /*
  18276. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  18277. ** allocation p. Also return true if p==NULL.
  18278. **
  18279. ** This routine is designed for use within an assert() statement, to
  18280. ** verify the type of an allocation. For example:
  18281. **
  18282. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18283. */
  18284. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  18285. int rc = 1;
  18286. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  18287. struct MemBlockHdr *pHdr;
  18288. pHdr = sqlite3MemsysGetHeader(p);
  18289. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  18290. if( (pHdr->eType&eType)!=0 ){
  18291. rc = 0;
  18292. }
  18293. }
  18294. return rc;
  18295. }
  18296. /*
  18297. ** Set the number of backtrace levels kept for each allocation.
  18298. ** A value of zero turns off backtracing. The number is always rounded
  18299. ** up to a multiple of 2.
  18300. */
  18301. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  18302. if( depth<0 ){ depth = 0; }
  18303. if( depth>20 ){ depth = 20; }
  18304. depth = (depth+1)&0xfe;
  18305. mem.nBacktrace = depth;
  18306. }
  18307. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  18308. mem.xBacktrace = xBacktrace;
  18309. }
  18310. /*
  18311. ** Set the title string for subsequent allocations.
  18312. */
  18313. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  18314. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  18315. sqlite3_mutex_enter(mem.mutex);
  18316. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  18317. memcpy(mem.zTitle, zTitle, n);
  18318. mem.zTitle[n] = 0;
  18319. mem.nTitle = ROUND8(n);
  18320. sqlite3_mutex_leave(mem.mutex);
  18321. }
  18322. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  18323. struct MemBlockHdr *pHdr;
  18324. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  18325. void **pBt = (void**)pHdr;
  18326. pBt -= pHdr->nBacktraceSlots;
  18327. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  18328. }
  18329. }
  18330. /*
  18331. ** Open the file indicated and write a log of all unfreed memory
  18332. ** allocations into that log.
  18333. */
  18334. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  18335. FILE *out;
  18336. struct MemBlockHdr *pHdr;
  18337. void **pBt;
  18338. int i;
  18339. out = fopen(zFilename, "w");
  18340. if( out==0 ){
  18341. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18342. zFilename);
  18343. return;
  18344. }
  18345. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  18346. char *z = (char*)pHdr;
  18347. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  18348. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  18349. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  18350. if( pHdr->nBacktrace ){
  18351. fflush(out);
  18352. pBt = (void**)pHdr;
  18353. pBt -= pHdr->nBacktraceSlots;
  18354. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  18355. fprintf(out, "\n");
  18356. }
  18357. }
  18358. fprintf(out, "COUNTS:\n");
  18359. for(i=0; i<NCSIZE-1; i++){
  18360. if( mem.nAlloc[i] ){
  18361. fprintf(out, " %5d: %10d %10d %10d\n",
  18362. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  18363. }
  18364. }
  18365. if( mem.nAlloc[NCSIZE-1] ){
  18366. fprintf(out, " %5d: %10d %10d %10d\n",
  18367. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  18368. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  18369. }
  18370. fclose(out);
  18371. }
  18372. /*
  18373. ** Return the number of times sqlite3MemMalloc() has been called.
  18374. */
  18375. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  18376. int i;
  18377. int nTotal = 0;
  18378. for(i=0; i<NCSIZE; i++){
  18379. nTotal += mem.nAlloc[i];
  18380. }
  18381. return nTotal;
  18382. }
  18383. #endif /* SQLITE_MEMDEBUG */
  18384. /************** End of mem2.c ************************************************/
  18385. /************** Begin file mem3.c ********************************************/
  18386. /*
  18387. ** 2007 October 14
  18388. **
  18389. ** The author disclaims copyright to this source code. In place of
  18390. ** a legal notice, here is a blessing:
  18391. **
  18392. ** May you do good and not evil.
  18393. ** May you find forgiveness for yourself and forgive others.
  18394. ** May you share freely, never taking more than you give.
  18395. **
  18396. *************************************************************************
  18397. ** This file contains the C functions that implement a memory
  18398. ** allocation subsystem for use by SQLite.
  18399. **
  18400. ** This version of the memory allocation subsystem omits all
  18401. ** use of malloc(). The SQLite user supplies a block of memory
  18402. ** before calling sqlite3_initialize() from which allocations
  18403. ** are made and returned by the xMalloc() and xRealloc()
  18404. ** implementations. Once sqlite3_initialize() has been called,
  18405. ** the amount of memory available to SQLite is fixed and cannot
  18406. ** be changed.
  18407. **
  18408. ** This version of the memory allocation subsystem is included
  18409. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  18410. */
  18411. /* #include "sqliteInt.h" */
  18412. /*
  18413. ** This version of the memory allocator is only built into the library
  18414. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  18415. ** mean that the library will use a memory-pool by default, just that
  18416. ** it is available. The mempool allocator is activated by calling
  18417. ** sqlite3_config().
  18418. */
  18419. #ifdef SQLITE_ENABLE_MEMSYS3
  18420. /*
  18421. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  18422. */
  18423. #define MX_SMALL 10
  18424. /*
  18425. ** Number of freelist hash slots
  18426. */
  18427. #define N_HASH 61
  18428. /*
  18429. ** A memory allocation (also called a "chunk") consists of two or
  18430. ** more blocks where each block is 8 bytes. The first 8 bytes are
  18431. ** a header that is not returned to the user.
  18432. **
  18433. ** A chunk is two or more blocks that is either checked out or
  18434. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  18435. ** size of the allocation in blocks if the allocation is free.
  18436. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  18437. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  18438. ** is true if the previous chunk is checked out and false if the
  18439. ** previous chunk is free. The u.hdr.prevSize field is the size of
  18440. ** the previous chunk in blocks if the previous chunk is on the
  18441. ** freelist. If the previous chunk is checked out, then
  18442. ** u.hdr.prevSize can be part of the data for that chunk and should
  18443. ** not be read or written.
  18444. **
  18445. ** We often identify a chunk by its index in mem3.aPool[]. When
  18446. ** this is done, the chunk index refers to the second block of
  18447. ** the chunk. In this way, the first chunk has an index of 1.
  18448. ** A chunk index of 0 means "no such chunk" and is the equivalent
  18449. ** of a NULL pointer.
  18450. **
  18451. ** The second block of free chunks is of the form u.list. The
  18452. ** two fields form a double-linked list of chunks of related sizes.
  18453. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  18454. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  18455. **
  18456. ** The second block of a chunk is user data if the chunk is checked
  18457. ** out. If a chunk is checked out, the user data may extend into
  18458. ** the u.hdr.prevSize value of the following chunk.
  18459. */
  18460. typedef struct Mem3Block Mem3Block;
  18461. struct Mem3Block {
  18462. union {
  18463. struct {
  18464. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  18465. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  18466. } hdr;
  18467. struct {
  18468. u32 next; /* Index in mem3.aPool[] of next free chunk */
  18469. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  18470. } list;
  18471. } u;
  18472. };
  18473. /*
  18474. ** All of the static variables used by this module are collected
  18475. ** into a single structure named "mem3". This is to keep the
  18476. ** static variables organized and to reduce namespace pollution
  18477. ** when this module is combined with other in the amalgamation.
  18478. */
  18479. static SQLITE_WSD struct Mem3Global {
  18480. /*
  18481. ** Memory available for allocation. nPool is the size of the array
  18482. ** (in Mem3Blocks) pointed to by aPool less 2.
  18483. */
  18484. u32 nPool;
  18485. Mem3Block *aPool;
  18486. /*
  18487. ** True if we are evaluating an out-of-memory callback.
  18488. */
  18489. int alarmBusy;
  18490. /*
  18491. ** Mutex to control access to the memory allocation subsystem.
  18492. */
  18493. sqlite3_mutex *mutex;
  18494. /*
  18495. ** The minimum amount of free space that we have seen.
  18496. */
  18497. u32 mnMaster;
  18498. /*
  18499. ** iMaster is the index of the master chunk. Most new allocations
  18500. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  18501. ** of the current master. iMaster is 0 if there is not master chunk.
  18502. ** The master chunk is not in either the aiHash[] or aiSmall[].
  18503. */
  18504. u32 iMaster;
  18505. u32 szMaster;
  18506. /*
  18507. ** Array of lists of free blocks according to the block size
  18508. ** for smaller chunks, or a hash on the block size for larger
  18509. ** chunks.
  18510. */
  18511. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  18512. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  18513. } mem3 = { 97535575 };
  18514. #define mem3 GLOBAL(struct Mem3Global, mem3)
  18515. /*
  18516. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  18517. ** on. *pRoot is the list that i is a member of.
  18518. */
  18519. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  18520. u32 next = mem3.aPool[i].u.list.next;
  18521. u32 prev = mem3.aPool[i].u.list.prev;
  18522. assert( sqlite3_mutex_held(mem3.mutex) );
  18523. if( prev==0 ){
  18524. *pRoot = next;
  18525. }else{
  18526. mem3.aPool[prev].u.list.next = next;
  18527. }
  18528. if( next ){
  18529. mem3.aPool[next].u.list.prev = prev;
  18530. }
  18531. mem3.aPool[i].u.list.next = 0;
  18532. mem3.aPool[i].u.list.prev = 0;
  18533. }
  18534. /*
  18535. ** Unlink the chunk at index i from
  18536. ** whatever list is currently a member of.
  18537. */
  18538. static void memsys3Unlink(u32 i){
  18539. u32 size, hash;
  18540. assert( sqlite3_mutex_held(mem3.mutex) );
  18541. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  18542. assert( i>=1 );
  18543. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18544. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  18545. assert( size>=2 );
  18546. if( size <= MX_SMALL ){
  18547. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  18548. }else{
  18549. hash = size % N_HASH;
  18550. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  18551. }
  18552. }
  18553. /*
  18554. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  18555. ** at *pRoot.
  18556. */
  18557. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  18558. assert( sqlite3_mutex_held(mem3.mutex) );
  18559. mem3.aPool[i].u.list.next = *pRoot;
  18560. mem3.aPool[i].u.list.prev = 0;
  18561. if( *pRoot ){
  18562. mem3.aPool[*pRoot].u.list.prev = i;
  18563. }
  18564. *pRoot = i;
  18565. }
  18566. /*
  18567. ** Link the chunk at index i into either the appropriate
  18568. ** small chunk list, or into the large chunk hash table.
  18569. */
  18570. static void memsys3Link(u32 i){
  18571. u32 size, hash;
  18572. assert( sqlite3_mutex_held(mem3.mutex) );
  18573. assert( i>=1 );
  18574. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  18575. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18576. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  18577. assert( size>=2 );
  18578. if( size <= MX_SMALL ){
  18579. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  18580. }else{
  18581. hash = size % N_HASH;
  18582. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  18583. }
  18584. }
  18585. /*
  18586. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  18587. ** will already be held (obtained by code in malloc.c) if
  18588. ** sqlite3GlobalConfig.bMemStat is true.
  18589. */
  18590. static void memsys3Enter(void){
  18591. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  18592. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18593. }
  18594. sqlite3_mutex_enter(mem3.mutex);
  18595. }
  18596. static void memsys3Leave(void){
  18597. sqlite3_mutex_leave(mem3.mutex);
  18598. }
  18599. /*
  18600. ** Called when we are unable to satisfy an allocation of nBytes.
  18601. */
  18602. static void memsys3OutOfMemory(int nByte){
  18603. if( !mem3.alarmBusy ){
  18604. mem3.alarmBusy = 1;
  18605. assert( sqlite3_mutex_held(mem3.mutex) );
  18606. sqlite3_mutex_leave(mem3.mutex);
  18607. sqlite3_release_memory(nByte);
  18608. sqlite3_mutex_enter(mem3.mutex);
  18609. mem3.alarmBusy = 0;
  18610. }
  18611. }
  18612. /*
  18613. ** Chunk i is a free chunk that has been unlinked. Adjust its
  18614. ** size parameters for check-out and return a pointer to the
  18615. ** user portion of the chunk.
  18616. */
  18617. static void *memsys3Checkout(u32 i, u32 nBlock){
  18618. u32 x;
  18619. assert( sqlite3_mutex_held(mem3.mutex) );
  18620. assert( i>=1 );
  18621. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  18622. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  18623. x = mem3.aPool[i-1].u.hdr.size4x;
  18624. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  18625. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  18626. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  18627. return &mem3.aPool[i];
  18628. }
  18629. /*
  18630. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  18631. ** Return a pointer to the new allocation. Or, if the master chunk
  18632. ** is not large enough, return 0.
  18633. */
  18634. static void *memsys3FromMaster(u32 nBlock){
  18635. assert( sqlite3_mutex_held(mem3.mutex) );
  18636. assert( mem3.szMaster>=nBlock );
  18637. if( nBlock>=mem3.szMaster-1 ){
  18638. /* Use the entire master */
  18639. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  18640. mem3.iMaster = 0;
  18641. mem3.szMaster = 0;
  18642. mem3.mnMaster = 0;
  18643. return p;
  18644. }else{
  18645. /* Split the master block. Return the tail. */
  18646. u32 newi, x;
  18647. newi = mem3.iMaster + mem3.szMaster - nBlock;
  18648. assert( newi > mem3.iMaster+1 );
  18649. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  18650. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  18651. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  18652. mem3.szMaster -= nBlock;
  18653. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  18654. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18655. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18656. if( mem3.szMaster < mem3.mnMaster ){
  18657. mem3.mnMaster = mem3.szMaster;
  18658. }
  18659. return (void*)&mem3.aPool[newi];
  18660. }
  18661. }
  18662. /*
  18663. ** *pRoot is the head of a list of free chunks of the same size
  18664. ** or same size hash. In other words, *pRoot is an entry in either
  18665. ** mem3.aiSmall[] or mem3.aiHash[].
  18666. **
  18667. ** This routine examines all entries on the given list and tries
  18668. ** to coalesce each entries with adjacent free chunks.
  18669. **
  18670. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  18671. ** the current mem3.iMaster with the new larger chunk. In order for
  18672. ** this mem3.iMaster replacement to work, the master chunk must be
  18673. ** linked into the hash tables. That is not the normal state of
  18674. ** affairs, of course. The calling routine must link the master
  18675. ** chunk before invoking this routine, then must unlink the (possibly
  18676. ** changed) master chunk once this routine has finished.
  18677. */
  18678. static void memsys3Merge(u32 *pRoot){
  18679. u32 iNext, prev, size, i, x;
  18680. assert( sqlite3_mutex_held(mem3.mutex) );
  18681. for(i=*pRoot; i>0; i=iNext){
  18682. iNext = mem3.aPool[i].u.list.next;
  18683. size = mem3.aPool[i-1].u.hdr.size4x;
  18684. assert( (size&1)==0 );
  18685. if( (size&2)==0 ){
  18686. memsys3UnlinkFromList(i, pRoot);
  18687. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  18688. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  18689. if( prev==iNext ){
  18690. iNext = mem3.aPool[prev].u.list.next;
  18691. }
  18692. memsys3Unlink(prev);
  18693. size = i + size/4 - prev;
  18694. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  18695. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  18696. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  18697. memsys3Link(prev);
  18698. i = prev;
  18699. }else{
  18700. size /= 4;
  18701. }
  18702. if( size>mem3.szMaster ){
  18703. mem3.iMaster = i;
  18704. mem3.szMaster = size;
  18705. }
  18706. }
  18707. }
  18708. /*
  18709. ** Return a block of memory of at least nBytes in size.
  18710. ** Return NULL if unable.
  18711. **
  18712. ** This function assumes that the necessary mutexes, if any, are
  18713. ** already held by the caller. Hence "Unsafe".
  18714. */
  18715. static void *memsys3MallocUnsafe(int nByte){
  18716. u32 i;
  18717. u32 nBlock;
  18718. u32 toFree;
  18719. assert( sqlite3_mutex_held(mem3.mutex) );
  18720. assert( sizeof(Mem3Block)==8 );
  18721. if( nByte<=12 ){
  18722. nBlock = 2;
  18723. }else{
  18724. nBlock = (nByte + 11)/8;
  18725. }
  18726. assert( nBlock>=2 );
  18727. /* STEP 1:
  18728. ** Look for an entry of the correct size in either the small
  18729. ** chunk table or in the large chunk hash table. This is
  18730. ** successful most of the time (about 9 times out of 10).
  18731. */
  18732. if( nBlock <= MX_SMALL ){
  18733. i = mem3.aiSmall[nBlock-2];
  18734. if( i>0 ){
  18735. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  18736. return memsys3Checkout(i, nBlock);
  18737. }
  18738. }else{
  18739. int hash = nBlock % N_HASH;
  18740. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  18741. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  18742. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  18743. return memsys3Checkout(i, nBlock);
  18744. }
  18745. }
  18746. }
  18747. /* STEP 2:
  18748. ** Try to satisfy the allocation by carving a piece off of the end
  18749. ** of the master chunk. This step usually works if step 1 fails.
  18750. */
  18751. if( mem3.szMaster>=nBlock ){
  18752. return memsys3FromMaster(nBlock);
  18753. }
  18754. /* STEP 3:
  18755. ** Loop through the entire memory pool. Coalesce adjacent free
  18756. ** chunks. Recompute the master chunk as the largest free chunk.
  18757. ** Then try again to satisfy the allocation by carving a piece off
  18758. ** of the end of the master chunk. This step happens very
  18759. ** rarely (we hope!)
  18760. */
  18761. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  18762. memsys3OutOfMemory(toFree);
  18763. if( mem3.iMaster ){
  18764. memsys3Link(mem3.iMaster);
  18765. mem3.iMaster = 0;
  18766. mem3.szMaster = 0;
  18767. }
  18768. for(i=0; i<N_HASH; i++){
  18769. memsys3Merge(&mem3.aiHash[i]);
  18770. }
  18771. for(i=0; i<MX_SMALL-1; i++){
  18772. memsys3Merge(&mem3.aiSmall[i]);
  18773. }
  18774. if( mem3.szMaster ){
  18775. memsys3Unlink(mem3.iMaster);
  18776. if( mem3.szMaster>=nBlock ){
  18777. return memsys3FromMaster(nBlock);
  18778. }
  18779. }
  18780. }
  18781. /* If none of the above worked, then we fail. */
  18782. return 0;
  18783. }
  18784. /*
  18785. ** Free an outstanding memory allocation.
  18786. **
  18787. ** This function assumes that the necessary mutexes, if any, are
  18788. ** already held by the caller. Hence "Unsafe".
  18789. */
  18790. static void memsys3FreeUnsafe(void *pOld){
  18791. Mem3Block *p = (Mem3Block*)pOld;
  18792. int i;
  18793. u32 size, x;
  18794. assert( sqlite3_mutex_held(mem3.mutex) );
  18795. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  18796. i = p - mem3.aPool;
  18797. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  18798. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18799. assert( i+size<=mem3.nPool+1 );
  18800. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  18801. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  18802. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  18803. memsys3Link(i);
  18804. /* Try to expand the master using the newly freed chunk */
  18805. if( mem3.iMaster ){
  18806. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  18807. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  18808. mem3.iMaster -= size;
  18809. mem3.szMaster += size;
  18810. memsys3Unlink(mem3.iMaster);
  18811. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18812. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18813. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  18814. }
  18815. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18816. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  18817. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  18818. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  18819. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18820. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  18821. }
  18822. }
  18823. }
  18824. /*
  18825. ** Return the size of an outstanding allocation, in bytes. The
  18826. ** size returned omits the 8-byte header overhead. This only
  18827. ** works for chunks that are currently checked out.
  18828. */
  18829. static int memsys3Size(void *p){
  18830. Mem3Block *pBlock;
  18831. assert( p!=0 );
  18832. pBlock = (Mem3Block*)p;
  18833. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  18834. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  18835. }
  18836. /*
  18837. ** Round up a request size to the next valid allocation size.
  18838. */
  18839. static int memsys3Roundup(int n){
  18840. if( n<=12 ){
  18841. return 12;
  18842. }else{
  18843. return ((n+11)&~7) - 4;
  18844. }
  18845. }
  18846. /*
  18847. ** Allocate nBytes of memory.
  18848. */
  18849. static void *memsys3Malloc(int nBytes){
  18850. sqlite3_int64 *p;
  18851. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  18852. memsys3Enter();
  18853. p = memsys3MallocUnsafe(nBytes);
  18854. memsys3Leave();
  18855. return (void*)p;
  18856. }
  18857. /*
  18858. ** Free memory.
  18859. */
  18860. static void memsys3Free(void *pPrior){
  18861. assert( pPrior );
  18862. memsys3Enter();
  18863. memsys3FreeUnsafe(pPrior);
  18864. memsys3Leave();
  18865. }
  18866. /*
  18867. ** Change the size of an existing memory allocation
  18868. */
  18869. static void *memsys3Realloc(void *pPrior, int nBytes){
  18870. int nOld;
  18871. void *p;
  18872. if( pPrior==0 ){
  18873. return sqlite3_malloc(nBytes);
  18874. }
  18875. if( nBytes<=0 ){
  18876. sqlite3_free(pPrior);
  18877. return 0;
  18878. }
  18879. nOld = memsys3Size(pPrior);
  18880. if( nBytes<=nOld && nBytes>=nOld-128 ){
  18881. return pPrior;
  18882. }
  18883. memsys3Enter();
  18884. p = memsys3MallocUnsafe(nBytes);
  18885. if( p ){
  18886. if( nOld<nBytes ){
  18887. memcpy(p, pPrior, nOld);
  18888. }else{
  18889. memcpy(p, pPrior, nBytes);
  18890. }
  18891. memsys3FreeUnsafe(pPrior);
  18892. }
  18893. memsys3Leave();
  18894. return p;
  18895. }
  18896. /*
  18897. ** Initialize this module.
  18898. */
  18899. static int memsys3Init(void *NotUsed){
  18900. UNUSED_PARAMETER(NotUsed);
  18901. if( !sqlite3GlobalConfig.pHeap ){
  18902. return SQLITE_ERROR;
  18903. }
  18904. /* Store a pointer to the memory block in global structure mem3. */
  18905. assert( sizeof(Mem3Block)==8 );
  18906. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  18907. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  18908. /* Initialize the master block. */
  18909. mem3.szMaster = mem3.nPool;
  18910. mem3.mnMaster = mem3.szMaster;
  18911. mem3.iMaster = 1;
  18912. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  18913. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  18914. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  18915. return SQLITE_OK;
  18916. }
  18917. /*
  18918. ** Deinitialize this module.
  18919. */
  18920. static void memsys3Shutdown(void *NotUsed){
  18921. UNUSED_PARAMETER(NotUsed);
  18922. mem3.mutex = 0;
  18923. return;
  18924. }
  18925. /*
  18926. ** Open the file indicated and write a log of all unfreed memory
  18927. ** allocations into that log.
  18928. */
  18929. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  18930. #ifdef SQLITE_DEBUG
  18931. FILE *out;
  18932. u32 i, j;
  18933. u32 size;
  18934. if( zFilename==0 || zFilename[0]==0 ){
  18935. out = stdout;
  18936. }else{
  18937. out = fopen(zFilename, "w");
  18938. if( out==0 ){
  18939. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18940. zFilename);
  18941. return;
  18942. }
  18943. }
  18944. memsys3Enter();
  18945. fprintf(out, "CHUNKS:\n");
  18946. for(i=1; i<=mem3.nPool; i+=size/4){
  18947. size = mem3.aPool[i-1].u.hdr.size4x;
  18948. if( size/4<=1 ){
  18949. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  18950. assert( 0 );
  18951. break;
  18952. }
  18953. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  18954. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  18955. assert( 0 );
  18956. break;
  18957. }
  18958. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  18959. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  18960. assert( 0 );
  18961. break;
  18962. }
  18963. if( size&1 ){
  18964. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  18965. }else{
  18966. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  18967. i==mem3.iMaster ? " **master**" : "");
  18968. }
  18969. }
  18970. for(i=0; i<MX_SMALL-1; i++){
  18971. if( mem3.aiSmall[i]==0 ) continue;
  18972. fprintf(out, "small(%2d):", i);
  18973. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  18974. fprintf(out, " %p(%d)", &mem3.aPool[j],
  18975. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  18976. }
  18977. fprintf(out, "\n");
  18978. }
  18979. for(i=0; i<N_HASH; i++){
  18980. if( mem3.aiHash[i]==0 ) continue;
  18981. fprintf(out, "hash(%2d):", i);
  18982. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  18983. fprintf(out, " %p(%d)", &mem3.aPool[j],
  18984. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  18985. }
  18986. fprintf(out, "\n");
  18987. }
  18988. fprintf(out, "master=%d\n", mem3.iMaster);
  18989. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  18990. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  18991. sqlite3_mutex_leave(mem3.mutex);
  18992. if( out==stdout ){
  18993. fflush(stdout);
  18994. }else{
  18995. fclose(out);
  18996. }
  18997. #else
  18998. UNUSED_PARAMETER(zFilename);
  18999. #endif
  19000. }
  19001. /*
  19002. ** This routine is the only routine in this file with external
  19003. ** linkage.
  19004. **
  19005. ** Populate the low-level memory allocation function pointers in
  19006. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  19007. ** arguments specify the block of memory to manage.
  19008. **
  19009. ** This routine is only called by sqlite3_config(), and therefore
  19010. ** is not required to be threadsafe (it is not).
  19011. */
  19012. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  19013. static const sqlite3_mem_methods mempoolMethods = {
  19014. memsys3Malloc,
  19015. memsys3Free,
  19016. memsys3Realloc,
  19017. memsys3Size,
  19018. memsys3Roundup,
  19019. memsys3Init,
  19020. memsys3Shutdown,
  19021. 0
  19022. };
  19023. return &mempoolMethods;
  19024. }
  19025. #endif /* SQLITE_ENABLE_MEMSYS3 */
  19026. /************** End of mem3.c ************************************************/
  19027. /************** Begin file mem5.c ********************************************/
  19028. /*
  19029. ** 2007 October 14
  19030. **
  19031. ** The author disclaims copyright to this source code. In place of
  19032. ** a legal notice, here is a blessing:
  19033. **
  19034. ** May you do good and not evil.
  19035. ** May you find forgiveness for yourself and forgive others.
  19036. ** May you share freely, never taking more than you give.
  19037. **
  19038. *************************************************************************
  19039. ** This file contains the C functions that implement a memory
  19040. ** allocation subsystem for use by SQLite.
  19041. **
  19042. ** This version of the memory allocation subsystem omits all
  19043. ** use of malloc(). The application gives SQLite a block of memory
  19044. ** before calling sqlite3_initialize() from which allocations
  19045. ** are made and returned by the xMalloc() and xRealloc()
  19046. ** implementations. Once sqlite3_initialize() has been called,
  19047. ** the amount of memory available to SQLite is fixed and cannot
  19048. ** be changed.
  19049. **
  19050. ** This version of the memory allocation subsystem is included
  19051. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  19052. **
  19053. ** This memory allocator uses the following algorithm:
  19054. **
  19055. ** 1. All memory allocation sizes are rounded up to a power of 2.
  19056. **
  19057. ** 2. If two adjacent free blocks are the halves of a larger block,
  19058. ** then the two blocks are coalesced into the single larger block.
  19059. **
  19060. ** 3. New memory is allocated from the first available free block.
  19061. **
  19062. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  19063. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  19064. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  19065. **
  19066. ** Let n be the size of the largest allocation divided by the minimum
  19067. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  19068. ** be the maximum amount of memory ever outstanding at one time. Let
  19069. ** N be the total amount of memory available for allocation. Robson
  19070. ** proved that this memory allocator will never breakdown due to
  19071. ** fragmentation as long as the following constraint holds:
  19072. **
  19073. ** N >= M*(1 + log2(n)/2) - n + 1
  19074. **
  19075. ** The sqlite3_status() logic tracks the maximum values of n and M so
  19076. ** that an application can, at any time, verify this constraint.
  19077. */
  19078. /* #include "sqliteInt.h" */
  19079. /*
  19080. ** This version of the memory allocator is used only when
  19081. ** SQLITE_ENABLE_MEMSYS5 is defined.
  19082. */
  19083. #ifdef SQLITE_ENABLE_MEMSYS5
  19084. /*
  19085. ** A minimum allocation is an instance of the following structure.
  19086. ** Larger allocations are an array of these structures where the
  19087. ** size of the array is a power of 2.
  19088. **
  19089. ** The size of this object must be a power of two. That fact is
  19090. ** verified in memsys5Init().
  19091. */
  19092. typedef struct Mem5Link Mem5Link;
  19093. struct Mem5Link {
  19094. int next; /* Index of next free chunk */
  19095. int prev; /* Index of previous free chunk */
  19096. };
  19097. /*
  19098. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  19099. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  19100. ** it is not actually possible to reach this limit.
  19101. */
  19102. #define LOGMAX 30
  19103. /*
  19104. ** Masks used for mem5.aCtrl[] elements.
  19105. */
  19106. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  19107. #define CTRL_FREE 0x20 /* True if not checked out */
  19108. /*
  19109. ** All of the static variables used by this module are collected
  19110. ** into a single structure named "mem5". This is to keep the
  19111. ** static variables organized and to reduce namespace pollution
  19112. ** when this module is combined with other in the amalgamation.
  19113. */
  19114. static SQLITE_WSD struct Mem5Global {
  19115. /*
  19116. ** Memory available for allocation
  19117. */
  19118. int szAtom; /* Smallest possible allocation in bytes */
  19119. int nBlock; /* Number of szAtom sized blocks in zPool */
  19120. u8 *zPool; /* Memory available to be allocated */
  19121. /*
  19122. ** Mutex to control access to the memory allocation subsystem.
  19123. */
  19124. sqlite3_mutex *mutex;
  19125. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19126. /*
  19127. ** Performance statistics
  19128. */
  19129. u64 nAlloc; /* Total number of calls to malloc */
  19130. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  19131. u64 totalExcess; /* Total internal fragmentation */
  19132. u32 currentOut; /* Current checkout, including internal fragmentation */
  19133. u32 currentCount; /* Current number of distinct checkouts */
  19134. u32 maxOut; /* Maximum instantaneous currentOut */
  19135. u32 maxCount; /* Maximum instantaneous currentCount */
  19136. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  19137. #endif
  19138. /*
  19139. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  19140. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  19141. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  19142. */
  19143. int aiFreelist[LOGMAX+1];
  19144. /*
  19145. ** Space for tracking which blocks are checked out and the size
  19146. ** of each block. One byte per block.
  19147. */
  19148. u8 *aCtrl;
  19149. } mem5;
  19150. /*
  19151. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  19152. */
  19153. #define mem5 GLOBAL(struct Mem5Global, mem5)
  19154. /*
  19155. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  19156. ** structures, return a pointer to the idx-th such link.
  19157. */
  19158. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  19159. /*
  19160. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  19161. ** on. It should be found on mem5.aiFreelist[iLogsize].
  19162. */
  19163. static void memsys5Unlink(int i, int iLogsize){
  19164. int next, prev;
  19165. assert( i>=0 && i<mem5.nBlock );
  19166. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  19167. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  19168. next = MEM5LINK(i)->next;
  19169. prev = MEM5LINK(i)->prev;
  19170. if( prev<0 ){
  19171. mem5.aiFreelist[iLogsize] = next;
  19172. }else{
  19173. MEM5LINK(prev)->next = next;
  19174. }
  19175. if( next>=0 ){
  19176. MEM5LINK(next)->prev = prev;
  19177. }
  19178. }
  19179. /*
  19180. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  19181. ** free list.
  19182. */
  19183. static void memsys5Link(int i, int iLogsize){
  19184. int x;
  19185. assert( sqlite3_mutex_held(mem5.mutex) );
  19186. assert( i>=0 && i<mem5.nBlock );
  19187. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  19188. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  19189. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  19190. MEM5LINK(i)->prev = -1;
  19191. if( x>=0 ){
  19192. assert( x<mem5.nBlock );
  19193. MEM5LINK(x)->prev = i;
  19194. }
  19195. mem5.aiFreelist[iLogsize] = i;
  19196. }
  19197. /*
  19198. ** Obtain or release the mutex needed to access global data structures.
  19199. */
  19200. static void memsys5Enter(void){
  19201. sqlite3_mutex_enter(mem5.mutex);
  19202. }
  19203. static void memsys5Leave(void){
  19204. sqlite3_mutex_leave(mem5.mutex);
  19205. }
  19206. /*
  19207. ** Return the size of an outstanding allocation, in bytes.
  19208. ** This only works for chunks that are currently checked out.
  19209. */
  19210. static int memsys5Size(void *p){
  19211. int iSize, i;
  19212. assert( p!=0 );
  19213. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  19214. assert( i>=0 && i<mem5.nBlock );
  19215. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  19216. return iSize;
  19217. }
  19218. /*
  19219. ** Return a block of memory of at least nBytes in size.
  19220. ** Return NULL if unable. Return NULL if nBytes==0.
  19221. **
  19222. ** The caller guarantees that nByte is positive.
  19223. **
  19224. ** The caller has obtained a mutex prior to invoking this
  19225. ** routine so there is never any chance that two or more
  19226. ** threads can be in this routine at the same time.
  19227. */
  19228. static void *memsys5MallocUnsafe(int nByte){
  19229. int i; /* Index of a mem5.aPool[] slot */
  19230. int iBin; /* Index into mem5.aiFreelist[] */
  19231. int iFullSz; /* Size of allocation rounded up to power of 2 */
  19232. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  19233. /* nByte must be a positive */
  19234. assert( nByte>0 );
  19235. /* No more than 1GiB per allocation */
  19236. if( nByte > 0x40000000 ) return 0;
  19237. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19238. /* Keep track of the maximum allocation request. Even unfulfilled
  19239. ** requests are counted */
  19240. if( (u32)nByte>mem5.maxRequest ){
  19241. mem5.maxRequest = nByte;
  19242. }
  19243. #endif
  19244. /* Round nByte up to the next valid power of two */
  19245. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  19246. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  19247. ** block. If not, then split a block of the next larger power of
  19248. ** two in order to create a new free block of size iLogsize.
  19249. */
  19250. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  19251. if( iBin>LOGMAX ){
  19252. testcase( sqlite3GlobalConfig.xLog!=0 );
  19253. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  19254. return 0;
  19255. }
  19256. i = mem5.aiFreelist[iBin];
  19257. memsys5Unlink(i, iBin);
  19258. while( iBin>iLogsize ){
  19259. int newSize;
  19260. iBin--;
  19261. newSize = 1 << iBin;
  19262. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  19263. memsys5Link(i+newSize, iBin);
  19264. }
  19265. mem5.aCtrl[i] = iLogsize;
  19266. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19267. /* Update allocator performance statistics. */
  19268. mem5.nAlloc++;
  19269. mem5.totalAlloc += iFullSz;
  19270. mem5.totalExcess += iFullSz - nByte;
  19271. mem5.currentCount++;
  19272. mem5.currentOut += iFullSz;
  19273. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  19274. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  19275. #endif
  19276. #ifdef SQLITE_DEBUG
  19277. /* Make sure the allocated memory does not assume that it is set to zero
  19278. ** or retains a value from a previous allocation */
  19279. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  19280. #endif
  19281. /* Return a pointer to the allocated memory. */
  19282. return (void*)&mem5.zPool[i*mem5.szAtom];
  19283. }
  19284. /*
  19285. ** Free an outstanding memory allocation.
  19286. */
  19287. static void memsys5FreeUnsafe(void *pOld){
  19288. u32 size, iLogsize;
  19289. int iBlock;
  19290. /* Set iBlock to the index of the block pointed to by pOld in
  19291. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  19292. */
  19293. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  19294. /* Check that the pointer pOld points to a valid, non-free block. */
  19295. assert( iBlock>=0 && iBlock<mem5.nBlock );
  19296. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  19297. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  19298. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  19299. size = 1<<iLogsize;
  19300. assert( iBlock+size-1<(u32)mem5.nBlock );
  19301. mem5.aCtrl[iBlock] |= CTRL_FREE;
  19302. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  19303. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19304. assert( mem5.currentCount>0 );
  19305. assert( mem5.currentOut>=(size*mem5.szAtom) );
  19306. mem5.currentCount--;
  19307. mem5.currentOut -= size*mem5.szAtom;
  19308. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  19309. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  19310. #endif
  19311. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  19312. while( ALWAYS(iLogsize<LOGMAX) ){
  19313. int iBuddy;
  19314. if( (iBlock>>iLogsize) & 1 ){
  19315. iBuddy = iBlock - size;
  19316. assert( iBuddy>=0 );
  19317. }else{
  19318. iBuddy = iBlock + size;
  19319. if( iBuddy>=mem5.nBlock ) break;
  19320. }
  19321. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  19322. memsys5Unlink(iBuddy, iLogsize);
  19323. iLogsize++;
  19324. if( iBuddy<iBlock ){
  19325. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  19326. mem5.aCtrl[iBlock] = 0;
  19327. iBlock = iBuddy;
  19328. }else{
  19329. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  19330. mem5.aCtrl[iBuddy] = 0;
  19331. }
  19332. size *= 2;
  19333. }
  19334. #ifdef SQLITE_DEBUG
  19335. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  19336. ** not used after being freed */
  19337. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  19338. #endif
  19339. memsys5Link(iBlock, iLogsize);
  19340. }
  19341. /*
  19342. ** Allocate nBytes of memory.
  19343. */
  19344. static void *memsys5Malloc(int nBytes){
  19345. sqlite3_int64 *p = 0;
  19346. if( nBytes>0 ){
  19347. memsys5Enter();
  19348. p = memsys5MallocUnsafe(nBytes);
  19349. memsys5Leave();
  19350. }
  19351. return (void*)p;
  19352. }
  19353. /*
  19354. ** Free memory.
  19355. **
  19356. ** The outer layer memory allocator prevents this routine from
  19357. ** being called with pPrior==0.
  19358. */
  19359. static void memsys5Free(void *pPrior){
  19360. assert( pPrior!=0 );
  19361. memsys5Enter();
  19362. memsys5FreeUnsafe(pPrior);
  19363. memsys5Leave();
  19364. }
  19365. /*
  19366. ** Change the size of an existing memory allocation.
  19367. **
  19368. ** The outer layer memory allocator prevents this routine from
  19369. ** being called with pPrior==0.
  19370. **
  19371. ** nBytes is always a value obtained from a prior call to
  19372. ** memsys5Round(). Hence nBytes is always a non-negative power
  19373. ** of two. If nBytes==0 that means that an oversize allocation
  19374. ** (an allocation larger than 0x40000000) was requested and this
  19375. ** routine should return 0 without freeing pPrior.
  19376. */
  19377. static void *memsys5Realloc(void *pPrior, int nBytes){
  19378. int nOld;
  19379. void *p;
  19380. assert( pPrior!=0 );
  19381. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  19382. assert( nBytes>=0 );
  19383. if( nBytes==0 ){
  19384. return 0;
  19385. }
  19386. nOld = memsys5Size(pPrior);
  19387. if( nBytes<=nOld ){
  19388. return pPrior;
  19389. }
  19390. p = memsys5Malloc(nBytes);
  19391. if( p ){
  19392. memcpy(p, pPrior, nOld);
  19393. memsys5Free(pPrior);
  19394. }
  19395. return p;
  19396. }
  19397. /*
  19398. ** Round up a request size to the next valid allocation size. If
  19399. ** the allocation is too large to be handled by this allocation system,
  19400. ** return 0.
  19401. **
  19402. ** All allocations must be a power of two and must be expressed by a
  19403. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  19404. ** or 1073741824 bytes.
  19405. */
  19406. static int memsys5Roundup(int n){
  19407. int iFullSz;
  19408. if( n > 0x40000000 ) return 0;
  19409. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  19410. return iFullSz;
  19411. }
  19412. /*
  19413. ** Return the ceiling of the logarithm base 2 of iValue.
  19414. **
  19415. ** Examples: memsys5Log(1) -> 0
  19416. ** memsys5Log(2) -> 1
  19417. ** memsys5Log(4) -> 2
  19418. ** memsys5Log(5) -> 3
  19419. ** memsys5Log(8) -> 3
  19420. ** memsys5Log(9) -> 4
  19421. */
  19422. static int memsys5Log(int iValue){
  19423. int iLog;
  19424. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  19425. return iLog;
  19426. }
  19427. /*
  19428. ** Initialize the memory allocator.
  19429. **
  19430. ** This routine is not threadsafe. The caller must be holding a mutex
  19431. ** to prevent multiple threads from entering at the same time.
  19432. */
  19433. static int memsys5Init(void *NotUsed){
  19434. int ii; /* Loop counter */
  19435. int nByte; /* Number of bytes of memory available to this allocator */
  19436. u8 *zByte; /* Memory usable by this allocator */
  19437. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  19438. int iOffset; /* An offset into mem5.aCtrl[] */
  19439. UNUSED_PARAMETER(NotUsed);
  19440. /* For the purposes of this routine, disable the mutex */
  19441. mem5.mutex = 0;
  19442. /* The size of a Mem5Link object must be a power of two. Verify that
  19443. ** this is case.
  19444. */
  19445. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  19446. nByte = sqlite3GlobalConfig.nHeap;
  19447. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  19448. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  19449. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  19450. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  19451. mem5.szAtom = (1<<nMinLog);
  19452. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  19453. mem5.szAtom = mem5.szAtom << 1;
  19454. }
  19455. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  19456. mem5.zPool = zByte;
  19457. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  19458. for(ii=0; ii<=LOGMAX; ii++){
  19459. mem5.aiFreelist[ii] = -1;
  19460. }
  19461. iOffset = 0;
  19462. for(ii=LOGMAX; ii>=0; ii--){
  19463. int nAlloc = (1<<ii);
  19464. if( (iOffset+nAlloc)<=mem5.nBlock ){
  19465. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  19466. memsys5Link(iOffset, ii);
  19467. iOffset += nAlloc;
  19468. }
  19469. assert((iOffset+nAlloc)>mem5.nBlock);
  19470. }
  19471. /* If a mutex is required for normal operation, allocate one */
  19472. if( sqlite3GlobalConfig.bMemstat==0 ){
  19473. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  19474. }
  19475. return SQLITE_OK;
  19476. }
  19477. /*
  19478. ** Deinitialize this module.
  19479. */
  19480. static void memsys5Shutdown(void *NotUsed){
  19481. UNUSED_PARAMETER(NotUsed);
  19482. mem5.mutex = 0;
  19483. return;
  19484. }
  19485. #ifdef SQLITE_TEST
  19486. /*
  19487. ** Open the file indicated and write a log of all unfreed memory
  19488. ** allocations into that log.
  19489. */
  19490. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  19491. FILE *out;
  19492. int i, j, n;
  19493. int nMinLog;
  19494. if( zFilename==0 || zFilename[0]==0 ){
  19495. out = stdout;
  19496. }else{
  19497. out = fopen(zFilename, "w");
  19498. if( out==0 ){
  19499. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  19500. zFilename);
  19501. return;
  19502. }
  19503. }
  19504. memsys5Enter();
  19505. nMinLog = memsys5Log(mem5.szAtom);
  19506. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  19507. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  19508. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  19509. }
  19510. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  19511. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  19512. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  19513. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  19514. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  19515. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  19516. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  19517. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  19518. memsys5Leave();
  19519. if( out==stdout ){
  19520. fflush(stdout);
  19521. }else{
  19522. fclose(out);
  19523. }
  19524. }
  19525. #endif
  19526. /*
  19527. ** This routine is the only routine in this file with external
  19528. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  19529. ** struct populated with the memsys5 methods.
  19530. */
  19531. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  19532. static const sqlite3_mem_methods memsys5Methods = {
  19533. memsys5Malloc,
  19534. memsys5Free,
  19535. memsys5Realloc,
  19536. memsys5Size,
  19537. memsys5Roundup,
  19538. memsys5Init,
  19539. memsys5Shutdown,
  19540. 0
  19541. };
  19542. return &memsys5Methods;
  19543. }
  19544. #endif /* SQLITE_ENABLE_MEMSYS5 */
  19545. /************** End of mem5.c ************************************************/
  19546. /************** Begin file mutex.c *******************************************/
  19547. /*
  19548. ** 2007 August 14
  19549. **
  19550. ** The author disclaims copyright to this source code. In place of
  19551. ** a legal notice, here is a blessing:
  19552. **
  19553. ** May you do good and not evil.
  19554. ** May you find forgiveness for yourself and forgive others.
  19555. ** May you share freely, never taking more than you give.
  19556. **
  19557. *************************************************************************
  19558. ** This file contains the C functions that implement mutexes.
  19559. **
  19560. ** This file contains code that is common across all mutex implementations.
  19561. */
  19562. /* #include "sqliteInt.h" */
  19563. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  19564. /*
  19565. ** For debugging purposes, record when the mutex subsystem is initialized
  19566. ** and uninitialized so that we can assert() if there is an attempt to
  19567. ** allocate a mutex while the system is uninitialized.
  19568. */
  19569. static SQLITE_WSD int mutexIsInit = 0;
  19570. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  19571. #ifndef SQLITE_MUTEX_OMIT
  19572. /*
  19573. ** Initialize the mutex system.
  19574. */
  19575. SQLITE_PRIVATE int sqlite3MutexInit(void){
  19576. int rc = SQLITE_OK;
  19577. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  19578. /* If the xMutexAlloc method has not been set, then the user did not
  19579. ** install a mutex implementation via sqlite3_config() prior to
  19580. ** sqlite3_initialize() being called. This block copies pointers to
  19581. ** the default implementation into the sqlite3GlobalConfig structure.
  19582. */
  19583. sqlite3_mutex_methods const *pFrom;
  19584. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  19585. if( sqlite3GlobalConfig.bCoreMutex ){
  19586. pFrom = sqlite3DefaultMutex();
  19587. }else{
  19588. pFrom = sqlite3NoopMutex();
  19589. }
  19590. pTo->xMutexInit = pFrom->xMutexInit;
  19591. pTo->xMutexEnd = pFrom->xMutexEnd;
  19592. pTo->xMutexFree = pFrom->xMutexFree;
  19593. pTo->xMutexEnter = pFrom->xMutexEnter;
  19594. pTo->xMutexTry = pFrom->xMutexTry;
  19595. pTo->xMutexLeave = pFrom->xMutexLeave;
  19596. pTo->xMutexHeld = pFrom->xMutexHeld;
  19597. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  19598. sqlite3MemoryBarrier();
  19599. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  19600. }
  19601. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  19602. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  19603. #ifdef SQLITE_DEBUG
  19604. GLOBAL(int, mutexIsInit) = 1;
  19605. #endif
  19606. return rc;
  19607. }
  19608. /*
  19609. ** Shutdown the mutex system. This call frees resources allocated by
  19610. ** sqlite3MutexInit().
  19611. */
  19612. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  19613. int rc = SQLITE_OK;
  19614. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  19615. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  19616. }
  19617. #ifdef SQLITE_DEBUG
  19618. GLOBAL(int, mutexIsInit) = 0;
  19619. #endif
  19620. return rc;
  19621. }
  19622. /*
  19623. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  19624. */
  19625. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
  19626. #ifndef SQLITE_OMIT_AUTOINIT
  19627. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  19628. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  19629. #endif
  19630. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  19631. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  19632. }
  19633. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  19634. if( !sqlite3GlobalConfig.bCoreMutex ){
  19635. return 0;
  19636. }
  19637. assert( GLOBAL(int, mutexIsInit) );
  19638. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  19639. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  19640. }
  19641. /*
  19642. ** Free a dynamic mutex.
  19643. */
  19644. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
  19645. if( p ){
  19646. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  19647. sqlite3GlobalConfig.mutex.xMutexFree(p);
  19648. }
  19649. }
  19650. /*
  19651. ** Obtain the mutex p. If some other thread already has the mutex, block
  19652. ** until it can be obtained.
  19653. */
  19654. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
  19655. if( p ){
  19656. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  19657. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  19658. }
  19659. }
  19660. /*
  19661. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  19662. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  19663. */
  19664. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
  19665. int rc = SQLITE_OK;
  19666. if( p ){
  19667. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  19668. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  19669. }
  19670. return rc;
  19671. }
  19672. /*
  19673. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  19674. ** entered by the same thread. The behavior is undefined if the mutex
  19675. ** is not currently entered. If a NULL pointer is passed as an argument
  19676. ** this function is a no-op.
  19677. */
  19678. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
  19679. if( p ){
  19680. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  19681. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  19682. }
  19683. }
  19684. #ifndef NDEBUG
  19685. /*
  19686. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19687. ** intended for use inside assert() statements.
  19688. */
  19689. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
  19690. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  19691. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  19692. }
  19693. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
  19694. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  19695. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  19696. }
  19697. #endif
  19698. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  19699. /************** End of mutex.c ***********************************************/
  19700. /************** Begin file mutex_noop.c **************************************/
  19701. /*
  19702. ** 2008 October 07
  19703. **
  19704. ** The author disclaims copyright to this source code. In place of
  19705. ** a legal notice, here is a blessing:
  19706. **
  19707. ** May you do good and not evil.
  19708. ** May you find forgiveness for yourself and forgive others.
  19709. ** May you share freely, never taking more than you give.
  19710. **
  19711. *************************************************************************
  19712. ** This file contains the C functions that implement mutexes.
  19713. **
  19714. ** This implementation in this file does not provide any mutual
  19715. ** exclusion and is thus suitable for use only in applications
  19716. ** that use SQLite in a single thread. The routines defined
  19717. ** here are place-holders. Applications can substitute working
  19718. ** mutex routines at start-time using the
  19719. **
  19720. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  19721. **
  19722. ** interface.
  19723. **
  19724. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  19725. ** that does error checking on mutexes to make sure they are being
  19726. ** called correctly.
  19727. */
  19728. /* #include "sqliteInt.h" */
  19729. #ifndef SQLITE_MUTEX_OMIT
  19730. #ifndef SQLITE_DEBUG
  19731. /*
  19732. ** Stub routines for all mutex methods.
  19733. **
  19734. ** This routines provide no mutual exclusion or error checking.
  19735. */
  19736. static int noopMutexInit(void){ return SQLITE_OK; }
  19737. static int noopMutexEnd(void){ return SQLITE_OK; }
  19738. static sqlite3_mutex *noopMutexAlloc(int id){
  19739. UNUSED_PARAMETER(id);
  19740. return (sqlite3_mutex*)8;
  19741. }
  19742. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19743. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19744. static int noopMutexTry(sqlite3_mutex *p){
  19745. UNUSED_PARAMETER(p);
  19746. return SQLITE_OK;
  19747. }
  19748. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19749. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  19750. static const sqlite3_mutex_methods sMutex = {
  19751. noopMutexInit,
  19752. noopMutexEnd,
  19753. noopMutexAlloc,
  19754. noopMutexFree,
  19755. noopMutexEnter,
  19756. noopMutexTry,
  19757. noopMutexLeave,
  19758. 0,
  19759. 0,
  19760. };
  19761. return &sMutex;
  19762. }
  19763. #endif /* !SQLITE_DEBUG */
  19764. #ifdef SQLITE_DEBUG
  19765. /*
  19766. ** In this implementation, error checking is provided for testing
  19767. ** and debugging purposes. The mutexes still do not provide any
  19768. ** mutual exclusion.
  19769. */
  19770. /*
  19771. ** The mutex object
  19772. */
  19773. typedef struct sqlite3_debug_mutex {
  19774. int id; /* The mutex type */
  19775. int cnt; /* Number of entries without a matching leave */
  19776. } sqlite3_debug_mutex;
  19777. /*
  19778. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19779. ** intended for use inside assert() statements.
  19780. */
  19781. static int debugMutexHeld(sqlite3_mutex *pX){
  19782. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19783. return p==0 || p->cnt>0;
  19784. }
  19785. static int debugMutexNotheld(sqlite3_mutex *pX){
  19786. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19787. return p==0 || p->cnt==0;
  19788. }
  19789. /*
  19790. ** Initialize and deinitialize the mutex subsystem.
  19791. */
  19792. static int debugMutexInit(void){ return SQLITE_OK; }
  19793. static int debugMutexEnd(void){ return SQLITE_OK; }
  19794. /*
  19795. ** The sqlite3_mutex_alloc() routine allocates a new
  19796. ** mutex and returns a pointer to it. If it returns NULL
  19797. ** that means that a mutex could not be allocated.
  19798. */
  19799. static sqlite3_mutex *debugMutexAlloc(int id){
  19800. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  19801. sqlite3_debug_mutex *pNew = 0;
  19802. switch( id ){
  19803. case SQLITE_MUTEX_FAST:
  19804. case SQLITE_MUTEX_RECURSIVE: {
  19805. pNew = sqlite3Malloc(sizeof(*pNew));
  19806. if( pNew ){
  19807. pNew->id = id;
  19808. pNew->cnt = 0;
  19809. }
  19810. break;
  19811. }
  19812. default: {
  19813. #ifdef SQLITE_ENABLE_API_ARMOR
  19814. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  19815. (void)SQLITE_MISUSE_BKPT;
  19816. return 0;
  19817. }
  19818. #endif
  19819. pNew = &aStatic[id-2];
  19820. pNew->id = id;
  19821. break;
  19822. }
  19823. }
  19824. return (sqlite3_mutex*)pNew;
  19825. }
  19826. /*
  19827. ** This routine deallocates a previously allocated mutex.
  19828. */
  19829. static void debugMutexFree(sqlite3_mutex *pX){
  19830. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19831. assert( p->cnt==0 );
  19832. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  19833. sqlite3_free(p);
  19834. }else{
  19835. #ifdef SQLITE_ENABLE_API_ARMOR
  19836. (void)SQLITE_MISUSE_BKPT;
  19837. #endif
  19838. }
  19839. }
  19840. /*
  19841. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19842. ** to enter a mutex. If another thread is already within the mutex,
  19843. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19844. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19845. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19846. ** be entered multiple times by the same thread. In such cases the,
  19847. ** mutex must be exited an equal number of times before another thread
  19848. ** can enter. If the same thread tries to enter any other kind of mutex
  19849. ** more than once, the behavior is undefined.
  19850. */
  19851. static void debugMutexEnter(sqlite3_mutex *pX){
  19852. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19853. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19854. p->cnt++;
  19855. }
  19856. static int debugMutexTry(sqlite3_mutex *pX){
  19857. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19858. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19859. p->cnt++;
  19860. return SQLITE_OK;
  19861. }
  19862. /*
  19863. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19864. ** previously entered by the same thread. The behavior
  19865. ** is undefined if the mutex is not currently entered or
  19866. ** is not currently allocated. SQLite will never do either.
  19867. */
  19868. static void debugMutexLeave(sqlite3_mutex *pX){
  19869. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19870. assert( debugMutexHeld(pX) );
  19871. p->cnt--;
  19872. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19873. }
  19874. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  19875. static const sqlite3_mutex_methods sMutex = {
  19876. debugMutexInit,
  19877. debugMutexEnd,
  19878. debugMutexAlloc,
  19879. debugMutexFree,
  19880. debugMutexEnter,
  19881. debugMutexTry,
  19882. debugMutexLeave,
  19883. debugMutexHeld,
  19884. debugMutexNotheld
  19885. };
  19886. return &sMutex;
  19887. }
  19888. #endif /* SQLITE_DEBUG */
  19889. /*
  19890. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  19891. ** is used regardless of the run-time threadsafety setting.
  19892. */
  19893. #ifdef SQLITE_MUTEX_NOOP
  19894. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19895. return sqlite3NoopMutex();
  19896. }
  19897. #endif /* defined(SQLITE_MUTEX_NOOP) */
  19898. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  19899. /************** End of mutex_noop.c ******************************************/
  19900. /************** Begin file mutex_unix.c **************************************/
  19901. /*
  19902. ** 2007 August 28
  19903. **
  19904. ** The author disclaims copyright to this source code. In place of
  19905. ** a legal notice, here is a blessing:
  19906. **
  19907. ** May you do good and not evil.
  19908. ** May you find forgiveness for yourself and forgive others.
  19909. ** May you share freely, never taking more than you give.
  19910. **
  19911. *************************************************************************
  19912. ** This file contains the C functions that implement mutexes for pthreads
  19913. */
  19914. /* #include "sqliteInt.h" */
  19915. /*
  19916. ** The code in this file is only used if we are compiling threadsafe
  19917. ** under unix with pthreads.
  19918. **
  19919. ** Note that this implementation requires a version of pthreads that
  19920. ** supports recursive mutexes.
  19921. */
  19922. #ifdef SQLITE_MUTEX_PTHREADS
  19923. #include <pthread.h>
  19924. /*
  19925. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  19926. ** are necessary under two condidtions: (1) Debug builds and (2) using
  19927. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  19928. */
  19929. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  19930. # define SQLITE_MUTEX_NREF 1
  19931. #else
  19932. # define SQLITE_MUTEX_NREF 0
  19933. #endif
  19934. /*
  19935. ** Each recursive mutex is an instance of the following structure.
  19936. */
  19937. struct sqlite3_mutex {
  19938. pthread_mutex_t mutex; /* Mutex controlling the lock */
  19939. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  19940. int id; /* Mutex type */
  19941. #endif
  19942. #if SQLITE_MUTEX_NREF
  19943. volatile int nRef; /* Number of entrances */
  19944. volatile pthread_t owner; /* Thread that is within this mutex */
  19945. int trace; /* True to trace changes */
  19946. #endif
  19947. };
  19948. #if SQLITE_MUTEX_NREF
  19949. #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
  19950. #elif defined(SQLITE_ENABLE_API_ARMOR)
  19951. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
  19952. #else
  19953. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  19954. #endif
  19955. /*
  19956. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19957. ** intended for use only inside assert() statements. On some platforms,
  19958. ** there might be race conditions that can cause these routines to
  19959. ** deliver incorrect results. In particular, if pthread_equal() is
  19960. ** not an atomic operation, then these routines might delivery
  19961. ** incorrect results. On most platforms, pthread_equal() is a
  19962. ** comparison of two integers and is therefore atomic. But we are
  19963. ** told that HPUX is not such a platform. If so, then these routines
  19964. ** will not always work correctly on HPUX.
  19965. **
  19966. ** On those platforms where pthread_equal() is not atomic, SQLite
  19967. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  19968. ** make sure no assert() statements are evaluated and hence these
  19969. ** routines are never called.
  19970. */
  19971. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  19972. static int pthreadMutexHeld(sqlite3_mutex *p){
  19973. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  19974. }
  19975. static int pthreadMutexNotheld(sqlite3_mutex *p){
  19976. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  19977. }
  19978. #endif
  19979. /*
  19980. ** Try to provide a memory barrier operation, needed for initialization
  19981. ** and also for the implementation of xShmBarrier in the VFS in cases
  19982. ** where SQLite is compiled without mutexes.
  19983. */
  19984. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  19985. #if defined(SQLITE_MEMORY_BARRIER)
  19986. SQLITE_MEMORY_BARRIER;
  19987. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  19988. __sync_synchronize();
  19989. #endif
  19990. }
  19991. /*
  19992. ** Initialize and deinitialize the mutex subsystem.
  19993. */
  19994. static int pthreadMutexInit(void){ return SQLITE_OK; }
  19995. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  19996. /*
  19997. ** The sqlite3_mutex_alloc() routine allocates a new
  19998. ** mutex and returns a pointer to it. If it returns NULL
  19999. ** that means that a mutex could not be allocated. SQLite
  20000. ** will unwind its stack and return an error. The argument
  20001. ** to sqlite3_mutex_alloc() is one of these integer constants:
  20002. **
  20003. ** <ul>
  20004. ** <li> SQLITE_MUTEX_FAST
  20005. ** <li> SQLITE_MUTEX_RECURSIVE
  20006. ** <li> SQLITE_MUTEX_STATIC_MASTER
  20007. ** <li> SQLITE_MUTEX_STATIC_MEM
  20008. ** <li> SQLITE_MUTEX_STATIC_OPEN
  20009. ** <li> SQLITE_MUTEX_STATIC_PRNG
  20010. ** <li> SQLITE_MUTEX_STATIC_LRU
  20011. ** <li> SQLITE_MUTEX_STATIC_PMEM
  20012. ** <li> SQLITE_MUTEX_STATIC_APP1
  20013. ** <li> SQLITE_MUTEX_STATIC_APP2
  20014. ** <li> SQLITE_MUTEX_STATIC_APP3
  20015. ** <li> SQLITE_MUTEX_STATIC_VFS1
  20016. ** <li> SQLITE_MUTEX_STATIC_VFS2
  20017. ** <li> SQLITE_MUTEX_STATIC_VFS3
  20018. ** </ul>
  20019. **
  20020. ** The first two constants cause sqlite3_mutex_alloc() to create
  20021. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  20022. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  20023. ** The mutex implementation does not need to make a distinction
  20024. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  20025. ** not want to. But SQLite will only request a recursive mutex in
  20026. ** cases where it really needs one. If a faster non-recursive mutex
  20027. ** implementation is available on the host platform, the mutex subsystem
  20028. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  20029. **
  20030. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  20031. ** a pointer to a static preexisting mutex. Six static mutexes are
  20032. ** used by the current version of SQLite. Future versions of SQLite
  20033. ** may add additional static mutexes. Static mutexes are for internal
  20034. ** use by SQLite only. Applications that use SQLite mutexes should
  20035. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  20036. ** SQLITE_MUTEX_RECURSIVE.
  20037. **
  20038. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  20039. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  20040. ** returns a different mutex on every call. But for the static
  20041. ** mutex types, the same mutex is returned on every call that has
  20042. ** the same type number.
  20043. */
  20044. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  20045. static sqlite3_mutex staticMutexes[] = {
  20046. SQLITE3_MUTEX_INITIALIZER,
  20047. SQLITE3_MUTEX_INITIALIZER,
  20048. SQLITE3_MUTEX_INITIALIZER,
  20049. SQLITE3_MUTEX_INITIALIZER,
  20050. SQLITE3_MUTEX_INITIALIZER,
  20051. SQLITE3_MUTEX_INITIALIZER,
  20052. SQLITE3_MUTEX_INITIALIZER,
  20053. SQLITE3_MUTEX_INITIALIZER,
  20054. SQLITE3_MUTEX_INITIALIZER,
  20055. SQLITE3_MUTEX_INITIALIZER,
  20056. SQLITE3_MUTEX_INITIALIZER,
  20057. SQLITE3_MUTEX_INITIALIZER
  20058. };
  20059. sqlite3_mutex *p;
  20060. switch( iType ){
  20061. case SQLITE_MUTEX_RECURSIVE: {
  20062. p = sqlite3MallocZero( sizeof(*p) );
  20063. if( p ){
  20064. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  20065. /* If recursive mutexes are not available, we will have to
  20066. ** build our own. See below. */
  20067. pthread_mutex_init(&p->mutex, 0);
  20068. #else
  20069. /* Use a recursive mutex if it is available */
  20070. pthread_mutexattr_t recursiveAttr;
  20071. pthread_mutexattr_init(&recursiveAttr);
  20072. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  20073. pthread_mutex_init(&p->mutex, &recursiveAttr);
  20074. pthread_mutexattr_destroy(&recursiveAttr);
  20075. #endif
  20076. }
  20077. break;
  20078. }
  20079. case SQLITE_MUTEX_FAST: {
  20080. p = sqlite3MallocZero( sizeof(*p) );
  20081. if( p ){
  20082. pthread_mutex_init(&p->mutex, 0);
  20083. }
  20084. break;
  20085. }
  20086. default: {
  20087. #ifdef SQLITE_ENABLE_API_ARMOR
  20088. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  20089. (void)SQLITE_MISUSE_BKPT;
  20090. return 0;
  20091. }
  20092. #endif
  20093. p = &staticMutexes[iType-2];
  20094. break;
  20095. }
  20096. }
  20097. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  20098. if( p ) p->id = iType;
  20099. #endif
  20100. return p;
  20101. }
  20102. /*
  20103. ** This routine deallocates a previously
  20104. ** allocated mutex. SQLite is careful to deallocate every
  20105. ** mutex that it allocates.
  20106. */
  20107. static void pthreadMutexFree(sqlite3_mutex *p){
  20108. assert( p->nRef==0 );
  20109. #if SQLITE_ENABLE_API_ARMOR
  20110. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  20111. #endif
  20112. {
  20113. pthread_mutex_destroy(&p->mutex);
  20114. sqlite3_free(p);
  20115. }
  20116. #ifdef SQLITE_ENABLE_API_ARMOR
  20117. else{
  20118. (void)SQLITE_MISUSE_BKPT;
  20119. }
  20120. #endif
  20121. }
  20122. /*
  20123. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  20124. ** to enter a mutex. If another thread is already within the mutex,
  20125. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  20126. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  20127. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  20128. ** be entered multiple times by the same thread. In such cases the,
  20129. ** mutex must be exited an equal number of times before another thread
  20130. ** can enter. If the same thread tries to enter any other kind of mutex
  20131. ** more than once, the behavior is undefined.
  20132. */
  20133. static void pthreadMutexEnter(sqlite3_mutex *p){
  20134. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  20135. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  20136. /* If recursive mutexes are not available, then we have to grow
  20137. ** our own. This implementation assumes that pthread_equal()
  20138. ** is atomic - that it cannot be deceived into thinking self
  20139. ** and p->owner are equal if p->owner changes between two values
  20140. ** that are not equal to self while the comparison is taking place.
  20141. ** This implementation also assumes a coherent cache - that
  20142. ** separate processes cannot read different values from the same
  20143. ** address at the same time. If either of these two conditions
  20144. ** are not met, then the mutexes will fail and problems will result.
  20145. */
  20146. {
  20147. pthread_t self = pthread_self();
  20148. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  20149. p->nRef++;
  20150. }else{
  20151. pthread_mutex_lock(&p->mutex);
  20152. assert( p->nRef==0 );
  20153. p->owner = self;
  20154. p->nRef = 1;
  20155. }
  20156. }
  20157. #else
  20158. /* Use the built-in recursive mutexes if they are available.
  20159. */
  20160. pthread_mutex_lock(&p->mutex);
  20161. #if SQLITE_MUTEX_NREF
  20162. assert( p->nRef>0 || p->owner==0 );
  20163. p->owner = pthread_self();
  20164. p->nRef++;
  20165. #endif
  20166. #endif
  20167. #ifdef SQLITE_DEBUG
  20168. if( p->trace ){
  20169. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  20170. }
  20171. #endif
  20172. }
  20173. static int pthreadMutexTry(sqlite3_mutex *p){
  20174. int rc;
  20175. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  20176. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  20177. /* If recursive mutexes are not available, then we have to grow
  20178. ** our own. This implementation assumes that pthread_equal()
  20179. ** is atomic - that it cannot be deceived into thinking self
  20180. ** and p->owner are equal if p->owner changes between two values
  20181. ** that are not equal to self while the comparison is taking place.
  20182. ** This implementation also assumes a coherent cache - that
  20183. ** separate processes cannot read different values from the same
  20184. ** address at the same time. If either of these two conditions
  20185. ** are not met, then the mutexes will fail and problems will result.
  20186. */
  20187. {
  20188. pthread_t self = pthread_self();
  20189. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  20190. p->nRef++;
  20191. rc = SQLITE_OK;
  20192. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  20193. assert( p->nRef==0 );
  20194. p->owner = self;
  20195. p->nRef = 1;
  20196. rc = SQLITE_OK;
  20197. }else{
  20198. rc = SQLITE_BUSY;
  20199. }
  20200. }
  20201. #else
  20202. /* Use the built-in recursive mutexes if they are available.
  20203. */
  20204. if( pthread_mutex_trylock(&p->mutex)==0 ){
  20205. #if SQLITE_MUTEX_NREF
  20206. p->owner = pthread_self();
  20207. p->nRef++;
  20208. #endif
  20209. rc = SQLITE_OK;
  20210. }else{
  20211. rc = SQLITE_BUSY;
  20212. }
  20213. #endif
  20214. #ifdef SQLITE_DEBUG
  20215. if( rc==SQLITE_OK && p->trace ){
  20216. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  20217. }
  20218. #endif
  20219. return rc;
  20220. }
  20221. /*
  20222. ** The sqlite3_mutex_leave() routine exits a mutex that was
  20223. ** previously entered by the same thread. The behavior
  20224. ** is undefined if the mutex is not currently entered or
  20225. ** is not currently allocated. SQLite will never do either.
  20226. */
  20227. static void pthreadMutexLeave(sqlite3_mutex *p){
  20228. assert( pthreadMutexHeld(p) );
  20229. #if SQLITE_MUTEX_NREF
  20230. p->nRef--;
  20231. if( p->nRef==0 ) p->owner = 0;
  20232. #endif
  20233. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  20234. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  20235. if( p->nRef==0 ){
  20236. pthread_mutex_unlock(&p->mutex);
  20237. }
  20238. #else
  20239. pthread_mutex_unlock(&p->mutex);
  20240. #endif
  20241. #ifdef SQLITE_DEBUG
  20242. if( p->trace ){
  20243. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  20244. }
  20245. #endif
  20246. }
  20247. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  20248. static const sqlite3_mutex_methods sMutex = {
  20249. pthreadMutexInit,
  20250. pthreadMutexEnd,
  20251. pthreadMutexAlloc,
  20252. pthreadMutexFree,
  20253. pthreadMutexEnter,
  20254. pthreadMutexTry,
  20255. pthreadMutexLeave,
  20256. #ifdef SQLITE_DEBUG
  20257. pthreadMutexHeld,
  20258. pthreadMutexNotheld
  20259. #else
  20260. 0,
  20261. 0
  20262. #endif
  20263. };
  20264. return &sMutex;
  20265. }
  20266. #endif /* SQLITE_MUTEX_PTHREADS */
  20267. /************** End of mutex_unix.c ******************************************/
  20268. /************** Begin file mutex_w32.c ***************************************/
  20269. /*
  20270. ** 2007 August 14
  20271. **
  20272. ** The author disclaims copyright to this source code. In place of
  20273. ** a legal notice, here is a blessing:
  20274. **
  20275. ** May you do good and not evil.
  20276. ** May you find forgiveness for yourself and forgive others.
  20277. ** May you share freely, never taking more than you give.
  20278. **
  20279. *************************************************************************
  20280. ** This file contains the C functions that implement mutexes for Win32.
  20281. */
  20282. /* #include "sqliteInt.h" */
  20283. #if SQLITE_OS_WIN
  20284. /*
  20285. ** Include code that is common to all os_*.c files
  20286. */
  20287. /************** Include os_common.h in the middle of mutex_w32.c *************/
  20288. /************** Begin file os_common.h ***************************************/
  20289. /*
  20290. ** 2004 May 22
  20291. **
  20292. ** The author disclaims copyright to this source code. In place of
  20293. ** a legal notice, here is a blessing:
  20294. **
  20295. ** May you do good and not evil.
  20296. ** May you find forgiveness for yourself and forgive others.
  20297. ** May you share freely, never taking more than you give.
  20298. **
  20299. ******************************************************************************
  20300. **
  20301. ** This file contains macros and a little bit of code that is common to
  20302. ** all of the platform-specific files (os_*.c) and is #included into those
  20303. ** files.
  20304. **
  20305. ** This file should be #included by the os_*.c files only. It is not a
  20306. ** general purpose header file.
  20307. */
  20308. #ifndef _OS_COMMON_H_
  20309. #define _OS_COMMON_H_
  20310. /*
  20311. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  20312. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  20313. ** switch. The following code should catch this problem at compile-time.
  20314. */
  20315. #ifdef MEMORY_DEBUG
  20316. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  20317. #endif
  20318. /*
  20319. ** Macros for performance tracing. Normally turned off. Only works
  20320. ** on i486 hardware.
  20321. */
  20322. #ifdef SQLITE_PERFORMANCE_TRACE
  20323. /*
  20324. ** hwtime.h contains inline assembler code for implementing
  20325. ** high-performance timing routines.
  20326. */
  20327. /************** Include hwtime.h in the middle of os_common.h ****************/
  20328. /************** Begin file hwtime.h ******************************************/
  20329. /*
  20330. ** 2008 May 27
  20331. **
  20332. ** The author disclaims copyright to this source code. In place of
  20333. ** a legal notice, here is a blessing:
  20334. **
  20335. ** May you do good and not evil.
  20336. ** May you find forgiveness for yourself and forgive others.
  20337. ** May you share freely, never taking more than you give.
  20338. **
  20339. ******************************************************************************
  20340. **
  20341. ** This file contains inline asm code for retrieving "high-performance"
  20342. ** counters for x86 class CPUs.
  20343. */
  20344. #ifndef _HWTIME_H_
  20345. #define _HWTIME_H_
  20346. /*
  20347. ** The following routine only works on pentium-class (or newer) processors.
  20348. ** It uses the RDTSC opcode to read the cycle count value out of the
  20349. ** processor and returns that value. This can be used for high-res
  20350. ** profiling.
  20351. */
  20352. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  20353. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  20354. #if defined(__GNUC__)
  20355. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20356. unsigned int lo, hi;
  20357. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  20358. return (sqlite_uint64)hi << 32 | lo;
  20359. }
  20360. #elif defined(_MSC_VER)
  20361. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  20362. __asm {
  20363. rdtsc
  20364. ret ; return value at EDX:EAX
  20365. }
  20366. }
  20367. #endif
  20368. #elif (defined(__GNUC__) && defined(__x86_64__))
  20369. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20370. unsigned long val;
  20371. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  20372. return val;
  20373. }
  20374. #elif (defined(__GNUC__) && defined(__ppc__))
  20375. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20376. unsigned long long retval;
  20377. unsigned long junk;
  20378. __asm__ __volatile__ ("\n\
  20379. 1: mftbu %1\n\
  20380. mftb %L0\n\
  20381. mftbu %0\n\
  20382. cmpw %0,%1\n\
  20383. bne 1b"
  20384. : "=r" (retval), "=r" (junk));
  20385. return retval;
  20386. }
  20387. #else
  20388. #error Need implementation of sqlite3Hwtime() for your platform.
  20389. /*
  20390. ** To compile without implementing sqlite3Hwtime() for your platform,
  20391. ** you can remove the above #error and use the following
  20392. ** stub function. You will lose timing support for many
  20393. ** of the debugging and testing utilities, but it should at
  20394. ** least compile and run.
  20395. */
  20396. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  20397. #endif
  20398. #endif /* !defined(_HWTIME_H_) */
  20399. /************** End of hwtime.h **********************************************/
  20400. /************** Continuing where we left off in os_common.h ******************/
  20401. static sqlite_uint64 g_start;
  20402. static sqlite_uint64 g_elapsed;
  20403. #define TIMER_START g_start=sqlite3Hwtime()
  20404. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  20405. #define TIMER_ELAPSED g_elapsed
  20406. #else
  20407. #define TIMER_START
  20408. #define TIMER_END
  20409. #define TIMER_ELAPSED ((sqlite_uint64)0)
  20410. #endif
  20411. /*
  20412. ** If we compile with the SQLITE_TEST macro set, then the following block
  20413. ** of code will give us the ability to simulate a disk I/O error. This
  20414. ** is used for testing the I/O recovery logic.
  20415. */
  20416. #if defined(SQLITE_TEST)
  20417. SQLITE_API extern int sqlite3_io_error_hit;
  20418. SQLITE_API extern int sqlite3_io_error_hardhit;
  20419. SQLITE_API extern int sqlite3_io_error_pending;
  20420. SQLITE_API extern int sqlite3_io_error_persist;
  20421. SQLITE_API extern int sqlite3_io_error_benign;
  20422. SQLITE_API extern int sqlite3_diskfull_pending;
  20423. SQLITE_API extern int sqlite3_diskfull;
  20424. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  20425. #define SimulateIOError(CODE) \
  20426. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  20427. || sqlite3_io_error_pending-- == 1 ) \
  20428. { local_ioerr(); CODE; }
  20429. static void local_ioerr(){
  20430. IOTRACE(("IOERR\n"));
  20431. sqlite3_io_error_hit++;
  20432. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  20433. }
  20434. #define SimulateDiskfullError(CODE) \
  20435. if( sqlite3_diskfull_pending ){ \
  20436. if( sqlite3_diskfull_pending == 1 ){ \
  20437. local_ioerr(); \
  20438. sqlite3_diskfull = 1; \
  20439. sqlite3_io_error_hit = 1; \
  20440. CODE; \
  20441. }else{ \
  20442. sqlite3_diskfull_pending--; \
  20443. } \
  20444. }
  20445. #else
  20446. #define SimulateIOErrorBenign(X)
  20447. #define SimulateIOError(A)
  20448. #define SimulateDiskfullError(A)
  20449. #endif /* defined(SQLITE_TEST) */
  20450. /*
  20451. ** When testing, keep a count of the number of open files.
  20452. */
  20453. #if defined(SQLITE_TEST)
  20454. SQLITE_API extern int sqlite3_open_file_count;
  20455. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  20456. #else
  20457. #define OpenCounter(X)
  20458. #endif /* defined(SQLITE_TEST) */
  20459. #endif /* !defined(_OS_COMMON_H_) */
  20460. /************** End of os_common.h *******************************************/
  20461. /************** Continuing where we left off in mutex_w32.c ******************/
  20462. /*
  20463. ** Include the header file for the Windows VFS.
  20464. */
  20465. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  20466. /************** Begin file os_win.h ******************************************/
  20467. /*
  20468. ** 2013 November 25
  20469. **
  20470. ** The author disclaims copyright to this source code. In place of
  20471. ** a legal notice, here is a blessing:
  20472. **
  20473. ** May you do good and not evil.
  20474. ** May you find forgiveness for yourself and forgive others.
  20475. ** May you share freely, never taking more than you give.
  20476. **
  20477. ******************************************************************************
  20478. **
  20479. ** This file contains code that is specific to Windows.
  20480. */
  20481. #ifndef _OS_WIN_H_
  20482. #define _OS_WIN_H_
  20483. /*
  20484. ** Include the primary Windows SDK header file.
  20485. */
  20486. #include "windows.h"
  20487. #ifdef __CYGWIN__
  20488. # include <sys/cygwin.h>
  20489. # include <errno.h> /* amalgamator: dontcache */
  20490. #endif
  20491. /*
  20492. ** Determine if we are dealing with Windows NT.
  20493. **
  20494. ** We ought to be able to determine if we are compiling for Windows 9x or
  20495. ** Windows NT using the _WIN32_WINNT macro as follows:
  20496. **
  20497. ** #if defined(_WIN32_WINNT)
  20498. ** # define SQLITE_OS_WINNT 1
  20499. ** #else
  20500. ** # define SQLITE_OS_WINNT 0
  20501. ** #endif
  20502. **
  20503. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  20504. ** it ought to, so the above test does not work. We'll just assume that
  20505. ** everything is Windows NT unless the programmer explicitly says otherwise
  20506. ** by setting SQLITE_OS_WINNT to 0.
  20507. */
  20508. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  20509. # define SQLITE_OS_WINNT 1
  20510. #endif
  20511. /*
  20512. ** Determine if we are dealing with Windows CE - which has a much reduced
  20513. ** API.
  20514. */
  20515. #if defined(_WIN32_WCE)
  20516. # define SQLITE_OS_WINCE 1
  20517. #else
  20518. # define SQLITE_OS_WINCE 0
  20519. #endif
  20520. /*
  20521. ** Determine if we are dealing with WinRT, which provides only a subset of
  20522. ** the full Win32 API.
  20523. */
  20524. #if !defined(SQLITE_OS_WINRT)
  20525. # define SQLITE_OS_WINRT 0
  20526. #endif
  20527. /*
  20528. ** For WinCE, some API function parameters do not appear to be declared as
  20529. ** volatile.
  20530. */
  20531. #if SQLITE_OS_WINCE
  20532. # define SQLITE_WIN32_VOLATILE
  20533. #else
  20534. # define SQLITE_WIN32_VOLATILE volatile
  20535. #endif
  20536. /*
  20537. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  20538. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  20539. */
  20540. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  20541. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  20542. # define SQLITE_OS_WIN_THREADS 1
  20543. #else
  20544. # define SQLITE_OS_WIN_THREADS 0
  20545. #endif
  20546. #endif /* _OS_WIN_H_ */
  20547. /************** End of os_win.h **********************************************/
  20548. /************** Continuing where we left off in mutex_w32.c ******************/
  20549. #endif
  20550. /*
  20551. ** The code in this file is only used if we are compiling multithreaded
  20552. ** on a Win32 system.
  20553. */
  20554. #ifdef SQLITE_MUTEX_W32
  20555. /*
  20556. ** Each recursive mutex is an instance of the following structure.
  20557. */
  20558. struct sqlite3_mutex {
  20559. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  20560. int id; /* Mutex type */
  20561. #ifdef SQLITE_DEBUG
  20562. volatile int nRef; /* Number of enterances */
  20563. volatile DWORD owner; /* Thread holding this mutex */
  20564. volatile int trace; /* True to trace changes */
  20565. #endif
  20566. };
  20567. /*
  20568. ** These are the initializer values used when declaring a "static" mutex
  20569. ** on Win32. It should be noted that all mutexes require initialization
  20570. ** on the Win32 platform.
  20571. */
  20572. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  20573. #ifdef SQLITE_DEBUG
  20574. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  20575. 0L, (DWORD)0, 0 }
  20576. #else
  20577. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  20578. #endif
  20579. #ifdef SQLITE_DEBUG
  20580. /*
  20581. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  20582. ** intended for use only inside assert() statements.
  20583. */
  20584. static int winMutexHeld(sqlite3_mutex *p){
  20585. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  20586. }
  20587. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  20588. return p->nRef==0 || p->owner!=tid;
  20589. }
  20590. static int winMutexNotheld(sqlite3_mutex *p){
  20591. DWORD tid = GetCurrentThreadId();
  20592. return winMutexNotheld2(p, tid);
  20593. }
  20594. #endif
  20595. /*
  20596. ** Try to provide a memory barrier operation, needed for initialization
  20597. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  20598. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  20599. */
  20600. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  20601. #if defined(SQLITE_MEMORY_BARRIER)
  20602. SQLITE_MEMORY_BARRIER;
  20603. #elif defined(__GNUC__)
  20604. __sync_synchronize();
  20605. #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
  20606. defined(_MSC_VER) && _MSC_VER>=1300
  20607. _ReadWriteBarrier();
  20608. #elif defined(MemoryBarrier)
  20609. MemoryBarrier();
  20610. #endif
  20611. }
  20612. /*
  20613. ** Initialize and deinitialize the mutex subsystem.
  20614. */
  20615. static sqlite3_mutex winMutex_staticMutexes[] = {
  20616. SQLITE3_MUTEX_INITIALIZER,
  20617. SQLITE3_MUTEX_INITIALIZER,
  20618. SQLITE3_MUTEX_INITIALIZER,
  20619. SQLITE3_MUTEX_INITIALIZER,
  20620. SQLITE3_MUTEX_INITIALIZER,
  20621. SQLITE3_MUTEX_INITIALIZER,
  20622. SQLITE3_MUTEX_INITIALIZER,
  20623. SQLITE3_MUTEX_INITIALIZER,
  20624. SQLITE3_MUTEX_INITIALIZER,
  20625. SQLITE3_MUTEX_INITIALIZER,
  20626. SQLITE3_MUTEX_INITIALIZER,
  20627. SQLITE3_MUTEX_INITIALIZER
  20628. };
  20629. static int winMutex_isInit = 0;
  20630. static int winMutex_isNt = -1; /* <0 means "need to query" */
  20631. /* As the winMutexInit() and winMutexEnd() functions are called as part
  20632. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  20633. ** "interlocked" magic used here is probably not strictly necessary.
  20634. */
  20635. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  20636. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
  20637. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  20638. static int winMutexInit(void){
  20639. /* The first to increment to 1 does actual initialization */
  20640. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  20641. int i;
  20642. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  20643. #if SQLITE_OS_WINRT
  20644. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  20645. #else
  20646. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  20647. #endif
  20648. }
  20649. winMutex_isInit = 1;
  20650. }else{
  20651. /* Another thread is (in the process of) initializing the static
  20652. ** mutexes */
  20653. while( !winMutex_isInit ){
  20654. sqlite3_win32_sleep(1);
  20655. }
  20656. }
  20657. return SQLITE_OK;
  20658. }
  20659. static int winMutexEnd(void){
  20660. /* The first to decrement to 0 does actual shutdown
  20661. ** (which should be the last to shutdown.) */
  20662. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  20663. if( winMutex_isInit==1 ){
  20664. int i;
  20665. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  20666. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  20667. }
  20668. winMutex_isInit = 0;
  20669. }
  20670. }
  20671. return SQLITE_OK;
  20672. }
  20673. /*
  20674. ** The sqlite3_mutex_alloc() routine allocates a new
  20675. ** mutex and returns a pointer to it. If it returns NULL
  20676. ** that means that a mutex could not be allocated. SQLite
  20677. ** will unwind its stack and return an error. The argument
  20678. ** to sqlite3_mutex_alloc() is one of these integer constants:
  20679. **
  20680. ** <ul>
  20681. ** <li> SQLITE_MUTEX_FAST
  20682. ** <li> SQLITE_MUTEX_RECURSIVE
  20683. ** <li> SQLITE_MUTEX_STATIC_MASTER
  20684. ** <li> SQLITE_MUTEX_STATIC_MEM
  20685. ** <li> SQLITE_MUTEX_STATIC_OPEN
  20686. ** <li> SQLITE_MUTEX_STATIC_PRNG
  20687. ** <li> SQLITE_MUTEX_STATIC_LRU
  20688. ** <li> SQLITE_MUTEX_STATIC_PMEM
  20689. ** <li> SQLITE_MUTEX_STATIC_APP1
  20690. ** <li> SQLITE_MUTEX_STATIC_APP2
  20691. ** <li> SQLITE_MUTEX_STATIC_APP3
  20692. ** <li> SQLITE_MUTEX_STATIC_VFS1
  20693. ** <li> SQLITE_MUTEX_STATIC_VFS2
  20694. ** <li> SQLITE_MUTEX_STATIC_VFS3
  20695. ** </ul>
  20696. **
  20697. ** The first two constants cause sqlite3_mutex_alloc() to create
  20698. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  20699. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  20700. ** The mutex implementation does not need to make a distinction
  20701. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  20702. ** not want to. But SQLite will only request a recursive mutex in
  20703. ** cases where it really needs one. If a faster non-recursive mutex
  20704. ** implementation is available on the host platform, the mutex subsystem
  20705. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  20706. **
  20707. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  20708. ** a pointer to a static preexisting mutex. Six static mutexes are
  20709. ** used by the current version of SQLite. Future versions of SQLite
  20710. ** may add additional static mutexes. Static mutexes are for internal
  20711. ** use by SQLite only. Applications that use SQLite mutexes should
  20712. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  20713. ** SQLITE_MUTEX_RECURSIVE.
  20714. **
  20715. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  20716. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  20717. ** returns a different mutex on every call. But for the static
  20718. ** mutex types, the same mutex is returned on every call that has
  20719. ** the same type number.
  20720. */
  20721. static sqlite3_mutex *winMutexAlloc(int iType){
  20722. sqlite3_mutex *p;
  20723. switch( iType ){
  20724. case SQLITE_MUTEX_FAST:
  20725. case SQLITE_MUTEX_RECURSIVE: {
  20726. p = sqlite3MallocZero( sizeof(*p) );
  20727. if( p ){
  20728. p->id = iType;
  20729. #ifdef SQLITE_DEBUG
  20730. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  20731. p->trace = 1;
  20732. #endif
  20733. #endif
  20734. #if SQLITE_OS_WINRT
  20735. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  20736. #else
  20737. InitializeCriticalSection(&p->mutex);
  20738. #endif
  20739. }
  20740. break;
  20741. }
  20742. default: {
  20743. #ifdef SQLITE_ENABLE_API_ARMOR
  20744. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  20745. (void)SQLITE_MISUSE_BKPT;
  20746. return 0;
  20747. }
  20748. #endif
  20749. p = &winMutex_staticMutexes[iType-2];
  20750. p->id = iType;
  20751. #ifdef SQLITE_DEBUG
  20752. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  20753. p->trace = 1;
  20754. #endif
  20755. #endif
  20756. break;
  20757. }
  20758. }
  20759. return p;
  20760. }
  20761. /*
  20762. ** This routine deallocates a previously
  20763. ** allocated mutex. SQLite is careful to deallocate every
  20764. ** mutex that it allocates.
  20765. */
  20766. static void winMutexFree(sqlite3_mutex *p){
  20767. assert( p );
  20768. assert( p->nRef==0 && p->owner==0 );
  20769. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  20770. DeleteCriticalSection(&p->mutex);
  20771. sqlite3_free(p);
  20772. }else{
  20773. #ifdef SQLITE_ENABLE_API_ARMOR
  20774. (void)SQLITE_MISUSE_BKPT;
  20775. #endif
  20776. }
  20777. }
  20778. /*
  20779. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  20780. ** to enter a mutex. If another thread is already within the mutex,
  20781. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  20782. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  20783. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  20784. ** be entered multiple times by the same thread. In such cases the,
  20785. ** mutex must be exited an equal number of times before another thread
  20786. ** can enter. If the same thread tries to enter any other kind of mutex
  20787. ** more than once, the behavior is undefined.
  20788. */
  20789. static void winMutexEnter(sqlite3_mutex *p){
  20790. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20791. DWORD tid = GetCurrentThreadId();
  20792. #endif
  20793. #ifdef SQLITE_DEBUG
  20794. assert( p );
  20795. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  20796. #else
  20797. assert( p );
  20798. #endif
  20799. assert( winMutex_isInit==1 );
  20800. EnterCriticalSection(&p->mutex);
  20801. #ifdef SQLITE_DEBUG
  20802. assert( p->nRef>0 || p->owner==0 );
  20803. p->owner = tid;
  20804. p->nRef++;
  20805. if( p->trace ){
  20806. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  20807. tid, p, p->trace, p->nRef));
  20808. }
  20809. #endif
  20810. }
  20811. static int winMutexTry(sqlite3_mutex *p){
  20812. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20813. DWORD tid = GetCurrentThreadId();
  20814. #endif
  20815. int rc = SQLITE_BUSY;
  20816. assert( p );
  20817. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  20818. /*
  20819. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  20820. ** is used it is merely an optimization. So it is OK for it to always
  20821. ** fail.
  20822. **
  20823. ** The TryEnterCriticalSection() interface is only available on WinNT.
  20824. ** And some windows compilers complain if you try to use it without
  20825. ** first doing some #defines that prevent SQLite from building on Win98.
  20826. ** For that reason, we will omit this optimization for now. See
  20827. ** ticket #2685.
  20828. */
  20829. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  20830. assert( winMutex_isInit==1 );
  20831. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  20832. if( winMutex_isNt<0 ){
  20833. winMutex_isNt = sqlite3_win32_is_nt();
  20834. }
  20835. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  20836. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  20837. #ifdef SQLITE_DEBUG
  20838. p->owner = tid;
  20839. p->nRef++;
  20840. #endif
  20841. rc = SQLITE_OK;
  20842. }
  20843. #else
  20844. UNUSED_PARAMETER(p);
  20845. #endif
  20846. #ifdef SQLITE_DEBUG
  20847. if( p->trace ){
  20848. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  20849. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  20850. }
  20851. #endif
  20852. return rc;
  20853. }
  20854. /*
  20855. ** The sqlite3_mutex_leave() routine exits a mutex that was
  20856. ** previously entered by the same thread. The behavior
  20857. ** is undefined if the mutex is not currently entered or
  20858. ** is not currently allocated. SQLite will never do either.
  20859. */
  20860. static void winMutexLeave(sqlite3_mutex *p){
  20861. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20862. DWORD tid = GetCurrentThreadId();
  20863. #endif
  20864. assert( p );
  20865. #ifdef SQLITE_DEBUG
  20866. assert( p->nRef>0 );
  20867. assert( p->owner==tid );
  20868. p->nRef--;
  20869. if( p->nRef==0 ) p->owner = 0;
  20870. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  20871. #endif
  20872. assert( winMutex_isInit==1 );
  20873. LeaveCriticalSection(&p->mutex);
  20874. #ifdef SQLITE_DEBUG
  20875. if( p->trace ){
  20876. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  20877. tid, p, p->trace, p->nRef));
  20878. }
  20879. #endif
  20880. }
  20881. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  20882. static const sqlite3_mutex_methods sMutex = {
  20883. winMutexInit,
  20884. winMutexEnd,
  20885. winMutexAlloc,
  20886. winMutexFree,
  20887. winMutexEnter,
  20888. winMutexTry,
  20889. winMutexLeave,
  20890. #ifdef SQLITE_DEBUG
  20891. winMutexHeld,
  20892. winMutexNotheld
  20893. #else
  20894. 0,
  20895. 0
  20896. #endif
  20897. };
  20898. return &sMutex;
  20899. }
  20900. #endif /* SQLITE_MUTEX_W32 */
  20901. /************** End of mutex_w32.c *******************************************/
  20902. /************** Begin file malloc.c ******************************************/
  20903. /*
  20904. ** 2001 September 15
  20905. **
  20906. ** The author disclaims copyright to this source code. In place of
  20907. ** a legal notice, here is a blessing:
  20908. **
  20909. ** May you do good and not evil.
  20910. ** May you find forgiveness for yourself and forgive others.
  20911. ** May you share freely, never taking more than you give.
  20912. **
  20913. *************************************************************************
  20914. **
  20915. ** Memory allocation functions used throughout sqlite.
  20916. */
  20917. /* #include "sqliteInt.h" */
  20918. /* #include <stdarg.h> */
  20919. /*
  20920. ** Attempt to release up to n bytes of non-essential memory currently
  20921. ** held by SQLite. An example of non-essential memory is memory used to
  20922. ** cache database pages that are not currently in use.
  20923. */
  20924. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
  20925. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  20926. return sqlite3PcacheReleaseMemory(n);
  20927. #else
  20928. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  20929. ** is a no-op returning zero if SQLite is not compiled with
  20930. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  20931. UNUSED_PARAMETER(n);
  20932. return 0;
  20933. #endif
  20934. }
  20935. /*
  20936. ** An instance of the following object records the location of
  20937. ** each unused scratch buffer.
  20938. */
  20939. typedef struct ScratchFreeslot {
  20940. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  20941. } ScratchFreeslot;
  20942. /*
  20943. ** State information local to the memory allocation subsystem.
  20944. */
  20945. static SQLITE_WSD struct Mem0Global {
  20946. sqlite3_mutex *mutex; /* Mutex to serialize access */
  20947. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  20948. /*
  20949. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  20950. ** (so that a range test can be used to determine if an allocation
  20951. ** being freed came from pScratch) and a pointer to the list of
  20952. ** unused scratch allocations.
  20953. */
  20954. void *pScratchEnd;
  20955. ScratchFreeslot *pScratchFree;
  20956. u32 nScratchFree;
  20957. /*
  20958. ** True if heap is nearly "full" where "full" is defined by the
  20959. ** sqlite3_soft_heap_limit() setting.
  20960. */
  20961. int nearlyFull;
  20962. } mem0 = { 0, 0, 0, 0, 0, 0 };
  20963. #define mem0 GLOBAL(struct Mem0Global, mem0)
  20964. /*
  20965. ** Return the memory allocator mutex. sqlite3_status() needs it.
  20966. */
  20967. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  20968. return mem0.mutex;
  20969. }
  20970. #ifndef SQLITE_OMIT_DEPRECATED
  20971. /*
  20972. ** Deprecated external interface. It used to set an alarm callback
  20973. ** that was invoked when memory usage grew too large. Now it is a
  20974. ** no-op.
  20975. */
  20976. SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
  20977. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  20978. void *pArg,
  20979. sqlite3_int64 iThreshold
  20980. ){
  20981. (void)xCallback;
  20982. (void)pArg;
  20983. (void)iThreshold;
  20984. return SQLITE_OK;
  20985. }
  20986. #endif
  20987. /*
  20988. ** Set the soft heap-size limit for the library. Passing a zero or
  20989. ** negative value indicates no limit.
  20990. */
  20991. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
  20992. sqlite3_int64 priorLimit;
  20993. sqlite3_int64 excess;
  20994. sqlite3_int64 nUsed;
  20995. #ifndef SQLITE_OMIT_AUTOINIT
  20996. int rc = sqlite3_initialize();
  20997. if( rc ) return -1;
  20998. #endif
  20999. sqlite3_mutex_enter(mem0.mutex);
  21000. priorLimit = mem0.alarmThreshold;
  21001. if( n<0 ){
  21002. sqlite3_mutex_leave(mem0.mutex);
  21003. return priorLimit;
  21004. }
  21005. mem0.alarmThreshold = n;
  21006. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  21007. mem0.nearlyFull = (n>0 && n<=nUsed);
  21008. sqlite3_mutex_leave(mem0.mutex);
  21009. excess = sqlite3_memory_used() - n;
  21010. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  21011. return priorLimit;
  21012. }
  21013. SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
  21014. if( n<0 ) n = 0;
  21015. sqlite3_soft_heap_limit64(n);
  21016. }
  21017. /*
  21018. ** Initialize the memory allocation subsystem.
  21019. */
  21020. SQLITE_PRIVATE int sqlite3MallocInit(void){
  21021. int rc;
  21022. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  21023. sqlite3MemSetDefault();
  21024. }
  21025. memset(&mem0, 0, sizeof(mem0));
  21026. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21027. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  21028. && sqlite3GlobalConfig.nScratch>0 ){
  21029. int i, n, sz;
  21030. ScratchFreeslot *pSlot;
  21031. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  21032. sqlite3GlobalConfig.szScratch = sz;
  21033. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  21034. n = sqlite3GlobalConfig.nScratch;
  21035. mem0.pScratchFree = pSlot;
  21036. mem0.nScratchFree = n;
  21037. for(i=0; i<n-1; i++){
  21038. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  21039. pSlot = pSlot->pNext;
  21040. }
  21041. pSlot->pNext = 0;
  21042. mem0.pScratchEnd = (void*)&pSlot[1];
  21043. }else{
  21044. mem0.pScratchEnd = 0;
  21045. sqlite3GlobalConfig.pScratch = 0;
  21046. sqlite3GlobalConfig.szScratch = 0;
  21047. sqlite3GlobalConfig.nScratch = 0;
  21048. }
  21049. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  21050. || sqlite3GlobalConfig.nPage<=0 ){
  21051. sqlite3GlobalConfig.pPage = 0;
  21052. sqlite3GlobalConfig.szPage = 0;
  21053. }
  21054. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  21055. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  21056. return rc;
  21057. }
  21058. /*
  21059. ** Return true if the heap is currently under memory pressure - in other
  21060. ** words if the amount of heap used is close to the limit set by
  21061. ** sqlite3_soft_heap_limit().
  21062. */
  21063. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  21064. return mem0.nearlyFull;
  21065. }
  21066. /*
  21067. ** Deinitialize the memory allocation subsystem.
  21068. */
  21069. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  21070. if( sqlite3GlobalConfig.m.xShutdown ){
  21071. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  21072. }
  21073. memset(&mem0, 0, sizeof(mem0));
  21074. }
  21075. /*
  21076. ** Return the amount of memory currently checked out.
  21077. */
  21078. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
  21079. sqlite3_int64 res, mx;
  21080. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  21081. return res;
  21082. }
  21083. /*
  21084. ** Return the maximum amount of memory that has ever been
  21085. ** checked out since either the beginning of this process
  21086. ** or since the most recent reset.
  21087. */
  21088. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
  21089. sqlite3_int64 res, mx;
  21090. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  21091. return mx;
  21092. }
  21093. /*
  21094. ** Trigger the alarm
  21095. */
  21096. static void sqlite3MallocAlarm(int nByte){
  21097. if( mem0.alarmThreshold<=0 ) return;
  21098. sqlite3_mutex_leave(mem0.mutex);
  21099. sqlite3_release_memory(nByte);
  21100. sqlite3_mutex_enter(mem0.mutex);
  21101. }
  21102. /*
  21103. ** Do a memory allocation with statistics and alarms. Assume the
  21104. ** lock is already held.
  21105. */
  21106. static int mallocWithAlarm(int n, void **pp){
  21107. int nFull;
  21108. void *p;
  21109. assert( sqlite3_mutex_held(mem0.mutex) );
  21110. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  21111. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  21112. if( mem0.alarmThreshold>0 ){
  21113. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  21114. if( nUsed >= mem0.alarmThreshold - nFull ){
  21115. mem0.nearlyFull = 1;
  21116. sqlite3MallocAlarm(nFull);
  21117. }else{
  21118. mem0.nearlyFull = 0;
  21119. }
  21120. }
  21121. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  21122. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  21123. if( p==0 && mem0.alarmThreshold>0 ){
  21124. sqlite3MallocAlarm(nFull);
  21125. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  21126. }
  21127. #endif
  21128. if( p ){
  21129. nFull = sqlite3MallocSize(p);
  21130. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  21131. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  21132. }
  21133. *pp = p;
  21134. return nFull;
  21135. }
  21136. /*
  21137. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  21138. ** assumes the memory subsystem has already been initialized.
  21139. */
  21140. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  21141. void *p;
  21142. if( n==0 || n>=0x7fffff00 ){
  21143. /* A memory allocation of a number of bytes which is near the maximum
  21144. ** signed integer value might cause an integer overflow inside of the
  21145. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  21146. ** 255 bytes of overhead. SQLite itself will never use anything near
  21147. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  21148. p = 0;
  21149. }else if( sqlite3GlobalConfig.bMemstat ){
  21150. sqlite3_mutex_enter(mem0.mutex);
  21151. mallocWithAlarm((int)n, &p);
  21152. sqlite3_mutex_leave(mem0.mutex);
  21153. }else{
  21154. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  21155. }
  21156. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  21157. return p;
  21158. }
  21159. /*
  21160. ** This version of the memory allocation is for use by the application.
  21161. ** First make sure the memory subsystem is initialized, then do the
  21162. ** allocation.
  21163. */
  21164. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
  21165. #ifndef SQLITE_OMIT_AUTOINIT
  21166. if( sqlite3_initialize() ) return 0;
  21167. #endif
  21168. return n<=0 ? 0 : sqlite3Malloc(n);
  21169. }
  21170. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
  21171. #ifndef SQLITE_OMIT_AUTOINIT
  21172. if( sqlite3_initialize() ) return 0;
  21173. #endif
  21174. return sqlite3Malloc(n);
  21175. }
  21176. /*
  21177. ** Each thread may only have a single outstanding allocation from
  21178. ** xScratchMalloc(). We verify this constraint in the single-threaded
  21179. ** case by setting scratchAllocOut to 1 when an allocation
  21180. ** is outstanding clearing it when the allocation is freed.
  21181. */
  21182. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  21183. static int scratchAllocOut = 0;
  21184. #endif
  21185. /*
  21186. ** Allocate memory that is to be used and released right away.
  21187. ** This routine is similar to alloca() in that it is not intended
  21188. ** for situations where the memory might be held long-term. This
  21189. ** routine is intended to get memory to old large transient data
  21190. ** structures that would not normally fit on the stack of an
  21191. ** embedded processor.
  21192. */
  21193. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  21194. void *p;
  21195. assert( n>0 );
  21196. sqlite3_mutex_enter(mem0.mutex);
  21197. sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
  21198. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  21199. p = mem0.pScratchFree;
  21200. mem0.pScratchFree = mem0.pScratchFree->pNext;
  21201. mem0.nScratchFree--;
  21202. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  21203. sqlite3_mutex_leave(mem0.mutex);
  21204. }else{
  21205. sqlite3_mutex_leave(mem0.mutex);
  21206. p = sqlite3Malloc(n);
  21207. if( sqlite3GlobalConfig.bMemstat && p ){
  21208. sqlite3_mutex_enter(mem0.mutex);
  21209. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  21210. sqlite3_mutex_leave(mem0.mutex);
  21211. }
  21212. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  21213. }
  21214. assert( sqlite3_mutex_notheld(mem0.mutex) );
  21215. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  21216. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  21217. ** buffers per thread.
  21218. **
  21219. ** This can only be checked in single-threaded mode.
  21220. */
  21221. assert( scratchAllocOut==0 );
  21222. if( p ) scratchAllocOut++;
  21223. #endif
  21224. return p;
  21225. }
  21226. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  21227. if( p ){
  21228. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  21229. /* Verify that no more than two scratch allocation per thread
  21230. ** is outstanding at one time. (This is only checked in the
  21231. ** single-threaded case since checking in the multi-threaded case
  21232. ** would be much more complicated.) */
  21233. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  21234. scratchAllocOut--;
  21235. #endif
  21236. if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
  21237. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  21238. ScratchFreeslot *pSlot;
  21239. pSlot = (ScratchFreeslot*)p;
  21240. sqlite3_mutex_enter(mem0.mutex);
  21241. pSlot->pNext = mem0.pScratchFree;
  21242. mem0.pScratchFree = pSlot;
  21243. mem0.nScratchFree++;
  21244. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  21245. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  21246. sqlite3_mutex_leave(mem0.mutex);
  21247. }else{
  21248. /* Release memory back to the heap */
  21249. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  21250. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  21251. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  21252. if( sqlite3GlobalConfig.bMemstat ){
  21253. int iSize = sqlite3MallocSize(p);
  21254. sqlite3_mutex_enter(mem0.mutex);
  21255. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  21256. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  21257. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  21258. sqlite3GlobalConfig.m.xFree(p);
  21259. sqlite3_mutex_leave(mem0.mutex);
  21260. }else{
  21261. sqlite3GlobalConfig.m.xFree(p);
  21262. }
  21263. }
  21264. }
  21265. }
  21266. /*
  21267. ** TRUE if p is a lookaside memory allocation from db
  21268. */
  21269. #ifndef SQLITE_OMIT_LOOKASIDE
  21270. static int isLookaside(sqlite3 *db, void *p){
  21271. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  21272. }
  21273. #else
  21274. #define isLookaside(A,B) 0
  21275. #endif
  21276. /*
  21277. ** Return the size of a memory allocation previously obtained from
  21278. ** sqlite3Malloc() or sqlite3_malloc().
  21279. */
  21280. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  21281. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21282. return sqlite3GlobalConfig.m.xSize(p);
  21283. }
  21284. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  21285. assert( p!=0 );
  21286. if( db==0 || !isLookaside(db,p) ){
  21287. #if SQLITE_DEBUG
  21288. if( db==0 ){
  21289. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  21290. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21291. }else{
  21292. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21293. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21294. }
  21295. #endif
  21296. return sqlite3GlobalConfig.m.xSize(p);
  21297. }else{
  21298. assert( sqlite3_mutex_held(db->mutex) );
  21299. return db->lookaside.sz;
  21300. }
  21301. }
  21302. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
  21303. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  21304. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21305. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  21306. }
  21307. /*
  21308. ** Free memory previously obtained from sqlite3Malloc().
  21309. */
  21310. SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
  21311. if( p==0 ) return; /* IMP: R-49053-54554 */
  21312. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21313. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  21314. if( sqlite3GlobalConfig.bMemstat ){
  21315. sqlite3_mutex_enter(mem0.mutex);
  21316. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  21317. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  21318. sqlite3GlobalConfig.m.xFree(p);
  21319. sqlite3_mutex_leave(mem0.mutex);
  21320. }else{
  21321. sqlite3GlobalConfig.m.xFree(p);
  21322. }
  21323. }
  21324. /*
  21325. ** Add the size of memory allocation "p" to the count in
  21326. ** *db->pnBytesFreed.
  21327. */
  21328. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  21329. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  21330. }
  21331. /*
  21332. ** Free memory that might be associated with a particular database
  21333. ** connection.
  21334. */
  21335. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  21336. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  21337. if( p==0 ) return;
  21338. if( db ){
  21339. if( db->pnBytesFreed ){
  21340. measureAllocationSize(db, p);
  21341. return;
  21342. }
  21343. if( isLookaside(db, p) ){
  21344. LookasideSlot *pBuf = (LookasideSlot*)p;
  21345. #if SQLITE_DEBUG
  21346. /* Trash all content in the buffer being freed */
  21347. memset(p, 0xaa, db->lookaside.sz);
  21348. #endif
  21349. pBuf->pNext = db->lookaside.pFree;
  21350. db->lookaside.pFree = pBuf;
  21351. db->lookaside.nOut--;
  21352. return;
  21353. }
  21354. }
  21355. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21356. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21357. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  21358. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  21359. sqlite3_free(p);
  21360. }
  21361. /*
  21362. ** Change the size of an existing memory allocation
  21363. */
  21364. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  21365. int nOld, nNew, nDiff;
  21366. void *pNew;
  21367. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  21368. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  21369. if( pOld==0 ){
  21370. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  21371. }
  21372. if( nBytes==0 ){
  21373. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  21374. return 0;
  21375. }
  21376. if( nBytes>=0x7fffff00 ){
  21377. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  21378. return 0;
  21379. }
  21380. nOld = sqlite3MallocSize(pOld);
  21381. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  21382. ** argument to xRealloc is always a value returned by a prior call to
  21383. ** xRoundup. */
  21384. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  21385. if( nOld==nNew ){
  21386. pNew = pOld;
  21387. }else if( sqlite3GlobalConfig.bMemstat ){
  21388. sqlite3_mutex_enter(mem0.mutex);
  21389. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  21390. nDiff = nNew - nOld;
  21391. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  21392. mem0.alarmThreshold-nDiff ){
  21393. sqlite3MallocAlarm(nDiff);
  21394. }
  21395. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  21396. if( pNew==0 && mem0.alarmThreshold>0 ){
  21397. sqlite3MallocAlarm((int)nBytes);
  21398. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  21399. }
  21400. if( pNew ){
  21401. nNew = sqlite3MallocSize(pNew);
  21402. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  21403. }
  21404. sqlite3_mutex_leave(mem0.mutex);
  21405. }else{
  21406. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  21407. }
  21408. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  21409. return pNew;
  21410. }
  21411. /*
  21412. ** The public interface to sqlite3Realloc. Make sure that the memory
  21413. ** subsystem is initialized prior to invoking sqliteRealloc.
  21414. */
  21415. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
  21416. #ifndef SQLITE_OMIT_AUTOINIT
  21417. if( sqlite3_initialize() ) return 0;
  21418. #endif
  21419. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  21420. return sqlite3Realloc(pOld, n);
  21421. }
  21422. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  21423. #ifndef SQLITE_OMIT_AUTOINIT
  21424. if( sqlite3_initialize() ) return 0;
  21425. #endif
  21426. return sqlite3Realloc(pOld, n);
  21427. }
  21428. /*
  21429. ** Allocate and zero memory.
  21430. */
  21431. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  21432. void *p = sqlite3Malloc(n);
  21433. if( p ){
  21434. memset(p, 0, (size_t)n);
  21435. }
  21436. return p;
  21437. }
  21438. /*
  21439. ** Allocate and zero memory. If the allocation fails, make
  21440. ** the mallocFailed flag in the connection pointer.
  21441. */
  21442. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  21443. void *p;
  21444. testcase( db==0 );
  21445. p = sqlite3DbMallocRaw(db, n);
  21446. if( p ) memset(p, 0, (size_t)n);
  21447. return p;
  21448. }
  21449. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  21450. ** slower case when the allocation cannot be fulfilled using lookaside.
  21451. */
  21452. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  21453. void *p;
  21454. assert( db!=0 );
  21455. p = sqlite3Malloc(n);
  21456. if( !p ) sqlite3OomFault(db);
  21457. sqlite3MemdebugSetType(p,
  21458. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  21459. return p;
  21460. }
  21461. /*
  21462. ** Allocate memory, either lookaside (if possible) or heap.
  21463. ** If the allocation fails, set the mallocFailed flag in
  21464. ** the connection pointer.
  21465. **
  21466. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  21467. ** failure on the same database connection) then always return 0.
  21468. ** Hence for a particular database connection, once malloc starts
  21469. ** failing, it fails consistently until mallocFailed is reset.
  21470. ** This is an important assumption. There are many places in the
  21471. ** code that do things like this:
  21472. **
  21473. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  21474. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  21475. ** if( b ) a[10] = 9;
  21476. **
  21477. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  21478. ** that all prior mallocs (ex: "a") worked too.
  21479. **
  21480. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  21481. ** not a NULL pointer.
  21482. */
  21483. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  21484. void *p;
  21485. if( db ) return sqlite3DbMallocRawNN(db, n);
  21486. p = sqlite3Malloc(n);
  21487. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  21488. return p;
  21489. }
  21490. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  21491. #ifndef SQLITE_OMIT_LOOKASIDE
  21492. LookasideSlot *pBuf;
  21493. assert( db!=0 );
  21494. assert( sqlite3_mutex_held(db->mutex) );
  21495. assert( db->pnBytesFreed==0 );
  21496. if( db->lookaside.bDisable==0 ){
  21497. assert( db->mallocFailed==0 );
  21498. if( n>db->lookaside.sz ){
  21499. db->lookaside.anStat[1]++;
  21500. }else if( (pBuf = db->lookaside.pFree)==0 ){
  21501. db->lookaside.anStat[2]++;
  21502. }else{
  21503. db->lookaside.pFree = pBuf->pNext;
  21504. db->lookaside.nOut++;
  21505. db->lookaside.anStat[0]++;
  21506. if( db->lookaside.nOut>db->lookaside.mxOut ){
  21507. db->lookaside.mxOut = db->lookaside.nOut;
  21508. }
  21509. return (void*)pBuf;
  21510. }
  21511. }else if( db->mallocFailed ){
  21512. return 0;
  21513. }
  21514. #else
  21515. assert( db!=0 );
  21516. assert( sqlite3_mutex_held(db->mutex) );
  21517. assert( db->pnBytesFreed==0 );
  21518. if( db->mallocFailed ){
  21519. return 0;
  21520. }
  21521. #endif
  21522. return dbMallocRawFinish(db, n);
  21523. }
  21524. /* Forward declaration */
  21525. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  21526. /*
  21527. ** Resize the block of memory pointed to by p to n bytes. If the
  21528. ** resize fails, set the mallocFailed flag in the connection object.
  21529. */
  21530. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  21531. assert( db!=0 );
  21532. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  21533. assert( sqlite3_mutex_held(db->mutex) );
  21534. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  21535. return dbReallocFinish(db, p, n);
  21536. }
  21537. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  21538. void *pNew = 0;
  21539. assert( db!=0 );
  21540. assert( p!=0 );
  21541. if( db->mallocFailed==0 ){
  21542. if( isLookaside(db, p) ){
  21543. pNew = sqlite3DbMallocRawNN(db, n);
  21544. if( pNew ){
  21545. memcpy(pNew, p, db->lookaside.sz);
  21546. sqlite3DbFree(db, p);
  21547. }
  21548. }else{
  21549. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21550. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21551. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  21552. pNew = sqlite3_realloc64(p, n);
  21553. if( !pNew ){
  21554. sqlite3OomFault(db);
  21555. }
  21556. sqlite3MemdebugSetType(pNew,
  21557. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  21558. }
  21559. }
  21560. return pNew;
  21561. }
  21562. /*
  21563. ** Attempt to reallocate p. If the reallocation fails, then free p
  21564. ** and set the mallocFailed flag in the database connection.
  21565. */
  21566. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  21567. void *pNew;
  21568. pNew = sqlite3DbRealloc(db, p, n);
  21569. if( !pNew ){
  21570. sqlite3DbFree(db, p);
  21571. }
  21572. return pNew;
  21573. }
  21574. /*
  21575. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  21576. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  21577. ** is because when memory debugging is turned on, these two functions are
  21578. ** called via macros that record the current file and line number in the
  21579. ** ThreadData structure.
  21580. */
  21581. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  21582. char *zNew;
  21583. size_t n;
  21584. if( z==0 ){
  21585. return 0;
  21586. }
  21587. n = sqlite3Strlen30(z) + 1;
  21588. assert( (n&0x7fffffff)==n );
  21589. zNew = sqlite3DbMallocRaw(db, (int)n);
  21590. if( zNew ){
  21591. memcpy(zNew, z, n);
  21592. }
  21593. return zNew;
  21594. }
  21595. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  21596. char *zNew;
  21597. assert( db!=0 );
  21598. if( z==0 ){
  21599. return 0;
  21600. }
  21601. assert( (n&0x7fffffff)==n );
  21602. zNew = sqlite3DbMallocRawNN(db, n+1);
  21603. if( zNew ){
  21604. memcpy(zNew, z, (size_t)n);
  21605. zNew[n] = 0;
  21606. }
  21607. return zNew;
  21608. }
  21609. /*
  21610. ** Free any prior content in *pz and replace it with a copy of zNew.
  21611. */
  21612. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  21613. sqlite3DbFree(db, *pz);
  21614. *pz = sqlite3DbStrDup(db, zNew);
  21615. }
  21616. /*
  21617. ** Call this routine to record the fact that an OOM (out-of-memory) error
  21618. ** has happened. This routine will set db->mallocFailed, and also
  21619. ** temporarily disable the lookaside memory allocator and interrupt
  21620. ** any running VDBEs.
  21621. */
  21622. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  21623. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  21624. db->mallocFailed = 1;
  21625. if( db->nVdbeExec>0 ){
  21626. db->u1.isInterrupted = 1;
  21627. }
  21628. db->lookaside.bDisable++;
  21629. }
  21630. }
  21631. /*
  21632. ** This routine reactivates the memory allocator and clears the
  21633. ** db->mallocFailed flag as necessary.
  21634. **
  21635. ** The memory allocator is not restarted if there are running
  21636. ** VDBEs.
  21637. */
  21638. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  21639. if( db->mallocFailed && db->nVdbeExec==0 ){
  21640. db->mallocFailed = 0;
  21641. db->u1.isInterrupted = 0;
  21642. assert( db->lookaside.bDisable>0 );
  21643. db->lookaside.bDisable--;
  21644. }
  21645. }
  21646. /*
  21647. ** Take actions at the end of an API call to indicate an OOM error
  21648. */
  21649. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  21650. sqlite3OomClear(db);
  21651. sqlite3Error(db, SQLITE_NOMEM);
  21652. return SQLITE_NOMEM_BKPT;
  21653. }
  21654. /*
  21655. ** This function must be called before exiting any API function (i.e.
  21656. ** returning control to the user) that has called sqlite3_malloc or
  21657. ** sqlite3_realloc.
  21658. **
  21659. ** The returned value is normally a copy of the second argument to this
  21660. ** function. However, if a malloc() failure has occurred since the previous
  21661. ** invocation SQLITE_NOMEM is returned instead.
  21662. **
  21663. ** If an OOM as occurred, then the connection error-code (the value
  21664. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  21665. */
  21666. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  21667. /* If the db handle must hold the connection handle mutex here.
  21668. ** Otherwise the read (and possible write) of db->mallocFailed
  21669. ** is unsafe, as is the call to sqlite3Error().
  21670. */
  21671. assert( db!=0 );
  21672. assert( sqlite3_mutex_held(db->mutex) );
  21673. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  21674. return apiOomError(db);
  21675. }
  21676. return rc & db->errMask;
  21677. }
  21678. /************** End of malloc.c **********************************************/
  21679. /************** Begin file printf.c ******************************************/
  21680. /*
  21681. ** The "printf" code that follows dates from the 1980's. It is in
  21682. ** the public domain.
  21683. **
  21684. **************************************************************************
  21685. **
  21686. ** This file contains code for a set of "printf"-like routines. These
  21687. ** routines format strings much like the printf() from the standard C
  21688. ** library, though the implementation here has enhancements to support
  21689. ** SQLite.
  21690. */
  21691. /* #include "sqliteInt.h" */
  21692. /*
  21693. ** Conversion types fall into various categories as defined by the
  21694. ** following enumeration.
  21695. */
  21696. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  21697. #define etFLOAT 2 /* Floating point. %f */
  21698. #define etEXP 3 /* Exponentional notation. %e and %E */
  21699. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  21700. #define etSIZE 5 /* Return number of characters processed so far. %n */
  21701. #define etSTRING 6 /* Strings. %s */
  21702. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  21703. #define etPERCENT 8 /* Percent symbol. %% */
  21704. #define etCHARX 9 /* Characters. %c */
  21705. /* The rest are extensions, not normally found in printf() */
  21706. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  21707. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  21708. NULL pointers replaced by SQL NULL. %Q */
  21709. #define etTOKEN 12 /* a pointer to a Token structure */
  21710. #define etSRCLIST 13 /* a pointer to a SrcList */
  21711. #define etPOINTER 14 /* The %p conversion */
  21712. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  21713. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  21714. #define etINVALID 0 /* Any unrecognized conversion type */
  21715. /*
  21716. ** An "etByte" is an 8-bit unsigned value.
  21717. */
  21718. typedef unsigned char etByte;
  21719. /*
  21720. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  21721. ** by an instance of the following structure
  21722. */
  21723. typedef struct et_info { /* Information about each format field */
  21724. char fmttype; /* The format field code letter */
  21725. etByte base; /* The base for radix conversion */
  21726. etByte flags; /* One or more of FLAG_ constants below */
  21727. etByte type; /* Conversion paradigm */
  21728. etByte charset; /* Offset into aDigits[] of the digits string */
  21729. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  21730. } et_info;
  21731. /*
  21732. ** Allowed values for et_info.flags
  21733. */
  21734. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  21735. #define FLAG_INTERN 2 /* True if for internal use only */
  21736. #define FLAG_STRING 4 /* Allow infinity precision */
  21737. /*
  21738. ** The following table is searched linearly, so it is good to put the
  21739. ** most frequently used conversion types first.
  21740. */
  21741. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  21742. static const char aPrefix[] = "-x0\000X0";
  21743. static const et_info fmtinfo[] = {
  21744. { 'd', 10, 1, etRADIX, 0, 0 },
  21745. { 's', 0, 4, etSTRING, 0, 0 },
  21746. { 'g', 0, 1, etGENERIC, 30, 0 },
  21747. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  21748. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  21749. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  21750. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  21751. { 'c', 0, 0, etCHARX, 0, 0 },
  21752. { 'o', 8, 0, etRADIX, 0, 2 },
  21753. { 'u', 10, 0, etRADIX, 0, 0 },
  21754. { 'x', 16, 0, etRADIX, 16, 1 },
  21755. { 'X', 16, 0, etRADIX, 0, 4 },
  21756. #ifndef SQLITE_OMIT_FLOATING_POINT
  21757. { 'f', 0, 1, etFLOAT, 0, 0 },
  21758. { 'e', 0, 1, etEXP, 30, 0 },
  21759. { 'E', 0, 1, etEXP, 14, 0 },
  21760. { 'G', 0, 1, etGENERIC, 14, 0 },
  21761. #endif
  21762. { 'i', 10, 1, etRADIX, 0, 0 },
  21763. { 'n', 0, 0, etSIZE, 0, 0 },
  21764. { '%', 0, 0, etPERCENT, 0, 0 },
  21765. { 'p', 16, 0, etPOINTER, 0, 1 },
  21766. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  21767. ** use only */
  21768. { 'T', 0, 2, etTOKEN, 0, 0 },
  21769. { 'S', 0, 2, etSRCLIST, 0, 0 },
  21770. { 'r', 10, 3, etORDINAL, 0, 0 },
  21771. };
  21772. /*
  21773. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  21774. ** conversions will work.
  21775. */
  21776. #ifndef SQLITE_OMIT_FLOATING_POINT
  21777. /*
  21778. ** "*val" is a double such that 0.1 <= *val < 10.0
  21779. ** Return the ascii code for the leading digit of *val, then
  21780. ** multiply "*val" by 10.0 to renormalize.
  21781. **
  21782. ** Example:
  21783. ** input: *val = 3.14159
  21784. ** output: *val = 1.4159 function return = '3'
  21785. **
  21786. ** The counter *cnt is incremented each time. After counter exceeds
  21787. ** 16 (the number of significant digits in a 64-bit float) '0' is
  21788. ** always returned.
  21789. */
  21790. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  21791. int digit;
  21792. LONGDOUBLE_TYPE d;
  21793. if( (*cnt)<=0 ) return '0';
  21794. (*cnt)--;
  21795. digit = (int)*val;
  21796. d = digit;
  21797. digit += '0';
  21798. *val = (*val - d)*10.0;
  21799. return (char)digit;
  21800. }
  21801. #endif /* SQLITE_OMIT_FLOATING_POINT */
  21802. /*
  21803. ** Set the StrAccum object to an error mode.
  21804. */
  21805. static void setStrAccumError(StrAccum *p, u8 eError){
  21806. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  21807. p->accError = eError;
  21808. p->nAlloc = 0;
  21809. }
  21810. /*
  21811. ** Extra argument values from a PrintfArguments object
  21812. */
  21813. static sqlite3_int64 getIntArg(PrintfArguments *p){
  21814. if( p->nArg<=p->nUsed ) return 0;
  21815. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  21816. }
  21817. static double getDoubleArg(PrintfArguments *p){
  21818. if( p->nArg<=p->nUsed ) return 0.0;
  21819. return sqlite3_value_double(p->apArg[p->nUsed++]);
  21820. }
  21821. static char *getTextArg(PrintfArguments *p){
  21822. if( p->nArg<=p->nUsed ) return 0;
  21823. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  21824. }
  21825. /*
  21826. ** On machines with a small stack size, you can redefine the
  21827. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  21828. */
  21829. #ifndef SQLITE_PRINT_BUF_SIZE
  21830. # define SQLITE_PRINT_BUF_SIZE 70
  21831. #endif
  21832. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  21833. /*
  21834. ** Render a string given by "fmt" into the StrAccum object.
  21835. */
  21836. SQLITE_PRIVATE void sqlite3VXPrintf(
  21837. StrAccum *pAccum, /* Accumulate results here */
  21838. const char *fmt, /* Format string */
  21839. va_list ap /* arguments */
  21840. ){
  21841. int c; /* Next character in the format string */
  21842. char *bufpt; /* Pointer to the conversion buffer */
  21843. int precision; /* Precision of the current field */
  21844. int length; /* Length of the field */
  21845. int idx; /* A general purpose loop counter */
  21846. int width; /* Width of the current field */
  21847. etByte flag_leftjustify; /* True if "-" flag is present */
  21848. etByte flag_plussign; /* True if "+" flag is present */
  21849. etByte flag_blanksign; /* True if " " flag is present */
  21850. etByte flag_alternateform; /* True if "#" flag is present */
  21851. etByte flag_altform2; /* True if "!" flag is present */
  21852. etByte flag_zeropad; /* True if field width constant starts with zero */
  21853. etByte flag_long; /* True if "l" flag is present */
  21854. etByte flag_longlong; /* True if the "ll" flag is present */
  21855. etByte done; /* Loop termination flag */
  21856. etByte xtype = 0; /* Conversion paradigm */
  21857. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  21858. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  21859. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  21860. sqlite_uint64 longvalue; /* Value for integer types */
  21861. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  21862. const et_info *infop; /* Pointer to the appropriate info structure */
  21863. char *zOut; /* Rendering buffer */
  21864. int nOut; /* Size of the rendering buffer */
  21865. char *zExtra = 0; /* Malloced memory used by some conversion */
  21866. #ifndef SQLITE_OMIT_FLOATING_POINT
  21867. int exp, e2; /* exponent of real numbers */
  21868. int nsd; /* Number of significant digits returned */
  21869. double rounder; /* Used for rounding floating point values */
  21870. etByte flag_dp; /* True if decimal point should be shown */
  21871. etByte flag_rtz; /* True if trailing zeros should be removed */
  21872. #endif
  21873. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  21874. char buf[etBUFSIZE]; /* Conversion buffer */
  21875. bufpt = 0;
  21876. if( pAccum->printfFlags ){
  21877. if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  21878. pArgList = va_arg(ap, PrintfArguments*);
  21879. }
  21880. useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
  21881. }else{
  21882. bArgList = useIntern = 0;
  21883. }
  21884. for(; (c=(*fmt))!=0; ++fmt){
  21885. if( c!='%' ){
  21886. bufpt = (char *)fmt;
  21887. #if HAVE_STRCHRNUL
  21888. fmt = strchrnul(fmt, '%');
  21889. #else
  21890. do{ fmt++; }while( *fmt && *fmt != '%' );
  21891. #endif
  21892. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  21893. if( *fmt==0 ) break;
  21894. }
  21895. if( (c=(*++fmt))==0 ){
  21896. sqlite3StrAccumAppend(pAccum, "%", 1);
  21897. break;
  21898. }
  21899. /* Find out what flags are present */
  21900. flag_leftjustify = flag_plussign = flag_blanksign =
  21901. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  21902. done = 0;
  21903. do{
  21904. switch( c ){
  21905. case '-': flag_leftjustify = 1; break;
  21906. case '+': flag_plussign = 1; break;
  21907. case ' ': flag_blanksign = 1; break;
  21908. case '#': flag_alternateform = 1; break;
  21909. case '!': flag_altform2 = 1; break;
  21910. case '0': flag_zeropad = 1; break;
  21911. default: done = 1; break;
  21912. }
  21913. }while( !done && (c=(*++fmt))!=0 );
  21914. /* Get the field width */
  21915. if( c=='*' ){
  21916. if( bArgList ){
  21917. width = (int)getIntArg(pArgList);
  21918. }else{
  21919. width = va_arg(ap,int);
  21920. }
  21921. if( width<0 ){
  21922. flag_leftjustify = 1;
  21923. width = width >= -2147483647 ? -width : 0;
  21924. }
  21925. c = *++fmt;
  21926. }else{
  21927. unsigned wx = 0;
  21928. while( c>='0' && c<='9' ){
  21929. wx = wx*10 + c - '0';
  21930. c = *++fmt;
  21931. }
  21932. testcase( wx>0x7fffffff );
  21933. width = wx & 0x7fffffff;
  21934. }
  21935. assert( width>=0 );
  21936. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  21937. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  21938. width = SQLITE_PRINTF_PRECISION_LIMIT;
  21939. }
  21940. #endif
  21941. /* Get the precision */
  21942. if( c=='.' ){
  21943. c = *++fmt;
  21944. if( c=='*' ){
  21945. if( bArgList ){
  21946. precision = (int)getIntArg(pArgList);
  21947. }else{
  21948. precision = va_arg(ap,int);
  21949. }
  21950. c = *++fmt;
  21951. if( precision<0 ){
  21952. precision = precision >= -2147483647 ? -precision : -1;
  21953. }
  21954. }else{
  21955. unsigned px = 0;
  21956. while( c>='0' && c<='9' ){
  21957. px = px*10 + c - '0';
  21958. c = *++fmt;
  21959. }
  21960. testcase( px>0x7fffffff );
  21961. precision = px & 0x7fffffff;
  21962. }
  21963. }else{
  21964. precision = -1;
  21965. }
  21966. assert( precision>=(-1) );
  21967. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  21968. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  21969. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  21970. }
  21971. #endif
  21972. /* Get the conversion type modifier */
  21973. if( c=='l' ){
  21974. flag_long = 1;
  21975. c = *++fmt;
  21976. if( c=='l' ){
  21977. flag_longlong = 1;
  21978. c = *++fmt;
  21979. }else{
  21980. flag_longlong = 0;
  21981. }
  21982. }else{
  21983. flag_long = flag_longlong = 0;
  21984. }
  21985. /* Fetch the info entry for the field */
  21986. infop = &fmtinfo[0];
  21987. xtype = etINVALID;
  21988. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  21989. if( c==fmtinfo[idx].fmttype ){
  21990. infop = &fmtinfo[idx];
  21991. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  21992. xtype = infop->type;
  21993. }else{
  21994. return;
  21995. }
  21996. break;
  21997. }
  21998. }
  21999. /*
  22000. ** At this point, variables are initialized as follows:
  22001. **
  22002. ** flag_alternateform TRUE if a '#' is present.
  22003. ** flag_altform2 TRUE if a '!' is present.
  22004. ** flag_plussign TRUE if a '+' is present.
  22005. ** flag_leftjustify TRUE if a '-' is present or if the
  22006. ** field width was negative.
  22007. ** flag_zeropad TRUE if the width began with 0.
  22008. ** flag_long TRUE if the letter 'l' (ell) prefixed
  22009. ** the conversion character.
  22010. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  22011. ** the conversion character.
  22012. ** flag_blanksign TRUE if a ' ' is present.
  22013. ** width The specified field width. This is
  22014. ** always non-negative. Zero is the default.
  22015. ** precision The specified precision. The default
  22016. ** is -1.
  22017. ** xtype The class of the conversion.
  22018. ** infop Pointer to the appropriate info struct.
  22019. */
  22020. switch( xtype ){
  22021. case etPOINTER:
  22022. flag_longlong = sizeof(char*)==sizeof(i64);
  22023. flag_long = sizeof(char*)==sizeof(long int);
  22024. /* Fall through into the next case */
  22025. case etORDINAL:
  22026. case etRADIX:
  22027. if( infop->flags & FLAG_SIGNED ){
  22028. i64 v;
  22029. if( bArgList ){
  22030. v = getIntArg(pArgList);
  22031. }else if( flag_longlong ){
  22032. v = va_arg(ap,i64);
  22033. }else if( flag_long ){
  22034. v = va_arg(ap,long int);
  22035. }else{
  22036. v = va_arg(ap,int);
  22037. }
  22038. if( v<0 ){
  22039. if( v==SMALLEST_INT64 ){
  22040. longvalue = ((u64)1)<<63;
  22041. }else{
  22042. longvalue = -v;
  22043. }
  22044. prefix = '-';
  22045. }else{
  22046. longvalue = v;
  22047. if( flag_plussign ) prefix = '+';
  22048. else if( flag_blanksign ) prefix = ' ';
  22049. else prefix = 0;
  22050. }
  22051. }else{
  22052. if( bArgList ){
  22053. longvalue = (u64)getIntArg(pArgList);
  22054. }else if( flag_longlong ){
  22055. longvalue = va_arg(ap,u64);
  22056. }else if( flag_long ){
  22057. longvalue = va_arg(ap,unsigned long int);
  22058. }else{
  22059. longvalue = va_arg(ap,unsigned int);
  22060. }
  22061. prefix = 0;
  22062. }
  22063. if( longvalue==0 ) flag_alternateform = 0;
  22064. if( flag_zeropad && precision<width-(prefix!=0) ){
  22065. precision = width-(prefix!=0);
  22066. }
  22067. if( precision<etBUFSIZE-10 ){
  22068. nOut = etBUFSIZE;
  22069. zOut = buf;
  22070. }else{
  22071. nOut = precision + 10;
  22072. zOut = zExtra = sqlite3Malloc( nOut );
  22073. if( zOut==0 ){
  22074. setStrAccumError(pAccum, STRACCUM_NOMEM);
  22075. return;
  22076. }
  22077. }
  22078. bufpt = &zOut[nOut-1];
  22079. if( xtype==etORDINAL ){
  22080. static const char zOrd[] = "thstndrd";
  22081. int x = (int)(longvalue % 10);
  22082. if( x>=4 || (longvalue/10)%10==1 ){
  22083. x = 0;
  22084. }
  22085. *(--bufpt) = zOrd[x*2+1];
  22086. *(--bufpt) = zOrd[x*2];
  22087. }
  22088. {
  22089. const char *cset = &aDigits[infop->charset];
  22090. u8 base = infop->base;
  22091. do{ /* Convert to ascii */
  22092. *(--bufpt) = cset[longvalue%base];
  22093. longvalue = longvalue/base;
  22094. }while( longvalue>0 );
  22095. }
  22096. length = (int)(&zOut[nOut-1]-bufpt);
  22097. for(idx=precision-length; idx>0; idx--){
  22098. *(--bufpt) = '0'; /* Zero pad */
  22099. }
  22100. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  22101. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  22102. const char *pre;
  22103. char x;
  22104. pre = &aPrefix[infop->prefix];
  22105. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  22106. }
  22107. length = (int)(&zOut[nOut-1]-bufpt);
  22108. break;
  22109. case etFLOAT:
  22110. case etEXP:
  22111. case etGENERIC:
  22112. if( bArgList ){
  22113. realvalue = getDoubleArg(pArgList);
  22114. }else{
  22115. realvalue = va_arg(ap,double);
  22116. }
  22117. #ifdef SQLITE_OMIT_FLOATING_POINT
  22118. length = 0;
  22119. #else
  22120. if( precision<0 ) precision = 6; /* Set default precision */
  22121. if( realvalue<0.0 ){
  22122. realvalue = -realvalue;
  22123. prefix = '-';
  22124. }else{
  22125. if( flag_plussign ) prefix = '+';
  22126. else if( flag_blanksign ) prefix = ' ';
  22127. else prefix = 0;
  22128. }
  22129. if( xtype==etGENERIC && precision>0 ) precision--;
  22130. testcase( precision>0xfff );
  22131. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  22132. if( xtype==etFLOAT ) realvalue += rounder;
  22133. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  22134. exp = 0;
  22135. if( sqlite3IsNaN((double)realvalue) ){
  22136. bufpt = "NaN";
  22137. length = 3;
  22138. break;
  22139. }
  22140. if( realvalue>0.0 ){
  22141. LONGDOUBLE_TYPE scale = 1.0;
  22142. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  22143. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  22144. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  22145. realvalue /= scale;
  22146. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  22147. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  22148. if( exp>350 ){
  22149. bufpt = buf;
  22150. buf[0] = prefix;
  22151. memcpy(buf+(prefix!=0),"Inf",4);
  22152. length = 3+(prefix!=0);
  22153. break;
  22154. }
  22155. }
  22156. bufpt = buf;
  22157. /*
  22158. ** If the field type is etGENERIC, then convert to either etEXP
  22159. ** or etFLOAT, as appropriate.
  22160. */
  22161. if( xtype!=etFLOAT ){
  22162. realvalue += rounder;
  22163. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  22164. }
  22165. if( xtype==etGENERIC ){
  22166. flag_rtz = !flag_alternateform;
  22167. if( exp<-4 || exp>precision ){
  22168. xtype = etEXP;
  22169. }else{
  22170. precision = precision - exp;
  22171. xtype = etFLOAT;
  22172. }
  22173. }else{
  22174. flag_rtz = flag_altform2;
  22175. }
  22176. if( xtype==etEXP ){
  22177. e2 = 0;
  22178. }else{
  22179. e2 = exp;
  22180. }
  22181. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  22182. bufpt = zExtra
  22183. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  22184. if( bufpt==0 ){
  22185. setStrAccumError(pAccum, STRACCUM_NOMEM);
  22186. return;
  22187. }
  22188. }
  22189. zOut = bufpt;
  22190. nsd = 16 + flag_altform2*10;
  22191. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  22192. /* The sign in front of the number */
  22193. if( prefix ){
  22194. *(bufpt++) = prefix;
  22195. }
  22196. /* Digits prior to the decimal point */
  22197. if( e2<0 ){
  22198. *(bufpt++) = '0';
  22199. }else{
  22200. for(; e2>=0; e2--){
  22201. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  22202. }
  22203. }
  22204. /* The decimal point */
  22205. if( flag_dp ){
  22206. *(bufpt++) = '.';
  22207. }
  22208. /* "0" digits after the decimal point but before the first
  22209. ** significant digit of the number */
  22210. for(e2++; e2<0; precision--, e2++){
  22211. assert( precision>0 );
  22212. *(bufpt++) = '0';
  22213. }
  22214. /* Significant digits after the decimal point */
  22215. while( (precision--)>0 ){
  22216. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  22217. }
  22218. /* Remove trailing zeros and the "." if no digits follow the "." */
  22219. if( flag_rtz && flag_dp ){
  22220. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  22221. assert( bufpt>zOut );
  22222. if( bufpt[-1]=='.' ){
  22223. if( flag_altform2 ){
  22224. *(bufpt++) = '0';
  22225. }else{
  22226. *(--bufpt) = 0;
  22227. }
  22228. }
  22229. }
  22230. /* Add the "eNNN" suffix */
  22231. if( xtype==etEXP ){
  22232. *(bufpt++) = aDigits[infop->charset];
  22233. if( exp<0 ){
  22234. *(bufpt++) = '-'; exp = -exp;
  22235. }else{
  22236. *(bufpt++) = '+';
  22237. }
  22238. if( exp>=100 ){
  22239. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  22240. exp %= 100;
  22241. }
  22242. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  22243. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  22244. }
  22245. *bufpt = 0;
  22246. /* The converted number is in buf[] and zero terminated. Output it.
  22247. ** Note that the number is in the usual order, not reversed as with
  22248. ** integer conversions. */
  22249. length = (int)(bufpt-zOut);
  22250. bufpt = zOut;
  22251. /* Special case: Add leading zeros if the flag_zeropad flag is
  22252. ** set and we are not left justified */
  22253. if( flag_zeropad && !flag_leftjustify && length < width){
  22254. int i;
  22255. int nPad = width - length;
  22256. for(i=width; i>=nPad; i--){
  22257. bufpt[i] = bufpt[i-nPad];
  22258. }
  22259. i = prefix!=0;
  22260. while( nPad-- ) bufpt[i++] = '0';
  22261. length = width;
  22262. }
  22263. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  22264. break;
  22265. case etSIZE:
  22266. if( !bArgList ){
  22267. *(va_arg(ap,int*)) = pAccum->nChar;
  22268. }
  22269. length = width = 0;
  22270. break;
  22271. case etPERCENT:
  22272. buf[0] = '%';
  22273. bufpt = buf;
  22274. length = 1;
  22275. break;
  22276. case etCHARX:
  22277. if( bArgList ){
  22278. bufpt = getTextArg(pArgList);
  22279. c = bufpt ? bufpt[0] : 0;
  22280. }else{
  22281. c = va_arg(ap,int);
  22282. }
  22283. if( precision>1 ){
  22284. width -= precision-1;
  22285. if( width>1 && !flag_leftjustify ){
  22286. sqlite3AppendChar(pAccum, width-1, ' ');
  22287. width = 0;
  22288. }
  22289. sqlite3AppendChar(pAccum, precision-1, c);
  22290. }
  22291. length = 1;
  22292. buf[0] = c;
  22293. bufpt = buf;
  22294. break;
  22295. case etSTRING:
  22296. case etDYNSTRING:
  22297. if( bArgList ){
  22298. bufpt = getTextArg(pArgList);
  22299. xtype = etSTRING;
  22300. }else{
  22301. bufpt = va_arg(ap,char*);
  22302. }
  22303. if( bufpt==0 ){
  22304. bufpt = "";
  22305. }else if( xtype==etDYNSTRING ){
  22306. zExtra = bufpt;
  22307. }
  22308. if( precision>=0 ){
  22309. for(length=0; length<precision && bufpt[length]; length++){}
  22310. }else{
  22311. length = sqlite3Strlen30(bufpt);
  22312. }
  22313. break;
  22314. case etSQLESCAPE: /* Escape ' characters */
  22315. case etSQLESCAPE2: /* Escape ' and enclose in '...' */
  22316. case etSQLESCAPE3: { /* Escape " characters */
  22317. int i, j, k, n, isnull;
  22318. int needQuote;
  22319. char ch;
  22320. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  22321. char *escarg;
  22322. if( bArgList ){
  22323. escarg = getTextArg(pArgList);
  22324. }else{
  22325. escarg = va_arg(ap,char*);
  22326. }
  22327. isnull = escarg==0;
  22328. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  22329. k = precision;
  22330. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  22331. if( ch==q ) n++;
  22332. }
  22333. needQuote = !isnull && xtype==etSQLESCAPE2;
  22334. n += i + 3;
  22335. if( n>etBUFSIZE ){
  22336. bufpt = zExtra = sqlite3Malloc( n );
  22337. if( bufpt==0 ){
  22338. setStrAccumError(pAccum, STRACCUM_NOMEM);
  22339. return;
  22340. }
  22341. }else{
  22342. bufpt = buf;
  22343. }
  22344. j = 0;
  22345. if( needQuote ) bufpt[j++] = q;
  22346. k = i;
  22347. for(i=0; i<k; i++){
  22348. bufpt[j++] = ch = escarg[i];
  22349. if( ch==q ) bufpt[j++] = ch;
  22350. }
  22351. if( needQuote ) bufpt[j++] = q;
  22352. bufpt[j] = 0;
  22353. length = j;
  22354. /* The precision in %q and %Q means how many input characters to
  22355. ** consume, not the length of the output...
  22356. ** if( precision>=0 && precision<length ) length = precision; */
  22357. break;
  22358. }
  22359. case etTOKEN: {
  22360. Token *pToken = va_arg(ap, Token*);
  22361. assert( bArgList==0 );
  22362. if( pToken && pToken->n ){
  22363. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  22364. }
  22365. length = width = 0;
  22366. break;
  22367. }
  22368. case etSRCLIST: {
  22369. SrcList *pSrc = va_arg(ap, SrcList*);
  22370. int k = va_arg(ap, int);
  22371. struct SrcList_item *pItem = &pSrc->a[k];
  22372. assert( bArgList==0 );
  22373. assert( k>=0 && k<pSrc->nSrc );
  22374. if( pItem->zDatabase ){
  22375. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  22376. sqlite3StrAccumAppend(pAccum, ".", 1);
  22377. }
  22378. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  22379. length = width = 0;
  22380. break;
  22381. }
  22382. default: {
  22383. assert( xtype==etINVALID );
  22384. return;
  22385. }
  22386. }/* End switch over the format type */
  22387. /*
  22388. ** The text of the conversion is pointed to by "bufpt" and is
  22389. ** "length" characters long. The field width is "width". Do
  22390. ** the output.
  22391. */
  22392. width -= length;
  22393. if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  22394. sqlite3StrAccumAppend(pAccum, bufpt, length);
  22395. if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  22396. if( zExtra ){
  22397. sqlite3DbFree(pAccum->db, zExtra);
  22398. zExtra = 0;
  22399. }
  22400. }/* End for loop over the format string */
  22401. } /* End of function */
  22402. /*
  22403. ** Enlarge the memory allocation on a StrAccum object so that it is
  22404. ** able to accept at least N more bytes of text.
  22405. **
  22406. ** Return the number of bytes of text that StrAccum is able to accept
  22407. ** after the attempted enlargement. The value returned might be zero.
  22408. */
  22409. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  22410. char *zNew;
  22411. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  22412. if( p->accError ){
  22413. testcase(p->accError==STRACCUM_TOOBIG);
  22414. testcase(p->accError==STRACCUM_NOMEM);
  22415. return 0;
  22416. }
  22417. if( p->mxAlloc==0 ){
  22418. N = p->nAlloc - p->nChar - 1;
  22419. setStrAccumError(p, STRACCUM_TOOBIG);
  22420. return N;
  22421. }else{
  22422. char *zOld = isMalloced(p) ? p->zText : 0;
  22423. i64 szNew = p->nChar;
  22424. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  22425. szNew += N + 1;
  22426. if( szNew+p->nChar<=p->mxAlloc ){
  22427. /* Force exponential buffer size growth as long as it does not overflow,
  22428. ** to avoid having to call this routine too often */
  22429. szNew += p->nChar;
  22430. }
  22431. if( szNew > p->mxAlloc ){
  22432. sqlite3StrAccumReset(p);
  22433. setStrAccumError(p, STRACCUM_TOOBIG);
  22434. return 0;
  22435. }else{
  22436. p->nAlloc = (int)szNew;
  22437. }
  22438. if( p->db ){
  22439. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  22440. }else{
  22441. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  22442. }
  22443. if( zNew ){
  22444. assert( p->zText!=0 || p->nChar==0 );
  22445. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  22446. p->zText = zNew;
  22447. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  22448. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  22449. }else{
  22450. sqlite3StrAccumReset(p);
  22451. setStrAccumError(p, STRACCUM_NOMEM);
  22452. return 0;
  22453. }
  22454. }
  22455. return N;
  22456. }
  22457. /*
  22458. ** Append N copies of character c to the given string buffer.
  22459. */
  22460. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  22461. testcase( p->nChar + (i64)N > 0x7fffffff );
  22462. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  22463. return;
  22464. }
  22465. assert( (p->zText==p->zBase)==!isMalloced(p) );
  22466. while( (N--)>0 ) p->zText[p->nChar++] = c;
  22467. }
  22468. /*
  22469. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  22470. ** So enlarge if first, then do the append.
  22471. **
  22472. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  22473. ** work (enlarging the buffer) using tail recursion, so that the
  22474. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  22475. */
  22476. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  22477. N = sqlite3StrAccumEnlarge(p, N);
  22478. if( N>0 ){
  22479. memcpy(&p->zText[p->nChar], z, N);
  22480. p->nChar += N;
  22481. }
  22482. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  22483. }
  22484. /*
  22485. ** Append N bytes of text from z to the StrAccum object. Increase the
  22486. ** size of the memory allocation for StrAccum if necessary.
  22487. */
  22488. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  22489. assert( z!=0 || N==0 );
  22490. assert( p->zText!=0 || p->nChar==0 || p->accError );
  22491. assert( N>=0 );
  22492. assert( p->accError==0 || p->nAlloc==0 );
  22493. if( p->nChar+N >= p->nAlloc ){
  22494. enlargeAndAppend(p,z,N);
  22495. }else{
  22496. assert( p->zText );
  22497. p->nChar += N;
  22498. memcpy(&p->zText[p->nChar-N], z, N);
  22499. }
  22500. }
  22501. /*
  22502. ** Append the complete text of zero-terminated string z[] to the p string.
  22503. */
  22504. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  22505. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  22506. }
  22507. /*
  22508. ** Finish off a string by making sure it is zero-terminated.
  22509. ** Return a pointer to the resulting string. Return a NULL
  22510. ** pointer if any kind of error was encountered.
  22511. */
  22512. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  22513. if( p->zText ){
  22514. assert( (p->zText==p->zBase)==!isMalloced(p) );
  22515. p->zText[p->nChar] = 0;
  22516. if( p->mxAlloc>0 && !isMalloced(p) ){
  22517. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  22518. if( p->zText ){
  22519. memcpy(p->zText, p->zBase, p->nChar+1);
  22520. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  22521. }else{
  22522. setStrAccumError(p, STRACCUM_NOMEM);
  22523. }
  22524. }
  22525. }
  22526. return p->zText;
  22527. }
  22528. /*
  22529. ** Reset an StrAccum string. Reclaim all malloced memory.
  22530. */
  22531. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  22532. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  22533. if( isMalloced(p) ){
  22534. sqlite3DbFree(p->db, p->zText);
  22535. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  22536. }
  22537. p->zText = 0;
  22538. }
  22539. /*
  22540. ** Initialize a string accumulator.
  22541. **
  22542. ** p: The accumulator to be initialized.
  22543. ** db: Pointer to a database connection. May be NULL. Lookaside
  22544. ** memory is used if not NULL. db->mallocFailed is set appropriately
  22545. ** when not NULL.
  22546. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  22547. ** is malloced.
  22548. ** n: Size of zBase in bytes. If total space requirements never exceed
  22549. ** n then no memory allocations ever occur.
  22550. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  22551. ** allocations will ever occur.
  22552. */
  22553. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  22554. p->zText = p->zBase = zBase;
  22555. p->db = db;
  22556. p->nChar = 0;
  22557. p->nAlloc = n;
  22558. p->mxAlloc = mx;
  22559. p->accError = 0;
  22560. p->printfFlags = 0;
  22561. }
  22562. /*
  22563. ** Print into memory obtained from sqliteMalloc(). Use the internal
  22564. ** %-conversion extensions.
  22565. */
  22566. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  22567. char *z;
  22568. char zBase[SQLITE_PRINT_BUF_SIZE];
  22569. StrAccum acc;
  22570. assert( db!=0 );
  22571. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  22572. db->aLimit[SQLITE_LIMIT_LENGTH]);
  22573. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  22574. sqlite3VXPrintf(&acc, zFormat, ap);
  22575. z = sqlite3StrAccumFinish(&acc);
  22576. if( acc.accError==STRACCUM_NOMEM ){
  22577. sqlite3OomFault(db);
  22578. }
  22579. return z;
  22580. }
  22581. /*
  22582. ** Print into memory obtained from sqliteMalloc(). Use the internal
  22583. ** %-conversion extensions.
  22584. */
  22585. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  22586. va_list ap;
  22587. char *z;
  22588. va_start(ap, zFormat);
  22589. z = sqlite3VMPrintf(db, zFormat, ap);
  22590. va_end(ap);
  22591. return z;
  22592. }
  22593. /*
  22594. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  22595. ** %-conversion extensions.
  22596. */
  22597. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
  22598. char *z;
  22599. char zBase[SQLITE_PRINT_BUF_SIZE];
  22600. StrAccum acc;
  22601. #ifdef SQLITE_ENABLE_API_ARMOR
  22602. if( zFormat==0 ){
  22603. (void)SQLITE_MISUSE_BKPT;
  22604. return 0;
  22605. }
  22606. #endif
  22607. #ifndef SQLITE_OMIT_AUTOINIT
  22608. if( sqlite3_initialize() ) return 0;
  22609. #endif
  22610. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  22611. sqlite3VXPrintf(&acc, zFormat, ap);
  22612. z = sqlite3StrAccumFinish(&acc);
  22613. return z;
  22614. }
  22615. /*
  22616. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  22617. ** %-conversion extensions.
  22618. */
  22619. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
  22620. va_list ap;
  22621. char *z;
  22622. #ifndef SQLITE_OMIT_AUTOINIT
  22623. if( sqlite3_initialize() ) return 0;
  22624. #endif
  22625. va_start(ap, zFormat);
  22626. z = sqlite3_vmprintf(zFormat, ap);
  22627. va_end(ap);
  22628. return z;
  22629. }
  22630. /*
  22631. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  22632. ** current locale settings. This is important for SQLite because we
  22633. ** are not able to use a "," as the decimal point in place of "." as
  22634. ** specified by some locales.
  22635. **
  22636. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  22637. ** from the snprintf() standard. Unfortunately, it is too late to change
  22638. ** this without breaking compatibility, so we just have to live with the
  22639. ** mistake.
  22640. **
  22641. ** sqlite3_vsnprintf() is the varargs version.
  22642. */
  22643. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  22644. StrAccum acc;
  22645. if( n<=0 ) return zBuf;
  22646. #ifdef SQLITE_ENABLE_API_ARMOR
  22647. if( zBuf==0 || zFormat==0 ) {
  22648. (void)SQLITE_MISUSE_BKPT;
  22649. if( zBuf ) zBuf[0] = 0;
  22650. return zBuf;
  22651. }
  22652. #endif
  22653. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  22654. sqlite3VXPrintf(&acc, zFormat, ap);
  22655. return sqlite3StrAccumFinish(&acc);
  22656. }
  22657. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  22658. char *z;
  22659. va_list ap;
  22660. va_start(ap,zFormat);
  22661. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  22662. va_end(ap);
  22663. return z;
  22664. }
  22665. /*
  22666. ** This is the routine that actually formats the sqlite3_log() message.
  22667. ** We house it in a separate routine from sqlite3_log() to avoid using
  22668. ** stack space on small-stack systems when logging is disabled.
  22669. **
  22670. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  22671. ** allocate memory because it might be called while the memory allocator
  22672. ** mutex is held.
  22673. **
  22674. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  22675. ** certain format characters (%q) or for very large precisions or widths.
  22676. ** Care must be taken that any sqlite3_log() calls that occur while the
  22677. ** memory mutex is held do not use these mechanisms.
  22678. */
  22679. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  22680. StrAccum acc; /* String accumulator */
  22681. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  22682. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  22683. sqlite3VXPrintf(&acc, zFormat, ap);
  22684. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  22685. sqlite3StrAccumFinish(&acc));
  22686. }
  22687. /*
  22688. ** Format and write a message to the log if logging is enabled.
  22689. */
  22690. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
  22691. va_list ap; /* Vararg list */
  22692. if( sqlite3GlobalConfig.xLog ){
  22693. va_start(ap, zFormat);
  22694. renderLogMsg(iErrCode, zFormat, ap);
  22695. va_end(ap);
  22696. }
  22697. }
  22698. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  22699. /*
  22700. ** A version of printf() that understands %lld. Used for debugging.
  22701. ** The printf() built into some versions of windows does not understand %lld
  22702. ** and segfaults if you give it a long long int.
  22703. */
  22704. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  22705. va_list ap;
  22706. StrAccum acc;
  22707. char zBuf[500];
  22708. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  22709. va_start(ap,zFormat);
  22710. sqlite3VXPrintf(&acc, zFormat, ap);
  22711. va_end(ap);
  22712. sqlite3StrAccumFinish(&acc);
  22713. fprintf(stdout,"%s", zBuf);
  22714. fflush(stdout);
  22715. }
  22716. #endif
  22717. /*
  22718. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  22719. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  22720. */
  22721. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  22722. va_list ap;
  22723. va_start(ap,zFormat);
  22724. sqlite3VXPrintf(p, zFormat, ap);
  22725. va_end(ap);
  22726. }
  22727. /************** End of printf.c **********************************************/
  22728. /************** Begin file treeview.c ****************************************/
  22729. /*
  22730. ** 2015-06-08
  22731. **
  22732. ** The author disclaims copyright to this source code. In place of
  22733. ** a legal notice, here is a blessing:
  22734. **
  22735. ** May you do good and not evil.
  22736. ** May you find forgiveness for yourself and forgive others.
  22737. ** May you share freely, never taking more than you give.
  22738. **
  22739. *************************************************************************
  22740. **
  22741. ** This file contains C code to implement the TreeView debugging routines.
  22742. ** These routines print a parse tree to standard output for debugging and
  22743. ** analysis.
  22744. **
  22745. ** The interfaces in this file is only available when compiling
  22746. ** with SQLITE_DEBUG.
  22747. */
  22748. /* #include "sqliteInt.h" */
  22749. #ifdef SQLITE_DEBUG
  22750. /*
  22751. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  22752. ** is not the last item in the tree.
  22753. */
  22754. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  22755. if( p==0 ){
  22756. p = sqlite3_malloc64( sizeof(*p) );
  22757. if( p==0 ) return 0;
  22758. memset(p, 0, sizeof(*p));
  22759. }else{
  22760. p->iLevel++;
  22761. }
  22762. assert( moreToFollow==0 || moreToFollow==1 );
  22763. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  22764. return p;
  22765. }
  22766. /*
  22767. ** Finished with one layer of the tree
  22768. */
  22769. static void sqlite3TreeViewPop(TreeView *p){
  22770. if( p==0 ) return;
  22771. p->iLevel--;
  22772. if( p->iLevel<0 ) sqlite3_free(p);
  22773. }
  22774. /*
  22775. ** Generate a single line of output for the tree, with a prefix that contains
  22776. ** all the appropriate tree lines
  22777. */
  22778. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  22779. va_list ap;
  22780. int i;
  22781. StrAccum acc;
  22782. char zBuf[500];
  22783. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  22784. if( p ){
  22785. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  22786. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  22787. }
  22788. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  22789. }
  22790. va_start(ap, zFormat);
  22791. sqlite3VXPrintf(&acc, zFormat, ap);
  22792. va_end(ap);
  22793. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  22794. sqlite3StrAccumFinish(&acc);
  22795. fprintf(stdout,"%s", zBuf);
  22796. fflush(stdout);
  22797. }
  22798. /*
  22799. ** Shorthand for starting a new tree item that consists of a single label
  22800. */
  22801. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  22802. p = sqlite3TreeViewPush(p, moreFollows);
  22803. sqlite3TreeViewLine(p, "%s", zLabel);
  22804. }
  22805. /*
  22806. ** Generate a human-readable description of a WITH clause.
  22807. */
  22808. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  22809. int i;
  22810. if( pWith==0 ) return;
  22811. if( pWith->nCte==0 ) return;
  22812. if( pWith->pOuter ){
  22813. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  22814. }else{
  22815. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  22816. }
  22817. if( pWith->nCte>0 ){
  22818. pView = sqlite3TreeViewPush(pView, 1);
  22819. for(i=0; i<pWith->nCte; i++){
  22820. StrAccum x;
  22821. char zLine[1000];
  22822. const struct Cte *pCte = &pWith->a[i];
  22823. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  22824. sqlite3XPrintf(&x, "%s", pCte->zName);
  22825. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  22826. char cSep = '(';
  22827. int j;
  22828. for(j=0; j<pCte->pCols->nExpr; j++){
  22829. sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  22830. cSep = ',';
  22831. }
  22832. sqlite3XPrintf(&x, ")");
  22833. }
  22834. sqlite3XPrintf(&x, " AS");
  22835. sqlite3StrAccumFinish(&x);
  22836. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  22837. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  22838. sqlite3TreeViewPop(pView);
  22839. }
  22840. sqlite3TreeViewPop(pView);
  22841. }
  22842. }
  22843. /*
  22844. ** Generate a human-readable description of a the Select object.
  22845. */
  22846. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  22847. int n = 0;
  22848. int cnt = 0;
  22849. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22850. if( p->pWith ){
  22851. sqlite3TreeViewWith(pView, p->pWith, 1);
  22852. cnt = 1;
  22853. sqlite3TreeViewPush(pView, 1);
  22854. }
  22855. do{
  22856. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
  22857. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  22858. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
  22859. (int)p->nSelectRow
  22860. );
  22861. if( cnt++ ) sqlite3TreeViewPop(pView);
  22862. if( p->pPrior ){
  22863. n = 1000;
  22864. }else{
  22865. n = 0;
  22866. if( p->pSrc && p->pSrc->nSrc ) n++;
  22867. if( p->pWhere ) n++;
  22868. if( p->pGroupBy ) n++;
  22869. if( p->pHaving ) n++;
  22870. if( p->pOrderBy ) n++;
  22871. if( p->pLimit ) n++;
  22872. if( p->pOffset ) n++;
  22873. }
  22874. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  22875. if( p->pSrc && p->pSrc->nSrc ){
  22876. int i;
  22877. pView = sqlite3TreeViewPush(pView, (n--)>0);
  22878. sqlite3TreeViewLine(pView, "FROM");
  22879. for(i=0; i<p->pSrc->nSrc; i++){
  22880. struct SrcList_item *pItem = &p->pSrc->a[i];
  22881. StrAccum x;
  22882. char zLine[100];
  22883. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  22884. sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
  22885. if( pItem->zDatabase ){
  22886. sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  22887. }else if( pItem->zName ){
  22888. sqlite3XPrintf(&x, " %s", pItem->zName);
  22889. }
  22890. if( pItem->pTab ){
  22891. sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
  22892. }
  22893. if( pItem->zAlias ){
  22894. sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
  22895. }
  22896. if( pItem->fg.jointype & JT_LEFT ){
  22897. sqlite3XPrintf(&x, " LEFT-JOIN");
  22898. }
  22899. sqlite3StrAccumFinish(&x);
  22900. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  22901. if( pItem->pSelect ){
  22902. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  22903. }
  22904. if( pItem->fg.isTabFunc ){
  22905. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  22906. }
  22907. sqlite3TreeViewPop(pView);
  22908. }
  22909. sqlite3TreeViewPop(pView);
  22910. }
  22911. if( p->pWhere ){
  22912. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  22913. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  22914. sqlite3TreeViewPop(pView);
  22915. }
  22916. if( p->pGroupBy ){
  22917. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  22918. }
  22919. if( p->pHaving ){
  22920. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  22921. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  22922. sqlite3TreeViewPop(pView);
  22923. }
  22924. if( p->pOrderBy ){
  22925. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  22926. }
  22927. if( p->pLimit ){
  22928. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  22929. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  22930. sqlite3TreeViewPop(pView);
  22931. }
  22932. if( p->pOffset ){
  22933. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  22934. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  22935. sqlite3TreeViewPop(pView);
  22936. }
  22937. if( p->pPrior ){
  22938. const char *zOp = "UNION";
  22939. switch( p->op ){
  22940. case TK_ALL: zOp = "UNION ALL"; break;
  22941. case TK_INTERSECT: zOp = "INTERSECT"; break;
  22942. case TK_EXCEPT: zOp = "EXCEPT"; break;
  22943. }
  22944. sqlite3TreeViewItem(pView, zOp, 1);
  22945. }
  22946. p = p->pPrior;
  22947. }while( p!=0 );
  22948. sqlite3TreeViewPop(pView);
  22949. }
  22950. /*
  22951. ** Generate a human-readable explanation of an expression tree.
  22952. */
  22953. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  22954. const char *zBinOp = 0; /* Binary operator */
  22955. const char *zUniOp = 0; /* Unary operator */
  22956. char zFlgs[30];
  22957. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22958. if( pExpr==0 ){
  22959. sqlite3TreeViewLine(pView, "nil");
  22960. sqlite3TreeViewPop(pView);
  22961. return;
  22962. }
  22963. if( pExpr->flags ){
  22964. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  22965. }else{
  22966. zFlgs[0] = 0;
  22967. }
  22968. switch( pExpr->op ){
  22969. case TK_AGG_COLUMN: {
  22970. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  22971. pExpr->iTable, pExpr->iColumn, zFlgs);
  22972. break;
  22973. }
  22974. case TK_COLUMN: {
  22975. if( pExpr->iTable<0 ){
  22976. /* This only happens when coding check constraints */
  22977. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  22978. }else{
  22979. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  22980. pExpr->iTable, pExpr->iColumn, zFlgs);
  22981. }
  22982. break;
  22983. }
  22984. case TK_INTEGER: {
  22985. if( pExpr->flags & EP_IntValue ){
  22986. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  22987. }else{
  22988. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  22989. }
  22990. break;
  22991. }
  22992. #ifndef SQLITE_OMIT_FLOATING_POINT
  22993. case TK_FLOAT: {
  22994. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  22995. break;
  22996. }
  22997. #endif
  22998. case TK_STRING: {
  22999. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  23000. break;
  23001. }
  23002. case TK_NULL: {
  23003. sqlite3TreeViewLine(pView,"NULL");
  23004. break;
  23005. }
  23006. #ifndef SQLITE_OMIT_BLOB_LITERAL
  23007. case TK_BLOB: {
  23008. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  23009. break;
  23010. }
  23011. #endif
  23012. case TK_VARIABLE: {
  23013. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  23014. pExpr->u.zToken, pExpr->iColumn);
  23015. break;
  23016. }
  23017. case TK_REGISTER: {
  23018. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  23019. break;
  23020. }
  23021. case TK_ID: {
  23022. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  23023. break;
  23024. }
  23025. #ifndef SQLITE_OMIT_CAST
  23026. case TK_CAST: {
  23027. /* Expressions of the form: CAST(pLeft AS token) */
  23028. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  23029. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  23030. break;
  23031. }
  23032. #endif /* SQLITE_OMIT_CAST */
  23033. case TK_LT: zBinOp = "LT"; break;
  23034. case TK_LE: zBinOp = "LE"; break;
  23035. case TK_GT: zBinOp = "GT"; break;
  23036. case TK_GE: zBinOp = "GE"; break;
  23037. case TK_NE: zBinOp = "NE"; break;
  23038. case TK_EQ: zBinOp = "EQ"; break;
  23039. case TK_IS: zBinOp = "IS"; break;
  23040. case TK_ISNOT: zBinOp = "ISNOT"; break;
  23041. case TK_AND: zBinOp = "AND"; break;
  23042. case TK_OR: zBinOp = "OR"; break;
  23043. case TK_PLUS: zBinOp = "ADD"; break;
  23044. case TK_STAR: zBinOp = "MUL"; break;
  23045. case TK_MINUS: zBinOp = "SUB"; break;
  23046. case TK_REM: zBinOp = "REM"; break;
  23047. case TK_BITAND: zBinOp = "BITAND"; break;
  23048. case TK_BITOR: zBinOp = "BITOR"; break;
  23049. case TK_SLASH: zBinOp = "DIV"; break;
  23050. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  23051. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  23052. case TK_CONCAT: zBinOp = "CONCAT"; break;
  23053. case TK_DOT: zBinOp = "DOT"; break;
  23054. case TK_UMINUS: zUniOp = "UMINUS"; break;
  23055. case TK_UPLUS: zUniOp = "UPLUS"; break;
  23056. case TK_BITNOT: zUniOp = "BITNOT"; break;
  23057. case TK_NOT: zUniOp = "NOT"; break;
  23058. case TK_ISNULL: zUniOp = "ISNULL"; break;
  23059. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  23060. case TK_SPAN: {
  23061. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  23062. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  23063. break;
  23064. }
  23065. case TK_COLLATE: {
  23066. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  23067. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  23068. break;
  23069. }
  23070. case TK_AGG_FUNCTION:
  23071. case TK_FUNCTION: {
  23072. ExprList *pFarg; /* List of function arguments */
  23073. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  23074. pFarg = 0;
  23075. }else{
  23076. pFarg = pExpr->x.pList;
  23077. }
  23078. if( pExpr->op==TK_AGG_FUNCTION ){
  23079. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  23080. pExpr->op2, pExpr->u.zToken);
  23081. }else{
  23082. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  23083. }
  23084. if( pFarg ){
  23085. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  23086. }
  23087. break;
  23088. }
  23089. #ifndef SQLITE_OMIT_SUBQUERY
  23090. case TK_EXISTS: {
  23091. sqlite3TreeViewLine(pView, "EXISTS-expr");
  23092. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  23093. break;
  23094. }
  23095. case TK_SELECT: {
  23096. sqlite3TreeViewLine(pView, "SELECT-expr");
  23097. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  23098. break;
  23099. }
  23100. case TK_IN: {
  23101. sqlite3TreeViewLine(pView, "IN");
  23102. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  23103. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  23104. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  23105. }else{
  23106. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  23107. }
  23108. break;
  23109. }
  23110. #endif /* SQLITE_OMIT_SUBQUERY */
  23111. /*
  23112. ** x BETWEEN y AND z
  23113. **
  23114. ** This is equivalent to
  23115. **
  23116. ** x>=y AND x<=z
  23117. **
  23118. ** X is stored in pExpr->pLeft.
  23119. ** Y is stored in pExpr->pList->a[0].pExpr.
  23120. ** Z is stored in pExpr->pList->a[1].pExpr.
  23121. */
  23122. case TK_BETWEEN: {
  23123. Expr *pX = pExpr->pLeft;
  23124. Expr *pY = pExpr->x.pList->a[0].pExpr;
  23125. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  23126. sqlite3TreeViewLine(pView, "BETWEEN");
  23127. sqlite3TreeViewExpr(pView, pX, 1);
  23128. sqlite3TreeViewExpr(pView, pY, 1);
  23129. sqlite3TreeViewExpr(pView, pZ, 0);
  23130. break;
  23131. }
  23132. case TK_TRIGGER: {
  23133. /* If the opcode is TK_TRIGGER, then the expression is a reference
  23134. ** to a column in the new.* or old.* pseudo-tables available to
  23135. ** trigger programs. In this case Expr.iTable is set to 1 for the
  23136. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  23137. ** is set to the column of the pseudo-table to read, or to -1 to
  23138. ** read the rowid field.
  23139. */
  23140. sqlite3TreeViewLine(pView, "%s(%d)",
  23141. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  23142. break;
  23143. }
  23144. case TK_CASE: {
  23145. sqlite3TreeViewLine(pView, "CASE");
  23146. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  23147. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  23148. break;
  23149. }
  23150. #ifndef SQLITE_OMIT_TRIGGER
  23151. case TK_RAISE: {
  23152. const char *zType = "unk";
  23153. switch( pExpr->affinity ){
  23154. case OE_Rollback: zType = "rollback"; break;
  23155. case OE_Abort: zType = "abort"; break;
  23156. case OE_Fail: zType = "fail"; break;
  23157. case OE_Ignore: zType = "ignore"; break;
  23158. }
  23159. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  23160. break;
  23161. }
  23162. #endif
  23163. default: {
  23164. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  23165. break;
  23166. }
  23167. }
  23168. if( zBinOp ){
  23169. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  23170. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  23171. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  23172. }else if( zUniOp ){
  23173. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  23174. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  23175. }
  23176. sqlite3TreeViewPop(pView);
  23177. }
  23178. /*
  23179. ** Generate a human-readable explanation of an expression list.
  23180. */
  23181. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  23182. TreeView *pView,
  23183. const ExprList *pList,
  23184. u8 moreToFollow,
  23185. const char *zLabel
  23186. ){
  23187. int i;
  23188. pView = sqlite3TreeViewPush(pView, moreToFollow);
  23189. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  23190. if( pList==0 ){
  23191. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  23192. }else{
  23193. sqlite3TreeViewLine(pView, "%s", zLabel);
  23194. for(i=0; i<pList->nExpr; i++){
  23195. int j = pList->a[i].u.x.iOrderByCol;
  23196. if( j ){
  23197. sqlite3TreeViewPush(pView, 0);
  23198. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  23199. }
  23200. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  23201. if( j ) sqlite3TreeViewPop(pView);
  23202. }
  23203. }
  23204. sqlite3TreeViewPop(pView);
  23205. }
  23206. #endif /* SQLITE_DEBUG */
  23207. /************** End of treeview.c ********************************************/
  23208. /************** Begin file random.c ******************************************/
  23209. /*
  23210. ** 2001 September 15
  23211. **
  23212. ** The author disclaims copyright to this source code. In place of
  23213. ** a legal notice, here is a blessing:
  23214. **
  23215. ** May you do good and not evil.
  23216. ** May you find forgiveness for yourself and forgive others.
  23217. ** May you share freely, never taking more than you give.
  23218. **
  23219. *************************************************************************
  23220. ** This file contains code to implement a pseudo-random number
  23221. ** generator (PRNG) for SQLite.
  23222. **
  23223. ** Random numbers are used by some of the database backends in order
  23224. ** to generate random integer keys for tables or random filenames.
  23225. */
  23226. /* #include "sqliteInt.h" */
  23227. /* All threads share a single random number generator.
  23228. ** This structure is the current state of the generator.
  23229. */
  23230. static SQLITE_WSD struct sqlite3PrngType {
  23231. unsigned char isInit; /* True if initialized */
  23232. unsigned char i, j; /* State variables */
  23233. unsigned char s[256]; /* State variables */
  23234. } sqlite3Prng;
  23235. /*
  23236. ** Return N random bytes.
  23237. */
  23238. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
  23239. unsigned char t;
  23240. unsigned char *zBuf = pBuf;
  23241. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  23242. ** state vector. If writable static data is unsupported on the target,
  23243. ** we have to locate the state vector at run-time. In the more common
  23244. ** case where writable static data is supported, wsdPrng can refer directly
  23245. ** to the "sqlite3Prng" state vector declared above.
  23246. */
  23247. #ifdef SQLITE_OMIT_WSD
  23248. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  23249. # define wsdPrng p[0]
  23250. #else
  23251. # define wsdPrng sqlite3Prng
  23252. #endif
  23253. #if SQLITE_THREADSAFE
  23254. sqlite3_mutex *mutex;
  23255. #endif
  23256. #ifndef SQLITE_OMIT_AUTOINIT
  23257. if( sqlite3_initialize() ) return;
  23258. #endif
  23259. #if SQLITE_THREADSAFE
  23260. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  23261. #endif
  23262. sqlite3_mutex_enter(mutex);
  23263. if( N<=0 || pBuf==0 ){
  23264. wsdPrng.isInit = 0;
  23265. sqlite3_mutex_leave(mutex);
  23266. return;
  23267. }
  23268. /* Initialize the state of the random number generator once,
  23269. ** the first time this routine is called. The seed value does
  23270. ** not need to contain a lot of randomness since we are not
  23271. ** trying to do secure encryption or anything like that...
  23272. **
  23273. ** Nothing in this file or anywhere else in SQLite does any kind of
  23274. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  23275. ** number generator) not as an encryption device.
  23276. */
  23277. if( !wsdPrng.isInit ){
  23278. int i;
  23279. char k[256];
  23280. wsdPrng.j = 0;
  23281. wsdPrng.i = 0;
  23282. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  23283. for(i=0; i<256; i++){
  23284. wsdPrng.s[i] = (u8)i;
  23285. }
  23286. for(i=0; i<256; i++){
  23287. wsdPrng.j += wsdPrng.s[i] + k[i];
  23288. t = wsdPrng.s[wsdPrng.j];
  23289. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  23290. wsdPrng.s[i] = t;
  23291. }
  23292. wsdPrng.isInit = 1;
  23293. }
  23294. assert( N>0 );
  23295. do{
  23296. wsdPrng.i++;
  23297. t = wsdPrng.s[wsdPrng.i];
  23298. wsdPrng.j += t;
  23299. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  23300. wsdPrng.s[wsdPrng.j] = t;
  23301. t += wsdPrng.s[wsdPrng.i];
  23302. *(zBuf++) = wsdPrng.s[t];
  23303. }while( --N );
  23304. sqlite3_mutex_leave(mutex);
  23305. }
  23306. #ifndef SQLITE_OMIT_BUILTIN_TEST
  23307. /*
  23308. ** For testing purposes, we sometimes want to preserve the state of
  23309. ** PRNG and restore the PRNG to its saved state at a later time, or
  23310. ** to reset the PRNG to its initial state. These routines accomplish
  23311. ** those tasks.
  23312. **
  23313. ** The sqlite3_test_control() interface calls these routines to
  23314. ** control the PRNG.
  23315. */
  23316. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  23317. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  23318. memcpy(
  23319. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  23320. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  23321. sizeof(sqlite3Prng)
  23322. );
  23323. }
  23324. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  23325. memcpy(
  23326. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  23327. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  23328. sizeof(sqlite3Prng)
  23329. );
  23330. }
  23331. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  23332. /************** End of random.c **********************************************/
  23333. /************** Begin file threads.c *****************************************/
  23334. /*
  23335. ** 2012 July 21
  23336. **
  23337. ** The author disclaims copyright to this source code. In place of
  23338. ** a legal notice, here is a blessing:
  23339. **
  23340. ** May you do good and not evil.
  23341. ** May you find forgiveness for yourself and forgive others.
  23342. ** May you share freely, never taking more than you give.
  23343. **
  23344. ******************************************************************************
  23345. **
  23346. ** This file presents a simple cross-platform threading interface for
  23347. ** use internally by SQLite.
  23348. **
  23349. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  23350. ** runs independently of its creator until it is joined using
  23351. ** sqlite3ThreadJoin(), at which point it terminates.
  23352. **
  23353. ** Threads do not have to be real. It could be that the work of the
  23354. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  23355. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  23356. ** single threaded systems. Nothing in SQLite requires multiple threads.
  23357. ** This interface exists so that applications that want to take advantage
  23358. ** of multiple cores can do so, while also allowing applications to stay
  23359. ** single-threaded if desired.
  23360. */
  23361. /* #include "sqliteInt.h" */
  23362. #if SQLITE_OS_WIN
  23363. /* # include "os_win.h" */
  23364. #endif
  23365. #if SQLITE_MAX_WORKER_THREADS>0
  23366. /********************************* Unix Pthreads ****************************/
  23367. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  23368. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  23369. /* #include <pthread.h> */
  23370. /* A running thread */
  23371. struct SQLiteThread {
  23372. pthread_t tid; /* Thread ID */
  23373. int done; /* Set to true when thread finishes */
  23374. void *pOut; /* Result returned by the thread */
  23375. void *(*xTask)(void*); /* The thread routine */
  23376. void *pIn; /* Argument to the thread */
  23377. };
  23378. /* Create a new thread */
  23379. SQLITE_PRIVATE int sqlite3ThreadCreate(
  23380. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  23381. void *(*xTask)(void*), /* Routine to run in a separate thread */
  23382. void *pIn /* Argument passed into xTask() */
  23383. ){
  23384. SQLiteThread *p;
  23385. int rc;
  23386. assert( ppThread!=0 );
  23387. assert( xTask!=0 );
  23388. /* This routine is never used in single-threaded mode */
  23389. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  23390. *ppThread = 0;
  23391. p = sqlite3Malloc(sizeof(*p));
  23392. if( p==0 ) return SQLITE_NOMEM_BKPT;
  23393. memset(p, 0, sizeof(*p));
  23394. p->xTask = xTask;
  23395. p->pIn = pIn;
  23396. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  23397. ** function that returns SQLITE_ERROR when passed the argument 200, that
  23398. ** forces worker threads to run sequentially and deterministically
  23399. ** for testing purposes. */
  23400. if( sqlite3FaultSim(200) ){
  23401. rc = 1;
  23402. }else{
  23403. rc = pthread_create(&p->tid, 0, xTask, pIn);
  23404. }
  23405. if( rc ){
  23406. p->done = 1;
  23407. p->pOut = xTask(pIn);
  23408. }
  23409. *ppThread = p;
  23410. return SQLITE_OK;
  23411. }
  23412. /* Get the results of the thread */
  23413. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  23414. int rc;
  23415. assert( ppOut!=0 );
  23416. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  23417. if( p->done ){
  23418. *ppOut = p->pOut;
  23419. rc = SQLITE_OK;
  23420. }else{
  23421. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  23422. }
  23423. sqlite3_free(p);
  23424. return rc;
  23425. }
  23426. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  23427. /******************************** End Unix Pthreads *************************/
  23428. /********************************* Win32 Threads ****************************/
  23429. #if SQLITE_OS_WIN_THREADS
  23430. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  23431. #include <process.h>
  23432. /* A running thread */
  23433. struct SQLiteThread {
  23434. void *tid; /* The thread handle */
  23435. unsigned id; /* The thread identifier */
  23436. void *(*xTask)(void*); /* The routine to run as a thread */
  23437. void *pIn; /* Argument to xTask */
  23438. void *pResult; /* Result of xTask */
  23439. };
  23440. /* Thread procedure Win32 compatibility shim */
  23441. static unsigned __stdcall sqlite3ThreadProc(
  23442. void *pArg /* IN: Pointer to the SQLiteThread structure */
  23443. ){
  23444. SQLiteThread *p = (SQLiteThread *)pArg;
  23445. assert( p!=0 );
  23446. #if 0
  23447. /*
  23448. ** This assert appears to trigger spuriously on certain
  23449. ** versions of Windows, possibly due to _beginthreadex()
  23450. ** and/or CreateThread() not fully setting their thread
  23451. ** ID parameter before starting the thread.
  23452. */
  23453. assert( p->id==GetCurrentThreadId() );
  23454. #endif
  23455. assert( p->xTask!=0 );
  23456. p->pResult = p->xTask(p->pIn);
  23457. _endthreadex(0);
  23458. return 0; /* NOT REACHED */
  23459. }
  23460. /* Create a new thread */
  23461. SQLITE_PRIVATE int sqlite3ThreadCreate(
  23462. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  23463. void *(*xTask)(void*), /* Routine to run in a separate thread */
  23464. void *pIn /* Argument passed into xTask() */
  23465. ){
  23466. SQLiteThread *p;
  23467. assert( ppThread!=0 );
  23468. assert( xTask!=0 );
  23469. *ppThread = 0;
  23470. p = sqlite3Malloc(sizeof(*p));
  23471. if( p==0 ) return SQLITE_NOMEM_BKPT;
  23472. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  23473. ** function that returns SQLITE_ERROR when passed the argument 200, that
  23474. ** forces worker threads to run sequentially and deterministically
  23475. ** (via the sqlite3FaultSim() term of the conditional) for testing
  23476. ** purposes. */
  23477. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  23478. memset(p, 0, sizeof(*p));
  23479. }else{
  23480. p->xTask = xTask;
  23481. p->pIn = pIn;
  23482. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  23483. if( p->tid==0 ){
  23484. memset(p, 0, sizeof(*p));
  23485. }
  23486. }
  23487. if( p->xTask==0 ){
  23488. p->id = GetCurrentThreadId();
  23489. p->pResult = xTask(pIn);
  23490. }
  23491. *ppThread = p;
  23492. return SQLITE_OK;
  23493. }
  23494. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  23495. /* Get the results of the thread */
  23496. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  23497. DWORD rc;
  23498. BOOL bRc;
  23499. assert( ppOut!=0 );
  23500. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  23501. if( p->xTask==0 ){
  23502. /* assert( p->id==GetCurrentThreadId() ); */
  23503. rc = WAIT_OBJECT_0;
  23504. assert( p->tid==0 );
  23505. }else{
  23506. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  23507. rc = sqlite3Win32Wait((HANDLE)p->tid);
  23508. assert( rc!=WAIT_IO_COMPLETION );
  23509. bRc = CloseHandle((HANDLE)p->tid);
  23510. assert( bRc );
  23511. }
  23512. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  23513. sqlite3_free(p);
  23514. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  23515. }
  23516. #endif /* SQLITE_OS_WIN_THREADS */
  23517. /******************************** End Win32 Threads *************************/
  23518. /********************************* Single-Threaded **************************/
  23519. #ifndef SQLITE_THREADS_IMPLEMENTED
  23520. /*
  23521. ** This implementation does not actually create a new thread. It does the
  23522. ** work of the thread in the main thread, when either the thread is created
  23523. ** or when it is joined
  23524. */
  23525. /* A running thread */
  23526. struct SQLiteThread {
  23527. void *(*xTask)(void*); /* The routine to run as a thread */
  23528. void *pIn; /* Argument to xTask */
  23529. void *pResult; /* Result of xTask */
  23530. };
  23531. /* Create a new thread */
  23532. SQLITE_PRIVATE int sqlite3ThreadCreate(
  23533. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  23534. void *(*xTask)(void*), /* Routine to run in a separate thread */
  23535. void *pIn /* Argument passed into xTask() */
  23536. ){
  23537. SQLiteThread *p;
  23538. assert( ppThread!=0 );
  23539. assert( xTask!=0 );
  23540. *ppThread = 0;
  23541. p = sqlite3Malloc(sizeof(*p));
  23542. if( p==0 ) return SQLITE_NOMEM_BKPT;
  23543. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  23544. p->xTask = xTask;
  23545. p->pIn = pIn;
  23546. }else{
  23547. p->xTask = 0;
  23548. p->pResult = xTask(pIn);
  23549. }
  23550. *ppThread = p;
  23551. return SQLITE_OK;
  23552. }
  23553. /* Get the results of the thread */
  23554. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  23555. assert( ppOut!=0 );
  23556. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  23557. if( p->xTask ){
  23558. *ppOut = p->xTask(p->pIn);
  23559. }else{
  23560. *ppOut = p->pResult;
  23561. }
  23562. sqlite3_free(p);
  23563. #if defined(SQLITE_TEST)
  23564. {
  23565. void *pTstAlloc = sqlite3Malloc(10);
  23566. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  23567. sqlite3_free(pTstAlloc);
  23568. }
  23569. #endif
  23570. return SQLITE_OK;
  23571. }
  23572. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  23573. /****************************** End Single-Threaded *************************/
  23574. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  23575. /************** End of threads.c *********************************************/
  23576. /************** Begin file utf.c *********************************************/
  23577. /*
  23578. ** 2004 April 13
  23579. **
  23580. ** The author disclaims copyright to this source code. In place of
  23581. ** a legal notice, here is a blessing:
  23582. **
  23583. ** May you do good and not evil.
  23584. ** May you find forgiveness for yourself and forgive others.
  23585. ** May you share freely, never taking more than you give.
  23586. **
  23587. *************************************************************************
  23588. ** This file contains routines used to translate between UTF-8,
  23589. ** UTF-16, UTF-16BE, and UTF-16LE.
  23590. **
  23591. ** Notes on UTF-8:
  23592. **
  23593. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  23594. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  23595. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  23596. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  23597. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  23598. **
  23599. **
  23600. ** Notes on UTF-16: (with wwww+1==uuuuu)
  23601. **
  23602. ** Word-0 Word-1 Value
  23603. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  23604. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  23605. **
  23606. **
  23607. ** BOM or Byte Order Mark:
  23608. ** 0xff 0xfe little-endian utf-16 follows
  23609. ** 0xfe 0xff big-endian utf-16 follows
  23610. **
  23611. */
  23612. /* #include "sqliteInt.h" */
  23613. /* #include <assert.h> */
  23614. /* #include "vdbeInt.h" */
  23615. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  23616. /*
  23617. ** The following constant value is used by the SQLITE_BIGENDIAN and
  23618. ** SQLITE_LITTLEENDIAN macros.
  23619. */
  23620. SQLITE_PRIVATE const int sqlite3one = 1;
  23621. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  23622. /*
  23623. ** This lookup table is used to help decode the first byte of
  23624. ** a multi-byte UTF8 character.
  23625. */
  23626. static const unsigned char sqlite3Utf8Trans1[] = {
  23627. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  23628. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  23629. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  23630. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  23631. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  23632. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  23633. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  23634. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  23635. };
  23636. #define WRITE_UTF8(zOut, c) { \
  23637. if( c<0x00080 ){ \
  23638. *zOut++ = (u8)(c&0xFF); \
  23639. } \
  23640. else if( c<0x00800 ){ \
  23641. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  23642. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  23643. } \
  23644. else if( c<0x10000 ){ \
  23645. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  23646. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  23647. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  23648. }else{ \
  23649. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  23650. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  23651. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  23652. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  23653. } \
  23654. }
  23655. #define WRITE_UTF16LE(zOut, c) { \
  23656. if( c<=0xFFFF ){ \
  23657. *zOut++ = (u8)(c&0x00FF); \
  23658. *zOut++ = (u8)((c>>8)&0x00FF); \
  23659. }else{ \
  23660. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  23661. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  23662. *zOut++ = (u8)(c&0x00FF); \
  23663. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  23664. } \
  23665. }
  23666. #define WRITE_UTF16BE(zOut, c) { \
  23667. if( c<=0xFFFF ){ \
  23668. *zOut++ = (u8)((c>>8)&0x00FF); \
  23669. *zOut++ = (u8)(c&0x00FF); \
  23670. }else{ \
  23671. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  23672. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  23673. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  23674. *zOut++ = (u8)(c&0x00FF); \
  23675. } \
  23676. }
  23677. #define READ_UTF16LE(zIn, TERM, c){ \
  23678. c = (*zIn++); \
  23679. c += ((*zIn++)<<8); \
  23680. if( c>=0xD800 && c<0xE000 && TERM ){ \
  23681. int c2 = (*zIn++); \
  23682. c2 += ((*zIn++)<<8); \
  23683. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  23684. } \
  23685. }
  23686. #define READ_UTF16BE(zIn, TERM, c){ \
  23687. c = ((*zIn++)<<8); \
  23688. c += (*zIn++); \
  23689. if( c>=0xD800 && c<0xE000 && TERM ){ \
  23690. int c2 = ((*zIn++)<<8); \
  23691. c2 += (*zIn++); \
  23692. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  23693. } \
  23694. }
  23695. /*
  23696. ** Translate a single UTF-8 character. Return the unicode value.
  23697. **
  23698. ** During translation, assume that the byte that zTerm points
  23699. ** is a 0x00.
  23700. **
  23701. ** Write a pointer to the next unread byte back into *pzNext.
  23702. **
  23703. ** Notes On Invalid UTF-8:
  23704. **
  23705. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  23706. ** be encoded as a multi-byte character. Any multi-byte character that
  23707. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  23708. **
  23709. ** * This routine never allows a UTF16 surrogate value to be encoded.
  23710. ** If a multi-byte character attempts to encode a value between
  23711. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  23712. **
  23713. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  23714. ** byte of a character are interpreted as single-byte characters
  23715. ** and rendered as themselves even though they are technically
  23716. ** invalid characters.
  23717. **
  23718. ** * This routine accepts over-length UTF8 encodings
  23719. ** for unicode values 0x80 and greater. It does not change over-length
  23720. ** encodings to 0xfffd as some systems recommend.
  23721. */
  23722. #define READ_UTF8(zIn, zTerm, c) \
  23723. c = *(zIn++); \
  23724. if( c>=0xc0 ){ \
  23725. c = sqlite3Utf8Trans1[c-0xc0]; \
  23726. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  23727. c = (c<<6) + (0x3f & *(zIn++)); \
  23728. } \
  23729. if( c<0x80 \
  23730. || (c&0xFFFFF800)==0xD800 \
  23731. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  23732. }
  23733. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  23734. const unsigned char **pz /* Pointer to string from which to read char */
  23735. ){
  23736. unsigned int c;
  23737. /* Same as READ_UTF8() above but without the zTerm parameter.
  23738. ** For this routine, we assume the UTF8 string is always zero-terminated.
  23739. */
  23740. c = *((*pz)++);
  23741. if( c>=0xc0 ){
  23742. c = sqlite3Utf8Trans1[c-0xc0];
  23743. while( (*(*pz) & 0xc0)==0x80 ){
  23744. c = (c<<6) + (0x3f & *((*pz)++));
  23745. }
  23746. if( c<0x80
  23747. || (c&0xFFFFF800)==0xD800
  23748. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  23749. }
  23750. return c;
  23751. }
  23752. /*
  23753. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  23754. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  23755. */
  23756. /* #define TRANSLATE_TRACE 1 */
  23757. #ifndef SQLITE_OMIT_UTF16
  23758. /*
  23759. ** This routine transforms the internal text encoding used by pMem to
  23760. ** desiredEnc. It is an error if the string is already of the desired
  23761. ** encoding, or if *pMem does not contain a string value.
  23762. */
  23763. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  23764. int len; /* Maximum length of output string in bytes */
  23765. unsigned char *zOut; /* Output buffer */
  23766. unsigned char *zIn; /* Input iterator */
  23767. unsigned char *zTerm; /* End of input */
  23768. unsigned char *z; /* Output iterator */
  23769. unsigned int c;
  23770. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  23771. assert( pMem->flags&MEM_Str );
  23772. assert( pMem->enc!=desiredEnc );
  23773. assert( pMem->enc!=0 );
  23774. assert( pMem->n>=0 );
  23775. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  23776. {
  23777. char zBuf[100];
  23778. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  23779. fprintf(stderr, "INPUT: %s\n", zBuf);
  23780. }
  23781. #endif
  23782. /* If the translation is between UTF-16 little and big endian, then
  23783. ** all that is required is to swap the byte order. This case is handled
  23784. ** differently from the others.
  23785. */
  23786. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  23787. u8 temp;
  23788. int rc;
  23789. rc = sqlite3VdbeMemMakeWriteable(pMem);
  23790. if( rc!=SQLITE_OK ){
  23791. assert( rc==SQLITE_NOMEM );
  23792. return SQLITE_NOMEM_BKPT;
  23793. }
  23794. zIn = (u8*)pMem->z;
  23795. zTerm = &zIn[pMem->n&~1];
  23796. while( zIn<zTerm ){
  23797. temp = *zIn;
  23798. *zIn = *(zIn+1);
  23799. zIn++;
  23800. *zIn++ = temp;
  23801. }
  23802. pMem->enc = desiredEnc;
  23803. goto translate_out;
  23804. }
  23805. /* Set len to the maximum number of bytes required in the output buffer. */
  23806. if( desiredEnc==SQLITE_UTF8 ){
  23807. /* When converting from UTF-16, the maximum growth results from
  23808. ** translating a 2-byte character to a 4-byte UTF-8 character.
  23809. ** A single byte is required for the output string
  23810. ** nul-terminator.
  23811. */
  23812. pMem->n &= ~1;
  23813. len = pMem->n * 2 + 1;
  23814. }else{
  23815. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  23816. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  23817. ** character. Two bytes are required in the output buffer for the
  23818. ** nul-terminator.
  23819. */
  23820. len = pMem->n * 2 + 2;
  23821. }
  23822. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  23823. ** byte past the end.
  23824. **
  23825. ** Variable zOut is set to point at the output buffer, space obtained
  23826. ** from sqlite3_malloc().
  23827. */
  23828. zIn = (u8*)pMem->z;
  23829. zTerm = &zIn[pMem->n];
  23830. zOut = sqlite3DbMallocRaw(pMem->db, len);
  23831. if( !zOut ){
  23832. return SQLITE_NOMEM_BKPT;
  23833. }
  23834. z = zOut;
  23835. if( pMem->enc==SQLITE_UTF8 ){
  23836. if( desiredEnc==SQLITE_UTF16LE ){
  23837. /* UTF-8 -> UTF-16 Little-endian */
  23838. while( zIn<zTerm ){
  23839. READ_UTF8(zIn, zTerm, c);
  23840. WRITE_UTF16LE(z, c);
  23841. }
  23842. }else{
  23843. assert( desiredEnc==SQLITE_UTF16BE );
  23844. /* UTF-8 -> UTF-16 Big-endian */
  23845. while( zIn<zTerm ){
  23846. READ_UTF8(zIn, zTerm, c);
  23847. WRITE_UTF16BE(z, c);
  23848. }
  23849. }
  23850. pMem->n = (int)(z - zOut);
  23851. *z++ = 0;
  23852. }else{
  23853. assert( desiredEnc==SQLITE_UTF8 );
  23854. if( pMem->enc==SQLITE_UTF16LE ){
  23855. /* UTF-16 Little-endian -> UTF-8 */
  23856. while( zIn<zTerm ){
  23857. READ_UTF16LE(zIn, zIn<zTerm, c);
  23858. WRITE_UTF8(z, c);
  23859. }
  23860. }else{
  23861. /* UTF-16 Big-endian -> UTF-8 */
  23862. while( zIn<zTerm ){
  23863. READ_UTF16BE(zIn, zIn<zTerm, c);
  23864. WRITE_UTF8(z, c);
  23865. }
  23866. }
  23867. pMem->n = (int)(z - zOut);
  23868. }
  23869. *z = 0;
  23870. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  23871. c = pMem->flags;
  23872. sqlite3VdbeMemRelease(pMem);
  23873. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  23874. pMem->enc = desiredEnc;
  23875. pMem->z = (char*)zOut;
  23876. pMem->zMalloc = pMem->z;
  23877. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  23878. translate_out:
  23879. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  23880. {
  23881. char zBuf[100];
  23882. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  23883. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  23884. }
  23885. #endif
  23886. return SQLITE_OK;
  23887. }
  23888. /*
  23889. ** This routine checks for a byte-order mark at the beginning of the
  23890. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  23891. ** the encoding of the Mem adjusted. This routine does not do any
  23892. ** byte-swapping, it just sets Mem.enc appropriately.
  23893. **
  23894. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  23895. ** changed by this function.
  23896. */
  23897. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  23898. int rc = SQLITE_OK;
  23899. u8 bom = 0;
  23900. assert( pMem->n>=0 );
  23901. if( pMem->n>1 ){
  23902. u8 b1 = *(u8 *)pMem->z;
  23903. u8 b2 = *(((u8 *)pMem->z) + 1);
  23904. if( b1==0xFE && b2==0xFF ){
  23905. bom = SQLITE_UTF16BE;
  23906. }
  23907. if( b1==0xFF && b2==0xFE ){
  23908. bom = SQLITE_UTF16LE;
  23909. }
  23910. }
  23911. if( bom ){
  23912. rc = sqlite3VdbeMemMakeWriteable(pMem);
  23913. if( rc==SQLITE_OK ){
  23914. pMem->n -= 2;
  23915. memmove(pMem->z, &pMem->z[2], pMem->n);
  23916. pMem->z[pMem->n] = '\0';
  23917. pMem->z[pMem->n+1] = '\0';
  23918. pMem->flags |= MEM_Term;
  23919. pMem->enc = bom;
  23920. }
  23921. }
  23922. return rc;
  23923. }
  23924. #endif /* SQLITE_OMIT_UTF16 */
  23925. /*
  23926. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  23927. ** return the number of unicode characters in pZ up to (but not including)
  23928. ** the first 0x00 byte. If nByte is not less than zero, return the
  23929. ** number of unicode characters in the first nByte of pZ (or up to
  23930. ** the first 0x00, whichever comes first).
  23931. */
  23932. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  23933. int r = 0;
  23934. const u8 *z = (const u8*)zIn;
  23935. const u8 *zTerm;
  23936. if( nByte>=0 ){
  23937. zTerm = &z[nByte];
  23938. }else{
  23939. zTerm = (const u8*)(-1);
  23940. }
  23941. assert( z<=zTerm );
  23942. while( *z!=0 && z<zTerm ){
  23943. SQLITE_SKIP_UTF8(z);
  23944. r++;
  23945. }
  23946. return r;
  23947. }
  23948. /* This test function is not currently used by the automated test-suite.
  23949. ** Hence it is only available in debug builds.
  23950. */
  23951. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23952. /*
  23953. ** Translate UTF-8 to UTF-8.
  23954. **
  23955. ** This has the effect of making sure that the string is well-formed
  23956. ** UTF-8. Miscoded characters are removed.
  23957. **
  23958. ** The translation is done in-place and aborted if the output
  23959. ** overruns the input.
  23960. */
  23961. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  23962. unsigned char *zOut = zIn;
  23963. unsigned char *zStart = zIn;
  23964. u32 c;
  23965. while( zIn[0] && zOut<=zIn ){
  23966. c = sqlite3Utf8Read((const u8**)&zIn);
  23967. if( c!=0xfffd ){
  23968. WRITE_UTF8(zOut, c);
  23969. }
  23970. }
  23971. *zOut = 0;
  23972. return (int)(zOut - zStart);
  23973. }
  23974. #endif
  23975. #ifndef SQLITE_OMIT_UTF16
  23976. /*
  23977. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  23978. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  23979. ** be freed by the calling function.
  23980. **
  23981. ** NULL is returned if there is an allocation error.
  23982. */
  23983. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  23984. Mem m;
  23985. memset(&m, 0, sizeof(m));
  23986. m.db = db;
  23987. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  23988. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  23989. if( db->mallocFailed ){
  23990. sqlite3VdbeMemRelease(&m);
  23991. m.z = 0;
  23992. }
  23993. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  23994. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  23995. assert( m.z || db->mallocFailed );
  23996. return m.z;
  23997. }
  23998. /*
  23999. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  24000. ** Return the number of bytes in the first nChar unicode characters
  24001. ** in pZ. nChar must be non-negative.
  24002. */
  24003. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  24004. int c;
  24005. unsigned char const *z = zIn;
  24006. int n = 0;
  24007. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  24008. while( n<nChar ){
  24009. READ_UTF16BE(z, 1, c);
  24010. n++;
  24011. }
  24012. }else{
  24013. while( n<nChar ){
  24014. READ_UTF16LE(z, 1, c);
  24015. n++;
  24016. }
  24017. }
  24018. return (int)(z-(unsigned char const *)zIn);
  24019. }
  24020. #if defined(SQLITE_TEST)
  24021. /*
  24022. ** This routine is called from the TCL test function "translate_selftest".
  24023. ** It checks that the primitives for serializing and deserializing
  24024. ** characters in each encoding are inverses of each other.
  24025. */
  24026. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  24027. unsigned int i, t;
  24028. unsigned char zBuf[20];
  24029. unsigned char *z;
  24030. int n;
  24031. unsigned int c;
  24032. for(i=0; i<0x00110000; i++){
  24033. z = zBuf;
  24034. WRITE_UTF8(z, i);
  24035. n = (int)(z-zBuf);
  24036. assert( n>0 && n<=4 );
  24037. z[0] = 0;
  24038. z = zBuf;
  24039. c = sqlite3Utf8Read((const u8**)&z);
  24040. t = i;
  24041. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  24042. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  24043. assert( c==t );
  24044. assert( (z-zBuf)==n );
  24045. }
  24046. for(i=0; i<0x00110000; i++){
  24047. if( i>=0xD800 && i<0xE000 ) continue;
  24048. z = zBuf;
  24049. WRITE_UTF16LE(z, i);
  24050. n = (int)(z-zBuf);
  24051. assert( n>0 && n<=4 );
  24052. z[0] = 0;
  24053. z = zBuf;
  24054. READ_UTF16LE(z, 1, c);
  24055. assert( c==i );
  24056. assert( (z-zBuf)==n );
  24057. }
  24058. for(i=0; i<0x00110000; i++){
  24059. if( i>=0xD800 && i<0xE000 ) continue;
  24060. z = zBuf;
  24061. WRITE_UTF16BE(z, i);
  24062. n = (int)(z-zBuf);
  24063. assert( n>0 && n<=4 );
  24064. z[0] = 0;
  24065. z = zBuf;
  24066. READ_UTF16BE(z, 1, c);
  24067. assert( c==i );
  24068. assert( (z-zBuf)==n );
  24069. }
  24070. }
  24071. #endif /* SQLITE_TEST */
  24072. #endif /* SQLITE_OMIT_UTF16 */
  24073. /************** End of utf.c *************************************************/
  24074. /************** Begin file util.c ********************************************/
  24075. /*
  24076. ** 2001 September 15
  24077. **
  24078. ** The author disclaims copyright to this source code. In place of
  24079. ** a legal notice, here is a blessing:
  24080. **
  24081. ** May you do good and not evil.
  24082. ** May you find forgiveness for yourself and forgive others.
  24083. ** May you share freely, never taking more than you give.
  24084. **
  24085. *************************************************************************
  24086. ** Utility functions used throughout sqlite.
  24087. **
  24088. ** This file contains functions for allocating memory, comparing
  24089. ** strings, and stuff like that.
  24090. **
  24091. */
  24092. /* #include "sqliteInt.h" */
  24093. /* #include <stdarg.h> */
  24094. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  24095. # include <math.h>
  24096. #endif
  24097. /*
  24098. ** Routine needed to support the testcase() macro.
  24099. */
  24100. #ifdef SQLITE_COVERAGE_TEST
  24101. SQLITE_PRIVATE void sqlite3Coverage(int x){
  24102. static unsigned dummy = 0;
  24103. dummy += (unsigned)x;
  24104. }
  24105. #endif
  24106. /*
  24107. ** Give a callback to the test harness that can be used to simulate faults
  24108. ** in places where it is difficult or expensive to do so purely by means
  24109. ** of inputs.
  24110. **
  24111. ** The intent of the integer argument is to let the fault simulator know
  24112. ** which of multiple sqlite3FaultSim() calls has been hit.
  24113. **
  24114. ** Return whatever integer value the test callback returns, or return
  24115. ** SQLITE_OK if no test callback is installed.
  24116. */
  24117. #ifndef SQLITE_OMIT_BUILTIN_TEST
  24118. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  24119. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  24120. return xCallback ? xCallback(iTest) : SQLITE_OK;
  24121. }
  24122. #endif
  24123. #ifndef SQLITE_OMIT_FLOATING_POINT
  24124. /*
  24125. ** Return true if the floating point value is Not a Number (NaN).
  24126. **
  24127. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  24128. ** Otherwise, we have our own implementation that works on most systems.
  24129. */
  24130. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  24131. int rc; /* The value return */
  24132. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  24133. /*
  24134. ** Systems that support the isnan() library function should probably
  24135. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  24136. ** found that many systems do not have a working isnan() function so
  24137. ** this implementation is provided as an alternative.
  24138. **
  24139. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  24140. ** On the other hand, the use of -ffast-math comes with the following
  24141. ** warning:
  24142. **
  24143. ** This option [-ffast-math] should never be turned on by any
  24144. ** -O option since it can result in incorrect output for programs
  24145. ** which depend on an exact implementation of IEEE or ISO
  24146. ** rules/specifications for math functions.
  24147. **
  24148. ** Under MSVC, this NaN test may fail if compiled with a floating-
  24149. ** point precision mode other than /fp:precise. From the MSDN
  24150. ** documentation:
  24151. **
  24152. ** The compiler [with /fp:precise] will properly handle comparisons
  24153. ** involving NaN. For example, x != x evaluates to true if x is NaN
  24154. ** ...
  24155. */
  24156. #ifdef __FAST_MATH__
  24157. # error SQLite will not work correctly with the -ffast-math option of GCC.
  24158. #endif
  24159. volatile double y = x;
  24160. volatile double z = y;
  24161. rc = (y!=z);
  24162. #else /* if HAVE_ISNAN */
  24163. rc = isnan(x);
  24164. #endif /* HAVE_ISNAN */
  24165. testcase( rc );
  24166. return rc;
  24167. }
  24168. #endif /* SQLITE_OMIT_FLOATING_POINT */
  24169. /*
  24170. ** Compute a string length that is limited to what can be stored in
  24171. ** lower 30 bits of a 32-bit signed integer.
  24172. **
  24173. ** The value returned will never be negative. Nor will it ever be greater
  24174. ** than the actual length of the string. For very long strings (greater
  24175. ** than 1GiB) the value returned might be less than the true string length.
  24176. */
  24177. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  24178. if( z==0 ) return 0;
  24179. return 0x3fffffff & (int)strlen(z);
  24180. }
  24181. /*
  24182. ** Return the declared type of a column. Or return zDflt if the column
  24183. ** has no declared type.
  24184. **
  24185. ** The column type is an extra string stored after the zero-terminator on
  24186. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  24187. */
  24188. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  24189. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  24190. return pCol->zName + strlen(pCol->zName) + 1;
  24191. }
  24192. /*
  24193. ** Helper function for sqlite3Error() - called rarely. Broken out into
  24194. ** a separate routine to avoid unnecessary register saves on entry to
  24195. ** sqlite3Error().
  24196. */
  24197. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  24198. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  24199. sqlite3SystemError(db, err_code);
  24200. }
  24201. /*
  24202. ** Set the current error code to err_code and clear any prior error message.
  24203. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  24204. ** that would be appropriate.
  24205. */
  24206. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  24207. assert( db!=0 );
  24208. db->errCode = err_code;
  24209. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  24210. }
  24211. /*
  24212. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  24213. ** to do based on the SQLite error code in rc.
  24214. */
  24215. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  24216. if( rc==SQLITE_IOERR_NOMEM ) return;
  24217. rc &= 0xff;
  24218. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  24219. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  24220. }
  24221. }
  24222. /*
  24223. ** Set the most recent error code and error string for the sqlite
  24224. ** handle "db". The error code is set to "err_code".
  24225. **
  24226. ** If it is not NULL, string zFormat specifies the format of the
  24227. ** error string in the style of the printf functions: The following
  24228. ** format characters are allowed:
  24229. **
  24230. ** %s Insert a string
  24231. ** %z A string that should be freed after use
  24232. ** %d Insert an integer
  24233. ** %T Insert a token
  24234. ** %S Insert the first element of a SrcList
  24235. **
  24236. ** zFormat and any string tokens that follow it are assumed to be
  24237. ** encoded in UTF-8.
  24238. **
  24239. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  24240. ** should be called with err_code set to SQLITE_OK and zFormat set
  24241. ** to NULL.
  24242. */
  24243. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  24244. assert( db!=0 );
  24245. db->errCode = err_code;
  24246. sqlite3SystemError(db, err_code);
  24247. if( zFormat==0 ){
  24248. sqlite3Error(db, err_code);
  24249. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  24250. char *z;
  24251. va_list ap;
  24252. va_start(ap, zFormat);
  24253. z = sqlite3VMPrintf(db, zFormat, ap);
  24254. va_end(ap);
  24255. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  24256. }
  24257. }
  24258. /*
  24259. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  24260. ** The following formatting characters are allowed:
  24261. **
  24262. ** %s Insert a string
  24263. ** %z A string that should be freed after use
  24264. ** %d Insert an integer
  24265. ** %T Insert a token
  24266. ** %S Insert the first element of a SrcList
  24267. **
  24268. ** This function should be used to report any error that occurs while
  24269. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  24270. ** last thing the sqlite3_prepare() function does is copy the error
  24271. ** stored by this function into the database handle using sqlite3Error().
  24272. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  24273. ** during statement execution (sqlite3_step() etc.).
  24274. */
  24275. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  24276. char *zMsg;
  24277. va_list ap;
  24278. sqlite3 *db = pParse->db;
  24279. va_start(ap, zFormat);
  24280. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  24281. va_end(ap);
  24282. if( db->suppressErr ){
  24283. sqlite3DbFree(db, zMsg);
  24284. }else{
  24285. pParse->nErr++;
  24286. sqlite3DbFree(db, pParse->zErrMsg);
  24287. pParse->zErrMsg = zMsg;
  24288. pParse->rc = SQLITE_ERROR;
  24289. }
  24290. }
  24291. /*
  24292. ** Convert an SQL-style quoted string into a normal string by removing
  24293. ** the quote characters. The conversion is done in-place. If the
  24294. ** input does not begin with a quote character, then this routine
  24295. ** is a no-op.
  24296. **
  24297. ** The input string must be zero-terminated. A new zero-terminator
  24298. ** is added to the dequoted string.
  24299. **
  24300. ** The return value is -1 if no dequoting occurs or the length of the
  24301. ** dequoted string, exclusive of the zero terminator, if dequoting does
  24302. ** occur.
  24303. **
  24304. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  24305. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  24306. ** "a-b-c".
  24307. */
  24308. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  24309. char quote;
  24310. int i, j;
  24311. if( z==0 ) return -1;
  24312. quote = z[0];
  24313. switch( quote ){
  24314. case '\'': break;
  24315. case '"': break;
  24316. case '`': break; /* For MySQL compatibility */
  24317. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  24318. default: return -1;
  24319. }
  24320. for(i=1, j=0;; i++){
  24321. assert( z[i] );
  24322. if( z[i]==quote ){
  24323. if( z[i+1]==quote ){
  24324. z[j++] = quote;
  24325. i++;
  24326. }else{
  24327. break;
  24328. }
  24329. }else{
  24330. z[j++] = z[i];
  24331. }
  24332. }
  24333. z[j] = 0;
  24334. return j;
  24335. }
  24336. /*
  24337. ** Generate a Token object from a string
  24338. */
  24339. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  24340. p->z = z;
  24341. p->n = sqlite3Strlen30(z);
  24342. }
  24343. /* Convenient short-hand */
  24344. #define UpperToLower sqlite3UpperToLower
  24345. /*
  24346. ** Some systems have stricmp(). Others have strcasecmp(). Because
  24347. ** there is no consistency, we will define our own.
  24348. **
  24349. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  24350. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  24351. ** the contents of two buffers containing UTF-8 strings in a
  24352. ** case-independent fashion, using the same definition of "case
  24353. ** independence" that SQLite uses internally when comparing identifiers.
  24354. */
  24355. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
  24356. if( zLeft==0 ){
  24357. return zRight ? -1 : 0;
  24358. }else if( zRight==0 ){
  24359. return 1;
  24360. }
  24361. return sqlite3StrICmp(zLeft, zRight);
  24362. }
  24363. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  24364. unsigned char *a, *b;
  24365. int c;
  24366. a = (unsigned char *)zLeft;
  24367. b = (unsigned char *)zRight;
  24368. for(;;){
  24369. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  24370. if( c || *a==0 ) break;
  24371. a++;
  24372. b++;
  24373. }
  24374. return c;
  24375. }
  24376. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  24377. register unsigned char *a, *b;
  24378. if( zLeft==0 ){
  24379. return zRight ? -1 : 0;
  24380. }else if( zRight==0 ){
  24381. return 1;
  24382. }
  24383. a = (unsigned char *)zLeft;
  24384. b = (unsigned char *)zRight;
  24385. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  24386. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  24387. }
  24388. /*
  24389. ** The string z[] is an text representation of a real number.
  24390. ** Convert this string to a double and write it into *pResult.
  24391. **
  24392. ** The string z[] is length bytes in length (bytes, not characters) and
  24393. ** uses the encoding enc. The string is not necessarily zero-terminated.
  24394. **
  24395. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  24396. ** if the string is empty or contains extraneous text. Valid numbers
  24397. ** are in one of these formats:
  24398. **
  24399. ** [+-]digits[E[+-]digits]
  24400. ** [+-]digits.[digits][E[+-]digits]
  24401. ** [+-].digits[E[+-]digits]
  24402. **
  24403. ** Leading and trailing whitespace is ignored for the purpose of determining
  24404. ** validity.
  24405. **
  24406. ** If some prefix of the input string is a valid number, this routine
  24407. ** returns FALSE but it still converts the prefix and writes the result
  24408. ** into *pResult.
  24409. */
  24410. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  24411. #ifndef SQLITE_OMIT_FLOATING_POINT
  24412. int incr;
  24413. const char *zEnd = z + length;
  24414. /* sign * significand * (10 ^ (esign * exponent)) */
  24415. int sign = 1; /* sign of significand */
  24416. i64 s = 0; /* significand */
  24417. int d = 0; /* adjust exponent for shifting decimal point */
  24418. int esign = 1; /* sign of exponent */
  24419. int e = 0; /* exponent */
  24420. int eValid = 1; /* True exponent is either not used or is well-formed */
  24421. double result;
  24422. int nDigits = 0;
  24423. int nonNum = 0;
  24424. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  24425. *pResult = 0.0; /* Default return value, in case of an error */
  24426. if( enc==SQLITE_UTF8 ){
  24427. incr = 1;
  24428. }else{
  24429. int i;
  24430. incr = 2;
  24431. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  24432. for(i=3-enc; i<length && z[i]==0; i+=2){}
  24433. nonNum = i<length;
  24434. zEnd = z+i+enc-3;
  24435. z += (enc&1);
  24436. }
  24437. /* skip leading spaces */
  24438. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  24439. if( z>=zEnd ) return 0;
  24440. /* get sign of significand */
  24441. if( *z=='-' ){
  24442. sign = -1;
  24443. z+=incr;
  24444. }else if( *z=='+' ){
  24445. z+=incr;
  24446. }
  24447. /* skip leading zeroes */
  24448. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  24449. /* copy max significant digits to significand */
  24450. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  24451. s = s*10 + (*z - '0');
  24452. z+=incr, nDigits++;
  24453. }
  24454. /* skip non-significant significand digits
  24455. ** (increase exponent by d to shift decimal left) */
  24456. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  24457. if( z>=zEnd ) goto do_atof_calc;
  24458. /* if decimal point is present */
  24459. if( *z=='.' ){
  24460. z+=incr;
  24461. /* copy digits from after decimal to significand
  24462. ** (decrease exponent by d to shift decimal right) */
  24463. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  24464. s = s*10 + (*z - '0');
  24465. z+=incr, nDigits++, d--;
  24466. }
  24467. /* skip non-significant digits */
  24468. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  24469. }
  24470. if( z>=zEnd ) goto do_atof_calc;
  24471. /* if exponent is present */
  24472. if( *z=='e' || *z=='E' ){
  24473. z+=incr;
  24474. eValid = 0;
  24475. if( z>=zEnd ) goto do_atof_calc;
  24476. /* get sign of exponent */
  24477. if( *z=='-' ){
  24478. esign = -1;
  24479. z+=incr;
  24480. }else if( *z=='+' ){
  24481. z+=incr;
  24482. }
  24483. /* copy digits to exponent */
  24484. while( z<zEnd && sqlite3Isdigit(*z) ){
  24485. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  24486. z+=incr;
  24487. eValid = 1;
  24488. }
  24489. }
  24490. /* skip trailing spaces */
  24491. if( nDigits && eValid ){
  24492. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  24493. }
  24494. do_atof_calc:
  24495. /* adjust exponent by d, and update sign */
  24496. e = (e*esign) + d;
  24497. if( e<0 ) {
  24498. esign = -1;
  24499. e *= -1;
  24500. } else {
  24501. esign = 1;
  24502. }
  24503. /* if 0 significand */
  24504. if( !s ) {
  24505. /* In the IEEE 754 standard, zero is signed.
  24506. ** Add the sign if we've seen at least one digit */
  24507. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  24508. } else {
  24509. /* attempt to reduce exponent */
  24510. if( esign>0 ){
  24511. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  24512. }else{
  24513. while( !(s%10) && e>0 ) e--,s/=10;
  24514. }
  24515. /* adjust the sign of significand */
  24516. s = sign<0 ? -s : s;
  24517. /* if exponent, scale significand as appropriate
  24518. ** and store in result. */
  24519. if( e ){
  24520. LONGDOUBLE_TYPE scale = 1.0;
  24521. /* attempt to handle extremely small/large numbers better */
  24522. if( e>307 && e<342 ){
  24523. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  24524. if( esign<0 ){
  24525. result = s / scale;
  24526. result /= 1.0e+308;
  24527. }else{
  24528. result = s * scale;
  24529. result *= 1.0e+308;
  24530. }
  24531. }else if( e>=342 ){
  24532. if( esign<0 ){
  24533. result = 0.0*s;
  24534. }else{
  24535. result = 1e308*1e308*s; /* Infinity */
  24536. }
  24537. }else{
  24538. /* 1.0e+22 is the largest power of 10 than can be
  24539. ** represented exactly. */
  24540. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  24541. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  24542. if( esign<0 ){
  24543. result = s / scale;
  24544. }else{
  24545. result = s * scale;
  24546. }
  24547. }
  24548. } else {
  24549. result = (double)s;
  24550. }
  24551. }
  24552. /* store the result */
  24553. *pResult = result;
  24554. /* return true if number and no extra non-whitespace chracters after */
  24555. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  24556. #else
  24557. return !sqlite3Atoi64(z, pResult, length, enc);
  24558. #endif /* SQLITE_OMIT_FLOATING_POINT */
  24559. }
  24560. /*
  24561. ** Compare the 19-character string zNum against the text representation
  24562. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  24563. ** if zNum is less than, equal to, or greater than the string.
  24564. ** Note that zNum must contain exactly 19 characters.
  24565. **
  24566. ** Unlike memcmp() this routine is guaranteed to return the difference
  24567. ** in the values of the last digit if the only difference is in the
  24568. ** last digit. So, for example,
  24569. **
  24570. ** compare2pow63("9223372036854775800", 1)
  24571. **
  24572. ** will return -8.
  24573. */
  24574. static int compare2pow63(const char *zNum, int incr){
  24575. int c = 0;
  24576. int i;
  24577. /* 012345678901234567 */
  24578. const char *pow63 = "922337203685477580";
  24579. for(i=0; c==0 && i<18; i++){
  24580. c = (zNum[i*incr]-pow63[i])*10;
  24581. }
  24582. if( c==0 ){
  24583. c = zNum[18*incr] - '8';
  24584. testcase( c==(-1) );
  24585. testcase( c==0 );
  24586. testcase( c==(+1) );
  24587. }
  24588. return c;
  24589. }
  24590. /*
  24591. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  24592. ** routine does *not* accept hexadecimal notation.
  24593. **
  24594. ** If the zNum value is representable as a 64-bit twos-complement
  24595. ** integer, then write that value into *pNum and return 0.
  24596. **
  24597. ** If zNum is exactly 9223372036854775808, return 2. This special
  24598. ** case is broken out because while 9223372036854775808 cannot be a
  24599. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  24600. **
  24601. ** If zNum is too big for a 64-bit integer and is not
  24602. ** 9223372036854775808 or if zNum contains any non-numeric text,
  24603. ** then return 1.
  24604. **
  24605. ** length is the number of bytes in the string (bytes, not characters).
  24606. ** The string is not necessarily zero-terminated. The encoding is
  24607. ** given by enc.
  24608. */
  24609. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  24610. int incr;
  24611. u64 u = 0;
  24612. int neg = 0; /* assume positive */
  24613. int i;
  24614. int c = 0;
  24615. int nonNum = 0;
  24616. const char *zStart;
  24617. const char *zEnd = zNum + length;
  24618. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  24619. if( enc==SQLITE_UTF8 ){
  24620. incr = 1;
  24621. }else{
  24622. incr = 2;
  24623. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  24624. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  24625. nonNum = i<length;
  24626. zEnd = zNum+i+enc-3;
  24627. zNum += (enc&1);
  24628. }
  24629. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  24630. if( zNum<zEnd ){
  24631. if( *zNum=='-' ){
  24632. neg = 1;
  24633. zNum+=incr;
  24634. }else if( *zNum=='+' ){
  24635. zNum+=incr;
  24636. }
  24637. }
  24638. zStart = zNum;
  24639. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  24640. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  24641. u = u*10 + c - '0';
  24642. }
  24643. if( u>LARGEST_INT64 ){
  24644. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  24645. }else if( neg ){
  24646. *pNum = -(i64)u;
  24647. }else{
  24648. *pNum = (i64)u;
  24649. }
  24650. testcase( i==18 );
  24651. testcase( i==19 );
  24652. testcase( i==20 );
  24653. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
  24654. || i>19*incr || nonNum ){
  24655. /* zNum is empty or contains non-numeric text or is longer
  24656. ** than 19 digits (thus guaranteeing that it is too large) */
  24657. return 1;
  24658. }else if( i<19*incr ){
  24659. /* Less than 19 digits, so we know that it fits in 64 bits */
  24660. assert( u<=LARGEST_INT64 );
  24661. return 0;
  24662. }else{
  24663. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  24664. c = compare2pow63(zNum, incr);
  24665. if( c<0 ){
  24666. /* zNum is less than 9223372036854775808 so it fits */
  24667. assert( u<=LARGEST_INT64 );
  24668. return 0;
  24669. }else if( c>0 ){
  24670. /* zNum is greater than 9223372036854775808 so it overflows */
  24671. return 1;
  24672. }else{
  24673. /* zNum is exactly 9223372036854775808. Fits if negative. The
  24674. ** special case 2 overflow if positive */
  24675. assert( u-1==LARGEST_INT64 );
  24676. return neg ? 0 : 2;
  24677. }
  24678. }
  24679. }
  24680. /*
  24681. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  24682. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  24683. ** whereas sqlite3Atoi64() does not.
  24684. **
  24685. ** Returns:
  24686. **
  24687. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  24688. ** 1 Integer too large for a 64-bit signed integer or is malformed
  24689. ** 2 Special case of 9223372036854775808
  24690. */
  24691. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  24692. #ifndef SQLITE_OMIT_HEX_INTEGER
  24693. if( z[0]=='0'
  24694. && (z[1]=='x' || z[1]=='X')
  24695. && sqlite3Isxdigit(z[2])
  24696. ){
  24697. u64 u = 0;
  24698. int i, k;
  24699. for(i=2; z[i]=='0'; i++){}
  24700. for(k=i; sqlite3Isxdigit(z[k]); k++){
  24701. u = u*16 + sqlite3HexToInt(z[k]);
  24702. }
  24703. memcpy(pOut, &u, 8);
  24704. return (z[k]==0 && k-i<=16) ? 0 : 1;
  24705. }else
  24706. #endif /* SQLITE_OMIT_HEX_INTEGER */
  24707. {
  24708. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  24709. }
  24710. }
  24711. /*
  24712. ** If zNum represents an integer that will fit in 32-bits, then set
  24713. ** *pValue to that integer and return true. Otherwise return false.
  24714. **
  24715. ** This routine accepts both decimal and hexadecimal notation for integers.
  24716. **
  24717. ** Any non-numeric characters that following zNum are ignored.
  24718. ** This is different from sqlite3Atoi64() which requires the
  24719. ** input number to be zero-terminated.
  24720. */
  24721. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  24722. sqlite_int64 v = 0;
  24723. int i, c;
  24724. int neg = 0;
  24725. if( zNum[0]=='-' ){
  24726. neg = 1;
  24727. zNum++;
  24728. }else if( zNum[0]=='+' ){
  24729. zNum++;
  24730. }
  24731. #ifndef SQLITE_OMIT_HEX_INTEGER
  24732. else if( zNum[0]=='0'
  24733. && (zNum[1]=='x' || zNum[1]=='X')
  24734. && sqlite3Isxdigit(zNum[2])
  24735. ){
  24736. u32 u = 0;
  24737. zNum += 2;
  24738. while( zNum[0]=='0' ) zNum++;
  24739. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  24740. u = u*16 + sqlite3HexToInt(zNum[i]);
  24741. }
  24742. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  24743. memcpy(pValue, &u, 4);
  24744. return 1;
  24745. }else{
  24746. return 0;
  24747. }
  24748. }
  24749. #endif
  24750. while( zNum[0]=='0' ) zNum++;
  24751. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  24752. v = v*10 + c;
  24753. }
  24754. /* The longest decimal representation of a 32 bit integer is 10 digits:
  24755. **
  24756. ** 1234567890
  24757. ** 2^31 -> 2147483648
  24758. */
  24759. testcase( i==10 );
  24760. if( i>10 ){
  24761. return 0;
  24762. }
  24763. testcase( v-neg==2147483647 );
  24764. if( v-neg>2147483647 ){
  24765. return 0;
  24766. }
  24767. if( neg ){
  24768. v = -v;
  24769. }
  24770. *pValue = (int)v;
  24771. return 1;
  24772. }
  24773. /*
  24774. ** Return a 32-bit integer value extracted from a string. If the
  24775. ** string is not an integer, just return 0.
  24776. */
  24777. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  24778. int x = 0;
  24779. if( z ) sqlite3GetInt32(z, &x);
  24780. return x;
  24781. }
  24782. /*
  24783. ** The variable-length integer encoding is as follows:
  24784. **
  24785. ** KEY:
  24786. ** A = 0xxxxxxx 7 bits of data and one flag bit
  24787. ** B = 1xxxxxxx 7 bits of data and one flag bit
  24788. ** C = xxxxxxxx 8 bits of data
  24789. **
  24790. ** 7 bits - A
  24791. ** 14 bits - BA
  24792. ** 21 bits - BBA
  24793. ** 28 bits - BBBA
  24794. ** 35 bits - BBBBA
  24795. ** 42 bits - BBBBBA
  24796. ** 49 bits - BBBBBBA
  24797. ** 56 bits - BBBBBBBA
  24798. ** 64 bits - BBBBBBBBC
  24799. */
  24800. /*
  24801. ** Write a 64-bit variable-length integer to memory starting at p[0].
  24802. ** The length of data write will be between 1 and 9 bytes. The number
  24803. ** of bytes written is returned.
  24804. **
  24805. ** A variable-length integer consists of the lower 7 bits of each byte
  24806. ** for all bytes that have the 8th bit set and one byte with the 8th
  24807. ** bit clear. Except, if we get to the 9th byte, it stores the full
  24808. ** 8 bits and is the last byte.
  24809. */
  24810. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  24811. int i, j, n;
  24812. u8 buf[10];
  24813. if( v & (((u64)0xff000000)<<32) ){
  24814. p[8] = (u8)v;
  24815. v >>= 8;
  24816. for(i=7; i>=0; i--){
  24817. p[i] = (u8)((v & 0x7f) | 0x80);
  24818. v >>= 7;
  24819. }
  24820. return 9;
  24821. }
  24822. n = 0;
  24823. do{
  24824. buf[n++] = (u8)((v & 0x7f) | 0x80);
  24825. v >>= 7;
  24826. }while( v!=0 );
  24827. buf[0] &= 0x7f;
  24828. assert( n<=9 );
  24829. for(i=0, j=n-1; j>=0; j--, i++){
  24830. p[i] = buf[j];
  24831. }
  24832. return n;
  24833. }
  24834. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  24835. if( v<=0x7f ){
  24836. p[0] = v&0x7f;
  24837. return 1;
  24838. }
  24839. if( v<=0x3fff ){
  24840. p[0] = ((v>>7)&0x7f)|0x80;
  24841. p[1] = v&0x7f;
  24842. return 2;
  24843. }
  24844. return putVarint64(p,v);
  24845. }
  24846. /*
  24847. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  24848. ** are defined here rather than simply putting the constant expressions
  24849. ** inline in order to work around bugs in the RVT compiler.
  24850. **
  24851. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  24852. **
  24853. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  24854. */
  24855. #define SLOT_2_0 0x001fc07f
  24856. #define SLOT_4_2_0 0xf01fc07f
  24857. /*
  24858. ** Read a 64-bit variable-length integer from memory starting at p[0].
  24859. ** Return the number of bytes read. The value is stored in *v.
  24860. */
  24861. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  24862. u32 a,b,s;
  24863. a = *p;
  24864. /* a: p0 (unmasked) */
  24865. if (!(a&0x80))
  24866. {
  24867. *v = a;
  24868. return 1;
  24869. }
  24870. p++;
  24871. b = *p;
  24872. /* b: p1 (unmasked) */
  24873. if (!(b&0x80))
  24874. {
  24875. a &= 0x7f;
  24876. a = a<<7;
  24877. a |= b;
  24878. *v = a;
  24879. return 2;
  24880. }
  24881. /* Verify that constants are precomputed correctly */
  24882. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  24883. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  24884. p++;
  24885. a = a<<14;
  24886. a |= *p;
  24887. /* a: p0<<14 | p2 (unmasked) */
  24888. if (!(a&0x80))
  24889. {
  24890. a &= SLOT_2_0;
  24891. b &= 0x7f;
  24892. b = b<<7;
  24893. a |= b;
  24894. *v = a;
  24895. return 3;
  24896. }
  24897. /* CSE1 from below */
  24898. a &= SLOT_2_0;
  24899. p++;
  24900. b = b<<14;
  24901. b |= *p;
  24902. /* b: p1<<14 | p3 (unmasked) */
  24903. if (!(b&0x80))
  24904. {
  24905. b &= SLOT_2_0;
  24906. /* moved CSE1 up */
  24907. /* a &= (0x7f<<14)|(0x7f); */
  24908. a = a<<7;
  24909. a |= b;
  24910. *v = a;
  24911. return 4;
  24912. }
  24913. /* a: p0<<14 | p2 (masked) */
  24914. /* b: p1<<14 | p3 (unmasked) */
  24915. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24916. /* moved CSE1 up */
  24917. /* a &= (0x7f<<14)|(0x7f); */
  24918. b &= SLOT_2_0;
  24919. s = a;
  24920. /* s: p0<<14 | p2 (masked) */
  24921. p++;
  24922. a = a<<14;
  24923. a |= *p;
  24924. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  24925. if (!(a&0x80))
  24926. {
  24927. /* we can skip these cause they were (effectively) done above
  24928. ** while calculating s */
  24929. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  24930. /* b &= (0x7f<<14)|(0x7f); */
  24931. b = b<<7;
  24932. a |= b;
  24933. s = s>>18;
  24934. *v = ((u64)s)<<32 | a;
  24935. return 5;
  24936. }
  24937. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24938. s = s<<7;
  24939. s |= b;
  24940. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24941. p++;
  24942. b = b<<14;
  24943. b |= *p;
  24944. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  24945. if (!(b&0x80))
  24946. {
  24947. /* we can skip this cause it was (effectively) done above in calc'ing s */
  24948. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  24949. a &= SLOT_2_0;
  24950. a = a<<7;
  24951. a |= b;
  24952. s = s>>18;
  24953. *v = ((u64)s)<<32 | a;
  24954. return 6;
  24955. }
  24956. p++;
  24957. a = a<<14;
  24958. a |= *p;
  24959. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  24960. if (!(a&0x80))
  24961. {
  24962. a &= SLOT_4_2_0;
  24963. b &= SLOT_2_0;
  24964. b = b<<7;
  24965. a |= b;
  24966. s = s>>11;
  24967. *v = ((u64)s)<<32 | a;
  24968. return 7;
  24969. }
  24970. /* CSE2 from below */
  24971. a &= SLOT_2_0;
  24972. p++;
  24973. b = b<<14;
  24974. b |= *p;
  24975. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  24976. if (!(b&0x80))
  24977. {
  24978. b &= SLOT_4_2_0;
  24979. /* moved CSE2 up */
  24980. /* a &= (0x7f<<14)|(0x7f); */
  24981. a = a<<7;
  24982. a |= b;
  24983. s = s>>4;
  24984. *v = ((u64)s)<<32 | a;
  24985. return 8;
  24986. }
  24987. p++;
  24988. a = a<<15;
  24989. a |= *p;
  24990. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  24991. /* moved CSE2 up */
  24992. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  24993. b &= SLOT_2_0;
  24994. b = b<<8;
  24995. a |= b;
  24996. s = s<<4;
  24997. b = p[-4];
  24998. b &= 0x7f;
  24999. b = b>>3;
  25000. s |= b;
  25001. *v = ((u64)s)<<32 | a;
  25002. return 9;
  25003. }
  25004. /*
  25005. ** Read a 32-bit variable-length integer from memory starting at p[0].
  25006. ** Return the number of bytes read. The value is stored in *v.
  25007. **
  25008. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  25009. ** integer, then set *v to 0xffffffff.
  25010. **
  25011. ** A MACRO version, getVarint32, is provided which inlines the
  25012. ** single-byte case. All code should use the MACRO version as
  25013. ** this function assumes the single-byte case has already been handled.
  25014. */
  25015. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  25016. u32 a,b;
  25017. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  25018. ** by the getVarin32() macro */
  25019. a = *p;
  25020. /* a: p0 (unmasked) */
  25021. #ifndef getVarint32
  25022. if (!(a&0x80))
  25023. {
  25024. /* Values between 0 and 127 */
  25025. *v = a;
  25026. return 1;
  25027. }
  25028. #endif
  25029. /* The 2-byte case */
  25030. p++;
  25031. b = *p;
  25032. /* b: p1 (unmasked) */
  25033. if (!(b&0x80))
  25034. {
  25035. /* Values between 128 and 16383 */
  25036. a &= 0x7f;
  25037. a = a<<7;
  25038. *v = a | b;
  25039. return 2;
  25040. }
  25041. /* The 3-byte case */
  25042. p++;
  25043. a = a<<14;
  25044. a |= *p;
  25045. /* a: p0<<14 | p2 (unmasked) */
  25046. if (!(a&0x80))
  25047. {
  25048. /* Values between 16384 and 2097151 */
  25049. a &= (0x7f<<14)|(0x7f);
  25050. b &= 0x7f;
  25051. b = b<<7;
  25052. *v = a | b;
  25053. return 3;
  25054. }
  25055. /* A 32-bit varint is used to store size information in btrees.
  25056. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  25057. ** A 3-byte varint is sufficient, for example, to record the size
  25058. ** of a 1048569-byte BLOB or string.
  25059. **
  25060. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  25061. ** rare larger cases can be handled by the slower 64-bit varint
  25062. ** routine.
  25063. */
  25064. #if 1
  25065. {
  25066. u64 v64;
  25067. u8 n;
  25068. p -= 2;
  25069. n = sqlite3GetVarint(p, &v64);
  25070. assert( n>3 && n<=9 );
  25071. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  25072. *v = 0xffffffff;
  25073. }else{
  25074. *v = (u32)v64;
  25075. }
  25076. return n;
  25077. }
  25078. #else
  25079. /* For following code (kept for historical record only) shows an
  25080. ** unrolling for the 3- and 4-byte varint cases. This code is
  25081. ** slightly faster, but it is also larger and much harder to test.
  25082. */
  25083. p++;
  25084. b = b<<14;
  25085. b |= *p;
  25086. /* b: p1<<14 | p3 (unmasked) */
  25087. if (!(b&0x80))
  25088. {
  25089. /* Values between 2097152 and 268435455 */
  25090. b &= (0x7f<<14)|(0x7f);
  25091. a &= (0x7f<<14)|(0x7f);
  25092. a = a<<7;
  25093. *v = a | b;
  25094. return 4;
  25095. }
  25096. p++;
  25097. a = a<<14;
  25098. a |= *p;
  25099. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  25100. if (!(a&0x80))
  25101. {
  25102. /* Values between 268435456 and 34359738367 */
  25103. a &= SLOT_4_2_0;
  25104. b &= SLOT_4_2_0;
  25105. b = b<<7;
  25106. *v = a | b;
  25107. return 5;
  25108. }
  25109. /* We can only reach this point when reading a corrupt database
  25110. ** file. In that case we are not in any hurry. Use the (relatively
  25111. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  25112. ** value. */
  25113. {
  25114. u64 v64;
  25115. u8 n;
  25116. p -= 4;
  25117. n = sqlite3GetVarint(p, &v64);
  25118. assert( n>5 && n<=9 );
  25119. *v = (u32)v64;
  25120. return n;
  25121. }
  25122. #endif
  25123. }
  25124. /*
  25125. ** Return the number of bytes that will be needed to store the given
  25126. ** 64-bit integer.
  25127. */
  25128. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  25129. int i;
  25130. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  25131. return i;
  25132. }
  25133. /*
  25134. ** Read or write a four-byte big-endian integer value.
  25135. */
  25136. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  25137. #if SQLITE_BYTEORDER==4321
  25138. u32 x;
  25139. memcpy(&x,p,4);
  25140. return x;
  25141. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  25142. && defined(__GNUC__) && GCC_VERSION>=4003000
  25143. u32 x;
  25144. memcpy(&x,p,4);
  25145. return __builtin_bswap32(x);
  25146. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  25147. && defined(_MSC_VER) && _MSC_VER>=1300
  25148. u32 x;
  25149. memcpy(&x,p,4);
  25150. return _byteswap_ulong(x);
  25151. #else
  25152. testcase( p[0]&0x80 );
  25153. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  25154. #endif
  25155. }
  25156. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  25157. #if SQLITE_BYTEORDER==4321
  25158. memcpy(p,&v,4);
  25159. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  25160. && defined(__GNUC__) && GCC_VERSION>=4003000
  25161. u32 x = __builtin_bswap32(v);
  25162. memcpy(p,&x,4);
  25163. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  25164. && defined(_MSC_VER) && _MSC_VER>=1300
  25165. u32 x = _byteswap_ulong(v);
  25166. memcpy(p,&x,4);
  25167. #else
  25168. p[0] = (u8)(v>>24);
  25169. p[1] = (u8)(v>>16);
  25170. p[2] = (u8)(v>>8);
  25171. p[3] = (u8)v;
  25172. #endif
  25173. }
  25174. /*
  25175. ** Translate a single byte of Hex into an integer.
  25176. ** This routine only works if h really is a valid hexadecimal
  25177. ** character: 0..9a..fA..F
  25178. */
  25179. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  25180. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  25181. #ifdef SQLITE_ASCII
  25182. h += 9*(1&(h>>6));
  25183. #endif
  25184. #ifdef SQLITE_EBCDIC
  25185. h += 9*(1&~(h>>4));
  25186. #endif
  25187. return (u8)(h & 0xf);
  25188. }
  25189. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  25190. /*
  25191. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  25192. ** value. Return a pointer to its binary value. Space to hold the
  25193. ** binary value has been obtained from malloc and must be freed by
  25194. ** the calling routine.
  25195. */
  25196. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  25197. char *zBlob;
  25198. int i;
  25199. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  25200. n--;
  25201. if( zBlob ){
  25202. for(i=0; i<n; i+=2){
  25203. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  25204. }
  25205. zBlob[i/2] = 0;
  25206. }
  25207. return zBlob;
  25208. }
  25209. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  25210. /*
  25211. ** Log an error that is an API call on a connection pointer that should
  25212. ** not have been used. The "type" of connection pointer is given as the
  25213. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  25214. */
  25215. static void logBadConnection(const char *zType){
  25216. sqlite3_log(SQLITE_MISUSE,
  25217. "API call with %s database connection pointer",
  25218. zType
  25219. );
  25220. }
  25221. /*
  25222. ** Check to make sure we have a valid db pointer. This test is not
  25223. ** foolproof but it does provide some measure of protection against
  25224. ** misuse of the interface such as passing in db pointers that are
  25225. ** NULL or which have been previously closed. If this routine returns
  25226. ** 1 it means that the db pointer is valid and 0 if it should not be
  25227. ** dereferenced for any reason. The calling function should invoke
  25228. ** SQLITE_MISUSE immediately.
  25229. **
  25230. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  25231. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  25232. ** open properly and is not fit for general use but which can be
  25233. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  25234. */
  25235. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  25236. u32 magic;
  25237. if( db==0 ){
  25238. logBadConnection("NULL");
  25239. return 0;
  25240. }
  25241. magic = db->magic;
  25242. if( magic!=SQLITE_MAGIC_OPEN ){
  25243. if( sqlite3SafetyCheckSickOrOk(db) ){
  25244. testcase( sqlite3GlobalConfig.xLog!=0 );
  25245. logBadConnection("unopened");
  25246. }
  25247. return 0;
  25248. }else{
  25249. return 1;
  25250. }
  25251. }
  25252. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  25253. u32 magic;
  25254. magic = db->magic;
  25255. if( magic!=SQLITE_MAGIC_SICK &&
  25256. magic!=SQLITE_MAGIC_OPEN &&
  25257. magic!=SQLITE_MAGIC_BUSY ){
  25258. testcase( sqlite3GlobalConfig.xLog!=0 );
  25259. logBadConnection("invalid");
  25260. return 0;
  25261. }else{
  25262. return 1;
  25263. }
  25264. }
  25265. /*
  25266. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  25267. ** the other 64-bit signed integer at *pA and store the result in *pA.
  25268. ** Return 0 on success. Or if the operation would have resulted in an
  25269. ** overflow, leave *pA unchanged and return 1.
  25270. */
  25271. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  25272. i64 iA = *pA;
  25273. testcase( iA==0 ); testcase( iA==1 );
  25274. testcase( iB==-1 ); testcase( iB==0 );
  25275. if( iB>=0 ){
  25276. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  25277. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  25278. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  25279. }else{
  25280. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  25281. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  25282. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  25283. }
  25284. *pA += iB;
  25285. return 0;
  25286. }
  25287. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  25288. testcase( iB==SMALLEST_INT64+1 );
  25289. if( iB==SMALLEST_INT64 ){
  25290. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  25291. if( (*pA)>=0 ) return 1;
  25292. *pA -= iB;
  25293. return 0;
  25294. }else{
  25295. return sqlite3AddInt64(pA, -iB);
  25296. }
  25297. }
  25298. #define TWOPOWER32 (((i64)1)<<32)
  25299. #define TWOPOWER31 (((i64)1)<<31)
  25300. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  25301. i64 iA = *pA;
  25302. i64 iA1, iA0, iB1, iB0, r;
  25303. iA1 = iA/TWOPOWER32;
  25304. iA0 = iA % TWOPOWER32;
  25305. iB1 = iB/TWOPOWER32;
  25306. iB0 = iB % TWOPOWER32;
  25307. if( iA1==0 ){
  25308. if( iB1==0 ){
  25309. *pA *= iB;
  25310. return 0;
  25311. }
  25312. r = iA0*iB1;
  25313. }else if( iB1==0 ){
  25314. r = iA1*iB0;
  25315. }else{
  25316. /* If both iA1 and iB1 are non-zero, overflow will result */
  25317. return 1;
  25318. }
  25319. testcase( r==(-TWOPOWER31)-1 );
  25320. testcase( r==(-TWOPOWER31) );
  25321. testcase( r==TWOPOWER31 );
  25322. testcase( r==TWOPOWER31-1 );
  25323. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  25324. r *= TWOPOWER32;
  25325. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  25326. *pA = r;
  25327. return 0;
  25328. }
  25329. /*
  25330. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  25331. ** if the integer has a value of -2147483648, return +2147483647
  25332. */
  25333. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  25334. if( x>=0 ) return x;
  25335. if( x==(int)0x80000000 ) return 0x7fffffff;
  25336. return -x;
  25337. }
  25338. #ifdef SQLITE_ENABLE_8_3_NAMES
  25339. /*
  25340. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  25341. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  25342. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  25343. ** three characters, then shorten the suffix on z[] to be the last three
  25344. ** characters of the original suffix.
  25345. **
  25346. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  25347. ** do the suffix shortening regardless of URI parameter.
  25348. **
  25349. ** Examples:
  25350. **
  25351. ** test.db-journal => test.nal
  25352. ** test.db-wal => test.wal
  25353. ** test.db-shm => test.shm
  25354. ** test.db-mj7f3319fa => test.9fa
  25355. */
  25356. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  25357. #if SQLITE_ENABLE_8_3_NAMES<2
  25358. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  25359. #endif
  25360. {
  25361. int i, sz;
  25362. sz = sqlite3Strlen30(z);
  25363. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  25364. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  25365. }
  25366. }
  25367. #endif
  25368. /*
  25369. ** Find (an approximate) sum of two LogEst values. This computation is
  25370. ** not a simple "+" operator because LogEst is stored as a logarithmic
  25371. ** value.
  25372. **
  25373. */
  25374. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  25375. static const unsigned char x[] = {
  25376. 10, 10, /* 0,1 */
  25377. 9, 9, /* 2,3 */
  25378. 8, 8, /* 4,5 */
  25379. 7, 7, 7, /* 6,7,8 */
  25380. 6, 6, 6, /* 9,10,11 */
  25381. 5, 5, 5, /* 12-14 */
  25382. 4, 4, 4, 4, /* 15-18 */
  25383. 3, 3, 3, 3, 3, 3, /* 19-24 */
  25384. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  25385. };
  25386. if( a>=b ){
  25387. if( a>b+49 ) return a;
  25388. if( a>b+31 ) return a+1;
  25389. return a+x[a-b];
  25390. }else{
  25391. if( b>a+49 ) return b;
  25392. if( b>a+31 ) return b+1;
  25393. return b+x[b-a];
  25394. }
  25395. }
  25396. /*
  25397. ** Convert an integer into a LogEst. In other words, compute an
  25398. ** approximation for 10*log2(x).
  25399. */
  25400. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  25401. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  25402. LogEst y = 40;
  25403. if( x<8 ){
  25404. if( x<2 ) return 0;
  25405. while( x<8 ){ y -= 10; x <<= 1; }
  25406. }else{
  25407. while( x>255 ){ y += 40; x >>= 4; }
  25408. while( x>15 ){ y += 10; x >>= 1; }
  25409. }
  25410. return a[x&7] + y - 10;
  25411. }
  25412. #ifndef SQLITE_OMIT_VIRTUALTABLE
  25413. /*
  25414. ** Convert a double into a LogEst
  25415. ** In other words, compute an approximation for 10*log2(x).
  25416. */
  25417. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  25418. u64 a;
  25419. LogEst e;
  25420. assert( sizeof(x)==8 && sizeof(a)==8 );
  25421. if( x<=1 ) return 0;
  25422. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  25423. memcpy(&a, &x, 8);
  25424. e = (a>>52) - 1022;
  25425. return e*10;
  25426. }
  25427. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  25428. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  25429. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  25430. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  25431. /*
  25432. ** Convert a LogEst into an integer.
  25433. **
  25434. ** Note that this routine is only used when one or more of various
  25435. ** non-standard compile-time options is enabled.
  25436. */
  25437. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  25438. u64 n;
  25439. if( x<10 ) return 1;
  25440. n = x%10;
  25441. x /= 10;
  25442. if( n>=5 ) n -= 2;
  25443. else if( n>=1 ) n -= 1;
  25444. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  25445. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  25446. if( x>60 ) return (u64)LARGEST_INT64;
  25447. #else
  25448. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  25449. ** possible to this routine is 310, resulting in a maximum x of 31 */
  25450. assert( x<=60 );
  25451. #endif
  25452. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  25453. }
  25454. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  25455. /************** End of util.c ************************************************/
  25456. /************** Begin file hash.c ********************************************/
  25457. /*
  25458. ** 2001 September 22
  25459. **
  25460. ** The author disclaims copyright to this source code. In place of
  25461. ** a legal notice, here is a blessing:
  25462. **
  25463. ** May you do good and not evil.
  25464. ** May you find forgiveness for yourself and forgive others.
  25465. ** May you share freely, never taking more than you give.
  25466. **
  25467. *************************************************************************
  25468. ** This is the implementation of generic hash-tables
  25469. ** used in SQLite.
  25470. */
  25471. /* #include "sqliteInt.h" */
  25472. /* #include <assert.h> */
  25473. /* Turn bulk memory into a hash table object by initializing the
  25474. ** fields of the Hash structure.
  25475. **
  25476. ** "pNew" is a pointer to the hash table that is to be initialized.
  25477. */
  25478. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  25479. assert( pNew!=0 );
  25480. pNew->first = 0;
  25481. pNew->count = 0;
  25482. pNew->htsize = 0;
  25483. pNew->ht = 0;
  25484. }
  25485. /* Remove all entries from a hash table. Reclaim all memory.
  25486. ** Call this routine to delete a hash table or to reset a hash table
  25487. ** to the empty state.
  25488. */
  25489. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  25490. HashElem *elem; /* For looping over all elements of the table */
  25491. assert( pH!=0 );
  25492. elem = pH->first;
  25493. pH->first = 0;
  25494. sqlite3_free(pH->ht);
  25495. pH->ht = 0;
  25496. pH->htsize = 0;
  25497. while( elem ){
  25498. HashElem *next_elem = elem->next;
  25499. sqlite3_free(elem);
  25500. elem = next_elem;
  25501. }
  25502. pH->count = 0;
  25503. }
  25504. /*
  25505. ** The hashing function.
  25506. */
  25507. static unsigned int strHash(const char *z){
  25508. unsigned int h = 0;
  25509. unsigned char c;
  25510. while( (c = (unsigned char)*z++)!=0 ){
  25511. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  25512. }
  25513. return h;
  25514. }
  25515. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  25516. ** insert pNew into the pEntry hash bucket.
  25517. */
  25518. static void insertElement(
  25519. Hash *pH, /* The complete hash table */
  25520. struct _ht *pEntry, /* The entry into which pNew is inserted */
  25521. HashElem *pNew /* The element to be inserted */
  25522. ){
  25523. HashElem *pHead; /* First element already in pEntry */
  25524. if( pEntry ){
  25525. pHead = pEntry->count ? pEntry->chain : 0;
  25526. pEntry->count++;
  25527. pEntry->chain = pNew;
  25528. }else{
  25529. pHead = 0;
  25530. }
  25531. if( pHead ){
  25532. pNew->next = pHead;
  25533. pNew->prev = pHead->prev;
  25534. if( pHead->prev ){ pHead->prev->next = pNew; }
  25535. else { pH->first = pNew; }
  25536. pHead->prev = pNew;
  25537. }else{
  25538. pNew->next = pH->first;
  25539. if( pH->first ){ pH->first->prev = pNew; }
  25540. pNew->prev = 0;
  25541. pH->first = pNew;
  25542. }
  25543. }
  25544. /* Resize the hash table so that it cantains "new_size" buckets.
  25545. **
  25546. ** The hash table might fail to resize if sqlite3_malloc() fails or
  25547. ** if the new size is the same as the prior size.
  25548. ** Return TRUE if the resize occurs and false if not.
  25549. */
  25550. static int rehash(Hash *pH, unsigned int new_size){
  25551. struct _ht *new_ht; /* The new hash table */
  25552. HashElem *elem, *next_elem; /* For looping over existing elements */
  25553. #if SQLITE_MALLOC_SOFT_LIMIT>0
  25554. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  25555. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  25556. }
  25557. if( new_size==pH->htsize ) return 0;
  25558. #endif
  25559. /* The inability to allocates space for a larger hash table is
  25560. ** a performance hit but it is not a fatal error. So mark the
  25561. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  25562. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  25563. ** only zeroes the requested number of bytes whereas this module will
  25564. ** use the actual amount of space allocated for the hash table (which
  25565. ** may be larger than the requested amount).
  25566. */
  25567. sqlite3BeginBenignMalloc();
  25568. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  25569. sqlite3EndBenignMalloc();
  25570. if( new_ht==0 ) return 0;
  25571. sqlite3_free(pH->ht);
  25572. pH->ht = new_ht;
  25573. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  25574. memset(new_ht, 0, new_size*sizeof(struct _ht));
  25575. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  25576. unsigned int h = strHash(elem->pKey) % new_size;
  25577. next_elem = elem->next;
  25578. insertElement(pH, &new_ht[h], elem);
  25579. }
  25580. return 1;
  25581. }
  25582. /* This function (for internal use only) locates an element in an
  25583. ** hash table that matches the given key. The hash for this key is
  25584. ** also computed and returned in the *pH parameter.
  25585. */
  25586. static HashElem *findElementWithHash(
  25587. const Hash *pH, /* The pH to be searched */
  25588. const char *pKey, /* The key we are searching for */
  25589. unsigned int *pHash /* Write the hash value here */
  25590. ){
  25591. HashElem *elem; /* Used to loop thru the element list */
  25592. int count; /* Number of elements left to test */
  25593. unsigned int h; /* The computed hash */
  25594. if( pH->ht ){
  25595. struct _ht *pEntry;
  25596. h = strHash(pKey) % pH->htsize;
  25597. pEntry = &pH->ht[h];
  25598. elem = pEntry->chain;
  25599. count = pEntry->count;
  25600. }else{
  25601. h = 0;
  25602. elem = pH->first;
  25603. count = pH->count;
  25604. }
  25605. *pHash = h;
  25606. while( count-- ){
  25607. assert( elem!=0 );
  25608. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  25609. return elem;
  25610. }
  25611. elem = elem->next;
  25612. }
  25613. return 0;
  25614. }
  25615. /* Remove a single entry from the hash table given a pointer to that
  25616. ** element and a hash on the element's key.
  25617. */
  25618. static void removeElementGivenHash(
  25619. Hash *pH, /* The pH containing "elem" */
  25620. HashElem* elem, /* The element to be removed from the pH */
  25621. unsigned int h /* Hash value for the element */
  25622. ){
  25623. struct _ht *pEntry;
  25624. if( elem->prev ){
  25625. elem->prev->next = elem->next;
  25626. }else{
  25627. pH->first = elem->next;
  25628. }
  25629. if( elem->next ){
  25630. elem->next->prev = elem->prev;
  25631. }
  25632. if( pH->ht ){
  25633. pEntry = &pH->ht[h];
  25634. if( pEntry->chain==elem ){
  25635. pEntry->chain = elem->next;
  25636. }
  25637. pEntry->count--;
  25638. assert( pEntry->count>=0 );
  25639. }
  25640. sqlite3_free( elem );
  25641. pH->count--;
  25642. if( pH->count==0 ){
  25643. assert( pH->first==0 );
  25644. assert( pH->count==0 );
  25645. sqlite3HashClear(pH);
  25646. }
  25647. }
  25648. /* Attempt to locate an element of the hash table pH with a key
  25649. ** that matches pKey. Return the data for this element if it is
  25650. ** found, or NULL if there is no match.
  25651. */
  25652. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  25653. HashElem *elem; /* The element that matches key */
  25654. unsigned int h; /* A hash on key */
  25655. assert( pH!=0 );
  25656. assert( pKey!=0 );
  25657. elem = findElementWithHash(pH, pKey, &h);
  25658. return elem ? elem->data : 0;
  25659. }
  25660. /* Insert an element into the hash table pH. The key is pKey
  25661. ** and the data is "data".
  25662. **
  25663. ** If no element exists with a matching key, then a new
  25664. ** element is created and NULL is returned.
  25665. **
  25666. ** If another element already exists with the same key, then the
  25667. ** new data replaces the old data and the old data is returned.
  25668. ** The key is not copied in this instance. If a malloc fails, then
  25669. ** the new data is returned and the hash table is unchanged.
  25670. **
  25671. ** If the "data" parameter to this function is NULL, then the
  25672. ** element corresponding to "key" is removed from the hash table.
  25673. */
  25674. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  25675. unsigned int h; /* the hash of the key modulo hash table size */
  25676. HashElem *elem; /* Used to loop thru the element list */
  25677. HashElem *new_elem; /* New element added to the pH */
  25678. assert( pH!=0 );
  25679. assert( pKey!=0 );
  25680. elem = findElementWithHash(pH,pKey,&h);
  25681. if( elem ){
  25682. void *old_data = elem->data;
  25683. if( data==0 ){
  25684. removeElementGivenHash(pH,elem,h);
  25685. }else{
  25686. elem->data = data;
  25687. elem->pKey = pKey;
  25688. }
  25689. return old_data;
  25690. }
  25691. if( data==0 ) return 0;
  25692. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  25693. if( new_elem==0 ) return data;
  25694. new_elem->pKey = pKey;
  25695. new_elem->data = data;
  25696. pH->count++;
  25697. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  25698. if( rehash(pH, pH->count*2) ){
  25699. assert( pH->htsize>0 );
  25700. h = strHash(pKey) % pH->htsize;
  25701. }
  25702. }
  25703. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  25704. return 0;
  25705. }
  25706. /************** End of hash.c ************************************************/
  25707. /************** Begin file opcodes.c *****************************************/
  25708. /* Automatically generated. Do not edit */
  25709. /* See the tool/mkopcodec.tcl script for details. */
  25710. #if !defined(SQLITE_OMIT_EXPLAIN) \
  25711. || defined(VDBE_PROFILE) \
  25712. || defined(SQLITE_DEBUG)
  25713. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  25714. # define OpHelp(X) "\0" X
  25715. #else
  25716. # define OpHelp(X)
  25717. #endif
  25718. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  25719. static const char *const azName[] = {
  25720. /* 0 */ "Savepoint" OpHelp(""),
  25721. /* 1 */ "AutoCommit" OpHelp(""),
  25722. /* 2 */ "Transaction" OpHelp(""),
  25723. /* 3 */ "SorterNext" OpHelp(""),
  25724. /* 4 */ "PrevIfOpen" OpHelp(""),
  25725. /* 5 */ "NextIfOpen" OpHelp(""),
  25726. /* 6 */ "Prev" OpHelp(""),
  25727. /* 7 */ "Next" OpHelp(""),
  25728. /* 8 */ "Checkpoint" OpHelp(""),
  25729. /* 9 */ "JournalMode" OpHelp(""),
  25730. /* 10 */ "Vacuum" OpHelp(""),
  25731. /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  25732. /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  25733. /* 13 */ "Goto" OpHelp(""),
  25734. /* 14 */ "Gosub" OpHelp(""),
  25735. /* 15 */ "Return" OpHelp(""),
  25736. /* 16 */ "InitCoroutine" OpHelp(""),
  25737. /* 17 */ "EndCoroutine" OpHelp(""),
  25738. /* 18 */ "Yield" OpHelp(""),
  25739. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  25740. /* 20 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  25741. /* 21 */ "Halt" OpHelp(""),
  25742. /* 22 */ "Integer" OpHelp("r[P2]=P1"),
  25743. /* 23 */ "Int64" OpHelp("r[P2]=P4"),
  25744. /* 24 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  25745. /* 25 */ "Null" OpHelp("r[P2..P3]=NULL"),
  25746. /* 26 */ "SoftNull" OpHelp("r[P1]=NULL"),
  25747. /* 27 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  25748. /* 28 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  25749. /* 29 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  25750. /* 30 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  25751. /* 31 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  25752. /* 32 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  25753. /* 33 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  25754. /* 34 */ "CollSeq" OpHelp(""),
  25755. /* 35 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  25756. /* 36 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  25757. /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  25758. /* 38 */ "MustBeInt" OpHelp(""),
  25759. /* 39 */ "RealAffinity" OpHelp(""),
  25760. /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
  25761. /* 41 */ "Permutation" OpHelp(""),
  25762. /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  25763. /* 43 */ "Jump" OpHelp(""),
  25764. /* 44 */ "Once" OpHelp(""),
  25765. /* 45 */ "If" OpHelp(""),
  25766. /* 46 */ "IfNot" OpHelp(""),
  25767. /* 47 */ "Column" OpHelp("r[P3]=PX"),
  25768. /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  25769. /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  25770. /* 50 */ "Count" OpHelp("r[P2]=count()"),
  25771. /* 51 */ "ReadCookie" OpHelp(""),
  25772. /* 52 */ "SetCookie" OpHelp(""),
  25773. /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  25774. /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  25775. /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  25776. /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  25777. /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  25778. /* 58 */ "SorterOpen" OpHelp(""),
  25779. /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  25780. /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  25781. /* 61 */ "Close" OpHelp(""),
  25782. /* 62 */ "ColumnsUsed" OpHelp(""),
  25783. /* 63 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  25784. /* 64 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  25785. /* 65 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  25786. /* 66 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  25787. /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  25788. /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
  25789. /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
  25790. /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
  25791. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  25792. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  25793. /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  25794. /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
  25795. /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  25796. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  25797. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  25798. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  25799. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  25800. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  25801. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  25802. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  25803. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  25804. /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  25805. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  25806. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  25807. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  25808. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  25809. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  25810. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  25811. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  25812. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  25813. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  25814. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  25815. /* 95 */ "Delete" OpHelp(""),
  25816. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  25817. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  25818. /* 98 */ "ResetCount" OpHelp(""),
  25819. /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  25820. /* 100 */ "SorterData" OpHelp("r[P2]=data"),
  25821. /* 101 */ "RowKey" OpHelp("r[P2]=key"),
  25822. /* 102 */ "RowData" OpHelp("r[P2]=data"),
  25823. /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
  25824. /* 104 */ "NullRow" OpHelp(""),
  25825. /* 105 */ "Last" OpHelp(""),
  25826. /* 106 */ "SorterSort" OpHelp(""),
  25827. /* 107 */ "Sort" OpHelp(""),
  25828. /* 108 */ "Rewind" OpHelp(""),
  25829. /* 109 */ "SorterInsert" OpHelp(""),
  25830. /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
  25831. /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  25832. /* 112 */ "Seek" OpHelp("Move P3 to P1.rowid"),
  25833. /* 113 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  25834. /* 114 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  25835. /* 115 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  25836. /* 116 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  25837. /* 117 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  25838. /* 118 */ "Destroy" OpHelp(""),
  25839. /* 119 */ "Clear" OpHelp(""),
  25840. /* 120 */ "ResetSorter" OpHelp(""),
  25841. /* 121 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  25842. /* 122 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  25843. /* 123 */ "ParseSchema" OpHelp(""),
  25844. /* 124 */ "LoadAnalysis" OpHelp(""),
  25845. /* 125 */ "DropTable" OpHelp(""),
  25846. /* 126 */ "DropIndex" OpHelp(""),
  25847. /* 127 */ "DropTrigger" OpHelp(""),
  25848. /* 128 */ "IntegrityCk" OpHelp(""),
  25849. /* 129 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  25850. /* 130 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  25851. /* 131 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  25852. /* 132 */ "Program" OpHelp(""),
  25853. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  25854. /* 134 */ "Param" OpHelp(""),
  25855. /* 135 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  25856. /* 136 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  25857. /* 137 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  25858. /* 138 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  25859. /* 139 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  25860. /* 140 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
  25861. /* 141 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  25862. /* 142 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
  25863. /* 143 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  25864. /* 144 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  25865. /* 145 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  25866. /* 146 */ "IncrVacuum" OpHelp(""),
  25867. /* 147 */ "Expire" OpHelp(""),
  25868. /* 148 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  25869. /* 149 */ "VBegin" OpHelp(""),
  25870. /* 150 */ "VCreate" OpHelp(""),
  25871. /* 151 */ "VDestroy" OpHelp(""),
  25872. /* 152 */ "VOpen" OpHelp(""),
  25873. /* 153 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  25874. /* 154 */ "VNext" OpHelp(""),
  25875. /* 155 */ "VRename" OpHelp(""),
  25876. /* 156 */ "Pagecount" OpHelp(""),
  25877. /* 157 */ "MaxPgcnt" OpHelp(""),
  25878. /* 158 */ "Init" OpHelp("Start at P2"),
  25879. /* 159 */ "CursorHint" OpHelp(""),
  25880. /* 160 */ "Noop" OpHelp(""),
  25881. /* 161 */ "Explain" OpHelp(""),
  25882. };
  25883. return azName[i];
  25884. }
  25885. #endif
  25886. /************** End of opcodes.c *********************************************/
  25887. /************** Begin file os_unix.c *****************************************/
  25888. /*
  25889. ** 2004 May 22
  25890. **
  25891. ** The author disclaims copyright to this source code. In place of
  25892. ** a legal notice, here is a blessing:
  25893. **
  25894. ** May you do good and not evil.
  25895. ** May you find forgiveness for yourself and forgive others.
  25896. ** May you share freely, never taking more than you give.
  25897. **
  25898. ******************************************************************************
  25899. **
  25900. ** This file contains the VFS implementation for unix-like operating systems
  25901. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  25902. **
  25903. ** There are actually several different VFS implementations in this file.
  25904. ** The differences are in the way that file locking is done. The default
  25905. ** implementation uses Posix Advisory Locks. Alternative implementations
  25906. ** use flock(), dot-files, various proprietary locking schemas, or simply
  25907. ** skip locking all together.
  25908. **
  25909. ** This source file is organized into divisions where the logic for various
  25910. ** subfunctions is contained within the appropriate division. PLEASE
  25911. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  25912. ** in the correct division and should be clearly labeled.
  25913. **
  25914. ** The layout of divisions is as follows:
  25915. **
  25916. ** * General-purpose declarations and utility functions.
  25917. ** * Unique file ID logic used by VxWorks.
  25918. ** * Various locking primitive implementations (all except proxy locking):
  25919. ** + for Posix Advisory Locks
  25920. ** + for no-op locks
  25921. ** + for dot-file locks
  25922. ** + for flock() locking
  25923. ** + for named semaphore locks (VxWorks only)
  25924. ** + for AFP filesystem locks (MacOSX only)
  25925. ** * sqlite3_file methods not associated with locking.
  25926. ** * Definitions of sqlite3_io_methods objects for all locking
  25927. ** methods plus "finder" functions for each locking method.
  25928. ** * sqlite3_vfs method implementations.
  25929. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  25930. ** * Definitions of sqlite3_vfs objects for all locking methods
  25931. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  25932. */
  25933. /* #include "sqliteInt.h" */
  25934. #if SQLITE_OS_UNIX /* This file is used on unix only */
  25935. /*
  25936. ** There are various methods for file locking used for concurrency
  25937. ** control:
  25938. **
  25939. ** 1. POSIX locking (the default),
  25940. ** 2. No locking,
  25941. ** 3. Dot-file locking,
  25942. ** 4. flock() locking,
  25943. ** 5. AFP locking (OSX only),
  25944. ** 6. Named POSIX semaphores (VXWorks only),
  25945. ** 7. proxy locking. (OSX only)
  25946. **
  25947. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  25948. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  25949. ** selection of the appropriate locking style based on the filesystem
  25950. ** where the database is located.
  25951. */
  25952. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  25953. # if defined(__APPLE__)
  25954. # define SQLITE_ENABLE_LOCKING_STYLE 1
  25955. # else
  25956. # define SQLITE_ENABLE_LOCKING_STYLE 0
  25957. # endif
  25958. #endif
  25959. /* Use pread() and pwrite() if they are available */
  25960. #if defined(__APPLE__)
  25961. # define HAVE_PREAD 1
  25962. # define HAVE_PWRITE 1
  25963. #endif
  25964. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  25965. # undef USE_PREAD
  25966. # define USE_PREAD64 1
  25967. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  25968. # undef USE_PREAD64
  25969. # define USE_PREAD 1
  25970. #endif
  25971. /*
  25972. ** standard include files.
  25973. */
  25974. #include <sys/types.h>
  25975. #include <sys/stat.h>
  25976. #include <fcntl.h>
  25977. #include <unistd.h>
  25978. /* #include <time.h> */
  25979. #include <sys/time.h>
  25980. #include <errno.h>
  25981. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  25982. # include <sys/mman.h>
  25983. #endif
  25984. #if SQLITE_ENABLE_LOCKING_STYLE
  25985. # include <sys/ioctl.h>
  25986. # include <sys/file.h>
  25987. # include <sys/param.h>
  25988. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  25989. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  25990. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  25991. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  25992. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  25993. # define HAVE_GETHOSTUUID 1
  25994. # else
  25995. # warning "gethostuuid() is disabled."
  25996. # endif
  25997. #endif
  25998. #if OS_VXWORKS
  25999. /* # include <sys/ioctl.h> */
  26000. # include <semaphore.h>
  26001. # include <limits.h>
  26002. #endif /* OS_VXWORKS */
  26003. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  26004. # include <sys/mount.h>
  26005. #endif
  26006. #ifdef HAVE_UTIME
  26007. # include <utime.h>
  26008. #endif
  26009. /*
  26010. ** Allowed values of unixFile.fsFlags
  26011. */
  26012. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  26013. /*
  26014. ** If we are to be thread-safe, include the pthreads header and define
  26015. ** the SQLITE_UNIX_THREADS macro.
  26016. */
  26017. #if SQLITE_THREADSAFE
  26018. /* # include <pthread.h> */
  26019. # define SQLITE_UNIX_THREADS 1
  26020. #endif
  26021. /*
  26022. ** Default permissions when creating a new file
  26023. */
  26024. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  26025. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  26026. #endif
  26027. /*
  26028. ** Default permissions when creating auto proxy dir
  26029. */
  26030. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  26031. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  26032. #endif
  26033. /*
  26034. ** Maximum supported path-length.
  26035. */
  26036. #define MAX_PATHNAME 512
  26037. /*
  26038. ** Maximum supported symbolic links
  26039. */
  26040. #define SQLITE_MAX_SYMLINKS 100
  26041. /* Always cast the getpid() return type for compatibility with
  26042. ** kernel modules in VxWorks. */
  26043. #define osGetpid(X) (pid_t)getpid()
  26044. /*
  26045. ** Only set the lastErrno if the error code is a real error and not
  26046. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  26047. */
  26048. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  26049. /* Forward references */
  26050. typedef struct unixShm unixShm; /* Connection shared memory */
  26051. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  26052. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  26053. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  26054. /*
  26055. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  26056. ** cannot be closed immediately. In these cases, instances of the following
  26057. ** structure are used to store the file descriptor while waiting for an
  26058. ** opportunity to either close or reuse it.
  26059. */
  26060. struct UnixUnusedFd {
  26061. int fd; /* File descriptor to close */
  26062. int flags; /* Flags this file descriptor was opened with */
  26063. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  26064. };
  26065. /*
  26066. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  26067. ** VFS implementations.
  26068. */
  26069. typedef struct unixFile unixFile;
  26070. struct unixFile {
  26071. sqlite3_io_methods const *pMethod; /* Always the first entry */
  26072. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  26073. unixInodeInfo *pInode; /* Info about locks on this inode */
  26074. int h; /* The file descriptor */
  26075. unsigned char eFileLock; /* The type of lock held on this fd */
  26076. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  26077. int lastErrno; /* The unix errno from last I/O error */
  26078. void *lockingContext; /* Locking style specific state */
  26079. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  26080. const char *zPath; /* Name of the file */
  26081. unixShm *pShm; /* Shared memory segment information */
  26082. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  26083. #if SQLITE_MAX_MMAP_SIZE>0
  26084. int nFetchOut; /* Number of outstanding xFetch refs */
  26085. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  26086. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  26087. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  26088. void *pMapRegion; /* Memory mapped region */
  26089. #endif
  26090. #ifdef __QNXNTO__
  26091. int sectorSize; /* Device sector size */
  26092. int deviceCharacteristics; /* Precomputed device characteristics */
  26093. #endif
  26094. #if SQLITE_ENABLE_LOCKING_STYLE
  26095. int openFlags; /* The flags specified at open() */
  26096. #endif
  26097. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  26098. unsigned fsFlags; /* cached details from statfs() */
  26099. #endif
  26100. #if OS_VXWORKS
  26101. struct vxworksFileId *pId; /* Unique file ID */
  26102. #endif
  26103. #ifdef SQLITE_DEBUG
  26104. /* The next group of variables are used to track whether or not the
  26105. ** transaction counter in bytes 24-27 of database files are updated
  26106. ** whenever any part of the database changes. An assertion fault will
  26107. ** occur if a file is updated without also updating the transaction
  26108. ** counter. This test is made to avoid new problems similar to the
  26109. ** one described by ticket #3584.
  26110. */
  26111. unsigned char transCntrChng; /* True if the transaction counter changed */
  26112. unsigned char dbUpdate; /* True if any part of database file changed */
  26113. unsigned char inNormalWrite; /* True if in a normal write operation */
  26114. #endif
  26115. #ifdef SQLITE_TEST
  26116. /* In test mode, increase the size of this structure a bit so that
  26117. ** it is larger than the struct CrashFile defined in test6.c.
  26118. */
  26119. char aPadding[32];
  26120. #endif
  26121. };
  26122. /* This variable holds the process id (pid) from when the xRandomness()
  26123. ** method was called. If xOpen() is called from a different process id,
  26124. ** indicating that a fork() has occurred, the PRNG will be reset.
  26125. */
  26126. static pid_t randomnessPid = 0;
  26127. /*
  26128. ** Allowed values for the unixFile.ctrlFlags bitmask:
  26129. */
  26130. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  26131. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  26132. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  26133. #ifndef SQLITE_DISABLE_DIRSYNC
  26134. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  26135. #else
  26136. # define UNIXFILE_DIRSYNC 0x00
  26137. #endif
  26138. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  26139. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  26140. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  26141. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  26142. /*
  26143. ** Include code that is common to all os_*.c files
  26144. */
  26145. /************** Include os_common.h in the middle of os_unix.c ***************/
  26146. /************** Begin file os_common.h ***************************************/
  26147. /*
  26148. ** 2004 May 22
  26149. **
  26150. ** The author disclaims copyright to this source code. In place of
  26151. ** a legal notice, here is a blessing:
  26152. **
  26153. ** May you do good and not evil.
  26154. ** May you find forgiveness for yourself and forgive others.
  26155. ** May you share freely, never taking more than you give.
  26156. **
  26157. ******************************************************************************
  26158. **
  26159. ** This file contains macros and a little bit of code that is common to
  26160. ** all of the platform-specific files (os_*.c) and is #included into those
  26161. ** files.
  26162. **
  26163. ** This file should be #included by the os_*.c files only. It is not a
  26164. ** general purpose header file.
  26165. */
  26166. #ifndef _OS_COMMON_H_
  26167. #define _OS_COMMON_H_
  26168. /*
  26169. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  26170. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  26171. ** switch. The following code should catch this problem at compile-time.
  26172. */
  26173. #ifdef MEMORY_DEBUG
  26174. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  26175. #endif
  26176. /*
  26177. ** Macros for performance tracing. Normally turned off. Only works
  26178. ** on i486 hardware.
  26179. */
  26180. #ifdef SQLITE_PERFORMANCE_TRACE
  26181. /*
  26182. ** hwtime.h contains inline assembler code for implementing
  26183. ** high-performance timing routines.
  26184. */
  26185. /************** Include hwtime.h in the middle of os_common.h ****************/
  26186. /************** Begin file hwtime.h ******************************************/
  26187. /*
  26188. ** 2008 May 27
  26189. **
  26190. ** The author disclaims copyright to this source code. In place of
  26191. ** a legal notice, here is a blessing:
  26192. **
  26193. ** May you do good and not evil.
  26194. ** May you find forgiveness for yourself and forgive others.
  26195. ** May you share freely, never taking more than you give.
  26196. **
  26197. ******************************************************************************
  26198. **
  26199. ** This file contains inline asm code for retrieving "high-performance"
  26200. ** counters for x86 class CPUs.
  26201. */
  26202. #ifndef _HWTIME_H_
  26203. #define _HWTIME_H_
  26204. /*
  26205. ** The following routine only works on pentium-class (or newer) processors.
  26206. ** It uses the RDTSC opcode to read the cycle count value out of the
  26207. ** processor and returns that value. This can be used for high-res
  26208. ** profiling.
  26209. */
  26210. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  26211. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  26212. #if defined(__GNUC__)
  26213. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  26214. unsigned int lo, hi;
  26215. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  26216. return (sqlite_uint64)hi << 32 | lo;
  26217. }
  26218. #elif defined(_MSC_VER)
  26219. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  26220. __asm {
  26221. rdtsc
  26222. ret ; return value at EDX:EAX
  26223. }
  26224. }
  26225. #endif
  26226. #elif (defined(__GNUC__) && defined(__x86_64__))
  26227. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  26228. unsigned long val;
  26229. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  26230. return val;
  26231. }
  26232. #elif (defined(__GNUC__) && defined(__ppc__))
  26233. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  26234. unsigned long long retval;
  26235. unsigned long junk;
  26236. __asm__ __volatile__ ("\n\
  26237. 1: mftbu %1\n\
  26238. mftb %L0\n\
  26239. mftbu %0\n\
  26240. cmpw %0,%1\n\
  26241. bne 1b"
  26242. : "=r" (retval), "=r" (junk));
  26243. return retval;
  26244. }
  26245. #else
  26246. #error Need implementation of sqlite3Hwtime() for your platform.
  26247. /*
  26248. ** To compile without implementing sqlite3Hwtime() for your platform,
  26249. ** you can remove the above #error and use the following
  26250. ** stub function. You will lose timing support for many
  26251. ** of the debugging and testing utilities, but it should at
  26252. ** least compile and run.
  26253. */
  26254. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  26255. #endif
  26256. #endif /* !defined(_HWTIME_H_) */
  26257. /************** End of hwtime.h **********************************************/
  26258. /************** Continuing where we left off in os_common.h ******************/
  26259. static sqlite_uint64 g_start;
  26260. static sqlite_uint64 g_elapsed;
  26261. #define TIMER_START g_start=sqlite3Hwtime()
  26262. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  26263. #define TIMER_ELAPSED g_elapsed
  26264. #else
  26265. #define TIMER_START
  26266. #define TIMER_END
  26267. #define TIMER_ELAPSED ((sqlite_uint64)0)
  26268. #endif
  26269. /*
  26270. ** If we compile with the SQLITE_TEST macro set, then the following block
  26271. ** of code will give us the ability to simulate a disk I/O error. This
  26272. ** is used for testing the I/O recovery logic.
  26273. */
  26274. #if defined(SQLITE_TEST)
  26275. SQLITE_API extern int sqlite3_io_error_hit;
  26276. SQLITE_API extern int sqlite3_io_error_hardhit;
  26277. SQLITE_API extern int sqlite3_io_error_pending;
  26278. SQLITE_API extern int sqlite3_io_error_persist;
  26279. SQLITE_API extern int sqlite3_io_error_benign;
  26280. SQLITE_API extern int sqlite3_diskfull_pending;
  26281. SQLITE_API extern int sqlite3_diskfull;
  26282. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  26283. #define SimulateIOError(CODE) \
  26284. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  26285. || sqlite3_io_error_pending-- == 1 ) \
  26286. { local_ioerr(); CODE; }
  26287. static void local_ioerr(){
  26288. IOTRACE(("IOERR\n"));
  26289. sqlite3_io_error_hit++;
  26290. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  26291. }
  26292. #define SimulateDiskfullError(CODE) \
  26293. if( sqlite3_diskfull_pending ){ \
  26294. if( sqlite3_diskfull_pending == 1 ){ \
  26295. local_ioerr(); \
  26296. sqlite3_diskfull = 1; \
  26297. sqlite3_io_error_hit = 1; \
  26298. CODE; \
  26299. }else{ \
  26300. sqlite3_diskfull_pending--; \
  26301. } \
  26302. }
  26303. #else
  26304. #define SimulateIOErrorBenign(X)
  26305. #define SimulateIOError(A)
  26306. #define SimulateDiskfullError(A)
  26307. #endif /* defined(SQLITE_TEST) */
  26308. /*
  26309. ** When testing, keep a count of the number of open files.
  26310. */
  26311. #if defined(SQLITE_TEST)
  26312. SQLITE_API extern int sqlite3_open_file_count;
  26313. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  26314. #else
  26315. #define OpenCounter(X)
  26316. #endif /* defined(SQLITE_TEST) */
  26317. #endif /* !defined(_OS_COMMON_H_) */
  26318. /************** End of os_common.h *******************************************/
  26319. /************** Continuing where we left off in os_unix.c ********************/
  26320. /*
  26321. ** Define various macros that are missing from some systems.
  26322. */
  26323. #ifndef O_LARGEFILE
  26324. # define O_LARGEFILE 0
  26325. #endif
  26326. #ifdef SQLITE_DISABLE_LFS
  26327. # undef O_LARGEFILE
  26328. # define O_LARGEFILE 0
  26329. #endif
  26330. #ifndef O_NOFOLLOW
  26331. # define O_NOFOLLOW 0
  26332. #endif
  26333. #ifndef O_BINARY
  26334. # define O_BINARY 0
  26335. #endif
  26336. /*
  26337. ** The threadid macro resolves to the thread-id or to 0. Used for
  26338. ** testing and debugging only.
  26339. */
  26340. #if SQLITE_THREADSAFE
  26341. #define threadid pthread_self()
  26342. #else
  26343. #define threadid 0
  26344. #endif
  26345. /*
  26346. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  26347. */
  26348. #if !defined(HAVE_MREMAP)
  26349. # if defined(__linux__) && defined(_GNU_SOURCE)
  26350. # define HAVE_MREMAP 1
  26351. # else
  26352. # define HAVE_MREMAP 0
  26353. # endif
  26354. #endif
  26355. /*
  26356. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  26357. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  26358. */
  26359. #ifdef __ANDROID__
  26360. # define lseek lseek64
  26361. #endif
  26362. /*
  26363. ** Different Unix systems declare open() in different ways. Same use
  26364. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  26365. ** The difference is important when using a pointer to the function.
  26366. **
  26367. ** The safest way to deal with the problem is to always use this wrapper
  26368. ** which always has the same well-defined interface.
  26369. */
  26370. static int posixOpen(const char *zFile, int flags, int mode){
  26371. return open(zFile, flags, mode);
  26372. }
  26373. /* Forward reference */
  26374. static int openDirectory(const char*, int*);
  26375. static int unixGetpagesize(void);
  26376. /*
  26377. ** Many system calls are accessed through pointer-to-functions so that
  26378. ** they may be overridden at runtime to facilitate fault injection during
  26379. ** testing and sandboxing. The following array holds the names and pointers
  26380. ** to all overrideable system calls.
  26381. */
  26382. static struct unix_syscall {
  26383. const char *zName; /* Name of the system call */
  26384. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  26385. sqlite3_syscall_ptr pDefault; /* Default value */
  26386. } aSyscall[] = {
  26387. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  26388. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  26389. { "close", (sqlite3_syscall_ptr)close, 0 },
  26390. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  26391. { "access", (sqlite3_syscall_ptr)access, 0 },
  26392. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  26393. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  26394. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  26395. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  26396. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  26397. /*
  26398. ** The DJGPP compiler environment looks mostly like Unix, but it
  26399. ** lacks the fcntl() system call. So redefine fcntl() to be something
  26400. ** that always succeeds. This means that locking does not occur under
  26401. ** DJGPP. But it is DOS - what did you expect?
  26402. */
  26403. #ifdef __DJGPP__
  26404. { "fstat", 0, 0 },
  26405. #define osFstat(a,b,c) 0
  26406. #else
  26407. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  26408. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  26409. #endif
  26410. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  26411. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  26412. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  26413. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  26414. { "read", (sqlite3_syscall_ptr)read, 0 },
  26415. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  26416. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  26417. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  26418. #else
  26419. { "pread", (sqlite3_syscall_ptr)0, 0 },
  26420. #endif
  26421. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  26422. #if defined(USE_PREAD64)
  26423. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  26424. #else
  26425. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  26426. #endif
  26427. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  26428. { "write", (sqlite3_syscall_ptr)write, 0 },
  26429. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  26430. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  26431. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  26432. #else
  26433. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  26434. #endif
  26435. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  26436. aSyscall[12].pCurrent)
  26437. #if defined(USE_PREAD64)
  26438. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  26439. #else
  26440. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  26441. #endif
  26442. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  26443. aSyscall[13].pCurrent)
  26444. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  26445. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  26446. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  26447. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  26448. #else
  26449. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  26450. #endif
  26451. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  26452. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  26453. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  26454. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  26455. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  26456. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  26457. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  26458. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  26459. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  26460. #if defined(HAVE_FCHOWN)
  26461. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  26462. #else
  26463. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  26464. #endif
  26465. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  26466. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  26467. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  26468. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  26469. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  26470. #else
  26471. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  26472. #endif
  26473. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  26474. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  26475. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  26476. #else
  26477. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  26478. #endif
  26479. #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
  26480. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  26481. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  26482. #else
  26483. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  26484. #endif
  26485. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  26486. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  26487. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  26488. #else
  26489. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  26490. #endif
  26491. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  26492. #if defined(HAVE_READLINK)
  26493. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  26494. #else
  26495. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  26496. #endif
  26497. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  26498. #if defined(HAVE_LSTAT)
  26499. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  26500. #else
  26501. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  26502. #endif
  26503. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  26504. }; /* End of the overrideable system calls */
  26505. /*
  26506. ** On some systems, calls to fchown() will trigger a message in a security
  26507. ** log if they come from non-root processes. So avoid calling fchown() if
  26508. ** we are not running as root.
  26509. */
  26510. static int robustFchown(int fd, uid_t uid, gid_t gid){
  26511. #if defined(HAVE_FCHOWN)
  26512. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  26513. #else
  26514. return 0;
  26515. #endif
  26516. }
  26517. /*
  26518. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  26519. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  26520. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  26521. ** system call named zName.
  26522. */
  26523. static int unixSetSystemCall(
  26524. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  26525. const char *zName, /* Name of system call to override */
  26526. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  26527. ){
  26528. unsigned int i;
  26529. int rc = SQLITE_NOTFOUND;
  26530. UNUSED_PARAMETER(pNotUsed);
  26531. if( zName==0 ){
  26532. /* If no zName is given, restore all system calls to their default
  26533. ** settings and return NULL
  26534. */
  26535. rc = SQLITE_OK;
  26536. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  26537. if( aSyscall[i].pDefault ){
  26538. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  26539. }
  26540. }
  26541. }else{
  26542. /* If zName is specified, operate on only the one system call
  26543. ** specified.
  26544. */
  26545. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  26546. if( strcmp(zName, aSyscall[i].zName)==0 ){
  26547. if( aSyscall[i].pDefault==0 ){
  26548. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  26549. }
  26550. rc = SQLITE_OK;
  26551. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  26552. aSyscall[i].pCurrent = pNewFunc;
  26553. break;
  26554. }
  26555. }
  26556. }
  26557. return rc;
  26558. }
  26559. /*
  26560. ** Return the value of a system call. Return NULL if zName is not a
  26561. ** recognized system call name. NULL is also returned if the system call
  26562. ** is currently undefined.
  26563. */
  26564. static sqlite3_syscall_ptr unixGetSystemCall(
  26565. sqlite3_vfs *pNotUsed,
  26566. const char *zName
  26567. ){
  26568. unsigned int i;
  26569. UNUSED_PARAMETER(pNotUsed);
  26570. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  26571. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  26572. }
  26573. return 0;
  26574. }
  26575. /*
  26576. ** Return the name of the first system call after zName. If zName==NULL
  26577. ** then return the name of the first system call. Return NULL if zName
  26578. ** is the last system call or if zName is not the name of a valid
  26579. ** system call.
  26580. */
  26581. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  26582. int i = -1;
  26583. UNUSED_PARAMETER(p);
  26584. if( zName ){
  26585. for(i=0; i<ArraySize(aSyscall)-1; i++){
  26586. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  26587. }
  26588. }
  26589. for(i++; i<ArraySize(aSyscall); i++){
  26590. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  26591. }
  26592. return 0;
  26593. }
  26594. /*
  26595. ** Do not accept any file descriptor less than this value, in order to avoid
  26596. ** opening database file using file descriptors that are commonly used for
  26597. ** standard input, output, and error.
  26598. */
  26599. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  26600. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  26601. #endif
  26602. /*
  26603. ** Invoke open(). Do so multiple times, until it either succeeds or
  26604. ** fails for some reason other than EINTR.
  26605. **
  26606. ** If the file creation mode "m" is 0 then set it to the default for
  26607. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  26608. ** 0644) as modified by the system umask. If m is not 0, then
  26609. ** make the file creation mode be exactly m ignoring the umask.
  26610. **
  26611. ** The m parameter will be non-zero only when creating -wal, -journal,
  26612. ** and -shm files. We want those files to have *exactly* the same
  26613. ** permissions as their original database, unadulterated by the umask.
  26614. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  26615. ** transaction crashes and leaves behind hot journals, then any
  26616. ** process that is able to write to the database will also be able to
  26617. ** recover the hot journals.
  26618. */
  26619. static int robust_open(const char *z, int f, mode_t m){
  26620. int fd;
  26621. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  26622. while(1){
  26623. #if defined(O_CLOEXEC)
  26624. fd = osOpen(z,f|O_CLOEXEC,m2);
  26625. #else
  26626. fd = osOpen(z,f,m2);
  26627. #endif
  26628. if( fd<0 ){
  26629. if( errno==EINTR ) continue;
  26630. break;
  26631. }
  26632. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  26633. osClose(fd);
  26634. sqlite3_log(SQLITE_WARNING,
  26635. "attempt to open \"%s\" as file descriptor %d", z, fd);
  26636. fd = -1;
  26637. if( osOpen("/dev/null", f, m)<0 ) break;
  26638. }
  26639. if( fd>=0 ){
  26640. if( m!=0 ){
  26641. struct stat statbuf;
  26642. if( osFstat(fd, &statbuf)==0
  26643. && statbuf.st_size==0
  26644. && (statbuf.st_mode&0777)!=m
  26645. ){
  26646. osFchmod(fd, m);
  26647. }
  26648. }
  26649. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  26650. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  26651. #endif
  26652. }
  26653. return fd;
  26654. }
  26655. /*
  26656. ** Helper functions to obtain and relinquish the global mutex. The
  26657. ** global mutex is used to protect the unixInodeInfo and
  26658. ** vxworksFileId objects used by this file, all of which may be
  26659. ** shared by multiple threads.
  26660. **
  26661. ** Function unixMutexHeld() is used to assert() that the global mutex
  26662. ** is held when required. This function is only used as part of assert()
  26663. ** statements. e.g.
  26664. **
  26665. ** unixEnterMutex()
  26666. ** assert( unixMutexHeld() );
  26667. ** unixEnterLeave()
  26668. */
  26669. static void unixEnterMutex(void){
  26670. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  26671. }
  26672. static void unixLeaveMutex(void){
  26673. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  26674. }
  26675. #ifdef SQLITE_DEBUG
  26676. static int unixMutexHeld(void) {
  26677. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  26678. }
  26679. #endif
  26680. #ifdef SQLITE_HAVE_OS_TRACE
  26681. /*
  26682. ** Helper function for printing out trace information from debugging
  26683. ** binaries. This returns the string representation of the supplied
  26684. ** integer lock-type.
  26685. */
  26686. static const char *azFileLock(int eFileLock){
  26687. switch( eFileLock ){
  26688. case NO_LOCK: return "NONE";
  26689. case SHARED_LOCK: return "SHARED";
  26690. case RESERVED_LOCK: return "RESERVED";
  26691. case PENDING_LOCK: return "PENDING";
  26692. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  26693. }
  26694. return "ERROR";
  26695. }
  26696. #endif
  26697. #ifdef SQLITE_LOCK_TRACE
  26698. /*
  26699. ** Print out information about all locking operations.
  26700. **
  26701. ** This routine is used for troubleshooting locks on multithreaded
  26702. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  26703. ** command-line option on the compiler. This code is normally
  26704. ** turned off.
  26705. */
  26706. static int lockTrace(int fd, int op, struct flock *p){
  26707. char *zOpName, *zType;
  26708. int s;
  26709. int savedErrno;
  26710. if( op==F_GETLK ){
  26711. zOpName = "GETLK";
  26712. }else if( op==F_SETLK ){
  26713. zOpName = "SETLK";
  26714. }else{
  26715. s = osFcntl(fd, op, p);
  26716. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  26717. return s;
  26718. }
  26719. if( p->l_type==F_RDLCK ){
  26720. zType = "RDLCK";
  26721. }else if( p->l_type==F_WRLCK ){
  26722. zType = "WRLCK";
  26723. }else if( p->l_type==F_UNLCK ){
  26724. zType = "UNLCK";
  26725. }else{
  26726. assert( 0 );
  26727. }
  26728. assert( p->l_whence==SEEK_SET );
  26729. s = osFcntl(fd, op, p);
  26730. savedErrno = errno;
  26731. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  26732. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  26733. (int)p->l_pid, s);
  26734. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  26735. struct flock l2;
  26736. l2 = *p;
  26737. osFcntl(fd, F_GETLK, &l2);
  26738. if( l2.l_type==F_RDLCK ){
  26739. zType = "RDLCK";
  26740. }else if( l2.l_type==F_WRLCK ){
  26741. zType = "WRLCK";
  26742. }else if( l2.l_type==F_UNLCK ){
  26743. zType = "UNLCK";
  26744. }else{
  26745. assert( 0 );
  26746. }
  26747. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  26748. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  26749. }
  26750. errno = savedErrno;
  26751. return s;
  26752. }
  26753. #undef osFcntl
  26754. #define osFcntl lockTrace
  26755. #endif /* SQLITE_LOCK_TRACE */
  26756. /*
  26757. ** Retry ftruncate() calls that fail due to EINTR
  26758. **
  26759. ** All calls to ftruncate() within this file should be made through
  26760. ** this wrapper. On the Android platform, bypassing the logic below
  26761. ** could lead to a corrupt database.
  26762. */
  26763. static int robust_ftruncate(int h, sqlite3_int64 sz){
  26764. int rc;
  26765. #ifdef __ANDROID__
  26766. /* On Android, ftruncate() always uses 32-bit offsets, even if
  26767. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  26768. ** truncate a file to any size larger than 2GiB. Silently ignore any
  26769. ** such attempts. */
  26770. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  26771. rc = SQLITE_OK;
  26772. }else
  26773. #endif
  26774. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  26775. return rc;
  26776. }
  26777. /*
  26778. ** This routine translates a standard POSIX errno code into something
  26779. ** useful to the clients of the sqlite3 functions. Specifically, it is
  26780. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  26781. ** and a variety of "please close the file descriptor NOW" errors into
  26782. ** SQLITE_IOERR
  26783. **
  26784. ** Errors during initialization of locks, or file system support for locks,
  26785. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  26786. */
  26787. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  26788. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  26789. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  26790. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  26791. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  26792. switch (posixError) {
  26793. case EACCES:
  26794. case EAGAIN:
  26795. case ETIMEDOUT:
  26796. case EBUSY:
  26797. case EINTR:
  26798. case ENOLCK:
  26799. /* random NFS retry error, unless during file system support
  26800. * introspection, in which it actually means what it says */
  26801. return SQLITE_BUSY;
  26802. case EPERM:
  26803. return SQLITE_PERM;
  26804. default:
  26805. return sqliteIOErr;
  26806. }
  26807. }
  26808. /******************************************************************************
  26809. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  26810. **
  26811. ** On most versions of unix, we can get a unique ID for a file by concatenating
  26812. ** the device number and the inode number. But this does not work on VxWorks.
  26813. ** On VxWorks, a unique file id must be based on the canonical filename.
  26814. **
  26815. ** A pointer to an instance of the following structure can be used as a
  26816. ** unique file ID in VxWorks. Each instance of this structure contains
  26817. ** a copy of the canonical filename. There is also a reference count.
  26818. ** The structure is reclaimed when the number of pointers to it drops to
  26819. ** zero.
  26820. **
  26821. ** There are never very many files open at one time and lookups are not
  26822. ** a performance-critical path, so it is sufficient to put these
  26823. ** structures on a linked list.
  26824. */
  26825. struct vxworksFileId {
  26826. struct vxworksFileId *pNext; /* Next in a list of them all */
  26827. int nRef; /* Number of references to this one */
  26828. int nName; /* Length of the zCanonicalName[] string */
  26829. char *zCanonicalName; /* Canonical filename */
  26830. };
  26831. #if OS_VXWORKS
  26832. /*
  26833. ** All unique filenames are held on a linked list headed by this
  26834. ** variable:
  26835. */
  26836. static struct vxworksFileId *vxworksFileList = 0;
  26837. /*
  26838. ** Simplify a filename into its canonical form
  26839. ** by making the following changes:
  26840. **
  26841. ** * removing any trailing and duplicate /
  26842. ** * convert /./ into just /
  26843. ** * convert /A/../ where A is any simple name into just /
  26844. **
  26845. ** Changes are made in-place. Return the new name length.
  26846. **
  26847. ** The original filename is in z[0..n-1]. Return the number of
  26848. ** characters in the simplified name.
  26849. */
  26850. static int vxworksSimplifyName(char *z, int n){
  26851. int i, j;
  26852. while( n>1 && z[n-1]=='/' ){ n--; }
  26853. for(i=j=0; i<n; i++){
  26854. if( z[i]=='/' ){
  26855. if( z[i+1]=='/' ) continue;
  26856. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  26857. i += 1;
  26858. continue;
  26859. }
  26860. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  26861. while( j>0 && z[j-1]!='/' ){ j--; }
  26862. if( j>0 ){ j--; }
  26863. i += 2;
  26864. continue;
  26865. }
  26866. }
  26867. z[j++] = z[i];
  26868. }
  26869. z[j] = 0;
  26870. return j;
  26871. }
  26872. /*
  26873. ** Find a unique file ID for the given absolute pathname. Return
  26874. ** a pointer to the vxworksFileId object. This pointer is the unique
  26875. ** file ID.
  26876. **
  26877. ** The nRef field of the vxworksFileId object is incremented before
  26878. ** the object is returned. A new vxworksFileId object is created
  26879. ** and added to the global list if necessary.
  26880. **
  26881. ** If a memory allocation error occurs, return NULL.
  26882. */
  26883. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  26884. struct vxworksFileId *pNew; /* search key and new file ID */
  26885. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  26886. int n; /* Length of zAbsoluteName string */
  26887. assert( zAbsoluteName[0]=='/' );
  26888. n = (int)strlen(zAbsoluteName);
  26889. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  26890. if( pNew==0 ) return 0;
  26891. pNew->zCanonicalName = (char*)&pNew[1];
  26892. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  26893. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  26894. /* Search for an existing entry that matching the canonical name.
  26895. ** If found, increment the reference count and return a pointer to
  26896. ** the existing file ID.
  26897. */
  26898. unixEnterMutex();
  26899. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  26900. if( pCandidate->nName==n
  26901. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  26902. ){
  26903. sqlite3_free(pNew);
  26904. pCandidate->nRef++;
  26905. unixLeaveMutex();
  26906. return pCandidate;
  26907. }
  26908. }
  26909. /* No match was found. We will make a new file ID */
  26910. pNew->nRef = 1;
  26911. pNew->nName = n;
  26912. pNew->pNext = vxworksFileList;
  26913. vxworksFileList = pNew;
  26914. unixLeaveMutex();
  26915. return pNew;
  26916. }
  26917. /*
  26918. ** Decrement the reference count on a vxworksFileId object. Free
  26919. ** the object when the reference count reaches zero.
  26920. */
  26921. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  26922. unixEnterMutex();
  26923. assert( pId->nRef>0 );
  26924. pId->nRef--;
  26925. if( pId->nRef==0 ){
  26926. struct vxworksFileId **pp;
  26927. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  26928. assert( *pp==pId );
  26929. *pp = pId->pNext;
  26930. sqlite3_free(pId);
  26931. }
  26932. unixLeaveMutex();
  26933. }
  26934. #endif /* OS_VXWORKS */
  26935. /*************** End of Unique File ID Utility Used By VxWorks ****************
  26936. ******************************************************************************/
  26937. /******************************************************************************
  26938. *************************** Posix Advisory Locking ****************************
  26939. **
  26940. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  26941. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  26942. ** sets or clears a lock, that operation overrides any prior locks set
  26943. ** by the same process. It does not explicitly say so, but this implies
  26944. ** that it overrides locks set by the same process using a different
  26945. ** file descriptor. Consider this test case:
  26946. **
  26947. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  26948. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  26949. **
  26950. ** Suppose ./file1 and ./file2 are really the same file (because
  26951. ** one is a hard or symbolic link to the other) then if you set
  26952. ** an exclusive lock on fd1, then try to get an exclusive lock
  26953. ** on fd2, it works. I would have expected the second lock to
  26954. ** fail since there was already a lock on the file due to fd1.
  26955. ** But not so. Since both locks came from the same process, the
  26956. ** second overrides the first, even though they were on different
  26957. ** file descriptors opened on different file names.
  26958. **
  26959. ** This means that we cannot use POSIX locks to synchronize file access
  26960. ** among competing threads of the same process. POSIX locks will work fine
  26961. ** to synchronize access for threads in separate processes, but not
  26962. ** threads within the same process.
  26963. **
  26964. ** To work around the problem, SQLite has to manage file locks internally
  26965. ** on its own. Whenever a new database is opened, we have to find the
  26966. ** specific inode of the database file (the inode is determined by the
  26967. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  26968. ** and check for locks already existing on that inode. When locks are
  26969. ** created or removed, we have to look at our own internal record of the
  26970. ** locks to see if another thread has previously set a lock on that same
  26971. ** inode.
  26972. **
  26973. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  26974. ** For VxWorks, we have to use the alternative unique ID system based on
  26975. ** canonical filename and implemented in the previous division.)
  26976. **
  26977. ** The sqlite3_file structure for POSIX is no longer just an integer file
  26978. ** descriptor. It is now a structure that holds the integer file
  26979. ** descriptor and a pointer to a structure that describes the internal
  26980. ** locks on the corresponding inode. There is one locking structure
  26981. ** per inode, so if the same inode is opened twice, both unixFile structures
  26982. ** point to the same locking structure. The locking structure keeps
  26983. ** a reference count (so we will know when to delete it) and a "cnt"
  26984. ** field that tells us its internal lock status. cnt==0 means the
  26985. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  26986. ** cnt>0 means there are cnt shared locks on the file.
  26987. **
  26988. ** Any attempt to lock or unlock a file first checks the locking
  26989. ** structure. The fcntl() system call is only invoked to set a
  26990. ** POSIX lock if the internal lock structure transitions between
  26991. ** a locked and an unlocked state.
  26992. **
  26993. ** But wait: there are yet more problems with POSIX advisory locks.
  26994. **
  26995. ** If you close a file descriptor that points to a file that has locks,
  26996. ** all locks on that file that are owned by the current process are
  26997. ** released. To work around this problem, each unixInodeInfo object
  26998. ** maintains a count of the number of pending locks on tha inode.
  26999. ** When an attempt is made to close an unixFile, if there are
  27000. ** other unixFile open on the same inode that are holding locks, the call
  27001. ** to close() the file descriptor is deferred until all of the locks clear.
  27002. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  27003. ** be closed and that list is walked (and cleared) when the last lock
  27004. ** clears.
  27005. **
  27006. ** Yet another problem: LinuxThreads do not play well with posix locks.
  27007. **
  27008. ** Many older versions of linux use the LinuxThreads library which is
  27009. ** not posix compliant. Under LinuxThreads, a lock created by thread
  27010. ** A cannot be modified or overridden by a different thread B.
  27011. ** Only thread A can modify the lock. Locking behavior is correct
  27012. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  27013. ** on linux - with NPTL a lock created by thread A can override locks
  27014. ** in thread B. But there is no way to know at compile-time which
  27015. ** threading library is being used. So there is no way to know at
  27016. ** compile-time whether or not thread A can override locks on thread B.
  27017. ** One has to do a run-time check to discover the behavior of the
  27018. ** current process.
  27019. **
  27020. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  27021. ** was dropped beginning with version 3.7.0. SQLite will still work with
  27022. ** LinuxThreads provided that (1) there is no more than one connection
  27023. ** per database file in the same process and (2) database connections
  27024. ** do not move across threads.
  27025. */
  27026. /*
  27027. ** An instance of the following structure serves as the key used
  27028. ** to locate a particular unixInodeInfo object.
  27029. */
  27030. struct unixFileId {
  27031. dev_t dev; /* Device number */
  27032. #if OS_VXWORKS
  27033. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  27034. #else
  27035. ino_t ino; /* Inode number */
  27036. #endif
  27037. };
  27038. /*
  27039. ** An instance of the following structure is allocated for each open
  27040. ** inode. Or, on LinuxThreads, there is one of these structures for
  27041. ** each inode opened by each thread.
  27042. **
  27043. ** A single inode can have multiple file descriptors, so each unixFile
  27044. ** structure contains a pointer to an instance of this object and this
  27045. ** object keeps a count of the number of unixFile pointing to it.
  27046. */
  27047. struct unixInodeInfo {
  27048. struct unixFileId fileId; /* The lookup key */
  27049. int nShared; /* Number of SHARED locks held */
  27050. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  27051. unsigned char bProcessLock; /* An exclusive process lock is held */
  27052. int nRef; /* Number of pointers to this structure */
  27053. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  27054. int nLock; /* Number of outstanding file locks */
  27055. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  27056. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  27057. unixInodeInfo *pPrev; /* .... doubly linked */
  27058. #if SQLITE_ENABLE_LOCKING_STYLE
  27059. unsigned long long sharedByte; /* for AFP simulated shared lock */
  27060. #endif
  27061. #if OS_VXWORKS
  27062. sem_t *pSem; /* Named POSIX semaphore */
  27063. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  27064. #endif
  27065. };
  27066. /*
  27067. ** A lists of all unixInodeInfo objects.
  27068. */
  27069. static unixInodeInfo *inodeList = 0;
  27070. /*
  27071. **
  27072. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  27073. ** unixLogError().
  27074. **
  27075. ** It is invoked after an error occurs in an OS function and errno has been
  27076. ** set. It logs a message using sqlite3_log() containing the current value of
  27077. ** errno and, if possible, the human-readable equivalent from strerror() or
  27078. ** strerror_r().
  27079. **
  27080. ** The first argument passed to the macro should be the error code that
  27081. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  27082. ** The two subsequent arguments should be the name of the OS function that
  27083. ** failed (e.g. "unlink", "open") and the associated file-system path,
  27084. ** if any.
  27085. */
  27086. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  27087. static int unixLogErrorAtLine(
  27088. int errcode, /* SQLite error code */
  27089. const char *zFunc, /* Name of OS function that failed */
  27090. const char *zPath, /* File path associated with error */
  27091. int iLine /* Source line number where error occurred */
  27092. ){
  27093. char *zErr; /* Message from strerror() or equivalent */
  27094. int iErrno = errno; /* Saved syscall error number */
  27095. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  27096. ** the strerror() function to obtain the human-readable error message
  27097. ** equivalent to errno. Otherwise, use strerror_r().
  27098. */
  27099. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  27100. char aErr[80];
  27101. memset(aErr, 0, sizeof(aErr));
  27102. zErr = aErr;
  27103. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  27104. ** assume that the system provides the GNU version of strerror_r() that
  27105. ** returns a pointer to a buffer containing the error message. That pointer
  27106. ** may point to aErr[], or it may point to some static storage somewhere.
  27107. ** Otherwise, assume that the system provides the POSIX version of
  27108. ** strerror_r(), which always writes an error message into aErr[].
  27109. **
  27110. ** If the code incorrectly assumes that it is the POSIX version that is
  27111. ** available, the error message will often be an empty string. Not a
  27112. ** huge problem. Incorrectly concluding that the GNU version is available
  27113. ** could lead to a segfault though.
  27114. */
  27115. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  27116. zErr =
  27117. # endif
  27118. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  27119. #elif SQLITE_THREADSAFE
  27120. /* This is a threadsafe build, but strerror_r() is not available. */
  27121. zErr = "";
  27122. #else
  27123. /* Non-threadsafe build, use strerror(). */
  27124. zErr = strerror(iErrno);
  27125. #endif
  27126. if( zPath==0 ) zPath = "";
  27127. sqlite3_log(errcode,
  27128. "os_unix.c:%d: (%d) %s(%s) - %s",
  27129. iLine, iErrno, zFunc, zPath, zErr
  27130. );
  27131. return errcode;
  27132. }
  27133. /*
  27134. ** Close a file descriptor.
  27135. **
  27136. ** We assume that close() almost always works, since it is only in a
  27137. ** very sick application or on a very sick platform that it might fail.
  27138. ** If it does fail, simply leak the file descriptor, but do log the
  27139. ** error.
  27140. **
  27141. ** Note that it is not safe to retry close() after EINTR since the
  27142. ** file descriptor might have already been reused by another thread.
  27143. ** So we don't even try to recover from an EINTR. Just log the error
  27144. ** and move on.
  27145. */
  27146. static void robust_close(unixFile *pFile, int h, int lineno){
  27147. if( osClose(h) ){
  27148. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  27149. pFile ? pFile->zPath : 0, lineno);
  27150. }
  27151. }
  27152. /*
  27153. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  27154. ** a convenient place to set a breakpoint.
  27155. */
  27156. static void storeLastErrno(unixFile *pFile, int error){
  27157. pFile->lastErrno = error;
  27158. }
  27159. /*
  27160. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  27161. */
  27162. static void closePendingFds(unixFile *pFile){
  27163. unixInodeInfo *pInode = pFile->pInode;
  27164. UnixUnusedFd *p;
  27165. UnixUnusedFd *pNext;
  27166. for(p=pInode->pUnused; p; p=pNext){
  27167. pNext = p->pNext;
  27168. robust_close(pFile, p->fd, __LINE__);
  27169. sqlite3_free(p);
  27170. }
  27171. pInode->pUnused = 0;
  27172. }
  27173. /*
  27174. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  27175. **
  27176. ** The mutex entered using the unixEnterMutex() function must be held
  27177. ** when this function is called.
  27178. */
  27179. static void releaseInodeInfo(unixFile *pFile){
  27180. unixInodeInfo *pInode = pFile->pInode;
  27181. assert( unixMutexHeld() );
  27182. if( ALWAYS(pInode) ){
  27183. pInode->nRef--;
  27184. if( pInode->nRef==0 ){
  27185. assert( pInode->pShmNode==0 );
  27186. closePendingFds(pFile);
  27187. if( pInode->pPrev ){
  27188. assert( pInode->pPrev->pNext==pInode );
  27189. pInode->pPrev->pNext = pInode->pNext;
  27190. }else{
  27191. assert( inodeList==pInode );
  27192. inodeList = pInode->pNext;
  27193. }
  27194. if( pInode->pNext ){
  27195. assert( pInode->pNext->pPrev==pInode );
  27196. pInode->pNext->pPrev = pInode->pPrev;
  27197. }
  27198. sqlite3_free(pInode);
  27199. }
  27200. }
  27201. }
  27202. /*
  27203. ** Given a file descriptor, locate the unixInodeInfo object that
  27204. ** describes that file descriptor. Create a new one if necessary. The
  27205. ** return value might be uninitialized if an error occurs.
  27206. **
  27207. ** The mutex entered using the unixEnterMutex() function must be held
  27208. ** when this function is called.
  27209. **
  27210. ** Return an appropriate error code.
  27211. */
  27212. static int findInodeInfo(
  27213. unixFile *pFile, /* Unix file with file desc used in the key */
  27214. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  27215. ){
  27216. int rc; /* System call return code */
  27217. int fd; /* The file descriptor for pFile */
  27218. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  27219. struct stat statbuf; /* Low-level file information */
  27220. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  27221. assert( unixMutexHeld() );
  27222. /* Get low-level information about the file that we can used to
  27223. ** create a unique name for the file.
  27224. */
  27225. fd = pFile->h;
  27226. rc = osFstat(fd, &statbuf);
  27227. if( rc!=0 ){
  27228. storeLastErrno(pFile, errno);
  27229. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  27230. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  27231. #endif
  27232. return SQLITE_IOERR;
  27233. }
  27234. #ifdef __APPLE__
  27235. /* On OS X on an msdos filesystem, the inode number is reported
  27236. ** incorrectly for zero-size files. See ticket #3260. To work
  27237. ** around this problem (we consider it a bug in OS X, not SQLite)
  27238. ** we always increase the file size to 1 by writing a single byte
  27239. ** prior to accessing the inode number. The one byte written is
  27240. ** an ASCII 'S' character which also happens to be the first byte
  27241. ** in the header of every SQLite database. In this way, if there
  27242. ** is a race condition such that another thread has already populated
  27243. ** the first page of the database, no damage is done.
  27244. */
  27245. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  27246. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  27247. if( rc!=1 ){
  27248. storeLastErrno(pFile, errno);
  27249. return SQLITE_IOERR;
  27250. }
  27251. rc = osFstat(fd, &statbuf);
  27252. if( rc!=0 ){
  27253. storeLastErrno(pFile, errno);
  27254. return SQLITE_IOERR;
  27255. }
  27256. }
  27257. #endif
  27258. memset(&fileId, 0, sizeof(fileId));
  27259. fileId.dev = statbuf.st_dev;
  27260. #if OS_VXWORKS
  27261. fileId.pId = pFile->pId;
  27262. #else
  27263. fileId.ino = statbuf.st_ino;
  27264. #endif
  27265. pInode = inodeList;
  27266. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  27267. pInode = pInode->pNext;
  27268. }
  27269. if( pInode==0 ){
  27270. pInode = sqlite3_malloc64( sizeof(*pInode) );
  27271. if( pInode==0 ){
  27272. return SQLITE_NOMEM_BKPT;
  27273. }
  27274. memset(pInode, 0, sizeof(*pInode));
  27275. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  27276. pInode->nRef = 1;
  27277. pInode->pNext = inodeList;
  27278. pInode->pPrev = 0;
  27279. if( inodeList ) inodeList->pPrev = pInode;
  27280. inodeList = pInode;
  27281. }else{
  27282. pInode->nRef++;
  27283. }
  27284. *ppInode = pInode;
  27285. return SQLITE_OK;
  27286. }
  27287. /*
  27288. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  27289. */
  27290. static int fileHasMoved(unixFile *pFile){
  27291. #if OS_VXWORKS
  27292. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  27293. #else
  27294. struct stat buf;
  27295. return pFile->pInode!=0 &&
  27296. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  27297. #endif
  27298. }
  27299. /*
  27300. ** Check a unixFile that is a database. Verify the following:
  27301. **
  27302. ** (1) There is exactly one hard link on the file
  27303. ** (2) The file is not a symbolic link
  27304. ** (3) The file has not been renamed or unlinked
  27305. **
  27306. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  27307. */
  27308. static void verifyDbFile(unixFile *pFile){
  27309. struct stat buf;
  27310. int rc;
  27311. /* These verifications occurs for the main database only */
  27312. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  27313. rc = osFstat(pFile->h, &buf);
  27314. if( rc!=0 ){
  27315. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  27316. return;
  27317. }
  27318. if( buf.st_nlink==0 ){
  27319. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  27320. return;
  27321. }
  27322. if( buf.st_nlink>1 ){
  27323. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  27324. return;
  27325. }
  27326. if( fileHasMoved(pFile) ){
  27327. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  27328. return;
  27329. }
  27330. }
  27331. /*
  27332. ** This routine checks if there is a RESERVED lock held on the specified
  27333. ** file by this or any other process. If such a lock is held, set *pResOut
  27334. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27335. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27336. */
  27337. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  27338. int rc = SQLITE_OK;
  27339. int reserved = 0;
  27340. unixFile *pFile = (unixFile*)id;
  27341. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27342. assert( pFile );
  27343. assert( pFile->eFileLock<=SHARED_LOCK );
  27344. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  27345. /* Check if a thread in this process holds such a lock */
  27346. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  27347. reserved = 1;
  27348. }
  27349. /* Otherwise see if some other process holds it.
  27350. */
  27351. #ifndef __DJGPP__
  27352. if( !reserved && !pFile->pInode->bProcessLock ){
  27353. struct flock lock;
  27354. lock.l_whence = SEEK_SET;
  27355. lock.l_start = RESERVED_BYTE;
  27356. lock.l_len = 1;
  27357. lock.l_type = F_WRLCK;
  27358. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  27359. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  27360. storeLastErrno(pFile, errno);
  27361. } else if( lock.l_type!=F_UNLCK ){
  27362. reserved = 1;
  27363. }
  27364. }
  27365. #endif
  27366. unixLeaveMutex();
  27367. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  27368. *pResOut = reserved;
  27369. return rc;
  27370. }
  27371. /*
  27372. ** Attempt to set a system-lock on the file pFile. The lock is
  27373. ** described by pLock.
  27374. **
  27375. ** If the pFile was opened read/write from unix-excl, then the only lock
  27376. ** ever obtained is an exclusive lock, and it is obtained exactly once
  27377. ** the first time any lock is attempted. All subsequent system locking
  27378. ** operations become no-ops. Locking operations still happen internally,
  27379. ** in order to coordinate access between separate database connections
  27380. ** within this process, but all of that is handled in memory and the
  27381. ** operating system does not participate.
  27382. **
  27383. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  27384. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  27385. ** and is read-only.
  27386. **
  27387. ** Zero is returned if the call completes successfully, or -1 if a call
  27388. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  27389. */
  27390. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  27391. int rc;
  27392. unixInodeInfo *pInode = pFile->pInode;
  27393. assert( unixMutexHeld() );
  27394. assert( pInode!=0 );
  27395. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  27396. if( pInode->bProcessLock==0 ){
  27397. struct flock lock;
  27398. assert( pInode->nLock==0 );
  27399. lock.l_whence = SEEK_SET;
  27400. lock.l_start = SHARED_FIRST;
  27401. lock.l_len = SHARED_SIZE;
  27402. lock.l_type = F_WRLCK;
  27403. rc = osFcntl(pFile->h, F_SETLK, &lock);
  27404. if( rc<0 ) return rc;
  27405. pInode->bProcessLock = 1;
  27406. pInode->nLock++;
  27407. }else{
  27408. rc = 0;
  27409. }
  27410. }else{
  27411. rc = osFcntl(pFile->h, F_SETLK, pLock);
  27412. }
  27413. return rc;
  27414. }
  27415. /*
  27416. ** Lock the file with the lock specified by parameter eFileLock - one
  27417. ** of the following:
  27418. **
  27419. ** (1) SHARED_LOCK
  27420. ** (2) RESERVED_LOCK
  27421. ** (3) PENDING_LOCK
  27422. ** (4) EXCLUSIVE_LOCK
  27423. **
  27424. ** Sometimes when requesting one lock state, additional lock states
  27425. ** are inserted in between. The locking might fail on one of the later
  27426. ** transitions leaving the lock state different from what it started but
  27427. ** still short of its goal. The following chart shows the allowed
  27428. ** transitions and the inserted intermediate states:
  27429. **
  27430. ** UNLOCKED -> SHARED
  27431. ** SHARED -> RESERVED
  27432. ** SHARED -> (PENDING) -> EXCLUSIVE
  27433. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27434. ** PENDING -> EXCLUSIVE
  27435. **
  27436. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27437. ** routine to lower a locking level.
  27438. */
  27439. static int unixLock(sqlite3_file *id, int eFileLock){
  27440. /* The following describes the implementation of the various locks and
  27441. ** lock transitions in terms of the POSIX advisory shared and exclusive
  27442. ** lock primitives (called read-locks and write-locks below, to avoid
  27443. ** confusion with SQLite lock names). The algorithms are complicated
  27444. ** slightly in order to be compatible with windows systems simultaneously
  27445. ** accessing the same database file, in case that is ever required.
  27446. **
  27447. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  27448. ** byte', each single bytes at well known offsets, and the 'shared byte
  27449. ** range', a range of 510 bytes at a well known offset.
  27450. **
  27451. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  27452. ** byte'. If this is successful, a random byte from the 'shared byte
  27453. ** range' is read-locked and the lock on the 'pending byte' released.
  27454. **
  27455. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  27456. ** A RESERVED lock is implemented by grabbing a write-lock on the
  27457. ** 'reserved byte'.
  27458. **
  27459. ** A process may only obtain a PENDING lock after it has obtained a
  27460. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  27461. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  27462. ** obtained, but existing SHARED locks are allowed to persist. A process
  27463. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  27464. ** This property is used by the algorithm for rolling back a journal file
  27465. ** after a crash.
  27466. **
  27467. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  27468. ** implemented by obtaining a write-lock on the entire 'shared byte
  27469. ** range'. Since all other locks require a read-lock on one of the bytes
  27470. ** within this range, this ensures that no other locks are held on the
  27471. ** database.
  27472. **
  27473. ** The reason a single byte cannot be used instead of the 'shared byte
  27474. ** range' is that some versions of windows do not support read-locks. By
  27475. ** locking a random byte from a range, concurrent SHARED locks may exist
  27476. ** even if the locking primitive used is always a write-lock.
  27477. */
  27478. int rc = SQLITE_OK;
  27479. unixFile *pFile = (unixFile*)id;
  27480. unixInodeInfo *pInode;
  27481. struct flock lock;
  27482. int tErrno = 0;
  27483. assert( pFile );
  27484. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  27485. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  27486. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  27487. osGetpid(0)));
  27488. /* If there is already a lock of this type or more restrictive on the
  27489. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  27490. ** unixEnterMutex() hasn't been called yet.
  27491. */
  27492. if( pFile->eFileLock>=eFileLock ){
  27493. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  27494. azFileLock(eFileLock)));
  27495. return SQLITE_OK;
  27496. }
  27497. /* Make sure the locking sequence is correct.
  27498. ** (1) We never move from unlocked to anything higher than shared lock.
  27499. ** (2) SQLite never explicitly requests a pendig lock.
  27500. ** (3) A shared lock is always held when a reserve lock is requested.
  27501. */
  27502. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  27503. assert( eFileLock!=PENDING_LOCK );
  27504. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  27505. /* This mutex is needed because pFile->pInode is shared across threads
  27506. */
  27507. unixEnterMutex();
  27508. pInode = pFile->pInode;
  27509. /* If some thread using this PID has a lock via a different unixFile*
  27510. ** handle that precludes the requested lock, return BUSY.
  27511. */
  27512. if( (pFile->eFileLock!=pInode->eFileLock &&
  27513. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  27514. ){
  27515. rc = SQLITE_BUSY;
  27516. goto end_lock;
  27517. }
  27518. /* If a SHARED lock is requested, and some thread using this PID already
  27519. ** has a SHARED or RESERVED lock, then increment reference counts and
  27520. ** return SQLITE_OK.
  27521. */
  27522. if( eFileLock==SHARED_LOCK &&
  27523. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  27524. assert( eFileLock==SHARED_LOCK );
  27525. assert( pFile->eFileLock==0 );
  27526. assert( pInode->nShared>0 );
  27527. pFile->eFileLock = SHARED_LOCK;
  27528. pInode->nShared++;
  27529. pInode->nLock++;
  27530. goto end_lock;
  27531. }
  27532. /* A PENDING lock is needed before acquiring a SHARED lock and before
  27533. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  27534. ** be released.
  27535. */
  27536. lock.l_len = 1L;
  27537. lock.l_whence = SEEK_SET;
  27538. if( eFileLock==SHARED_LOCK
  27539. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  27540. ){
  27541. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  27542. lock.l_start = PENDING_BYTE;
  27543. if( unixFileLock(pFile, &lock) ){
  27544. tErrno = errno;
  27545. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27546. if( rc!=SQLITE_BUSY ){
  27547. storeLastErrno(pFile, tErrno);
  27548. }
  27549. goto end_lock;
  27550. }
  27551. }
  27552. /* If control gets to this point, then actually go ahead and make
  27553. ** operating system calls for the specified lock.
  27554. */
  27555. if( eFileLock==SHARED_LOCK ){
  27556. assert( pInode->nShared==0 );
  27557. assert( pInode->eFileLock==0 );
  27558. assert( rc==SQLITE_OK );
  27559. /* Now get the read-lock */
  27560. lock.l_start = SHARED_FIRST;
  27561. lock.l_len = SHARED_SIZE;
  27562. if( unixFileLock(pFile, &lock) ){
  27563. tErrno = errno;
  27564. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27565. }
  27566. /* Drop the temporary PENDING lock */
  27567. lock.l_start = PENDING_BYTE;
  27568. lock.l_len = 1L;
  27569. lock.l_type = F_UNLCK;
  27570. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  27571. /* This could happen with a network mount */
  27572. tErrno = errno;
  27573. rc = SQLITE_IOERR_UNLOCK;
  27574. }
  27575. if( rc ){
  27576. if( rc!=SQLITE_BUSY ){
  27577. storeLastErrno(pFile, tErrno);
  27578. }
  27579. goto end_lock;
  27580. }else{
  27581. pFile->eFileLock = SHARED_LOCK;
  27582. pInode->nLock++;
  27583. pInode->nShared = 1;
  27584. }
  27585. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  27586. /* We are trying for an exclusive lock but another thread in this
  27587. ** same process is still holding a shared lock. */
  27588. rc = SQLITE_BUSY;
  27589. }else{
  27590. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  27591. ** assumed that there is a SHARED or greater lock on the file
  27592. ** already.
  27593. */
  27594. assert( 0!=pFile->eFileLock );
  27595. lock.l_type = F_WRLCK;
  27596. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  27597. if( eFileLock==RESERVED_LOCK ){
  27598. lock.l_start = RESERVED_BYTE;
  27599. lock.l_len = 1L;
  27600. }else{
  27601. lock.l_start = SHARED_FIRST;
  27602. lock.l_len = SHARED_SIZE;
  27603. }
  27604. if( unixFileLock(pFile, &lock) ){
  27605. tErrno = errno;
  27606. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27607. if( rc!=SQLITE_BUSY ){
  27608. storeLastErrno(pFile, tErrno);
  27609. }
  27610. }
  27611. }
  27612. #ifdef SQLITE_DEBUG
  27613. /* Set up the transaction-counter change checking flags when
  27614. ** transitioning from a SHARED to a RESERVED lock. The change
  27615. ** from SHARED to RESERVED marks the beginning of a normal
  27616. ** write operation (not a hot journal rollback).
  27617. */
  27618. if( rc==SQLITE_OK
  27619. && pFile->eFileLock<=SHARED_LOCK
  27620. && eFileLock==RESERVED_LOCK
  27621. ){
  27622. pFile->transCntrChng = 0;
  27623. pFile->dbUpdate = 0;
  27624. pFile->inNormalWrite = 1;
  27625. }
  27626. #endif
  27627. if( rc==SQLITE_OK ){
  27628. pFile->eFileLock = eFileLock;
  27629. pInode->eFileLock = eFileLock;
  27630. }else if( eFileLock==EXCLUSIVE_LOCK ){
  27631. pFile->eFileLock = PENDING_LOCK;
  27632. pInode->eFileLock = PENDING_LOCK;
  27633. }
  27634. end_lock:
  27635. unixLeaveMutex();
  27636. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  27637. rc==SQLITE_OK ? "ok" : "failed"));
  27638. return rc;
  27639. }
  27640. /*
  27641. ** Add the file descriptor used by file handle pFile to the corresponding
  27642. ** pUnused list.
  27643. */
  27644. static void setPendingFd(unixFile *pFile){
  27645. unixInodeInfo *pInode = pFile->pInode;
  27646. UnixUnusedFd *p = pFile->pUnused;
  27647. p->pNext = pInode->pUnused;
  27648. pInode->pUnused = p;
  27649. pFile->h = -1;
  27650. pFile->pUnused = 0;
  27651. }
  27652. /*
  27653. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27654. ** must be either NO_LOCK or SHARED_LOCK.
  27655. **
  27656. ** If the locking level of the file descriptor is already at or below
  27657. ** the requested locking level, this routine is a no-op.
  27658. **
  27659. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  27660. ** the byte range is divided into 2 parts and the first part is unlocked then
  27661. ** set to a read lock, then the other part is simply unlocked. This works
  27662. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  27663. ** remove the write lock on a region when a read lock is set.
  27664. */
  27665. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  27666. unixFile *pFile = (unixFile*)id;
  27667. unixInodeInfo *pInode;
  27668. struct flock lock;
  27669. int rc = SQLITE_OK;
  27670. assert( pFile );
  27671. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  27672. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  27673. osGetpid(0)));
  27674. assert( eFileLock<=SHARED_LOCK );
  27675. if( pFile->eFileLock<=eFileLock ){
  27676. return SQLITE_OK;
  27677. }
  27678. unixEnterMutex();
  27679. pInode = pFile->pInode;
  27680. assert( pInode->nShared!=0 );
  27681. if( pFile->eFileLock>SHARED_LOCK ){
  27682. assert( pInode->eFileLock==pFile->eFileLock );
  27683. #ifdef SQLITE_DEBUG
  27684. /* When reducing a lock such that other processes can start
  27685. ** reading the database file again, make sure that the
  27686. ** transaction counter was updated if any part of the database
  27687. ** file changed. If the transaction counter is not updated,
  27688. ** other connections to the same file might not realize that
  27689. ** the file has changed and hence might not know to flush their
  27690. ** cache. The use of a stale cache can lead to database corruption.
  27691. */
  27692. pFile->inNormalWrite = 0;
  27693. #endif
  27694. /* downgrading to a shared lock on NFS involves clearing the write lock
  27695. ** before establishing the readlock - to avoid a race condition we downgrade
  27696. ** the lock in 2 blocks, so that part of the range will be covered by a
  27697. ** write lock until the rest is covered by a read lock:
  27698. ** 1: [WWWWW]
  27699. ** 2: [....W]
  27700. ** 3: [RRRRW]
  27701. ** 4: [RRRR.]
  27702. */
  27703. if( eFileLock==SHARED_LOCK ){
  27704. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  27705. (void)handleNFSUnlock;
  27706. assert( handleNFSUnlock==0 );
  27707. #endif
  27708. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27709. if( handleNFSUnlock ){
  27710. int tErrno; /* Error code from system call errors */
  27711. off_t divSize = SHARED_SIZE - 1;
  27712. lock.l_type = F_UNLCK;
  27713. lock.l_whence = SEEK_SET;
  27714. lock.l_start = SHARED_FIRST;
  27715. lock.l_len = divSize;
  27716. if( unixFileLock(pFile, &lock)==(-1) ){
  27717. tErrno = errno;
  27718. rc = SQLITE_IOERR_UNLOCK;
  27719. storeLastErrno(pFile, tErrno);
  27720. goto end_unlock;
  27721. }
  27722. lock.l_type = F_RDLCK;
  27723. lock.l_whence = SEEK_SET;
  27724. lock.l_start = SHARED_FIRST;
  27725. lock.l_len = divSize;
  27726. if( unixFileLock(pFile, &lock)==(-1) ){
  27727. tErrno = errno;
  27728. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  27729. if( IS_LOCK_ERROR(rc) ){
  27730. storeLastErrno(pFile, tErrno);
  27731. }
  27732. goto end_unlock;
  27733. }
  27734. lock.l_type = F_UNLCK;
  27735. lock.l_whence = SEEK_SET;
  27736. lock.l_start = SHARED_FIRST+divSize;
  27737. lock.l_len = SHARED_SIZE-divSize;
  27738. if( unixFileLock(pFile, &lock)==(-1) ){
  27739. tErrno = errno;
  27740. rc = SQLITE_IOERR_UNLOCK;
  27741. storeLastErrno(pFile, tErrno);
  27742. goto end_unlock;
  27743. }
  27744. }else
  27745. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  27746. {
  27747. lock.l_type = F_RDLCK;
  27748. lock.l_whence = SEEK_SET;
  27749. lock.l_start = SHARED_FIRST;
  27750. lock.l_len = SHARED_SIZE;
  27751. if( unixFileLock(pFile, &lock) ){
  27752. /* In theory, the call to unixFileLock() cannot fail because another
  27753. ** process is holding an incompatible lock. If it does, this
  27754. ** indicates that the other process is not following the locking
  27755. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  27756. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  27757. ** an assert to fail). */
  27758. rc = SQLITE_IOERR_RDLOCK;
  27759. storeLastErrno(pFile, errno);
  27760. goto end_unlock;
  27761. }
  27762. }
  27763. }
  27764. lock.l_type = F_UNLCK;
  27765. lock.l_whence = SEEK_SET;
  27766. lock.l_start = PENDING_BYTE;
  27767. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  27768. if( unixFileLock(pFile, &lock)==0 ){
  27769. pInode->eFileLock = SHARED_LOCK;
  27770. }else{
  27771. rc = SQLITE_IOERR_UNLOCK;
  27772. storeLastErrno(pFile, errno);
  27773. goto end_unlock;
  27774. }
  27775. }
  27776. if( eFileLock==NO_LOCK ){
  27777. /* Decrement the shared lock counter. Release the lock using an
  27778. ** OS call only when all threads in this same process have released
  27779. ** the lock.
  27780. */
  27781. pInode->nShared--;
  27782. if( pInode->nShared==0 ){
  27783. lock.l_type = F_UNLCK;
  27784. lock.l_whence = SEEK_SET;
  27785. lock.l_start = lock.l_len = 0L;
  27786. if( unixFileLock(pFile, &lock)==0 ){
  27787. pInode->eFileLock = NO_LOCK;
  27788. }else{
  27789. rc = SQLITE_IOERR_UNLOCK;
  27790. storeLastErrno(pFile, errno);
  27791. pInode->eFileLock = NO_LOCK;
  27792. pFile->eFileLock = NO_LOCK;
  27793. }
  27794. }
  27795. /* Decrement the count of locks against this same file. When the
  27796. ** count reaches zero, close any other file descriptors whose close
  27797. ** was deferred because of outstanding locks.
  27798. */
  27799. pInode->nLock--;
  27800. assert( pInode->nLock>=0 );
  27801. if( pInode->nLock==0 ){
  27802. closePendingFds(pFile);
  27803. }
  27804. }
  27805. end_unlock:
  27806. unixLeaveMutex();
  27807. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  27808. return rc;
  27809. }
  27810. /*
  27811. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27812. ** must be either NO_LOCK or SHARED_LOCK.
  27813. **
  27814. ** If the locking level of the file descriptor is already at or below
  27815. ** the requested locking level, this routine is a no-op.
  27816. */
  27817. static int unixUnlock(sqlite3_file *id, int eFileLock){
  27818. #if SQLITE_MAX_MMAP_SIZE>0
  27819. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  27820. #endif
  27821. return posixUnlock(id, eFileLock, 0);
  27822. }
  27823. #if SQLITE_MAX_MMAP_SIZE>0
  27824. static int unixMapfile(unixFile *pFd, i64 nByte);
  27825. static void unixUnmapfile(unixFile *pFd);
  27826. #endif
  27827. /*
  27828. ** This function performs the parts of the "close file" operation
  27829. ** common to all locking schemes. It closes the directory and file
  27830. ** handles, if they are valid, and sets all fields of the unixFile
  27831. ** structure to 0.
  27832. **
  27833. ** It is *not* necessary to hold the mutex when this routine is called,
  27834. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  27835. ** vxworksReleaseFileId() routine.
  27836. */
  27837. static int closeUnixFile(sqlite3_file *id){
  27838. unixFile *pFile = (unixFile*)id;
  27839. #if SQLITE_MAX_MMAP_SIZE>0
  27840. unixUnmapfile(pFile);
  27841. #endif
  27842. if( pFile->h>=0 ){
  27843. robust_close(pFile, pFile->h, __LINE__);
  27844. pFile->h = -1;
  27845. }
  27846. #if OS_VXWORKS
  27847. if( pFile->pId ){
  27848. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  27849. osUnlink(pFile->pId->zCanonicalName);
  27850. }
  27851. vxworksReleaseFileId(pFile->pId);
  27852. pFile->pId = 0;
  27853. }
  27854. #endif
  27855. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  27856. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  27857. osUnlink(pFile->zPath);
  27858. sqlite3_free(*(char**)&pFile->zPath);
  27859. pFile->zPath = 0;
  27860. }
  27861. #endif
  27862. OSTRACE(("CLOSE %-3d\n", pFile->h));
  27863. OpenCounter(-1);
  27864. sqlite3_free(pFile->pUnused);
  27865. memset(pFile, 0, sizeof(unixFile));
  27866. return SQLITE_OK;
  27867. }
  27868. /*
  27869. ** Close a file.
  27870. */
  27871. static int unixClose(sqlite3_file *id){
  27872. int rc = SQLITE_OK;
  27873. unixFile *pFile = (unixFile *)id;
  27874. verifyDbFile(pFile);
  27875. unixUnlock(id, NO_LOCK);
  27876. unixEnterMutex();
  27877. /* unixFile.pInode is always valid here. Otherwise, a different close
  27878. ** routine (e.g. nolockClose()) would be called instead.
  27879. */
  27880. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  27881. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  27882. /* If there are outstanding locks, do not actually close the file just
  27883. ** yet because that would clear those locks. Instead, add the file
  27884. ** descriptor to pInode->pUnused list. It will be automatically closed
  27885. ** when the last lock is cleared.
  27886. */
  27887. setPendingFd(pFile);
  27888. }
  27889. releaseInodeInfo(pFile);
  27890. rc = closeUnixFile(id);
  27891. unixLeaveMutex();
  27892. return rc;
  27893. }
  27894. /************** End of the posix advisory lock implementation *****************
  27895. ******************************************************************************/
  27896. /******************************************************************************
  27897. ****************************** No-op Locking **********************************
  27898. **
  27899. ** Of the various locking implementations available, this is by far the
  27900. ** simplest: locking is ignored. No attempt is made to lock the database
  27901. ** file for reading or writing.
  27902. **
  27903. ** This locking mode is appropriate for use on read-only databases
  27904. ** (ex: databases that are burned into CD-ROM, for example.) It can
  27905. ** also be used if the application employs some external mechanism to
  27906. ** prevent simultaneous access of the same database by two or more
  27907. ** database connections. But there is a serious risk of database
  27908. ** corruption if this locking mode is used in situations where multiple
  27909. ** database connections are accessing the same database file at the same
  27910. ** time and one or more of those connections are writing.
  27911. */
  27912. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  27913. UNUSED_PARAMETER(NotUsed);
  27914. *pResOut = 0;
  27915. return SQLITE_OK;
  27916. }
  27917. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  27918. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  27919. return SQLITE_OK;
  27920. }
  27921. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  27922. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  27923. return SQLITE_OK;
  27924. }
  27925. /*
  27926. ** Close the file.
  27927. */
  27928. static int nolockClose(sqlite3_file *id) {
  27929. return closeUnixFile(id);
  27930. }
  27931. /******************* End of the no-op lock implementation *********************
  27932. ******************************************************************************/
  27933. /******************************************************************************
  27934. ************************* Begin dot-file Locking ******************************
  27935. **
  27936. ** The dotfile locking implementation uses the existence of separate lock
  27937. ** files (really a directory) to control access to the database. This works
  27938. ** on just about every filesystem imaginable. But there are serious downsides:
  27939. **
  27940. ** (1) There is zero concurrency. A single reader blocks all other
  27941. ** connections from reading or writing the database.
  27942. **
  27943. ** (2) An application crash or power loss can leave stale lock files
  27944. ** sitting around that need to be cleared manually.
  27945. **
  27946. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  27947. ** other locking strategy is available.
  27948. **
  27949. ** Dotfile locking works by creating a subdirectory in the same directory as
  27950. ** the database and with the same name but with a ".lock" extension added.
  27951. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  27952. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  27953. */
  27954. /*
  27955. ** The file suffix added to the data base filename in order to create the
  27956. ** lock directory.
  27957. */
  27958. #define DOTLOCK_SUFFIX ".lock"
  27959. /*
  27960. ** This routine checks if there is a RESERVED lock held on the specified
  27961. ** file by this or any other process. If such a lock is held, set *pResOut
  27962. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27963. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27964. **
  27965. ** In dotfile locking, either a lock exists or it does not. So in this
  27966. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  27967. ** is held on the file and false if the file is unlocked.
  27968. */
  27969. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  27970. int rc = SQLITE_OK;
  27971. int reserved = 0;
  27972. unixFile *pFile = (unixFile*)id;
  27973. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27974. assert( pFile );
  27975. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  27976. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  27977. *pResOut = reserved;
  27978. return rc;
  27979. }
  27980. /*
  27981. ** Lock the file with the lock specified by parameter eFileLock - one
  27982. ** of the following:
  27983. **
  27984. ** (1) SHARED_LOCK
  27985. ** (2) RESERVED_LOCK
  27986. ** (3) PENDING_LOCK
  27987. ** (4) EXCLUSIVE_LOCK
  27988. **
  27989. ** Sometimes when requesting one lock state, additional lock states
  27990. ** are inserted in between. The locking might fail on one of the later
  27991. ** transitions leaving the lock state different from what it started but
  27992. ** still short of its goal. The following chart shows the allowed
  27993. ** transitions and the inserted intermediate states:
  27994. **
  27995. ** UNLOCKED -> SHARED
  27996. ** SHARED -> RESERVED
  27997. ** SHARED -> (PENDING) -> EXCLUSIVE
  27998. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27999. ** PENDING -> EXCLUSIVE
  28000. **
  28001. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28002. ** routine to lower a locking level.
  28003. **
  28004. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  28005. ** But we track the other locking levels internally.
  28006. */
  28007. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  28008. unixFile *pFile = (unixFile*)id;
  28009. char *zLockFile = (char *)pFile->lockingContext;
  28010. int rc = SQLITE_OK;
  28011. /* If we have any lock, then the lock file already exists. All we have
  28012. ** to do is adjust our internal record of the lock level.
  28013. */
  28014. if( pFile->eFileLock > NO_LOCK ){
  28015. pFile->eFileLock = eFileLock;
  28016. /* Always update the timestamp on the old file */
  28017. #ifdef HAVE_UTIME
  28018. utime(zLockFile, NULL);
  28019. #else
  28020. utimes(zLockFile, NULL);
  28021. #endif
  28022. return SQLITE_OK;
  28023. }
  28024. /* grab an exclusive lock */
  28025. rc = osMkdir(zLockFile, 0777);
  28026. if( rc<0 ){
  28027. /* failed to open/create the lock directory */
  28028. int tErrno = errno;
  28029. if( EEXIST == tErrno ){
  28030. rc = SQLITE_BUSY;
  28031. } else {
  28032. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  28033. if( rc!=SQLITE_BUSY ){
  28034. storeLastErrno(pFile, tErrno);
  28035. }
  28036. }
  28037. return rc;
  28038. }
  28039. /* got it, set the type and return ok */
  28040. pFile->eFileLock = eFileLock;
  28041. return rc;
  28042. }
  28043. /*
  28044. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28045. ** must be either NO_LOCK or SHARED_LOCK.
  28046. **
  28047. ** If the locking level of the file descriptor is already at or below
  28048. ** the requested locking level, this routine is a no-op.
  28049. **
  28050. ** When the locking level reaches NO_LOCK, delete the lock file.
  28051. */
  28052. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  28053. unixFile *pFile = (unixFile*)id;
  28054. char *zLockFile = (char *)pFile->lockingContext;
  28055. int rc;
  28056. assert( pFile );
  28057. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  28058. pFile->eFileLock, osGetpid(0)));
  28059. assert( eFileLock<=SHARED_LOCK );
  28060. /* no-op if possible */
  28061. if( pFile->eFileLock==eFileLock ){
  28062. return SQLITE_OK;
  28063. }
  28064. /* To downgrade to shared, simply update our internal notion of the
  28065. ** lock state. No need to mess with the file on disk.
  28066. */
  28067. if( eFileLock==SHARED_LOCK ){
  28068. pFile->eFileLock = SHARED_LOCK;
  28069. return SQLITE_OK;
  28070. }
  28071. /* To fully unlock the database, delete the lock file */
  28072. assert( eFileLock==NO_LOCK );
  28073. rc = osRmdir(zLockFile);
  28074. if( rc<0 ){
  28075. int tErrno = errno;
  28076. if( tErrno==ENOENT ){
  28077. rc = SQLITE_OK;
  28078. }else{
  28079. rc = SQLITE_IOERR_UNLOCK;
  28080. storeLastErrno(pFile, tErrno);
  28081. }
  28082. return rc;
  28083. }
  28084. pFile->eFileLock = NO_LOCK;
  28085. return SQLITE_OK;
  28086. }
  28087. /*
  28088. ** Close a file. Make sure the lock has been released before closing.
  28089. */
  28090. static int dotlockClose(sqlite3_file *id) {
  28091. unixFile *pFile = (unixFile*)id;
  28092. assert( id!=0 );
  28093. dotlockUnlock(id, NO_LOCK);
  28094. sqlite3_free(pFile->lockingContext);
  28095. return closeUnixFile(id);
  28096. }
  28097. /****************** End of the dot-file lock implementation *******************
  28098. ******************************************************************************/
  28099. /******************************************************************************
  28100. ************************** Begin flock Locking ********************************
  28101. **
  28102. ** Use the flock() system call to do file locking.
  28103. **
  28104. ** flock() locking is like dot-file locking in that the various
  28105. ** fine-grain locking levels supported by SQLite are collapsed into
  28106. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  28107. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  28108. ** still works when you do this, but concurrency is reduced since
  28109. ** only a single process can be reading the database at a time.
  28110. **
  28111. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  28112. */
  28113. #if SQLITE_ENABLE_LOCKING_STYLE
  28114. /*
  28115. ** Retry flock() calls that fail with EINTR
  28116. */
  28117. #ifdef EINTR
  28118. static int robust_flock(int fd, int op){
  28119. int rc;
  28120. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  28121. return rc;
  28122. }
  28123. #else
  28124. # define robust_flock(a,b) flock(a,b)
  28125. #endif
  28126. /*
  28127. ** This routine checks if there is a RESERVED lock held on the specified
  28128. ** file by this or any other process. If such a lock is held, set *pResOut
  28129. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28130. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28131. */
  28132. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  28133. int rc = SQLITE_OK;
  28134. int reserved = 0;
  28135. unixFile *pFile = (unixFile*)id;
  28136. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  28137. assert( pFile );
  28138. /* Check if a thread in this process holds such a lock */
  28139. if( pFile->eFileLock>SHARED_LOCK ){
  28140. reserved = 1;
  28141. }
  28142. /* Otherwise see if some other process holds it. */
  28143. if( !reserved ){
  28144. /* attempt to get the lock */
  28145. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  28146. if( !lrc ){
  28147. /* got the lock, unlock it */
  28148. lrc = robust_flock(pFile->h, LOCK_UN);
  28149. if ( lrc ) {
  28150. int tErrno = errno;
  28151. /* unlock failed with an error */
  28152. lrc = SQLITE_IOERR_UNLOCK;
  28153. storeLastErrno(pFile, tErrno);
  28154. rc = lrc;
  28155. }
  28156. } else {
  28157. int tErrno = errno;
  28158. reserved = 1;
  28159. /* someone else might have it reserved */
  28160. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  28161. if( IS_LOCK_ERROR(lrc) ){
  28162. storeLastErrno(pFile, tErrno);
  28163. rc = lrc;
  28164. }
  28165. }
  28166. }
  28167. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  28168. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  28169. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  28170. rc = SQLITE_OK;
  28171. reserved=1;
  28172. }
  28173. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  28174. *pResOut = reserved;
  28175. return rc;
  28176. }
  28177. /*
  28178. ** Lock the file with the lock specified by parameter eFileLock - one
  28179. ** of the following:
  28180. **
  28181. ** (1) SHARED_LOCK
  28182. ** (2) RESERVED_LOCK
  28183. ** (3) PENDING_LOCK
  28184. ** (4) EXCLUSIVE_LOCK
  28185. **
  28186. ** Sometimes when requesting one lock state, additional lock states
  28187. ** are inserted in between. The locking might fail on one of the later
  28188. ** transitions leaving the lock state different from what it started but
  28189. ** still short of its goal. The following chart shows the allowed
  28190. ** transitions and the inserted intermediate states:
  28191. **
  28192. ** UNLOCKED -> SHARED
  28193. ** SHARED -> RESERVED
  28194. ** SHARED -> (PENDING) -> EXCLUSIVE
  28195. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28196. ** PENDING -> EXCLUSIVE
  28197. **
  28198. ** flock() only really support EXCLUSIVE locks. We track intermediate
  28199. ** lock states in the sqlite3_file structure, but all locks SHARED or
  28200. ** above are really EXCLUSIVE locks and exclude all other processes from
  28201. ** access the file.
  28202. **
  28203. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28204. ** routine to lower a locking level.
  28205. */
  28206. static int flockLock(sqlite3_file *id, int eFileLock) {
  28207. int rc = SQLITE_OK;
  28208. unixFile *pFile = (unixFile*)id;
  28209. assert( pFile );
  28210. /* if we already have a lock, it is exclusive.
  28211. ** Just adjust level and punt on outta here. */
  28212. if (pFile->eFileLock > NO_LOCK) {
  28213. pFile->eFileLock = eFileLock;
  28214. return SQLITE_OK;
  28215. }
  28216. /* grab an exclusive lock */
  28217. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  28218. int tErrno = errno;
  28219. /* didn't get, must be busy */
  28220. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  28221. if( IS_LOCK_ERROR(rc) ){
  28222. storeLastErrno(pFile, tErrno);
  28223. }
  28224. } else {
  28225. /* got it, set the type and return ok */
  28226. pFile->eFileLock = eFileLock;
  28227. }
  28228. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  28229. rc==SQLITE_OK ? "ok" : "failed"));
  28230. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  28231. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  28232. rc = SQLITE_BUSY;
  28233. }
  28234. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  28235. return rc;
  28236. }
  28237. /*
  28238. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28239. ** must be either NO_LOCK or SHARED_LOCK.
  28240. **
  28241. ** If the locking level of the file descriptor is already at or below
  28242. ** the requested locking level, this routine is a no-op.
  28243. */
  28244. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  28245. unixFile *pFile = (unixFile*)id;
  28246. assert( pFile );
  28247. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  28248. pFile->eFileLock, osGetpid(0)));
  28249. assert( eFileLock<=SHARED_LOCK );
  28250. /* no-op if possible */
  28251. if( pFile->eFileLock==eFileLock ){
  28252. return SQLITE_OK;
  28253. }
  28254. /* shared can just be set because we always have an exclusive */
  28255. if (eFileLock==SHARED_LOCK) {
  28256. pFile->eFileLock = eFileLock;
  28257. return SQLITE_OK;
  28258. }
  28259. /* no, really, unlock. */
  28260. if( robust_flock(pFile->h, LOCK_UN) ){
  28261. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  28262. return SQLITE_OK;
  28263. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  28264. return SQLITE_IOERR_UNLOCK;
  28265. }else{
  28266. pFile->eFileLock = NO_LOCK;
  28267. return SQLITE_OK;
  28268. }
  28269. }
  28270. /*
  28271. ** Close a file.
  28272. */
  28273. static int flockClose(sqlite3_file *id) {
  28274. assert( id!=0 );
  28275. flockUnlock(id, NO_LOCK);
  28276. return closeUnixFile(id);
  28277. }
  28278. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  28279. /******************* End of the flock lock implementation *********************
  28280. ******************************************************************************/
  28281. /******************************************************************************
  28282. ************************ Begin Named Semaphore Locking ************************
  28283. **
  28284. ** Named semaphore locking is only supported on VxWorks.
  28285. **
  28286. ** Semaphore locking is like dot-lock and flock in that it really only
  28287. ** supports EXCLUSIVE locking. Only a single process can read or write
  28288. ** the database file at a time. This reduces potential concurrency, but
  28289. ** makes the lock implementation much easier.
  28290. */
  28291. #if OS_VXWORKS
  28292. /*
  28293. ** This routine checks if there is a RESERVED lock held on the specified
  28294. ** file by this or any other process. If such a lock is held, set *pResOut
  28295. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28296. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28297. */
  28298. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  28299. int rc = SQLITE_OK;
  28300. int reserved = 0;
  28301. unixFile *pFile = (unixFile*)id;
  28302. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  28303. assert( pFile );
  28304. /* Check if a thread in this process holds such a lock */
  28305. if( pFile->eFileLock>SHARED_LOCK ){
  28306. reserved = 1;
  28307. }
  28308. /* Otherwise see if some other process holds it. */
  28309. if( !reserved ){
  28310. sem_t *pSem = pFile->pInode->pSem;
  28311. if( sem_trywait(pSem)==-1 ){
  28312. int tErrno = errno;
  28313. if( EAGAIN != tErrno ){
  28314. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  28315. storeLastErrno(pFile, tErrno);
  28316. } else {
  28317. /* someone else has the lock when we are in NO_LOCK */
  28318. reserved = (pFile->eFileLock < SHARED_LOCK);
  28319. }
  28320. }else{
  28321. /* we could have it if we want it */
  28322. sem_post(pSem);
  28323. }
  28324. }
  28325. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  28326. *pResOut = reserved;
  28327. return rc;
  28328. }
  28329. /*
  28330. ** Lock the file with the lock specified by parameter eFileLock - one
  28331. ** of the following:
  28332. **
  28333. ** (1) SHARED_LOCK
  28334. ** (2) RESERVED_LOCK
  28335. ** (3) PENDING_LOCK
  28336. ** (4) EXCLUSIVE_LOCK
  28337. **
  28338. ** Sometimes when requesting one lock state, additional lock states
  28339. ** are inserted in between. The locking might fail on one of the later
  28340. ** transitions leaving the lock state different from what it started but
  28341. ** still short of its goal. The following chart shows the allowed
  28342. ** transitions and the inserted intermediate states:
  28343. **
  28344. ** UNLOCKED -> SHARED
  28345. ** SHARED -> RESERVED
  28346. ** SHARED -> (PENDING) -> EXCLUSIVE
  28347. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28348. ** PENDING -> EXCLUSIVE
  28349. **
  28350. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  28351. ** lock states in the sqlite3_file structure, but all locks SHARED or
  28352. ** above are really EXCLUSIVE locks and exclude all other processes from
  28353. ** access the file.
  28354. **
  28355. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28356. ** routine to lower a locking level.
  28357. */
  28358. static int semXLock(sqlite3_file *id, int eFileLock) {
  28359. unixFile *pFile = (unixFile*)id;
  28360. sem_t *pSem = pFile->pInode->pSem;
  28361. int rc = SQLITE_OK;
  28362. /* if we already have a lock, it is exclusive.
  28363. ** Just adjust level and punt on outta here. */
  28364. if (pFile->eFileLock > NO_LOCK) {
  28365. pFile->eFileLock = eFileLock;
  28366. rc = SQLITE_OK;
  28367. goto sem_end_lock;
  28368. }
  28369. /* lock semaphore now but bail out when already locked. */
  28370. if( sem_trywait(pSem)==-1 ){
  28371. rc = SQLITE_BUSY;
  28372. goto sem_end_lock;
  28373. }
  28374. /* got it, set the type and return ok */
  28375. pFile->eFileLock = eFileLock;
  28376. sem_end_lock:
  28377. return rc;
  28378. }
  28379. /*
  28380. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28381. ** must be either NO_LOCK or SHARED_LOCK.
  28382. **
  28383. ** If the locking level of the file descriptor is already at or below
  28384. ** the requested locking level, this routine is a no-op.
  28385. */
  28386. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  28387. unixFile *pFile = (unixFile*)id;
  28388. sem_t *pSem = pFile->pInode->pSem;
  28389. assert( pFile );
  28390. assert( pSem );
  28391. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  28392. pFile->eFileLock, osGetpid(0)));
  28393. assert( eFileLock<=SHARED_LOCK );
  28394. /* no-op if possible */
  28395. if( pFile->eFileLock==eFileLock ){
  28396. return SQLITE_OK;
  28397. }
  28398. /* shared can just be set because we always have an exclusive */
  28399. if (eFileLock==SHARED_LOCK) {
  28400. pFile->eFileLock = eFileLock;
  28401. return SQLITE_OK;
  28402. }
  28403. /* no, really unlock. */
  28404. if ( sem_post(pSem)==-1 ) {
  28405. int rc, tErrno = errno;
  28406. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  28407. if( IS_LOCK_ERROR(rc) ){
  28408. storeLastErrno(pFile, tErrno);
  28409. }
  28410. return rc;
  28411. }
  28412. pFile->eFileLock = NO_LOCK;
  28413. return SQLITE_OK;
  28414. }
  28415. /*
  28416. ** Close a file.
  28417. */
  28418. static int semXClose(sqlite3_file *id) {
  28419. if( id ){
  28420. unixFile *pFile = (unixFile*)id;
  28421. semXUnlock(id, NO_LOCK);
  28422. assert( pFile );
  28423. unixEnterMutex();
  28424. releaseInodeInfo(pFile);
  28425. unixLeaveMutex();
  28426. closeUnixFile(id);
  28427. }
  28428. return SQLITE_OK;
  28429. }
  28430. #endif /* OS_VXWORKS */
  28431. /*
  28432. ** Named semaphore locking is only available on VxWorks.
  28433. **
  28434. *************** End of the named semaphore lock implementation ****************
  28435. ******************************************************************************/
  28436. /******************************************************************************
  28437. *************************** Begin AFP Locking *********************************
  28438. **
  28439. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  28440. ** on Apple Macintosh computers - both OS9 and OSX.
  28441. **
  28442. ** Third-party implementations of AFP are available. But this code here
  28443. ** only works on OSX.
  28444. */
  28445. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28446. /*
  28447. ** The afpLockingContext structure contains all afp lock specific state
  28448. */
  28449. typedef struct afpLockingContext afpLockingContext;
  28450. struct afpLockingContext {
  28451. int reserved;
  28452. const char *dbPath; /* Name of the open file */
  28453. };
  28454. struct ByteRangeLockPB2
  28455. {
  28456. unsigned long long offset; /* offset to first byte to lock */
  28457. unsigned long long length; /* nbr of bytes to lock */
  28458. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  28459. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  28460. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  28461. int fd; /* file desc to assoc this lock with */
  28462. };
  28463. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  28464. /*
  28465. ** This is a utility for setting or clearing a bit-range lock on an
  28466. ** AFP filesystem.
  28467. **
  28468. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  28469. */
  28470. static int afpSetLock(
  28471. const char *path, /* Name of the file to be locked or unlocked */
  28472. unixFile *pFile, /* Open file descriptor on path */
  28473. unsigned long long offset, /* First byte to be locked */
  28474. unsigned long long length, /* Number of bytes to lock */
  28475. int setLockFlag /* True to set lock. False to clear lock */
  28476. ){
  28477. struct ByteRangeLockPB2 pb;
  28478. int err;
  28479. pb.unLockFlag = setLockFlag ? 0 : 1;
  28480. pb.startEndFlag = 0;
  28481. pb.offset = offset;
  28482. pb.length = length;
  28483. pb.fd = pFile->h;
  28484. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  28485. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  28486. offset, length));
  28487. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  28488. if ( err==-1 ) {
  28489. int rc;
  28490. int tErrno = errno;
  28491. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  28492. path, tErrno, strerror(tErrno)));
  28493. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  28494. rc = SQLITE_BUSY;
  28495. #else
  28496. rc = sqliteErrorFromPosixError(tErrno,
  28497. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  28498. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  28499. if( IS_LOCK_ERROR(rc) ){
  28500. storeLastErrno(pFile, tErrno);
  28501. }
  28502. return rc;
  28503. } else {
  28504. return SQLITE_OK;
  28505. }
  28506. }
  28507. /*
  28508. ** This routine checks if there is a RESERVED lock held on the specified
  28509. ** file by this or any other process. If such a lock is held, set *pResOut
  28510. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28511. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28512. */
  28513. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  28514. int rc = SQLITE_OK;
  28515. int reserved = 0;
  28516. unixFile *pFile = (unixFile*)id;
  28517. afpLockingContext *context;
  28518. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  28519. assert( pFile );
  28520. context = (afpLockingContext *) pFile->lockingContext;
  28521. if( context->reserved ){
  28522. *pResOut = 1;
  28523. return SQLITE_OK;
  28524. }
  28525. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  28526. /* Check if a thread in this process holds such a lock */
  28527. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  28528. reserved = 1;
  28529. }
  28530. /* Otherwise see if some other process holds it.
  28531. */
  28532. if( !reserved ){
  28533. /* lock the RESERVED byte */
  28534. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  28535. if( SQLITE_OK==lrc ){
  28536. /* if we succeeded in taking the reserved lock, unlock it to restore
  28537. ** the original state */
  28538. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  28539. } else {
  28540. /* if we failed to get the lock then someone else must have it */
  28541. reserved = 1;
  28542. }
  28543. if( IS_LOCK_ERROR(lrc) ){
  28544. rc=lrc;
  28545. }
  28546. }
  28547. unixLeaveMutex();
  28548. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  28549. *pResOut = reserved;
  28550. return rc;
  28551. }
  28552. /*
  28553. ** Lock the file with the lock specified by parameter eFileLock - one
  28554. ** of the following:
  28555. **
  28556. ** (1) SHARED_LOCK
  28557. ** (2) RESERVED_LOCK
  28558. ** (3) PENDING_LOCK
  28559. ** (4) EXCLUSIVE_LOCK
  28560. **
  28561. ** Sometimes when requesting one lock state, additional lock states
  28562. ** are inserted in between. The locking might fail on one of the later
  28563. ** transitions leaving the lock state different from what it started but
  28564. ** still short of its goal. The following chart shows the allowed
  28565. ** transitions and the inserted intermediate states:
  28566. **
  28567. ** UNLOCKED -> SHARED
  28568. ** SHARED -> RESERVED
  28569. ** SHARED -> (PENDING) -> EXCLUSIVE
  28570. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28571. ** PENDING -> EXCLUSIVE
  28572. **
  28573. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28574. ** routine to lower a locking level.
  28575. */
  28576. static int afpLock(sqlite3_file *id, int eFileLock){
  28577. int rc = SQLITE_OK;
  28578. unixFile *pFile = (unixFile*)id;
  28579. unixInodeInfo *pInode = pFile->pInode;
  28580. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  28581. assert( pFile );
  28582. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  28583. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  28584. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  28585. /* If there is already a lock of this type or more restrictive on the
  28586. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  28587. ** unixEnterMutex() hasn't been called yet.
  28588. */
  28589. if( pFile->eFileLock>=eFileLock ){
  28590. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  28591. azFileLock(eFileLock)));
  28592. return SQLITE_OK;
  28593. }
  28594. /* Make sure the locking sequence is correct
  28595. ** (1) We never move from unlocked to anything higher than shared lock.
  28596. ** (2) SQLite never explicitly requests a pendig lock.
  28597. ** (3) A shared lock is always held when a reserve lock is requested.
  28598. */
  28599. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  28600. assert( eFileLock!=PENDING_LOCK );
  28601. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  28602. /* This mutex is needed because pFile->pInode is shared across threads
  28603. */
  28604. unixEnterMutex();
  28605. pInode = pFile->pInode;
  28606. /* If some thread using this PID has a lock via a different unixFile*
  28607. ** handle that precludes the requested lock, return BUSY.
  28608. */
  28609. if( (pFile->eFileLock!=pInode->eFileLock &&
  28610. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  28611. ){
  28612. rc = SQLITE_BUSY;
  28613. goto afp_end_lock;
  28614. }
  28615. /* If a SHARED lock is requested, and some thread using this PID already
  28616. ** has a SHARED or RESERVED lock, then increment reference counts and
  28617. ** return SQLITE_OK.
  28618. */
  28619. if( eFileLock==SHARED_LOCK &&
  28620. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  28621. assert( eFileLock==SHARED_LOCK );
  28622. assert( pFile->eFileLock==0 );
  28623. assert( pInode->nShared>0 );
  28624. pFile->eFileLock = SHARED_LOCK;
  28625. pInode->nShared++;
  28626. pInode->nLock++;
  28627. goto afp_end_lock;
  28628. }
  28629. /* A PENDING lock is needed before acquiring a SHARED lock and before
  28630. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  28631. ** be released.
  28632. */
  28633. if( eFileLock==SHARED_LOCK
  28634. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  28635. ){
  28636. int failed;
  28637. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  28638. if (failed) {
  28639. rc = failed;
  28640. goto afp_end_lock;
  28641. }
  28642. }
  28643. /* If control gets to this point, then actually go ahead and make
  28644. ** operating system calls for the specified lock.
  28645. */
  28646. if( eFileLock==SHARED_LOCK ){
  28647. int lrc1, lrc2, lrc1Errno = 0;
  28648. long lk, mask;
  28649. assert( pInode->nShared==0 );
  28650. assert( pInode->eFileLock==0 );
  28651. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  28652. /* Now get the read-lock SHARED_LOCK */
  28653. /* note that the quality of the randomness doesn't matter that much */
  28654. lk = random();
  28655. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  28656. lrc1 = afpSetLock(context->dbPath, pFile,
  28657. SHARED_FIRST+pInode->sharedByte, 1, 1);
  28658. if( IS_LOCK_ERROR(lrc1) ){
  28659. lrc1Errno = pFile->lastErrno;
  28660. }
  28661. /* Drop the temporary PENDING lock */
  28662. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  28663. if( IS_LOCK_ERROR(lrc1) ) {
  28664. storeLastErrno(pFile, lrc1Errno);
  28665. rc = lrc1;
  28666. goto afp_end_lock;
  28667. } else if( IS_LOCK_ERROR(lrc2) ){
  28668. rc = lrc2;
  28669. goto afp_end_lock;
  28670. } else if( lrc1 != SQLITE_OK ) {
  28671. rc = lrc1;
  28672. } else {
  28673. pFile->eFileLock = SHARED_LOCK;
  28674. pInode->nLock++;
  28675. pInode->nShared = 1;
  28676. }
  28677. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  28678. /* We are trying for an exclusive lock but another thread in this
  28679. ** same process is still holding a shared lock. */
  28680. rc = SQLITE_BUSY;
  28681. }else{
  28682. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  28683. ** assumed that there is a SHARED or greater lock on the file
  28684. ** already.
  28685. */
  28686. int failed = 0;
  28687. assert( 0!=pFile->eFileLock );
  28688. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  28689. /* Acquire a RESERVED lock */
  28690. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  28691. if( !failed ){
  28692. context->reserved = 1;
  28693. }
  28694. }
  28695. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  28696. /* Acquire an EXCLUSIVE lock */
  28697. /* Remove the shared lock before trying the range. we'll need to
  28698. ** reestablish the shared lock if we can't get the afpUnlock
  28699. */
  28700. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  28701. pInode->sharedByte, 1, 0)) ){
  28702. int failed2 = SQLITE_OK;
  28703. /* now attemmpt to get the exclusive lock range */
  28704. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  28705. SHARED_SIZE, 1);
  28706. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  28707. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  28708. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  28709. ** a critical I/O error
  28710. */
  28711. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  28712. SQLITE_IOERR_LOCK;
  28713. goto afp_end_lock;
  28714. }
  28715. }else{
  28716. rc = failed;
  28717. }
  28718. }
  28719. if( failed ){
  28720. rc = failed;
  28721. }
  28722. }
  28723. if( rc==SQLITE_OK ){
  28724. pFile->eFileLock = eFileLock;
  28725. pInode->eFileLock = eFileLock;
  28726. }else if( eFileLock==EXCLUSIVE_LOCK ){
  28727. pFile->eFileLock = PENDING_LOCK;
  28728. pInode->eFileLock = PENDING_LOCK;
  28729. }
  28730. afp_end_lock:
  28731. unixLeaveMutex();
  28732. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  28733. rc==SQLITE_OK ? "ok" : "failed"));
  28734. return rc;
  28735. }
  28736. /*
  28737. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28738. ** must be either NO_LOCK or SHARED_LOCK.
  28739. **
  28740. ** If the locking level of the file descriptor is already at or below
  28741. ** the requested locking level, this routine is a no-op.
  28742. */
  28743. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  28744. int rc = SQLITE_OK;
  28745. unixFile *pFile = (unixFile*)id;
  28746. unixInodeInfo *pInode;
  28747. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  28748. int skipShared = 0;
  28749. #ifdef SQLITE_TEST
  28750. int h = pFile->h;
  28751. #endif
  28752. assert( pFile );
  28753. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  28754. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  28755. osGetpid(0)));
  28756. assert( eFileLock<=SHARED_LOCK );
  28757. if( pFile->eFileLock<=eFileLock ){
  28758. return SQLITE_OK;
  28759. }
  28760. unixEnterMutex();
  28761. pInode = pFile->pInode;
  28762. assert( pInode->nShared!=0 );
  28763. if( pFile->eFileLock>SHARED_LOCK ){
  28764. assert( pInode->eFileLock==pFile->eFileLock );
  28765. SimulateIOErrorBenign(1);
  28766. SimulateIOError( h=(-1) )
  28767. SimulateIOErrorBenign(0);
  28768. #ifdef SQLITE_DEBUG
  28769. /* When reducing a lock such that other processes can start
  28770. ** reading the database file again, make sure that the
  28771. ** transaction counter was updated if any part of the database
  28772. ** file changed. If the transaction counter is not updated,
  28773. ** other connections to the same file might not realize that
  28774. ** the file has changed and hence might not know to flush their
  28775. ** cache. The use of a stale cache can lead to database corruption.
  28776. */
  28777. assert( pFile->inNormalWrite==0
  28778. || pFile->dbUpdate==0
  28779. || pFile->transCntrChng==1 );
  28780. pFile->inNormalWrite = 0;
  28781. #endif
  28782. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  28783. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  28784. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  28785. /* only re-establish the shared lock if necessary */
  28786. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  28787. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  28788. } else {
  28789. skipShared = 1;
  28790. }
  28791. }
  28792. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  28793. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  28794. }
  28795. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  28796. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  28797. if( !rc ){
  28798. context->reserved = 0;
  28799. }
  28800. }
  28801. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  28802. pInode->eFileLock = SHARED_LOCK;
  28803. }
  28804. }
  28805. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  28806. /* Decrement the shared lock counter. Release the lock using an
  28807. ** OS call only when all threads in this same process have released
  28808. ** the lock.
  28809. */
  28810. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  28811. pInode->nShared--;
  28812. if( pInode->nShared==0 ){
  28813. SimulateIOErrorBenign(1);
  28814. SimulateIOError( h=(-1) )
  28815. SimulateIOErrorBenign(0);
  28816. if( !skipShared ){
  28817. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  28818. }
  28819. if( !rc ){
  28820. pInode->eFileLock = NO_LOCK;
  28821. pFile->eFileLock = NO_LOCK;
  28822. }
  28823. }
  28824. if( rc==SQLITE_OK ){
  28825. pInode->nLock--;
  28826. assert( pInode->nLock>=0 );
  28827. if( pInode->nLock==0 ){
  28828. closePendingFds(pFile);
  28829. }
  28830. }
  28831. }
  28832. unixLeaveMutex();
  28833. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  28834. return rc;
  28835. }
  28836. /*
  28837. ** Close a file & cleanup AFP specific locking context
  28838. */
  28839. static int afpClose(sqlite3_file *id) {
  28840. int rc = SQLITE_OK;
  28841. unixFile *pFile = (unixFile*)id;
  28842. assert( id!=0 );
  28843. afpUnlock(id, NO_LOCK);
  28844. unixEnterMutex();
  28845. if( pFile->pInode && pFile->pInode->nLock ){
  28846. /* If there are outstanding locks, do not actually close the file just
  28847. ** yet because that would clear those locks. Instead, add the file
  28848. ** descriptor to pInode->aPending. It will be automatically closed when
  28849. ** the last lock is cleared.
  28850. */
  28851. setPendingFd(pFile);
  28852. }
  28853. releaseInodeInfo(pFile);
  28854. sqlite3_free(pFile->lockingContext);
  28855. rc = closeUnixFile(id);
  28856. unixLeaveMutex();
  28857. return rc;
  28858. }
  28859. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28860. /*
  28861. ** The code above is the AFP lock implementation. The code is specific
  28862. ** to MacOSX and does not work on other unix platforms. No alternative
  28863. ** is available. If you don't compile for a mac, then the "unix-afp"
  28864. ** VFS is not available.
  28865. **
  28866. ********************* End of the AFP lock implementation **********************
  28867. ******************************************************************************/
  28868. /******************************************************************************
  28869. *************************** Begin NFS Locking ********************************/
  28870. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28871. /*
  28872. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28873. ** must be either NO_LOCK or SHARED_LOCK.
  28874. **
  28875. ** If the locking level of the file descriptor is already at or below
  28876. ** the requested locking level, this routine is a no-op.
  28877. */
  28878. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  28879. return posixUnlock(id, eFileLock, 1);
  28880. }
  28881. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28882. /*
  28883. ** The code above is the NFS lock implementation. The code is specific
  28884. ** to MacOSX and does not work on other unix platforms. No alternative
  28885. ** is available.
  28886. **
  28887. ********************* End of the NFS lock implementation **********************
  28888. ******************************************************************************/
  28889. /******************************************************************************
  28890. **************** Non-locking sqlite3_file methods *****************************
  28891. **
  28892. ** The next division contains implementations for all methods of the
  28893. ** sqlite3_file object other than the locking methods. The locking
  28894. ** methods were defined in divisions above (one locking method per
  28895. ** division). Those methods that are common to all locking modes
  28896. ** are gather together into this division.
  28897. */
  28898. /*
  28899. ** Seek to the offset passed as the second argument, then read cnt
  28900. ** bytes into pBuf. Return the number of bytes actually read.
  28901. **
  28902. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  28903. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  28904. ** one system to another. Since SQLite does not define USE_PREAD
  28905. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  28906. ** See tickets #2741 and #2681.
  28907. **
  28908. ** To avoid stomping the errno value on a failed read the lastErrno value
  28909. ** is set before returning.
  28910. */
  28911. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  28912. int got;
  28913. int prior = 0;
  28914. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  28915. i64 newOffset;
  28916. #endif
  28917. TIMER_START;
  28918. assert( cnt==(cnt&0x1ffff) );
  28919. assert( id->h>2 );
  28920. do{
  28921. #if defined(USE_PREAD)
  28922. got = osPread(id->h, pBuf, cnt, offset);
  28923. SimulateIOError( got = -1 );
  28924. #elif defined(USE_PREAD64)
  28925. got = osPread64(id->h, pBuf, cnt, offset);
  28926. SimulateIOError( got = -1 );
  28927. #else
  28928. newOffset = lseek(id->h, offset, SEEK_SET);
  28929. SimulateIOError( newOffset = -1 );
  28930. if( newOffset<0 ){
  28931. storeLastErrno((unixFile*)id, errno);
  28932. return -1;
  28933. }
  28934. got = osRead(id->h, pBuf, cnt);
  28935. #endif
  28936. if( got==cnt ) break;
  28937. if( got<0 ){
  28938. if( errno==EINTR ){ got = 1; continue; }
  28939. prior = 0;
  28940. storeLastErrno((unixFile*)id, errno);
  28941. break;
  28942. }else if( got>0 ){
  28943. cnt -= got;
  28944. offset += got;
  28945. prior += got;
  28946. pBuf = (void*)(got + (char*)pBuf);
  28947. }
  28948. }while( got>0 );
  28949. TIMER_END;
  28950. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  28951. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  28952. return got+prior;
  28953. }
  28954. /*
  28955. ** Read data from a file into a buffer. Return SQLITE_OK if all
  28956. ** bytes were read successfully and SQLITE_IOERR if anything goes
  28957. ** wrong.
  28958. */
  28959. static int unixRead(
  28960. sqlite3_file *id,
  28961. void *pBuf,
  28962. int amt,
  28963. sqlite3_int64 offset
  28964. ){
  28965. unixFile *pFile = (unixFile *)id;
  28966. int got;
  28967. assert( id );
  28968. assert( offset>=0 );
  28969. assert( amt>0 );
  28970. /* If this is a database file (not a journal, master-journal or temp
  28971. ** file), the bytes in the locking range should never be read or written. */
  28972. #if 0
  28973. assert( pFile->pUnused==0
  28974. || offset>=PENDING_BYTE+512
  28975. || offset+amt<=PENDING_BYTE
  28976. );
  28977. #endif
  28978. #if SQLITE_MAX_MMAP_SIZE>0
  28979. /* Deal with as much of this read request as possible by transfering
  28980. ** data from the memory mapping using memcpy(). */
  28981. if( offset<pFile->mmapSize ){
  28982. if( offset+amt <= pFile->mmapSize ){
  28983. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  28984. return SQLITE_OK;
  28985. }else{
  28986. int nCopy = pFile->mmapSize - offset;
  28987. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  28988. pBuf = &((u8 *)pBuf)[nCopy];
  28989. amt -= nCopy;
  28990. offset += nCopy;
  28991. }
  28992. }
  28993. #endif
  28994. got = seekAndRead(pFile, offset, pBuf, amt);
  28995. if( got==amt ){
  28996. return SQLITE_OK;
  28997. }else if( got<0 ){
  28998. /* lastErrno set by seekAndRead */
  28999. return SQLITE_IOERR_READ;
  29000. }else{
  29001. storeLastErrno(pFile, 0); /* not a system error */
  29002. /* Unread parts of the buffer must be zero-filled */
  29003. memset(&((char*)pBuf)[got], 0, amt-got);
  29004. return SQLITE_IOERR_SHORT_READ;
  29005. }
  29006. }
  29007. /*
  29008. ** Attempt to seek the file-descriptor passed as the first argument to
  29009. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  29010. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  29011. ** return the actual number of bytes written (which may be less than
  29012. ** nBuf).
  29013. */
  29014. static int seekAndWriteFd(
  29015. int fd, /* File descriptor to write to */
  29016. i64 iOff, /* File offset to begin writing at */
  29017. const void *pBuf, /* Copy data from this buffer to the file */
  29018. int nBuf, /* Size of buffer pBuf in bytes */
  29019. int *piErrno /* OUT: Error number if error occurs */
  29020. ){
  29021. int rc = 0; /* Value returned by system call */
  29022. assert( nBuf==(nBuf&0x1ffff) );
  29023. assert( fd>2 );
  29024. assert( piErrno!=0 );
  29025. nBuf &= 0x1ffff;
  29026. TIMER_START;
  29027. #if defined(USE_PREAD)
  29028. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  29029. #elif defined(USE_PREAD64)
  29030. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  29031. #else
  29032. do{
  29033. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  29034. SimulateIOError( iSeek = -1 );
  29035. if( iSeek<0 ){
  29036. rc = -1;
  29037. break;
  29038. }
  29039. rc = osWrite(fd, pBuf, nBuf);
  29040. }while( rc<0 && errno==EINTR );
  29041. #endif
  29042. TIMER_END;
  29043. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  29044. if( rc<0 ) *piErrno = errno;
  29045. return rc;
  29046. }
  29047. /*
  29048. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  29049. ** Return the number of bytes actually read. Update the offset.
  29050. **
  29051. ** To avoid stomping the errno value on a failed write the lastErrno value
  29052. ** is set before returning.
  29053. */
  29054. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  29055. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  29056. }
  29057. /*
  29058. ** Write data from a buffer into a file. Return SQLITE_OK on success
  29059. ** or some other error code on failure.
  29060. */
  29061. static int unixWrite(
  29062. sqlite3_file *id,
  29063. const void *pBuf,
  29064. int amt,
  29065. sqlite3_int64 offset
  29066. ){
  29067. unixFile *pFile = (unixFile*)id;
  29068. int wrote = 0;
  29069. assert( id );
  29070. assert( amt>0 );
  29071. /* If this is a database file (not a journal, master-journal or temp
  29072. ** file), the bytes in the locking range should never be read or written. */
  29073. #if 0
  29074. assert( pFile->pUnused==0
  29075. || offset>=PENDING_BYTE+512
  29076. || offset+amt<=PENDING_BYTE
  29077. );
  29078. #endif
  29079. #ifdef SQLITE_DEBUG
  29080. /* If we are doing a normal write to a database file (as opposed to
  29081. ** doing a hot-journal rollback or a write to some file other than a
  29082. ** normal database file) then record the fact that the database
  29083. ** has changed. If the transaction counter is modified, record that
  29084. ** fact too.
  29085. */
  29086. if( pFile->inNormalWrite ){
  29087. pFile->dbUpdate = 1; /* The database has been modified */
  29088. if( offset<=24 && offset+amt>=27 ){
  29089. int rc;
  29090. char oldCntr[4];
  29091. SimulateIOErrorBenign(1);
  29092. rc = seekAndRead(pFile, 24, oldCntr, 4);
  29093. SimulateIOErrorBenign(0);
  29094. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  29095. pFile->transCntrChng = 1; /* The transaction counter has changed */
  29096. }
  29097. }
  29098. }
  29099. #endif
  29100. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  29101. /* Deal with as much of this write request as possible by transfering
  29102. ** data from the memory mapping using memcpy(). */
  29103. if( offset<pFile->mmapSize ){
  29104. if( offset+amt <= pFile->mmapSize ){
  29105. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  29106. return SQLITE_OK;
  29107. }else{
  29108. int nCopy = pFile->mmapSize - offset;
  29109. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  29110. pBuf = &((u8 *)pBuf)[nCopy];
  29111. amt -= nCopy;
  29112. offset += nCopy;
  29113. }
  29114. }
  29115. #endif
  29116. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  29117. amt -= wrote;
  29118. offset += wrote;
  29119. pBuf = &((char*)pBuf)[wrote];
  29120. }
  29121. SimulateIOError(( wrote=(-1), amt=1 ));
  29122. SimulateDiskfullError(( wrote=0, amt=1 ));
  29123. if( amt>wrote ){
  29124. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  29125. /* lastErrno set by seekAndWrite */
  29126. return SQLITE_IOERR_WRITE;
  29127. }else{
  29128. storeLastErrno(pFile, 0); /* not a system error */
  29129. return SQLITE_FULL;
  29130. }
  29131. }
  29132. return SQLITE_OK;
  29133. }
  29134. #ifdef SQLITE_TEST
  29135. /*
  29136. ** Count the number of fullsyncs and normal syncs. This is used to test
  29137. ** that syncs and fullsyncs are occurring at the right times.
  29138. */
  29139. SQLITE_API int sqlite3_sync_count = 0;
  29140. SQLITE_API int sqlite3_fullsync_count = 0;
  29141. #endif
  29142. /*
  29143. ** We do not trust systems to provide a working fdatasync(). Some do.
  29144. ** Others do no. To be safe, we will stick with the (slightly slower)
  29145. ** fsync(). If you know that your system does support fdatasync() correctly,
  29146. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  29147. */
  29148. #if !defined(fdatasync) && !HAVE_FDATASYNC
  29149. # define fdatasync fsync
  29150. #endif
  29151. /*
  29152. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  29153. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  29154. ** only available on Mac OS X. But that could change.
  29155. */
  29156. #ifdef F_FULLFSYNC
  29157. # define HAVE_FULLFSYNC 1
  29158. #else
  29159. # define HAVE_FULLFSYNC 0
  29160. #endif
  29161. /*
  29162. ** The fsync() system call does not work as advertised on many
  29163. ** unix systems. The following procedure is an attempt to make
  29164. ** it work better.
  29165. **
  29166. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  29167. ** for testing when we want to run through the test suite quickly.
  29168. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  29169. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  29170. ** or power failure will likely corrupt the database file.
  29171. **
  29172. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  29173. ** The idea behind dataOnly is that it should only write the file content
  29174. ** to disk, not the inode. We only set dataOnly if the file size is
  29175. ** unchanged since the file size is part of the inode. However,
  29176. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  29177. ** file size has changed. The only real difference between fdatasync()
  29178. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  29179. ** inode if the mtime or owner or other inode attributes have changed.
  29180. ** We only care about the file size, not the other file attributes, so
  29181. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  29182. ** So, we always use fdatasync() if it is available, regardless of
  29183. ** the value of the dataOnly flag.
  29184. */
  29185. static int full_fsync(int fd, int fullSync, int dataOnly){
  29186. int rc;
  29187. /* The following "ifdef/elif/else/" block has the same structure as
  29188. ** the one below. It is replicated here solely to avoid cluttering
  29189. ** up the real code with the UNUSED_PARAMETER() macros.
  29190. */
  29191. #ifdef SQLITE_NO_SYNC
  29192. UNUSED_PARAMETER(fd);
  29193. UNUSED_PARAMETER(fullSync);
  29194. UNUSED_PARAMETER(dataOnly);
  29195. #elif HAVE_FULLFSYNC
  29196. UNUSED_PARAMETER(dataOnly);
  29197. #else
  29198. UNUSED_PARAMETER(fullSync);
  29199. UNUSED_PARAMETER(dataOnly);
  29200. #endif
  29201. /* Record the number of times that we do a normal fsync() and
  29202. ** FULLSYNC. This is used during testing to verify that this procedure
  29203. ** gets called with the correct arguments.
  29204. */
  29205. #ifdef SQLITE_TEST
  29206. if( fullSync ) sqlite3_fullsync_count++;
  29207. sqlite3_sync_count++;
  29208. #endif
  29209. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  29210. ** no-op. But go ahead and call fstat() to validate the file
  29211. ** descriptor as we need a method to provoke a failure during
  29212. ** coverate testing.
  29213. */
  29214. #ifdef SQLITE_NO_SYNC
  29215. {
  29216. struct stat buf;
  29217. rc = osFstat(fd, &buf);
  29218. }
  29219. #elif HAVE_FULLFSYNC
  29220. if( fullSync ){
  29221. rc = osFcntl(fd, F_FULLFSYNC, 0);
  29222. }else{
  29223. rc = 1;
  29224. }
  29225. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  29226. ** It shouldn't be possible for fullfsync to fail on the local
  29227. ** file system (on OSX), so failure indicates that FULLFSYNC
  29228. ** isn't supported for this file system. So, attempt an fsync
  29229. ** and (for now) ignore the overhead of a superfluous fcntl call.
  29230. ** It'd be better to detect fullfsync support once and avoid
  29231. ** the fcntl call every time sync is called.
  29232. */
  29233. if( rc ) rc = fsync(fd);
  29234. #elif defined(__APPLE__)
  29235. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  29236. ** so currently we default to the macro that redefines fdatasync to fsync
  29237. */
  29238. rc = fsync(fd);
  29239. #else
  29240. rc = fdatasync(fd);
  29241. #if OS_VXWORKS
  29242. if( rc==-1 && errno==ENOTSUP ){
  29243. rc = fsync(fd);
  29244. }
  29245. #endif /* OS_VXWORKS */
  29246. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  29247. if( OS_VXWORKS && rc!= -1 ){
  29248. rc = 0;
  29249. }
  29250. return rc;
  29251. }
  29252. /*
  29253. ** Open a file descriptor to the directory containing file zFilename.
  29254. ** If successful, *pFd is set to the opened file descriptor and
  29255. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  29256. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  29257. ** value.
  29258. **
  29259. ** The directory file descriptor is used for only one thing - to
  29260. ** fsync() a directory to make sure file creation and deletion events
  29261. ** are flushed to disk. Such fsyncs are not needed on newer
  29262. ** journaling filesystems, but are required on older filesystems.
  29263. **
  29264. ** This routine can be overridden using the xSetSysCall interface.
  29265. ** The ability to override this routine was added in support of the
  29266. ** chromium sandbox. Opening a directory is a security risk (we are
  29267. ** told) so making it overrideable allows the chromium sandbox to
  29268. ** replace this routine with a harmless no-op. To make this routine
  29269. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  29270. ** *pFd set to a negative number.
  29271. **
  29272. ** If SQLITE_OK is returned, the caller is responsible for closing
  29273. ** the file descriptor *pFd using close().
  29274. */
  29275. static int openDirectory(const char *zFilename, int *pFd){
  29276. int ii;
  29277. int fd = -1;
  29278. char zDirname[MAX_PATHNAME+1];
  29279. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  29280. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  29281. if( ii>0 ){
  29282. zDirname[ii] = '\0';
  29283. }else{
  29284. if( zDirname[0]!='/' ) zDirname[0] = '.';
  29285. zDirname[1] = 0;
  29286. }
  29287. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  29288. if( fd>=0 ){
  29289. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  29290. }
  29291. *pFd = fd;
  29292. if( fd>=0 ) return SQLITE_OK;
  29293. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  29294. }
  29295. /*
  29296. ** Make sure all writes to a particular file are committed to disk.
  29297. **
  29298. ** If dataOnly==0 then both the file itself and its metadata (file
  29299. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  29300. ** file data is synced.
  29301. **
  29302. ** Under Unix, also make sure that the directory entry for the file
  29303. ** has been created by fsync-ing the directory that contains the file.
  29304. ** If we do not do this and we encounter a power failure, the directory
  29305. ** entry for the journal might not exist after we reboot. The next
  29306. ** SQLite to access the file will not know that the journal exists (because
  29307. ** the directory entry for the journal was never created) and the transaction
  29308. ** will not roll back - possibly leading to database corruption.
  29309. */
  29310. static int unixSync(sqlite3_file *id, int flags){
  29311. int rc;
  29312. unixFile *pFile = (unixFile*)id;
  29313. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  29314. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  29315. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  29316. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  29317. || (flags&0x0F)==SQLITE_SYNC_FULL
  29318. );
  29319. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  29320. ** line is to test that doing so does not cause any problems.
  29321. */
  29322. SimulateDiskfullError( return SQLITE_FULL );
  29323. assert( pFile );
  29324. OSTRACE(("SYNC %-3d\n", pFile->h));
  29325. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  29326. SimulateIOError( rc=1 );
  29327. if( rc ){
  29328. storeLastErrno(pFile, errno);
  29329. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  29330. }
  29331. /* Also fsync the directory containing the file if the DIRSYNC flag
  29332. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  29333. ** are unable to fsync a directory, so ignore errors on the fsync.
  29334. */
  29335. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  29336. int dirfd;
  29337. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  29338. HAVE_FULLFSYNC, isFullsync));
  29339. rc = osOpenDirectory(pFile->zPath, &dirfd);
  29340. if( rc==SQLITE_OK ){
  29341. full_fsync(dirfd, 0, 0);
  29342. robust_close(pFile, dirfd, __LINE__);
  29343. }else{
  29344. assert( rc==SQLITE_CANTOPEN );
  29345. rc = SQLITE_OK;
  29346. }
  29347. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  29348. }
  29349. return rc;
  29350. }
  29351. /*
  29352. ** Truncate an open file to a specified size
  29353. */
  29354. static int unixTruncate(sqlite3_file *id, i64 nByte){
  29355. unixFile *pFile = (unixFile *)id;
  29356. int rc;
  29357. assert( pFile );
  29358. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  29359. /* If the user has configured a chunk-size for this file, truncate the
  29360. ** file so that it consists of an integer number of chunks (i.e. the
  29361. ** actual file size after the operation may be larger than the requested
  29362. ** size).
  29363. */
  29364. if( pFile->szChunk>0 ){
  29365. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  29366. }
  29367. rc = robust_ftruncate(pFile->h, nByte);
  29368. if( rc ){
  29369. storeLastErrno(pFile, errno);
  29370. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  29371. }else{
  29372. #ifdef SQLITE_DEBUG
  29373. /* If we are doing a normal write to a database file (as opposed to
  29374. ** doing a hot-journal rollback or a write to some file other than a
  29375. ** normal database file) and we truncate the file to zero length,
  29376. ** that effectively updates the change counter. This might happen
  29377. ** when restoring a database using the backup API from a zero-length
  29378. ** source.
  29379. */
  29380. if( pFile->inNormalWrite && nByte==0 ){
  29381. pFile->transCntrChng = 1;
  29382. }
  29383. #endif
  29384. #if SQLITE_MAX_MMAP_SIZE>0
  29385. /* If the file was just truncated to a size smaller than the currently
  29386. ** mapped region, reduce the effective mapping size as well. SQLite will
  29387. ** use read() and write() to access data beyond this point from now on.
  29388. */
  29389. if( nByte<pFile->mmapSize ){
  29390. pFile->mmapSize = nByte;
  29391. }
  29392. #endif
  29393. return SQLITE_OK;
  29394. }
  29395. }
  29396. /*
  29397. ** Determine the current size of a file in bytes
  29398. */
  29399. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  29400. int rc;
  29401. struct stat buf;
  29402. assert( id );
  29403. rc = osFstat(((unixFile*)id)->h, &buf);
  29404. SimulateIOError( rc=1 );
  29405. if( rc!=0 ){
  29406. storeLastErrno((unixFile*)id, errno);
  29407. return SQLITE_IOERR_FSTAT;
  29408. }
  29409. *pSize = buf.st_size;
  29410. /* When opening a zero-size database, the findInodeInfo() procedure
  29411. ** writes a single byte into that file in order to work around a bug
  29412. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  29413. ** layers, we need to report this file size as zero even though it is
  29414. ** really 1. Ticket #3260.
  29415. */
  29416. if( *pSize==1 ) *pSize = 0;
  29417. return SQLITE_OK;
  29418. }
  29419. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29420. /*
  29421. ** Handler for proxy-locking file-control verbs. Defined below in the
  29422. ** proxying locking division.
  29423. */
  29424. static int proxyFileControl(sqlite3_file*,int,void*);
  29425. #endif
  29426. /*
  29427. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  29428. ** file-control operation. Enlarge the database to nBytes in size
  29429. ** (rounded up to the next chunk-size). If the database is already
  29430. ** nBytes or larger, this routine is a no-op.
  29431. */
  29432. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  29433. if( pFile->szChunk>0 ){
  29434. i64 nSize; /* Required file size */
  29435. struct stat buf; /* Used to hold return values of fstat() */
  29436. if( osFstat(pFile->h, &buf) ){
  29437. return SQLITE_IOERR_FSTAT;
  29438. }
  29439. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  29440. if( nSize>(i64)buf.st_size ){
  29441. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  29442. /* The code below is handling the return value of osFallocate()
  29443. ** correctly. posix_fallocate() is defined to "returns zero on success,
  29444. ** or an error number on failure". See the manpage for details. */
  29445. int err;
  29446. do{
  29447. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  29448. }while( err==EINTR );
  29449. if( err ) return SQLITE_IOERR_WRITE;
  29450. #else
  29451. /* If the OS does not have posix_fallocate(), fake it. Write a
  29452. ** single byte to the last byte in each block that falls entirely
  29453. ** within the extended region. Then, if required, a single byte
  29454. ** at offset (nSize-1), to set the size of the file correctly.
  29455. ** This is a similar technique to that used by glibc on systems
  29456. ** that do not have a real fallocate() call.
  29457. */
  29458. int nBlk = buf.st_blksize; /* File-system block size */
  29459. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  29460. i64 iWrite; /* Next offset to write to */
  29461. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  29462. assert( iWrite>=buf.st_size );
  29463. assert( ((iWrite+1)%nBlk)==0 );
  29464. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  29465. if( iWrite>=nSize ) iWrite = nSize - 1;
  29466. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  29467. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  29468. }
  29469. #endif
  29470. }
  29471. }
  29472. #if SQLITE_MAX_MMAP_SIZE>0
  29473. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  29474. int rc;
  29475. if( pFile->szChunk<=0 ){
  29476. if( robust_ftruncate(pFile->h, nByte) ){
  29477. storeLastErrno(pFile, errno);
  29478. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  29479. }
  29480. }
  29481. rc = unixMapfile(pFile, nByte);
  29482. return rc;
  29483. }
  29484. #endif
  29485. return SQLITE_OK;
  29486. }
  29487. /*
  29488. ** If *pArg is initially negative then this is a query. Set *pArg to
  29489. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  29490. **
  29491. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  29492. */
  29493. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  29494. if( *pArg<0 ){
  29495. *pArg = (pFile->ctrlFlags & mask)!=0;
  29496. }else if( (*pArg)==0 ){
  29497. pFile->ctrlFlags &= ~mask;
  29498. }else{
  29499. pFile->ctrlFlags |= mask;
  29500. }
  29501. }
  29502. /* Forward declaration */
  29503. static int unixGetTempname(int nBuf, char *zBuf);
  29504. /*
  29505. ** Information and control of an open file handle.
  29506. */
  29507. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  29508. unixFile *pFile = (unixFile*)id;
  29509. switch( op ){
  29510. case SQLITE_FCNTL_LOCKSTATE: {
  29511. *(int*)pArg = pFile->eFileLock;
  29512. return SQLITE_OK;
  29513. }
  29514. case SQLITE_FCNTL_LAST_ERRNO: {
  29515. *(int*)pArg = pFile->lastErrno;
  29516. return SQLITE_OK;
  29517. }
  29518. case SQLITE_FCNTL_CHUNK_SIZE: {
  29519. pFile->szChunk = *(int *)pArg;
  29520. return SQLITE_OK;
  29521. }
  29522. case SQLITE_FCNTL_SIZE_HINT: {
  29523. int rc;
  29524. SimulateIOErrorBenign(1);
  29525. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  29526. SimulateIOErrorBenign(0);
  29527. return rc;
  29528. }
  29529. case SQLITE_FCNTL_PERSIST_WAL: {
  29530. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  29531. return SQLITE_OK;
  29532. }
  29533. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  29534. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  29535. return SQLITE_OK;
  29536. }
  29537. case SQLITE_FCNTL_VFSNAME: {
  29538. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  29539. return SQLITE_OK;
  29540. }
  29541. case SQLITE_FCNTL_TEMPFILENAME: {
  29542. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  29543. if( zTFile ){
  29544. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  29545. *(char**)pArg = zTFile;
  29546. }
  29547. return SQLITE_OK;
  29548. }
  29549. case SQLITE_FCNTL_HAS_MOVED: {
  29550. *(int*)pArg = fileHasMoved(pFile);
  29551. return SQLITE_OK;
  29552. }
  29553. #if SQLITE_MAX_MMAP_SIZE>0
  29554. case SQLITE_FCNTL_MMAP_SIZE: {
  29555. i64 newLimit = *(i64*)pArg;
  29556. int rc = SQLITE_OK;
  29557. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  29558. newLimit = sqlite3GlobalConfig.mxMmap;
  29559. }
  29560. *(i64*)pArg = pFile->mmapSizeMax;
  29561. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  29562. pFile->mmapSizeMax = newLimit;
  29563. if( pFile->mmapSize>0 ){
  29564. unixUnmapfile(pFile);
  29565. rc = unixMapfile(pFile, -1);
  29566. }
  29567. }
  29568. return rc;
  29569. }
  29570. #endif
  29571. #ifdef SQLITE_DEBUG
  29572. /* The pager calls this method to signal that it has done
  29573. ** a rollback and that the database is therefore unchanged and
  29574. ** it hence it is OK for the transaction change counter to be
  29575. ** unchanged.
  29576. */
  29577. case SQLITE_FCNTL_DB_UNCHANGED: {
  29578. ((unixFile*)id)->dbUpdate = 0;
  29579. return SQLITE_OK;
  29580. }
  29581. #endif
  29582. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29583. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  29584. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  29585. return proxyFileControl(id,op,pArg);
  29586. }
  29587. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  29588. }
  29589. return SQLITE_NOTFOUND;
  29590. }
  29591. /*
  29592. ** Return the sector size in bytes of the underlying block device for
  29593. ** the specified file. This is almost always 512 bytes, but may be
  29594. ** larger for some devices.
  29595. **
  29596. ** SQLite code assumes this function cannot fail. It also assumes that
  29597. ** if two files are created in the same file-system directory (i.e.
  29598. ** a database and its journal file) that the sector size will be the
  29599. ** same for both.
  29600. */
  29601. #ifndef __QNXNTO__
  29602. static int unixSectorSize(sqlite3_file *NotUsed){
  29603. UNUSED_PARAMETER(NotUsed);
  29604. return SQLITE_DEFAULT_SECTOR_SIZE;
  29605. }
  29606. #endif
  29607. /*
  29608. ** The following version of unixSectorSize() is optimized for QNX.
  29609. */
  29610. #ifdef __QNXNTO__
  29611. #include <sys/dcmd_blk.h>
  29612. #include <sys/statvfs.h>
  29613. static int unixSectorSize(sqlite3_file *id){
  29614. unixFile *pFile = (unixFile*)id;
  29615. if( pFile->sectorSize == 0 ){
  29616. struct statvfs fsInfo;
  29617. /* Set defaults for non-supported filesystems */
  29618. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  29619. pFile->deviceCharacteristics = 0;
  29620. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  29621. return pFile->sectorSize;
  29622. }
  29623. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  29624. pFile->sectorSize = fsInfo.f_bsize;
  29625. pFile->deviceCharacteristics =
  29626. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  29627. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29628. ** the write succeeds */
  29629. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29630. ** so it is ordered */
  29631. 0;
  29632. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  29633. pFile->sectorSize = fsInfo.f_bsize;
  29634. pFile->deviceCharacteristics =
  29635. /* etfs cluster size writes are atomic */
  29636. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  29637. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29638. ** the write succeeds */
  29639. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29640. ** so it is ordered */
  29641. 0;
  29642. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  29643. pFile->sectorSize = fsInfo.f_bsize;
  29644. pFile->deviceCharacteristics =
  29645. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  29646. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29647. ** the write succeeds */
  29648. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29649. ** so it is ordered */
  29650. 0;
  29651. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  29652. pFile->sectorSize = fsInfo.f_bsize;
  29653. pFile->deviceCharacteristics =
  29654. /* full bitset of atomics from max sector size and smaller */
  29655. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  29656. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29657. ** so it is ordered */
  29658. 0;
  29659. }else if( strstr(fsInfo.f_basetype, "dos") ){
  29660. pFile->sectorSize = fsInfo.f_bsize;
  29661. pFile->deviceCharacteristics =
  29662. /* full bitset of atomics from max sector size and smaller */
  29663. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  29664. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29665. ** so it is ordered */
  29666. 0;
  29667. }else{
  29668. pFile->deviceCharacteristics =
  29669. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  29670. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29671. ** the write succeeds */
  29672. 0;
  29673. }
  29674. }
  29675. /* Last chance verification. If the sector size isn't a multiple of 512
  29676. ** then it isn't valid.*/
  29677. if( pFile->sectorSize % 512 != 0 ){
  29678. pFile->deviceCharacteristics = 0;
  29679. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  29680. }
  29681. return pFile->sectorSize;
  29682. }
  29683. #endif /* __QNXNTO__ */
  29684. /*
  29685. ** Return the device characteristics for the file.
  29686. **
  29687. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  29688. ** However, that choice is controversial since technically the underlying
  29689. ** file system does not always provide powersafe overwrites. (In other
  29690. ** words, after a power-loss event, parts of the file that were never
  29691. ** written might end up being altered.) However, non-PSOW behavior is very,
  29692. ** very rare. And asserting PSOW makes a large reduction in the amount
  29693. ** of required I/O for journaling, since a lot of padding is eliminated.
  29694. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  29695. ** available to turn it off and URI query parameter available to turn it off.
  29696. */
  29697. static int unixDeviceCharacteristics(sqlite3_file *id){
  29698. unixFile *p = (unixFile*)id;
  29699. int rc = 0;
  29700. #ifdef __QNXNTO__
  29701. if( p->sectorSize==0 ) unixSectorSize(id);
  29702. rc = p->deviceCharacteristics;
  29703. #endif
  29704. if( p->ctrlFlags & UNIXFILE_PSOW ){
  29705. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  29706. }
  29707. return rc;
  29708. }
  29709. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  29710. /*
  29711. ** Return the system page size.
  29712. **
  29713. ** This function should not be called directly by other code in this file.
  29714. ** Instead, it should be called via macro osGetpagesize().
  29715. */
  29716. static int unixGetpagesize(void){
  29717. #if OS_VXWORKS
  29718. return 1024;
  29719. #elif defined(_BSD_SOURCE)
  29720. return getpagesize();
  29721. #else
  29722. return (int)sysconf(_SC_PAGESIZE);
  29723. #endif
  29724. }
  29725. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  29726. #ifndef SQLITE_OMIT_WAL
  29727. /*
  29728. ** Object used to represent an shared memory buffer.
  29729. **
  29730. ** When multiple threads all reference the same wal-index, each thread
  29731. ** has its own unixShm object, but they all point to a single instance
  29732. ** of this unixShmNode object. In other words, each wal-index is opened
  29733. ** only once per process.
  29734. **
  29735. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  29736. ** We could coalesce this object into unixInodeInfo, but that would mean
  29737. ** every open file that does not use shared memory (in other words, most
  29738. ** open files) would have to carry around this extra information. So
  29739. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  29740. ** and the unixShmNode object is created only when needed.
  29741. **
  29742. ** unixMutexHeld() must be true when creating or destroying
  29743. ** this object or while reading or writing the following fields:
  29744. **
  29745. ** nRef
  29746. **
  29747. ** The following fields are read-only after the object is created:
  29748. **
  29749. ** fid
  29750. ** zFilename
  29751. **
  29752. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  29753. ** unixMutexHeld() is true when reading or writing any other field
  29754. ** in this structure.
  29755. */
  29756. struct unixShmNode {
  29757. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  29758. sqlite3_mutex *mutex; /* Mutex to access this object */
  29759. char *zFilename; /* Name of the mmapped file */
  29760. int h; /* Open file descriptor */
  29761. int szRegion; /* Size of shared-memory regions */
  29762. u16 nRegion; /* Size of array apRegion */
  29763. u8 isReadonly; /* True if read-only */
  29764. char **apRegion; /* Array of mapped shared-memory regions */
  29765. int nRef; /* Number of unixShm objects pointing to this */
  29766. unixShm *pFirst; /* All unixShm objects pointing to this */
  29767. #ifdef SQLITE_DEBUG
  29768. u8 exclMask; /* Mask of exclusive locks held */
  29769. u8 sharedMask; /* Mask of shared locks held */
  29770. u8 nextShmId; /* Next available unixShm.id value */
  29771. #endif
  29772. };
  29773. /*
  29774. ** Structure used internally by this VFS to record the state of an
  29775. ** open shared memory connection.
  29776. **
  29777. ** The following fields are initialized when this object is created and
  29778. ** are read-only thereafter:
  29779. **
  29780. ** unixShm.pFile
  29781. ** unixShm.id
  29782. **
  29783. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  29784. ** while accessing any read/write fields.
  29785. */
  29786. struct unixShm {
  29787. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  29788. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  29789. u8 hasMutex; /* True if holding the unixShmNode mutex */
  29790. u8 id; /* Id of this connection within its unixShmNode */
  29791. u16 sharedMask; /* Mask of shared locks held */
  29792. u16 exclMask; /* Mask of exclusive locks held */
  29793. };
  29794. /*
  29795. ** Constants used for locking
  29796. */
  29797. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  29798. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  29799. /*
  29800. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  29801. **
  29802. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  29803. ** otherwise.
  29804. */
  29805. static int unixShmSystemLock(
  29806. unixFile *pFile, /* Open connection to the WAL file */
  29807. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  29808. int ofst, /* First byte of the locking range */
  29809. int n /* Number of bytes to lock */
  29810. ){
  29811. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  29812. struct flock f; /* The posix advisory locking structure */
  29813. int rc = SQLITE_OK; /* Result code form fcntl() */
  29814. /* Access to the unixShmNode object is serialized by the caller */
  29815. pShmNode = pFile->pInode->pShmNode;
  29816. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  29817. /* Shared locks never span more than one byte */
  29818. assert( n==1 || lockType!=F_RDLCK );
  29819. /* Locks are within range */
  29820. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  29821. if( pShmNode->h>=0 ){
  29822. /* Initialize the locking parameters */
  29823. memset(&f, 0, sizeof(f));
  29824. f.l_type = lockType;
  29825. f.l_whence = SEEK_SET;
  29826. f.l_start = ofst;
  29827. f.l_len = n;
  29828. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  29829. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  29830. }
  29831. /* Update the global lock state and do debug tracing */
  29832. #ifdef SQLITE_DEBUG
  29833. { u16 mask;
  29834. OSTRACE(("SHM-LOCK "));
  29835. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  29836. if( rc==SQLITE_OK ){
  29837. if( lockType==F_UNLCK ){
  29838. OSTRACE(("unlock %d ok", ofst));
  29839. pShmNode->exclMask &= ~mask;
  29840. pShmNode->sharedMask &= ~mask;
  29841. }else if( lockType==F_RDLCK ){
  29842. OSTRACE(("read-lock %d ok", ofst));
  29843. pShmNode->exclMask &= ~mask;
  29844. pShmNode->sharedMask |= mask;
  29845. }else{
  29846. assert( lockType==F_WRLCK );
  29847. OSTRACE(("write-lock %d ok", ofst));
  29848. pShmNode->exclMask |= mask;
  29849. pShmNode->sharedMask &= ~mask;
  29850. }
  29851. }else{
  29852. if( lockType==F_UNLCK ){
  29853. OSTRACE(("unlock %d failed", ofst));
  29854. }else if( lockType==F_RDLCK ){
  29855. OSTRACE(("read-lock failed"));
  29856. }else{
  29857. assert( lockType==F_WRLCK );
  29858. OSTRACE(("write-lock %d failed", ofst));
  29859. }
  29860. }
  29861. OSTRACE((" - afterwards %03x,%03x\n",
  29862. pShmNode->sharedMask, pShmNode->exclMask));
  29863. }
  29864. #endif
  29865. return rc;
  29866. }
  29867. /*
  29868. ** Return the minimum number of 32KB shm regions that should be mapped at
  29869. ** a time, assuming that each mapping must be an integer multiple of the
  29870. ** current system page-size.
  29871. **
  29872. ** Usually, this is 1. The exception seems to be systems that are configured
  29873. ** to use 64KB pages - in this case each mapping must cover at least two
  29874. ** shm regions.
  29875. */
  29876. static int unixShmRegionPerMap(void){
  29877. int shmsz = 32*1024; /* SHM region size */
  29878. int pgsz = osGetpagesize(); /* System page size */
  29879. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  29880. if( pgsz<shmsz ) return 1;
  29881. return pgsz/shmsz;
  29882. }
  29883. /*
  29884. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  29885. **
  29886. ** This is not a VFS shared-memory method; it is a utility function called
  29887. ** by VFS shared-memory methods.
  29888. */
  29889. static void unixShmPurge(unixFile *pFd){
  29890. unixShmNode *p = pFd->pInode->pShmNode;
  29891. assert( unixMutexHeld() );
  29892. if( p && ALWAYS(p->nRef==0) ){
  29893. int nShmPerMap = unixShmRegionPerMap();
  29894. int i;
  29895. assert( p->pInode==pFd->pInode );
  29896. sqlite3_mutex_free(p->mutex);
  29897. for(i=0; i<p->nRegion; i+=nShmPerMap){
  29898. if( p->h>=0 ){
  29899. osMunmap(p->apRegion[i], p->szRegion);
  29900. }else{
  29901. sqlite3_free(p->apRegion[i]);
  29902. }
  29903. }
  29904. sqlite3_free(p->apRegion);
  29905. if( p->h>=0 ){
  29906. robust_close(pFd, p->h, __LINE__);
  29907. p->h = -1;
  29908. }
  29909. p->pInode->pShmNode = 0;
  29910. sqlite3_free(p);
  29911. }
  29912. }
  29913. /*
  29914. ** Open a shared-memory area associated with open database file pDbFd.
  29915. ** This particular implementation uses mmapped files.
  29916. **
  29917. ** The file used to implement shared-memory is in the same directory
  29918. ** as the open database file and has the same name as the open database
  29919. ** file with the "-shm" suffix added. For example, if the database file
  29920. ** is "/home/user1/config.db" then the file that is created and mmapped
  29921. ** for shared memory will be called "/home/user1/config.db-shm".
  29922. **
  29923. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  29924. ** some other tmpfs mount. But if a file in a different directory
  29925. ** from the database file is used, then differing access permissions
  29926. ** or a chroot() might cause two different processes on the same
  29927. ** database to end up using different files for shared memory -
  29928. ** meaning that their memory would not really be shared - resulting
  29929. ** in database corruption. Nevertheless, this tmpfs file usage
  29930. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  29931. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  29932. ** option results in an incompatible build of SQLite; builds of SQLite
  29933. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  29934. ** same database file at the same time, database corruption will likely
  29935. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  29936. ** "unsupported" and may go away in a future SQLite release.
  29937. **
  29938. ** When opening a new shared-memory file, if no other instances of that
  29939. ** file are currently open, in this process or in other processes, then
  29940. ** the file must be truncated to zero length or have its header cleared.
  29941. **
  29942. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  29943. ** that means that an exclusive lock is held on the database file and
  29944. ** that no other processes are able to read or write the database. In
  29945. ** that case, we do not really need shared memory. No shared memory
  29946. ** file is created. The shared memory will be simulated with heap memory.
  29947. */
  29948. static int unixOpenSharedMemory(unixFile *pDbFd){
  29949. struct unixShm *p = 0; /* The connection to be opened */
  29950. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  29951. int rc; /* Result code */
  29952. unixInodeInfo *pInode; /* The inode of fd */
  29953. char *zShmFilename; /* Name of the file used for SHM */
  29954. int nShmFilename; /* Size of the SHM filename in bytes */
  29955. /* Allocate space for the new unixShm object. */
  29956. p = sqlite3_malloc64( sizeof(*p) );
  29957. if( p==0 ) return SQLITE_NOMEM_BKPT;
  29958. memset(p, 0, sizeof(*p));
  29959. assert( pDbFd->pShm==0 );
  29960. /* Check to see if a unixShmNode object already exists. Reuse an existing
  29961. ** one if present. Create a new one if necessary.
  29962. */
  29963. unixEnterMutex();
  29964. pInode = pDbFd->pInode;
  29965. pShmNode = pInode->pShmNode;
  29966. if( pShmNode==0 ){
  29967. struct stat sStat; /* fstat() info for database file */
  29968. #ifndef SQLITE_SHM_DIRECTORY
  29969. const char *zBasePath = pDbFd->zPath;
  29970. #endif
  29971. /* Call fstat() to figure out the permissions on the database file. If
  29972. ** a new *-shm file is created, an attempt will be made to create it
  29973. ** with the same permissions.
  29974. */
  29975. if( osFstat(pDbFd->h, &sStat) ){
  29976. rc = SQLITE_IOERR_FSTAT;
  29977. goto shm_open_err;
  29978. }
  29979. #ifdef SQLITE_SHM_DIRECTORY
  29980. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  29981. #else
  29982. nShmFilename = 6 + (int)strlen(zBasePath);
  29983. #endif
  29984. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  29985. if( pShmNode==0 ){
  29986. rc = SQLITE_NOMEM_BKPT;
  29987. goto shm_open_err;
  29988. }
  29989. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  29990. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  29991. #ifdef SQLITE_SHM_DIRECTORY
  29992. sqlite3_snprintf(nShmFilename, zShmFilename,
  29993. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  29994. (u32)sStat.st_ino, (u32)sStat.st_dev);
  29995. #else
  29996. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  29997. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  29998. #endif
  29999. pShmNode->h = -1;
  30000. pDbFd->pInode->pShmNode = pShmNode;
  30001. pShmNode->pInode = pDbFd->pInode;
  30002. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  30003. if( pShmNode->mutex==0 ){
  30004. rc = SQLITE_NOMEM_BKPT;
  30005. goto shm_open_err;
  30006. }
  30007. if( pInode->bProcessLock==0 ){
  30008. int openFlags = O_RDWR | O_CREAT;
  30009. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  30010. openFlags = O_RDONLY;
  30011. pShmNode->isReadonly = 1;
  30012. }
  30013. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  30014. if( pShmNode->h<0 ){
  30015. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  30016. goto shm_open_err;
  30017. }
  30018. /* If this process is running as root, make sure that the SHM file
  30019. ** is owned by the same user that owns the original database. Otherwise,
  30020. ** the original owner will not be able to connect.
  30021. */
  30022. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  30023. /* Check to see if another process is holding the dead-man switch.
  30024. ** If not, truncate the file to zero length.
  30025. */
  30026. rc = SQLITE_OK;
  30027. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  30028. if( robust_ftruncate(pShmNode->h, 0) ){
  30029. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  30030. }
  30031. }
  30032. if( rc==SQLITE_OK ){
  30033. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  30034. }
  30035. if( rc ) goto shm_open_err;
  30036. }
  30037. }
  30038. /* Make the new connection a child of the unixShmNode */
  30039. p->pShmNode = pShmNode;
  30040. #ifdef SQLITE_DEBUG
  30041. p->id = pShmNode->nextShmId++;
  30042. #endif
  30043. pShmNode->nRef++;
  30044. pDbFd->pShm = p;
  30045. unixLeaveMutex();
  30046. /* The reference count on pShmNode has already been incremented under
  30047. ** the cover of the unixEnterMutex() mutex and the pointer from the
  30048. ** new (struct unixShm) object to the pShmNode has been set. All that is
  30049. ** left to do is to link the new object into the linked list starting
  30050. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  30051. ** mutex.
  30052. */
  30053. sqlite3_mutex_enter(pShmNode->mutex);
  30054. p->pNext = pShmNode->pFirst;
  30055. pShmNode->pFirst = p;
  30056. sqlite3_mutex_leave(pShmNode->mutex);
  30057. return SQLITE_OK;
  30058. /* Jump here on any error */
  30059. shm_open_err:
  30060. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  30061. sqlite3_free(p);
  30062. unixLeaveMutex();
  30063. return rc;
  30064. }
  30065. /*
  30066. ** This function is called to obtain a pointer to region iRegion of the
  30067. ** shared-memory associated with the database file fd. Shared-memory regions
  30068. ** are numbered starting from zero. Each shared-memory region is szRegion
  30069. ** bytes in size.
  30070. **
  30071. ** If an error occurs, an error code is returned and *pp is set to NULL.
  30072. **
  30073. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  30074. ** region has not been allocated (by any client, including one running in a
  30075. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  30076. ** bExtend is non-zero and the requested shared-memory region has not yet
  30077. ** been allocated, it is allocated by this function.
  30078. **
  30079. ** If the shared-memory region has already been allocated or is allocated by
  30080. ** this call as described above, then it is mapped into this processes
  30081. ** address space (if it is not already), *pp is set to point to the mapped
  30082. ** memory and SQLITE_OK returned.
  30083. */
  30084. static int unixShmMap(
  30085. sqlite3_file *fd, /* Handle open on database file */
  30086. int iRegion, /* Region to retrieve */
  30087. int szRegion, /* Size of regions */
  30088. int bExtend, /* True to extend file if necessary */
  30089. void volatile **pp /* OUT: Mapped memory */
  30090. ){
  30091. unixFile *pDbFd = (unixFile*)fd;
  30092. unixShm *p;
  30093. unixShmNode *pShmNode;
  30094. int rc = SQLITE_OK;
  30095. int nShmPerMap = unixShmRegionPerMap();
  30096. int nReqRegion;
  30097. /* If the shared-memory file has not yet been opened, open it now. */
  30098. if( pDbFd->pShm==0 ){
  30099. rc = unixOpenSharedMemory(pDbFd);
  30100. if( rc!=SQLITE_OK ) return rc;
  30101. }
  30102. p = pDbFd->pShm;
  30103. pShmNode = p->pShmNode;
  30104. sqlite3_mutex_enter(pShmNode->mutex);
  30105. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  30106. assert( pShmNode->pInode==pDbFd->pInode );
  30107. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  30108. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  30109. /* Minimum number of regions required to be mapped. */
  30110. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  30111. if( pShmNode->nRegion<nReqRegion ){
  30112. char **apNew; /* New apRegion[] array */
  30113. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  30114. struct stat sStat; /* Used by fstat() */
  30115. pShmNode->szRegion = szRegion;
  30116. if( pShmNode->h>=0 ){
  30117. /* The requested region is not mapped into this processes address space.
  30118. ** Check to see if it has been allocated (i.e. if the wal-index file is
  30119. ** large enough to contain the requested region).
  30120. */
  30121. if( osFstat(pShmNode->h, &sStat) ){
  30122. rc = SQLITE_IOERR_SHMSIZE;
  30123. goto shmpage_out;
  30124. }
  30125. if( sStat.st_size<nByte ){
  30126. /* The requested memory region does not exist. If bExtend is set to
  30127. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  30128. */
  30129. if( !bExtend ){
  30130. goto shmpage_out;
  30131. }
  30132. /* Alternatively, if bExtend is true, extend the file. Do this by
  30133. ** writing a single byte to the end of each (OS) page being
  30134. ** allocated or extended. Technically, we need only write to the
  30135. ** last page in order to extend the file. But writing to all new
  30136. ** pages forces the OS to allocate them immediately, which reduces
  30137. ** the chances of SIGBUS while accessing the mapped region later on.
  30138. */
  30139. else{
  30140. static const int pgsz = 4096;
  30141. int iPg;
  30142. /* Write to the last byte of each newly allocated or extended page */
  30143. assert( (nByte % pgsz)==0 );
  30144. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  30145. int x = 0;
  30146. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  30147. const char *zFile = pShmNode->zFilename;
  30148. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  30149. goto shmpage_out;
  30150. }
  30151. }
  30152. }
  30153. }
  30154. }
  30155. /* Map the requested memory region into this processes address space. */
  30156. apNew = (char **)sqlite3_realloc(
  30157. pShmNode->apRegion, nReqRegion*sizeof(char *)
  30158. );
  30159. if( !apNew ){
  30160. rc = SQLITE_IOERR_NOMEM_BKPT;
  30161. goto shmpage_out;
  30162. }
  30163. pShmNode->apRegion = apNew;
  30164. while( pShmNode->nRegion<nReqRegion ){
  30165. int nMap = szRegion*nShmPerMap;
  30166. int i;
  30167. void *pMem;
  30168. if( pShmNode->h>=0 ){
  30169. pMem = osMmap(0, nMap,
  30170. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  30171. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  30172. );
  30173. if( pMem==MAP_FAILED ){
  30174. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  30175. goto shmpage_out;
  30176. }
  30177. }else{
  30178. pMem = sqlite3_malloc64(szRegion);
  30179. if( pMem==0 ){
  30180. rc = SQLITE_NOMEM_BKPT;
  30181. goto shmpage_out;
  30182. }
  30183. memset(pMem, 0, szRegion);
  30184. }
  30185. for(i=0; i<nShmPerMap; i++){
  30186. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  30187. }
  30188. pShmNode->nRegion += nShmPerMap;
  30189. }
  30190. }
  30191. shmpage_out:
  30192. if( pShmNode->nRegion>iRegion ){
  30193. *pp = pShmNode->apRegion[iRegion];
  30194. }else{
  30195. *pp = 0;
  30196. }
  30197. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  30198. sqlite3_mutex_leave(pShmNode->mutex);
  30199. return rc;
  30200. }
  30201. /*
  30202. ** Change the lock state for a shared-memory segment.
  30203. **
  30204. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  30205. ** different here than in posix. In xShmLock(), one can go from unlocked
  30206. ** to shared and back or from unlocked to exclusive and back. But one may
  30207. ** not go from shared to exclusive or from exclusive to shared.
  30208. */
  30209. static int unixShmLock(
  30210. sqlite3_file *fd, /* Database file holding the shared memory */
  30211. int ofst, /* First lock to acquire or release */
  30212. int n, /* Number of locks to acquire or release */
  30213. int flags /* What to do with the lock */
  30214. ){
  30215. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  30216. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  30217. unixShm *pX; /* For looping over all siblings */
  30218. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  30219. int rc = SQLITE_OK; /* Result code */
  30220. u16 mask; /* Mask of locks to take or release */
  30221. assert( pShmNode==pDbFd->pInode->pShmNode );
  30222. assert( pShmNode->pInode==pDbFd->pInode );
  30223. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  30224. assert( n>=1 );
  30225. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  30226. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  30227. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  30228. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  30229. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  30230. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  30231. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  30232. mask = (1<<(ofst+n)) - (1<<ofst);
  30233. assert( n>1 || mask==(1<<ofst) );
  30234. sqlite3_mutex_enter(pShmNode->mutex);
  30235. if( flags & SQLITE_SHM_UNLOCK ){
  30236. u16 allMask = 0; /* Mask of locks held by siblings */
  30237. /* See if any siblings hold this same lock */
  30238. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  30239. if( pX==p ) continue;
  30240. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  30241. allMask |= pX->sharedMask;
  30242. }
  30243. /* Unlock the system-level locks */
  30244. if( (mask & allMask)==0 ){
  30245. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  30246. }else{
  30247. rc = SQLITE_OK;
  30248. }
  30249. /* Undo the local locks */
  30250. if( rc==SQLITE_OK ){
  30251. p->exclMask &= ~mask;
  30252. p->sharedMask &= ~mask;
  30253. }
  30254. }else if( flags & SQLITE_SHM_SHARED ){
  30255. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  30256. /* Find out which shared locks are already held by sibling connections.
  30257. ** If any sibling already holds an exclusive lock, go ahead and return
  30258. ** SQLITE_BUSY.
  30259. */
  30260. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  30261. if( (pX->exclMask & mask)!=0 ){
  30262. rc = SQLITE_BUSY;
  30263. break;
  30264. }
  30265. allShared |= pX->sharedMask;
  30266. }
  30267. /* Get shared locks at the system level, if necessary */
  30268. if( rc==SQLITE_OK ){
  30269. if( (allShared & mask)==0 ){
  30270. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  30271. }else{
  30272. rc = SQLITE_OK;
  30273. }
  30274. }
  30275. /* Get the local shared locks */
  30276. if( rc==SQLITE_OK ){
  30277. p->sharedMask |= mask;
  30278. }
  30279. }else{
  30280. /* Make sure no sibling connections hold locks that will block this
  30281. ** lock. If any do, return SQLITE_BUSY right away.
  30282. */
  30283. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  30284. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  30285. rc = SQLITE_BUSY;
  30286. break;
  30287. }
  30288. }
  30289. /* Get the exclusive locks at the system level. Then if successful
  30290. ** also mark the local connection as being locked.
  30291. */
  30292. if( rc==SQLITE_OK ){
  30293. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  30294. if( rc==SQLITE_OK ){
  30295. assert( (p->sharedMask & mask)==0 );
  30296. p->exclMask |= mask;
  30297. }
  30298. }
  30299. }
  30300. sqlite3_mutex_leave(pShmNode->mutex);
  30301. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  30302. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  30303. return rc;
  30304. }
  30305. /*
  30306. ** Implement a memory barrier or memory fence on shared memory.
  30307. **
  30308. ** All loads and stores begun before the barrier must complete before
  30309. ** any load or store begun after the barrier.
  30310. */
  30311. static void unixShmBarrier(
  30312. sqlite3_file *fd /* Database file holding the shared memory */
  30313. ){
  30314. UNUSED_PARAMETER(fd);
  30315. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  30316. unixEnterMutex(); /* Also mutex, for redundancy */
  30317. unixLeaveMutex();
  30318. }
  30319. /*
  30320. ** Close a connection to shared-memory. Delete the underlying
  30321. ** storage if deleteFlag is true.
  30322. **
  30323. ** If there is no shared memory associated with the connection then this
  30324. ** routine is a harmless no-op.
  30325. */
  30326. static int unixShmUnmap(
  30327. sqlite3_file *fd, /* The underlying database file */
  30328. int deleteFlag /* Delete shared-memory if true */
  30329. ){
  30330. unixShm *p; /* The connection to be closed */
  30331. unixShmNode *pShmNode; /* The underlying shared-memory file */
  30332. unixShm **pp; /* For looping over sibling connections */
  30333. unixFile *pDbFd; /* The underlying database file */
  30334. pDbFd = (unixFile*)fd;
  30335. p = pDbFd->pShm;
  30336. if( p==0 ) return SQLITE_OK;
  30337. pShmNode = p->pShmNode;
  30338. assert( pShmNode==pDbFd->pInode->pShmNode );
  30339. assert( pShmNode->pInode==pDbFd->pInode );
  30340. /* Remove connection p from the set of connections associated
  30341. ** with pShmNode */
  30342. sqlite3_mutex_enter(pShmNode->mutex);
  30343. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  30344. *pp = p->pNext;
  30345. /* Free the connection p */
  30346. sqlite3_free(p);
  30347. pDbFd->pShm = 0;
  30348. sqlite3_mutex_leave(pShmNode->mutex);
  30349. /* If pShmNode->nRef has reached 0, then close the underlying
  30350. ** shared-memory file, too */
  30351. unixEnterMutex();
  30352. assert( pShmNode->nRef>0 );
  30353. pShmNode->nRef--;
  30354. if( pShmNode->nRef==0 ){
  30355. if( deleteFlag && pShmNode->h>=0 ){
  30356. osUnlink(pShmNode->zFilename);
  30357. }
  30358. unixShmPurge(pDbFd);
  30359. }
  30360. unixLeaveMutex();
  30361. return SQLITE_OK;
  30362. }
  30363. #else
  30364. # define unixShmMap 0
  30365. # define unixShmLock 0
  30366. # define unixShmBarrier 0
  30367. # define unixShmUnmap 0
  30368. #endif /* #ifndef SQLITE_OMIT_WAL */
  30369. #if SQLITE_MAX_MMAP_SIZE>0
  30370. /*
  30371. ** If it is currently memory mapped, unmap file pFd.
  30372. */
  30373. static void unixUnmapfile(unixFile *pFd){
  30374. assert( pFd->nFetchOut==0 );
  30375. if( pFd->pMapRegion ){
  30376. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  30377. pFd->pMapRegion = 0;
  30378. pFd->mmapSize = 0;
  30379. pFd->mmapSizeActual = 0;
  30380. }
  30381. }
  30382. /*
  30383. ** Attempt to set the size of the memory mapping maintained by file
  30384. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  30385. **
  30386. ** If successful, this function sets the following variables:
  30387. **
  30388. ** unixFile.pMapRegion
  30389. ** unixFile.mmapSize
  30390. ** unixFile.mmapSizeActual
  30391. **
  30392. ** If unsuccessful, an error message is logged via sqlite3_log() and
  30393. ** the three variables above are zeroed. In this case SQLite should
  30394. ** continue accessing the database using the xRead() and xWrite()
  30395. ** methods.
  30396. */
  30397. static void unixRemapfile(
  30398. unixFile *pFd, /* File descriptor object */
  30399. i64 nNew /* Required mapping size */
  30400. ){
  30401. const char *zErr = "mmap";
  30402. int h = pFd->h; /* File descriptor open on db file */
  30403. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  30404. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  30405. u8 *pNew = 0; /* Location of new mapping */
  30406. int flags = PROT_READ; /* Flags to pass to mmap() */
  30407. assert( pFd->nFetchOut==0 );
  30408. assert( nNew>pFd->mmapSize );
  30409. assert( nNew<=pFd->mmapSizeMax );
  30410. assert( nNew>0 );
  30411. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  30412. assert( MAP_FAILED!=0 );
  30413. #ifdef SQLITE_MMAP_READWRITE
  30414. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  30415. #endif
  30416. if( pOrig ){
  30417. #if HAVE_MREMAP
  30418. i64 nReuse = pFd->mmapSize;
  30419. #else
  30420. const int szSyspage = osGetpagesize();
  30421. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  30422. #endif
  30423. u8 *pReq = &pOrig[nReuse];
  30424. /* Unmap any pages of the existing mapping that cannot be reused. */
  30425. if( nReuse!=nOrig ){
  30426. osMunmap(pReq, nOrig-nReuse);
  30427. }
  30428. #if HAVE_MREMAP
  30429. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  30430. zErr = "mremap";
  30431. #else
  30432. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  30433. if( pNew!=MAP_FAILED ){
  30434. if( pNew!=pReq ){
  30435. osMunmap(pNew, nNew - nReuse);
  30436. pNew = 0;
  30437. }else{
  30438. pNew = pOrig;
  30439. }
  30440. }
  30441. #endif
  30442. /* The attempt to extend the existing mapping failed. Free it. */
  30443. if( pNew==MAP_FAILED || pNew==0 ){
  30444. osMunmap(pOrig, nReuse);
  30445. }
  30446. }
  30447. /* If pNew is still NULL, try to create an entirely new mapping. */
  30448. if( pNew==0 ){
  30449. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  30450. }
  30451. if( pNew==MAP_FAILED ){
  30452. pNew = 0;
  30453. nNew = 0;
  30454. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  30455. /* If the mmap() above failed, assume that all subsequent mmap() calls
  30456. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  30457. ** in this case. */
  30458. pFd->mmapSizeMax = 0;
  30459. }
  30460. pFd->pMapRegion = (void *)pNew;
  30461. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  30462. }
  30463. /*
  30464. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  30465. ** is already mapped, the existing mapping is replaced by the new). Or, if
  30466. ** there already exists a mapping for this file, and there are still
  30467. ** outstanding xFetch() references to it, this function is a no-op.
  30468. **
  30469. ** If parameter nByte is non-negative, then it is the requested size of
  30470. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  30471. ** requested size is the size of the file on disk. The actual size of the
  30472. ** created mapping is either the requested size or the value configured
  30473. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  30474. **
  30475. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  30476. ** recreated as a result of outstanding references) or an SQLite error
  30477. ** code otherwise.
  30478. */
  30479. static int unixMapfile(unixFile *pFd, i64 nMap){
  30480. assert( nMap>=0 || pFd->nFetchOut==0 );
  30481. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  30482. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  30483. if( nMap<0 ){
  30484. struct stat statbuf; /* Low-level file information */
  30485. if( osFstat(pFd->h, &statbuf) ){
  30486. return SQLITE_IOERR_FSTAT;
  30487. }
  30488. nMap = statbuf.st_size;
  30489. }
  30490. if( nMap>pFd->mmapSizeMax ){
  30491. nMap = pFd->mmapSizeMax;
  30492. }
  30493. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  30494. if( nMap!=pFd->mmapSize ){
  30495. unixRemapfile(pFd, nMap);
  30496. }
  30497. return SQLITE_OK;
  30498. }
  30499. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  30500. /*
  30501. ** If possible, return a pointer to a mapping of file fd starting at offset
  30502. ** iOff. The mapping must be valid for at least nAmt bytes.
  30503. **
  30504. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  30505. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  30506. ** Finally, if an error does occur, return an SQLite error code. The final
  30507. ** value of *pp is undefined in this case.
  30508. **
  30509. ** If this function does return a pointer, the caller must eventually
  30510. ** release the reference by calling unixUnfetch().
  30511. */
  30512. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  30513. #if SQLITE_MAX_MMAP_SIZE>0
  30514. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  30515. #endif
  30516. *pp = 0;
  30517. #if SQLITE_MAX_MMAP_SIZE>0
  30518. if( pFd->mmapSizeMax>0 ){
  30519. if( pFd->pMapRegion==0 ){
  30520. int rc = unixMapfile(pFd, -1);
  30521. if( rc!=SQLITE_OK ) return rc;
  30522. }
  30523. if( pFd->mmapSize >= iOff+nAmt ){
  30524. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  30525. pFd->nFetchOut++;
  30526. }
  30527. }
  30528. #endif
  30529. return SQLITE_OK;
  30530. }
  30531. /*
  30532. ** If the third argument is non-NULL, then this function releases a
  30533. ** reference obtained by an earlier call to unixFetch(). The second
  30534. ** argument passed to this function must be the same as the corresponding
  30535. ** argument that was passed to the unixFetch() invocation.
  30536. **
  30537. ** Or, if the third argument is NULL, then this function is being called
  30538. ** to inform the VFS layer that, according to POSIX, any existing mapping
  30539. ** may now be invalid and should be unmapped.
  30540. */
  30541. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  30542. #if SQLITE_MAX_MMAP_SIZE>0
  30543. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  30544. UNUSED_PARAMETER(iOff);
  30545. /* If p==0 (unmap the entire file) then there must be no outstanding
  30546. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  30547. ** then there must be at least one outstanding. */
  30548. assert( (p==0)==(pFd->nFetchOut==0) );
  30549. /* If p!=0, it must match the iOff value. */
  30550. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  30551. if( p ){
  30552. pFd->nFetchOut--;
  30553. }else{
  30554. unixUnmapfile(pFd);
  30555. }
  30556. assert( pFd->nFetchOut>=0 );
  30557. #else
  30558. UNUSED_PARAMETER(fd);
  30559. UNUSED_PARAMETER(p);
  30560. UNUSED_PARAMETER(iOff);
  30561. #endif
  30562. return SQLITE_OK;
  30563. }
  30564. /*
  30565. ** Here ends the implementation of all sqlite3_file methods.
  30566. **
  30567. ********************** End sqlite3_file Methods *******************************
  30568. ******************************************************************************/
  30569. /*
  30570. ** This division contains definitions of sqlite3_io_methods objects that
  30571. ** implement various file locking strategies. It also contains definitions
  30572. ** of "finder" functions. A finder-function is used to locate the appropriate
  30573. ** sqlite3_io_methods object for a particular database file. The pAppData
  30574. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  30575. ** the correct finder-function for that VFS.
  30576. **
  30577. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  30578. ** object. The only interesting finder-function is autolockIoFinder, which
  30579. ** looks at the filesystem type and tries to guess the best locking
  30580. ** strategy from that.
  30581. **
  30582. ** For finder-function F, two objects are created:
  30583. **
  30584. ** (1) The real finder-function named "FImpt()".
  30585. **
  30586. ** (2) A constant pointer to this function named just "F".
  30587. **
  30588. **
  30589. ** A pointer to the F pointer is used as the pAppData value for VFS
  30590. ** objects. We have to do this instead of letting pAppData point
  30591. ** directly at the finder-function since C90 rules prevent a void*
  30592. ** from be cast into a function pointer.
  30593. **
  30594. **
  30595. ** Each instance of this macro generates two objects:
  30596. **
  30597. ** * A constant sqlite3_io_methods object call METHOD that has locking
  30598. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  30599. **
  30600. ** * An I/O method finder function called FINDER that returns a pointer
  30601. ** to the METHOD object in the previous bullet.
  30602. */
  30603. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  30604. static const sqlite3_io_methods METHOD = { \
  30605. VERSION, /* iVersion */ \
  30606. CLOSE, /* xClose */ \
  30607. unixRead, /* xRead */ \
  30608. unixWrite, /* xWrite */ \
  30609. unixTruncate, /* xTruncate */ \
  30610. unixSync, /* xSync */ \
  30611. unixFileSize, /* xFileSize */ \
  30612. LOCK, /* xLock */ \
  30613. UNLOCK, /* xUnlock */ \
  30614. CKLOCK, /* xCheckReservedLock */ \
  30615. unixFileControl, /* xFileControl */ \
  30616. unixSectorSize, /* xSectorSize */ \
  30617. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  30618. SHMMAP, /* xShmMap */ \
  30619. unixShmLock, /* xShmLock */ \
  30620. unixShmBarrier, /* xShmBarrier */ \
  30621. unixShmUnmap, /* xShmUnmap */ \
  30622. unixFetch, /* xFetch */ \
  30623. unixUnfetch, /* xUnfetch */ \
  30624. }; \
  30625. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  30626. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  30627. return &METHOD; \
  30628. } \
  30629. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  30630. = FINDER##Impl;
  30631. /*
  30632. ** Here are all of the sqlite3_io_methods objects for each of the
  30633. ** locking strategies. Functions that return pointers to these methods
  30634. ** are also created.
  30635. */
  30636. IOMETHODS(
  30637. posixIoFinder, /* Finder function name */
  30638. posixIoMethods, /* sqlite3_io_methods object name */
  30639. 3, /* shared memory and mmap are enabled */
  30640. unixClose, /* xClose method */
  30641. unixLock, /* xLock method */
  30642. unixUnlock, /* xUnlock method */
  30643. unixCheckReservedLock, /* xCheckReservedLock method */
  30644. unixShmMap /* xShmMap method */
  30645. )
  30646. IOMETHODS(
  30647. nolockIoFinder, /* Finder function name */
  30648. nolockIoMethods, /* sqlite3_io_methods object name */
  30649. 3, /* shared memory is disabled */
  30650. nolockClose, /* xClose method */
  30651. nolockLock, /* xLock method */
  30652. nolockUnlock, /* xUnlock method */
  30653. nolockCheckReservedLock, /* xCheckReservedLock method */
  30654. 0 /* xShmMap method */
  30655. )
  30656. IOMETHODS(
  30657. dotlockIoFinder, /* Finder function name */
  30658. dotlockIoMethods, /* sqlite3_io_methods object name */
  30659. 1, /* shared memory is disabled */
  30660. dotlockClose, /* xClose method */
  30661. dotlockLock, /* xLock method */
  30662. dotlockUnlock, /* xUnlock method */
  30663. dotlockCheckReservedLock, /* xCheckReservedLock method */
  30664. 0 /* xShmMap method */
  30665. )
  30666. #if SQLITE_ENABLE_LOCKING_STYLE
  30667. IOMETHODS(
  30668. flockIoFinder, /* Finder function name */
  30669. flockIoMethods, /* sqlite3_io_methods object name */
  30670. 1, /* shared memory is disabled */
  30671. flockClose, /* xClose method */
  30672. flockLock, /* xLock method */
  30673. flockUnlock, /* xUnlock method */
  30674. flockCheckReservedLock, /* xCheckReservedLock method */
  30675. 0 /* xShmMap method */
  30676. )
  30677. #endif
  30678. #if OS_VXWORKS
  30679. IOMETHODS(
  30680. semIoFinder, /* Finder function name */
  30681. semIoMethods, /* sqlite3_io_methods object name */
  30682. 1, /* shared memory is disabled */
  30683. semXClose, /* xClose method */
  30684. semXLock, /* xLock method */
  30685. semXUnlock, /* xUnlock method */
  30686. semXCheckReservedLock, /* xCheckReservedLock method */
  30687. 0 /* xShmMap method */
  30688. )
  30689. #endif
  30690. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30691. IOMETHODS(
  30692. afpIoFinder, /* Finder function name */
  30693. afpIoMethods, /* sqlite3_io_methods object name */
  30694. 1, /* shared memory is disabled */
  30695. afpClose, /* xClose method */
  30696. afpLock, /* xLock method */
  30697. afpUnlock, /* xUnlock method */
  30698. afpCheckReservedLock, /* xCheckReservedLock method */
  30699. 0 /* xShmMap method */
  30700. )
  30701. #endif
  30702. /*
  30703. ** The proxy locking method is a "super-method" in the sense that it
  30704. ** opens secondary file descriptors for the conch and lock files and
  30705. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  30706. ** secondary files. For this reason, the division that implements
  30707. ** proxy locking is located much further down in the file. But we need
  30708. ** to go ahead and define the sqlite3_io_methods and finder function
  30709. ** for proxy locking here. So we forward declare the I/O methods.
  30710. */
  30711. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30712. static int proxyClose(sqlite3_file*);
  30713. static int proxyLock(sqlite3_file*, int);
  30714. static int proxyUnlock(sqlite3_file*, int);
  30715. static int proxyCheckReservedLock(sqlite3_file*, int*);
  30716. IOMETHODS(
  30717. proxyIoFinder, /* Finder function name */
  30718. proxyIoMethods, /* sqlite3_io_methods object name */
  30719. 1, /* shared memory is disabled */
  30720. proxyClose, /* xClose method */
  30721. proxyLock, /* xLock method */
  30722. proxyUnlock, /* xUnlock method */
  30723. proxyCheckReservedLock, /* xCheckReservedLock method */
  30724. 0 /* xShmMap method */
  30725. )
  30726. #endif
  30727. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  30728. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30729. IOMETHODS(
  30730. nfsIoFinder, /* Finder function name */
  30731. nfsIoMethods, /* sqlite3_io_methods object name */
  30732. 1, /* shared memory is disabled */
  30733. unixClose, /* xClose method */
  30734. unixLock, /* xLock method */
  30735. nfsUnlock, /* xUnlock method */
  30736. unixCheckReservedLock, /* xCheckReservedLock method */
  30737. 0 /* xShmMap method */
  30738. )
  30739. #endif
  30740. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30741. /*
  30742. ** This "finder" function attempts to determine the best locking strategy
  30743. ** for the database file "filePath". It then returns the sqlite3_io_methods
  30744. ** object that implements that strategy.
  30745. **
  30746. ** This is for MacOSX only.
  30747. */
  30748. static const sqlite3_io_methods *autolockIoFinderImpl(
  30749. const char *filePath, /* name of the database file */
  30750. unixFile *pNew /* open file object for the database file */
  30751. ){
  30752. static const struct Mapping {
  30753. const char *zFilesystem; /* Filesystem type name */
  30754. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  30755. } aMap[] = {
  30756. { "hfs", &posixIoMethods },
  30757. { "ufs", &posixIoMethods },
  30758. { "afpfs", &afpIoMethods },
  30759. { "smbfs", &afpIoMethods },
  30760. { "webdav", &nolockIoMethods },
  30761. { 0, 0 }
  30762. };
  30763. int i;
  30764. struct statfs fsInfo;
  30765. struct flock lockInfo;
  30766. if( !filePath ){
  30767. /* If filePath==NULL that means we are dealing with a transient file
  30768. ** that does not need to be locked. */
  30769. return &nolockIoMethods;
  30770. }
  30771. if( statfs(filePath, &fsInfo) != -1 ){
  30772. if( fsInfo.f_flags & MNT_RDONLY ){
  30773. return &nolockIoMethods;
  30774. }
  30775. for(i=0; aMap[i].zFilesystem; i++){
  30776. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  30777. return aMap[i].pMethods;
  30778. }
  30779. }
  30780. }
  30781. /* Default case. Handles, amongst others, "nfs".
  30782. ** Test byte-range lock using fcntl(). If the call succeeds,
  30783. ** assume that the file-system supports POSIX style locks.
  30784. */
  30785. lockInfo.l_len = 1;
  30786. lockInfo.l_start = 0;
  30787. lockInfo.l_whence = SEEK_SET;
  30788. lockInfo.l_type = F_RDLCK;
  30789. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  30790. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  30791. return &nfsIoMethods;
  30792. } else {
  30793. return &posixIoMethods;
  30794. }
  30795. }else{
  30796. return &dotlockIoMethods;
  30797. }
  30798. }
  30799. static const sqlite3_io_methods
  30800. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  30801. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30802. #if OS_VXWORKS
  30803. /*
  30804. ** This "finder" function for VxWorks checks to see if posix advisory
  30805. ** locking works. If it does, then that is what is used. If it does not
  30806. ** work, then fallback to named semaphore locking.
  30807. */
  30808. static const sqlite3_io_methods *vxworksIoFinderImpl(
  30809. const char *filePath, /* name of the database file */
  30810. unixFile *pNew /* the open file object */
  30811. ){
  30812. struct flock lockInfo;
  30813. if( !filePath ){
  30814. /* If filePath==NULL that means we are dealing with a transient file
  30815. ** that does not need to be locked. */
  30816. return &nolockIoMethods;
  30817. }
  30818. /* Test if fcntl() is supported and use POSIX style locks.
  30819. ** Otherwise fall back to the named semaphore method.
  30820. */
  30821. lockInfo.l_len = 1;
  30822. lockInfo.l_start = 0;
  30823. lockInfo.l_whence = SEEK_SET;
  30824. lockInfo.l_type = F_RDLCK;
  30825. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  30826. return &posixIoMethods;
  30827. }else{
  30828. return &semIoMethods;
  30829. }
  30830. }
  30831. static const sqlite3_io_methods
  30832. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  30833. #endif /* OS_VXWORKS */
  30834. /*
  30835. ** An abstract type for a pointer to an IO method finder function:
  30836. */
  30837. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  30838. /****************************************************************************
  30839. **************************** sqlite3_vfs methods ****************************
  30840. **
  30841. ** This division contains the implementation of methods on the
  30842. ** sqlite3_vfs object.
  30843. */
  30844. /*
  30845. ** Initialize the contents of the unixFile structure pointed to by pId.
  30846. */
  30847. static int fillInUnixFile(
  30848. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  30849. int h, /* Open file descriptor of file being opened */
  30850. sqlite3_file *pId, /* Write to the unixFile structure here */
  30851. const char *zFilename, /* Name of the file being opened */
  30852. int ctrlFlags /* Zero or more UNIXFILE_* values */
  30853. ){
  30854. const sqlite3_io_methods *pLockingStyle;
  30855. unixFile *pNew = (unixFile *)pId;
  30856. int rc = SQLITE_OK;
  30857. assert( pNew->pInode==NULL );
  30858. /* Usually the path zFilename should not be a relative pathname. The
  30859. ** exception is when opening the proxy "conch" file in builds that
  30860. ** include the special Apple locking styles.
  30861. */
  30862. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30863. assert( zFilename==0 || zFilename[0]=='/'
  30864. || pVfs->pAppData==(void*)&autolockIoFinder );
  30865. #else
  30866. assert( zFilename==0 || zFilename[0]=='/' );
  30867. #endif
  30868. /* No locking occurs in temporary files */
  30869. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  30870. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  30871. pNew->h = h;
  30872. pNew->pVfs = pVfs;
  30873. pNew->zPath = zFilename;
  30874. pNew->ctrlFlags = (u8)ctrlFlags;
  30875. #if SQLITE_MAX_MMAP_SIZE>0
  30876. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  30877. #endif
  30878. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  30879. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  30880. pNew->ctrlFlags |= UNIXFILE_PSOW;
  30881. }
  30882. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  30883. pNew->ctrlFlags |= UNIXFILE_EXCL;
  30884. }
  30885. #if OS_VXWORKS
  30886. pNew->pId = vxworksFindFileId(zFilename);
  30887. if( pNew->pId==0 ){
  30888. ctrlFlags |= UNIXFILE_NOLOCK;
  30889. rc = SQLITE_NOMEM_BKPT;
  30890. }
  30891. #endif
  30892. if( ctrlFlags & UNIXFILE_NOLOCK ){
  30893. pLockingStyle = &nolockIoMethods;
  30894. }else{
  30895. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  30896. #if SQLITE_ENABLE_LOCKING_STYLE
  30897. /* Cache zFilename in the locking context (AFP and dotlock override) for
  30898. ** proxyLock activation is possible (remote proxy is based on db name)
  30899. ** zFilename remains valid until file is closed, to support */
  30900. pNew->lockingContext = (void*)zFilename;
  30901. #endif
  30902. }
  30903. if( pLockingStyle == &posixIoMethods
  30904. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30905. || pLockingStyle == &nfsIoMethods
  30906. #endif
  30907. ){
  30908. unixEnterMutex();
  30909. rc = findInodeInfo(pNew, &pNew->pInode);
  30910. if( rc!=SQLITE_OK ){
  30911. /* If an error occurred in findInodeInfo(), close the file descriptor
  30912. ** immediately, before releasing the mutex. findInodeInfo() may fail
  30913. ** in two scenarios:
  30914. **
  30915. ** (a) A call to fstat() failed.
  30916. ** (b) A malloc failed.
  30917. **
  30918. ** Scenario (b) may only occur if the process is holding no other
  30919. ** file descriptors open on the same file. If there were other file
  30920. ** descriptors on this file, then no malloc would be required by
  30921. ** findInodeInfo(). If this is the case, it is quite safe to close
  30922. ** handle h - as it is guaranteed that no posix locks will be released
  30923. ** by doing so.
  30924. **
  30925. ** If scenario (a) caused the error then things are not so safe. The
  30926. ** implicit assumption here is that if fstat() fails, things are in
  30927. ** such bad shape that dropping a lock or two doesn't matter much.
  30928. */
  30929. robust_close(pNew, h, __LINE__);
  30930. h = -1;
  30931. }
  30932. unixLeaveMutex();
  30933. }
  30934. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30935. else if( pLockingStyle == &afpIoMethods ){
  30936. /* AFP locking uses the file path so it needs to be included in
  30937. ** the afpLockingContext.
  30938. */
  30939. afpLockingContext *pCtx;
  30940. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  30941. if( pCtx==0 ){
  30942. rc = SQLITE_NOMEM_BKPT;
  30943. }else{
  30944. /* NB: zFilename exists and remains valid until the file is closed
  30945. ** according to requirement F11141. So we do not need to make a
  30946. ** copy of the filename. */
  30947. pCtx->dbPath = zFilename;
  30948. pCtx->reserved = 0;
  30949. srandomdev();
  30950. unixEnterMutex();
  30951. rc = findInodeInfo(pNew, &pNew->pInode);
  30952. if( rc!=SQLITE_OK ){
  30953. sqlite3_free(pNew->lockingContext);
  30954. robust_close(pNew, h, __LINE__);
  30955. h = -1;
  30956. }
  30957. unixLeaveMutex();
  30958. }
  30959. }
  30960. #endif
  30961. else if( pLockingStyle == &dotlockIoMethods ){
  30962. /* Dotfile locking uses the file path so it needs to be included in
  30963. ** the dotlockLockingContext
  30964. */
  30965. char *zLockFile;
  30966. int nFilename;
  30967. assert( zFilename!=0 );
  30968. nFilename = (int)strlen(zFilename) + 6;
  30969. zLockFile = (char *)sqlite3_malloc64(nFilename);
  30970. if( zLockFile==0 ){
  30971. rc = SQLITE_NOMEM_BKPT;
  30972. }else{
  30973. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  30974. }
  30975. pNew->lockingContext = zLockFile;
  30976. }
  30977. #if OS_VXWORKS
  30978. else if( pLockingStyle == &semIoMethods ){
  30979. /* Named semaphore locking uses the file path so it needs to be
  30980. ** included in the semLockingContext
  30981. */
  30982. unixEnterMutex();
  30983. rc = findInodeInfo(pNew, &pNew->pInode);
  30984. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  30985. char *zSemName = pNew->pInode->aSemName;
  30986. int n;
  30987. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  30988. pNew->pId->zCanonicalName);
  30989. for( n=1; zSemName[n]; n++ )
  30990. if( zSemName[n]=='/' ) zSemName[n] = '_';
  30991. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  30992. if( pNew->pInode->pSem == SEM_FAILED ){
  30993. rc = SQLITE_NOMEM_BKPT;
  30994. pNew->pInode->aSemName[0] = '\0';
  30995. }
  30996. }
  30997. unixLeaveMutex();
  30998. }
  30999. #endif
  31000. storeLastErrno(pNew, 0);
  31001. #if OS_VXWORKS
  31002. if( rc!=SQLITE_OK ){
  31003. if( h>=0 ) robust_close(pNew, h, __LINE__);
  31004. h = -1;
  31005. osUnlink(zFilename);
  31006. pNew->ctrlFlags |= UNIXFILE_DELETE;
  31007. }
  31008. #endif
  31009. if( rc!=SQLITE_OK ){
  31010. if( h>=0 ) robust_close(pNew, h, __LINE__);
  31011. }else{
  31012. pNew->pMethod = pLockingStyle;
  31013. OpenCounter(+1);
  31014. verifyDbFile(pNew);
  31015. }
  31016. return rc;
  31017. }
  31018. /*
  31019. ** Return the name of a directory in which to put temporary files.
  31020. ** If no suitable temporary file directory can be found, return NULL.
  31021. */
  31022. static const char *unixTempFileDir(void){
  31023. static const char *azDirs[] = {
  31024. 0,
  31025. 0,
  31026. "/var/tmp",
  31027. "/usr/tmp",
  31028. "/tmp",
  31029. "."
  31030. };
  31031. unsigned int i;
  31032. struct stat buf;
  31033. const char *zDir = sqlite3_temp_directory;
  31034. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  31035. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  31036. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  31037. if( zDir==0 ) continue;
  31038. if( osStat(zDir, &buf) ) continue;
  31039. if( !S_ISDIR(buf.st_mode) ) continue;
  31040. if( osAccess(zDir, 07) ) continue;
  31041. break;
  31042. }
  31043. return zDir;
  31044. }
  31045. /*
  31046. ** Create a temporary file name in zBuf. zBuf must be allocated
  31047. ** by the calling process and must be big enough to hold at least
  31048. ** pVfs->mxPathname bytes.
  31049. */
  31050. static int unixGetTempname(int nBuf, char *zBuf){
  31051. const char *zDir;
  31052. int iLimit = 0;
  31053. /* It's odd to simulate an io-error here, but really this is just
  31054. ** using the io-error infrastructure to test that SQLite handles this
  31055. ** function failing.
  31056. */
  31057. SimulateIOError( return SQLITE_IOERR );
  31058. zDir = unixTempFileDir();
  31059. do{
  31060. u64 r;
  31061. sqlite3_randomness(sizeof(r), &r);
  31062. assert( nBuf>2 );
  31063. zBuf[nBuf-2] = 0;
  31064. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  31065. zDir, r, 0);
  31066. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  31067. }while( osAccess(zBuf,0)==0 );
  31068. return SQLITE_OK;
  31069. }
  31070. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31071. /*
  31072. ** Routine to transform a unixFile into a proxy-locking unixFile.
  31073. ** Implementation in the proxy-lock division, but used by unixOpen()
  31074. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  31075. */
  31076. static int proxyTransformUnixFile(unixFile*, const char*);
  31077. #endif
  31078. /*
  31079. ** Search for an unused file descriptor that was opened on the database
  31080. ** file (not a journal or master-journal file) identified by pathname
  31081. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  31082. ** argument to this function.
  31083. **
  31084. ** Such a file descriptor may exist if a database connection was closed
  31085. ** but the associated file descriptor could not be closed because some
  31086. ** other file descriptor open on the same file is holding a file-lock.
  31087. ** Refer to comments in the unixClose() function and the lengthy comment
  31088. ** describing "Posix Advisory Locking" at the start of this file for
  31089. ** further details. Also, ticket #4018.
  31090. **
  31091. ** If a suitable file descriptor is found, then it is returned. If no
  31092. ** such file descriptor is located, -1 is returned.
  31093. */
  31094. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  31095. UnixUnusedFd *pUnused = 0;
  31096. /* Do not search for an unused file descriptor on vxworks. Not because
  31097. ** vxworks would not benefit from the change (it might, we're not sure),
  31098. ** but because no way to test it is currently available. It is better
  31099. ** not to risk breaking vxworks support for the sake of such an obscure
  31100. ** feature. */
  31101. #if !OS_VXWORKS
  31102. struct stat sStat; /* Results of stat() call */
  31103. /* A stat() call may fail for various reasons. If this happens, it is
  31104. ** almost certain that an open() call on the same path will also fail.
  31105. ** For this reason, if an error occurs in the stat() call here, it is
  31106. ** ignored and -1 is returned. The caller will try to open a new file
  31107. ** descriptor on the same path, fail, and return an error to SQLite.
  31108. **
  31109. ** Even if a subsequent open() call does succeed, the consequences of
  31110. ** not searching for a reusable file descriptor are not dire. */
  31111. if( 0==osStat(zPath, &sStat) ){
  31112. unixInodeInfo *pInode;
  31113. unixEnterMutex();
  31114. pInode = inodeList;
  31115. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  31116. || pInode->fileId.ino!=sStat.st_ino) ){
  31117. pInode = pInode->pNext;
  31118. }
  31119. if( pInode ){
  31120. UnixUnusedFd **pp;
  31121. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  31122. pUnused = *pp;
  31123. if( pUnused ){
  31124. *pp = pUnused->pNext;
  31125. }
  31126. }
  31127. unixLeaveMutex();
  31128. }
  31129. #endif /* if !OS_VXWORKS */
  31130. return pUnused;
  31131. }
  31132. /*
  31133. ** This function is called by unixOpen() to determine the unix permissions
  31134. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  31135. ** and a value suitable for passing as the third argument to open(2) is
  31136. ** written to *pMode. If an IO error occurs, an SQLite error code is
  31137. ** returned and the value of *pMode is not modified.
  31138. **
  31139. ** In most cases, this routine sets *pMode to 0, which will become
  31140. ** an indication to robust_open() to create the file using
  31141. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  31142. ** But if the file being opened is a WAL or regular journal file, then
  31143. ** this function queries the file-system for the permissions on the
  31144. ** corresponding database file and sets *pMode to this value. Whenever
  31145. ** possible, WAL and journal files are created using the same permissions
  31146. ** as the associated database file.
  31147. **
  31148. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  31149. ** original filename is unavailable. But 8_3_NAMES is only used for
  31150. ** FAT filesystems and permissions do not matter there, so just use
  31151. ** the default permissions.
  31152. */
  31153. static int findCreateFileMode(
  31154. const char *zPath, /* Path of file (possibly) being created */
  31155. int flags, /* Flags passed as 4th argument to xOpen() */
  31156. mode_t *pMode, /* OUT: Permissions to open file with */
  31157. uid_t *pUid, /* OUT: uid to set on the file */
  31158. gid_t *pGid /* OUT: gid to set on the file */
  31159. ){
  31160. int rc = SQLITE_OK; /* Return Code */
  31161. *pMode = 0;
  31162. *pUid = 0;
  31163. *pGid = 0;
  31164. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  31165. char zDb[MAX_PATHNAME+1]; /* Database file path */
  31166. int nDb; /* Number of valid bytes in zDb */
  31167. struct stat sStat; /* Output of stat() on database file */
  31168. /* zPath is a path to a WAL or journal file. The following block derives
  31169. ** the path to the associated database file from zPath. This block handles
  31170. ** the following naming conventions:
  31171. **
  31172. ** "<path to db>-journal"
  31173. ** "<path to db>-wal"
  31174. ** "<path to db>-journalNN"
  31175. ** "<path to db>-walNN"
  31176. **
  31177. ** where NN is a decimal number. The NN naming schemes are
  31178. ** used by the test_multiplex.c module.
  31179. */
  31180. nDb = sqlite3Strlen30(zPath) - 1;
  31181. while( zPath[nDb]!='-' ){
  31182. #ifndef SQLITE_ENABLE_8_3_NAMES
  31183. /* In the normal case (8+3 filenames disabled) the journal filename
  31184. ** is guaranteed to contain a '-' character. */
  31185. assert( nDb>0 );
  31186. assert( sqlite3Isalnum(zPath[nDb]) );
  31187. #else
  31188. /* If 8+3 names are possible, then the journal file might not contain
  31189. ** a '-' character. So check for that case and return early. */
  31190. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  31191. #endif
  31192. nDb--;
  31193. }
  31194. memcpy(zDb, zPath, nDb);
  31195. zDb[nDb] = '\0';
  31196. if( 0==osStat(zDb, &sStat) ){
  31197. *pMode = sStat.st_mode & 0777;
  31198. *pUid = sStat.st_uid;
  31199. *pGid = sStat.st_gid;
  31200. }else{
  31201. rc = SQLITE_IOERR_FSTAT;
  31202. }
  31203. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  31204. *pMode = 0600;
  31205. }
  31206. return rc;
  31207. }
  31208. /*
  31209. ** Open the file zPath.
  31210. **
  31211. ** Previously, the SQLite OS layer used three functions in place of this
  31212. ** one:
  31213. **
  31214. ** sqlite3OsOpenReadWrite();
  31215. ** sqlite3OsOpenReadOnly();
  31216. ** sqlite3OsOpenExclusive();
  31217. **
  31218. ** These calls correspond to the following combinations of flags:
  31219. **
  31220. ** ReadWrite() -> (READWRITE | CREATE)
  31221. ** ReadOnly() -> (READONLY)
  31222. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  31223. **
  31224. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  31225. ** true, the file was configured to be automatically deleted when the
  31226. ** file handle closed. To achieve the same effect using this new
  31227. ** interface, add the DELETEONCLOSE flag to those specified above for
  31228. ** OpenExclusive().
  31229. */
  31230. static int unixOpen(
  31231. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  31232. const char *zPath, /* Pathname of file to be opened */
  31233. sqlite3_file *pFile, /* The file descriptor to be filled in */
  31234. int flags, /* Input flags to control the opening */
  31235. int *pOutFlags /* Output flags returned to SQLite core */
  31236. ){
  31237. unixFile *p = (unixFile *)pFile;
  31238. int fd = -1; /* File descriptor returned by open() */
  31239. int openFlags = 0; /* Flags to pass to open() */
  31240. int eType = flags&0xFFFFFF00; /* Type of file to open */
  31241. int noLock; /* True to omit locking primitives */
  31242. int rc = SQLITE_OK; /* Function Return Code */
  31243. int ctrlFlags = 0; /* UNIXFILE_* flags */
  31244. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  31245. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  31246. int isCreate = (flags & SQLITE_OPEN_CREATE);
  31247. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  31248. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  31249. #if SQLITE_ENABLE_LOCKING_STYLE
  31250. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  31251. #endif
  31252. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  31253. struct statfs fsInfo;
  31254. #endif
  31255. /* If creating a master or main-file journal, this function will open
  31256. ** a file-descriptor on the directory too. The first time unixSync()
  31257. ** is called the directory file descriptor will be fsync()ed and close()d.
  31258. */
  31259. int syncDir = (isCreate && (
  31260. eType==SQLITE_OPEN_MASTER_JOURNAL
  31261. || eType==SQLITE_OPEN_MAIN_JOURNAL
  31262. || eType==SQLITE_OPEN_WAL
  31263. ));
  31264. /* If argument zPath is a NULL pointer, this function is required to open
  31265. ** a temporary file. Use this buffer to store the file name in.
  31266. */
  31267. char zTmpname[MAX_PATHNAME+2];
  31268. const char *zName = zPath;
  31269. /* Check the following statements are true:
  31270. **
  31271. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  31272. ** (b) if CREATE is set, then READWRITE must also be set, and
  31273. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  31274. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  31275. */
  31276. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  31277. assert(isCreate==0 || isReadWrite);
  31278. assert(isExclusive==0 || isCreate);
  31279. assert(isDelete==0 || isCreate);
  31280. /* The main DB, main journal, WAL file and master journal are never
  31281. ** automatically deleted. Nor are they ever temporary files. */
  31282. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  31283. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  31284. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  31285. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  31286. /* Assert that the upper layer has set one of the "file-type" flags. */
  31287. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  31288. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  31289. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  31290. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  31291. );
  31292. /* Detect a pid change and reset the PRNG. There is a race condition
  31293. ** here such that two or more threads all trying to open databases at
  31294. ** the same instant might all reset the PRNG. But multiple resets
  31295. ** are harmless.
  31296. */
  31297. if( randomnessPid!=osGetpid(0) ){
  31298. randomnessPid = osGetpid(0);
  31299. sqlite3_randomness(0,0);
  31300. }
  31301. memset(p, 0, sizeof(unixFile));
  31302. if( eType==SQLITE_OPEN_MAIN_DB ){
  31303. UnixUnusedFd *pUnused;
  31304. pUnused = findReusableFd(zName, flags);
  31305. if( pUnused ){
  31306. fd = pUnused->fd;
  31307. }else{
  31308. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  31309. if( !pUnused ){
  31310. return SQLITE_NOMEM_BKPT;
  31311. }
  31312. }
  31313. p->pUnused = pUnused;
  31314. /* Database filenames are double-zero terminated if they are not
  31315. ** URIs with parameters. Hence, they can always be passed into
  31316. ** sqlite3_uri_parameter(). */
  31317. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  31318. }else if( !zName ){
  31319. /* If zName is NULL, the upper layer is requesting a temp file. */
  31320. assert(isDelete && !syncDir);
  31321. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  31322. if( rc!=SQLITE_OK ){
  31323. return rc;
  31324. }
  31325. zName = zTmpname;
  31326. /* Generated temporary filenames are always double-zero terminated
  31327. ** for use by sqlite3_uri_parameter(). */
  31328. assert( zName[strlen(zName)+1]==0 );
  31329. }
  31330. /* Determine the value of the flags parameter passed to POSIX function
  31331. ** open(). These must be calculated even if open() is not called, as
  31332. ** they may be stored as part of the file handle and used by the
  31333. ** 'conch file' locking functions later on. */
  31334. if( isReadonly ) openFlags |= O_RDONLY;
  31335. if( isReadWrite ) openFlags |= O_RDWR;
  31336. if( isCreate ) openFlags |= O_CREAT;
  31337. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  31338. openFlags |= (O_LARGEFILE|O_BINARY);
  31339. if( fd<0 ){
  31340. mode_t openMode; /* Permissions to create file with */
  31341. uid_t uid; /* Userid for the file */
  31342. gid_t gid; /* Groupid for the file */
  31343. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  31344. if( rc!=SQLITE_OK ){
  31345. assert( !p->pUnused );
  31346. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  31347. return rc;
  31348. }
  31349. fd = robust_open(zName, openFlags, openMode);
  31350. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  31351. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  31352. if( fd<0 && errno!=EISDIR && isReadWrite ){
  31353. /* Failed to open the file for read/write access. Try read-only. */
  31354. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  31355. openFlags &= ~(O_RDWR|O_CREAT);
  31356. flags |= SQLITE_OPEN_READONLY;
  31357. openFlags |= O_RDONLY;
  31358. isReadonly = 1;
  31359. fd = robust_open(zName, openFlags, openMode);
  31360. }
  31361. if( fd<0 ){
  31362. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  31363. goto open_finished;
  31364. }
  31365. /* If this process is running as root and if creating a new rollback
  31366. ** journal or WAL file, set the ownership of the journal or WAL to be
  31367. ** the same as the original database.
  31368. */
  31369. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  31370. robustFchown(fd, uid, gid);
  31371. }
  31372. }
  31373. assert( fd>=0 );
  31374. if( pOutFlags ){
  31375. *pOutFlags = flags;
  31376. }
  31377. if( p->pUnused ){
  31378. p->pUnused->fd = fd;
  31379. p->pUnused->flags = flags;
  31380. }
  31381. if( isDelete ){
  31382. #if OS_VXWORKS
  31383. zPath = zName;
  31384. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  31385. zPath = sqlite3_mprintf("%s", zName);
  31386. if( zPath==0 ){
  31387. robust_close(p, fd, __LINE__);
  31388. return SQLITE_NOMEM_BKPT;
  31389. }
  31390. #else
  31391. osUnlink(zName);
  31392. #endif
  31393. }
  31394. #if SQLITE_ENABLE_LOCKING_STYLE
  31395. else{
  31396. p->openFlags = openFlags;
  31397. }
  31398. #endif
  31399. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  31400. if( fstatfs(fd, &fsInfo) == -1 ){
  31401. storeLastErrno(p, errno);
  31402. robust_close(p, fd, __LINE__);
  31403. return SQLITE_IOERR_ACCESS;
  31404. }
  31405. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  31406. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  31407. }
  31408. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  31409. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  31410. }
  31411. #endif
  31412. /* Set up appropriate ctrlFlags */
  31413. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  31414. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  31415. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  31416. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  31417. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  31418. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  31419. #if SQLITE_ENABLE_LOCKING_STYLE
  31420. #if SQLITE_PREFER_PROXY_LOCKING
  31421. isAutoProxy = 1;
  31422. #endif
  31423. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  31424. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  31425. int useProxy = 0;
  31426. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  31427. ** never use proxy, NULL means use proxy for non-local files only. */
  31428. if( envforce!=NULL ){
  31429. useProxy = atoi(envforce)>0;
  31430. }else{
  31431. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  31432. }
  31433. if( useProxy ){
  31434. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  31435. if( rc==SQLITE_OK ){
  31436. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  31437. if( rc!=SQLITE_OK ){
  31438. /* Use unixClose to clean up the resources added in fillInUnixFile
  31439. ** and clear all the structure's references. Specifically,
  31440. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  31441. */
  31442. unixClose(pFile);
  31443. return rc;
  31444. }
  31445. }
  31446. goto open_finished;
  31447. }
  31448. }
  31449. #endif
  31450. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  31451. open_finished:
  31452. if( rc!=SQLITE_OK ){
  31453. sqlite3_free(p->pUnused);
  31454. }
  31455. return rc;
  31456. }
  31457. /*
  31458. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  31459. ** the directory after deleting the file.
  31460. */
  31461. static int unixDelete(
  31462. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  31463. const char *zPath, /* Name of file to be deleted */
  31464. int dirSync /* If true, fsync() directory after deleting file */
  31465. ){
  31466. int rc = SQLITE_OK;
  31467. UNUSED_PARAMETER(NotUsed);
  31468. SimulateIOError(return SQLITE_IOERR_DELETE);
  31469. if( osUnlink(zPath)==(-1) ){
  31470. if( errno==ENOENT
  31471. #if OS_VXWORKS
  31472. || osAccess(zPath,0)!=0
  31473. #endif
  31474. ){
  31475. rc = SQLITE_IOERR_DELETE_NOENT;
  31476. }else{
  31477. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  31478. }
  31479. return rc;
  31480. }
  31481. #ifndef SQLITE_DISABLE_DIRSYNC
  31482. if( (dirSync & 1)!=0 ){
  31483. int fd;
  31484. rc = osOpenDirectory(zPath, &fd);
  31485. if( rc==SQLITE_OK ){
  31486. if( full_fsync(fd,0,0) ){
  31487. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  31488. }
  31489. robust_close(0, fd, __LINE__);
  31490. }else{
  31491. assert( rc==SQLITE_CANTOPEN );
  31492. rc = SQLITE_OK;
  31493. }
  31494. }
  31495. #endif
  31496. return rc;
  31497. }
  31498. /*
  31499. ** Test the existence of or access permissions of file zPath. The
  31500. ** test performed depends on the value of flags:
  31501. **
  31502. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  31503. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  31504. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  31505. **
  31506. ** Otherwise return 0.
  31507. */
  31508. static int unixAccess(
  31509. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  31510. const char *zPath, /* Path of the file to examine */
  31511. int flags, /* What do we want to learn about the zPath file? */
  31512. int *pResOut /* Write result boolean here */
  31513. ){
  31514. UNUSED_PARAMETER(NotUsed);
  31515. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  31516. assert( pResOut!=0 );
  31517. /* The spec says there are three possible values for flags. But only
  31518. ** two of them are actually used */
  31519. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  31520. if( flags==SQLITE_ACCESS_EXISTS ){
  31521. struct stat buf;
  31522. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  31523. }else{
  31524. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  31525. }
  31526. return SQLITE_OK;
  31527. }
  31528. /*
  31529. **
  31530. */
  31531. static int mkFullPathname(
  31532. const char *zPath, /* Input path */
  31533. char *zOut, /* Output buffer */
  31534. int nOut /* Allocated size of buffer zOut */
  31535. ){
  31536. int nPath = sqlite3Strlen30(zPath);
  31537. int iOff = 0;
  31538. if( zPath[0]!='/' ){
  31539. if( osGetcwd(zOut, nOut-2)==0 ){
  31540. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  31541. }
  31542. iOff = sqlite3Strlen30(zOut);
  31543. zOut[iOff++] = '/';
  31544. }
  31545. if( (iOff+nPath+1)>nOut ){
  31546. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  31547. ** even if it returns an error. */
  31548. zOut[iOff] = '\0';
  31549. return SQLITE_CANTOPEN_BKPT;
  31550. }
  31551. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  31552. return SQLITE_OK;
  31553. }
  31554. /*
  31555. ** Turn a relative pathname into a full pathname. The relative path
  31556. ** is stored as a nul-terminated string in the buffer pointed to by
  31557. ** zPath.
  31558. **
  31559. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  31560. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  31561. ** this buffer before returning.
  31562. */
  31563. static int unixFullPathname(
  31564. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  31565. const char *zPath, /* Possibly relative input path */
  31566. int nOut, /* Size of output buffer in bytes */
  31567. char *zOut /* Output buffer */
  31568. ){
  31569. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  31570. return mkFullPathname(zPath, zOut, nOut);
  31571. #else
  31572. int rc = SQLITE_OK;
  31573. int nByte;
  31574. int nLink = 1; /* Number of symbolic links followed so far */
  31575. const char *zIn = zPath; /* Input path for each iteration of loop */
  31576. char *zDel = 0;
  31577. assert( pVfs->mxPathname==MAX_PATHNAME );
  31578. UNUSED_PARAMETER(pVfs);
  31579. /* It's odd to simulate an io-error here, but really this is just
  31580. ** using the io-error infrastructure to test that SQLite handles this
  31581. ** function failing. This function could fail if, for example, the
  31582. ** current working directory has been unlinked.
  31583. */
  31584. SimulateIOError( return SQLITE_ERROR );
  31585. do {
  31586. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  31587. ** link, or false otherwise. */
  31588. int bLink = 0;
  31589. struct stat buf;
  31590. if( osLstat(zIn, &buf)!=0 ){
  31591. if( errno!=ENOENT ){
  31592. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  31593. }
  31594. }else{
  31595. bLink = S_ISLNK(buf.st_mode);
  31596. }
  31597. if( bLink ){
  31598. if( zDel==0 ){
  31599. zDel = sqlite3_malloc(nOut);
  31600. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  31601. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  31602. rc = SQLITE_CANTOPEN_BKPT;
  31603. }
  31604. if( rc==SQLITE_OK ){
  31605. nByte = osReadlink(zIn, zDel, nOut-1);
  31606. if( nByte<0 ){
  31607. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  31608. }else{
  31609. if( zDel[0]!='/' ){
  31610. int n;
  31611. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  31612. if( nByte+n+1>nOut ){
  31613. rc = SQLITE_CANTOPEN_BKPT;
  31614. }else{
  31615. memmove(&zDel[n], zDel, nByte+1);
  31616. memcpy(zDel, zIn, n);
  31617. nByte += n;
  31618. }
  31619. }
  31620. zDel[nByte] = '\0';
  31621. }
  31622. }
  31623. zIn = zDel;
  31624. }
  31625. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  31626. if( rc==SQLITE_OK && zIn!=zOut ){
  31627. rc = mkFullPathname(zIn, zOut, nOut);
  31628. }
  31629. if( bLink==0 ) break;
  31630. zIn = zOut;
  31631. }while( rc==SQLITE_OK );
  31632. sqlite3_free(zDel);
  31633. return rc;
  31634. #endif /* HAVE_READLINK && HAVE_LSTAT */
  31635. }
  31636. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  31637. /*
  31638. ** Interfaces for opening a shared library, finding entry points
  31639. ** within the shared library, and closing the shared library.
  31640. */
  31641. #include <dlfcn.h>
  31642. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  31643. UNUSED_PARAMETER(NotUsed);
  31644. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  31645. }
  31646. /*
  31647. ** SQLite calls this function immediately after a call to unixDlSym() or
  31648. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  31649. ** message is available, it is written to zBufOut. If no error message
  31650. ** is available, zBufOut is left unmodified and SQLite uses a default
  31651. ** error message.
  31652. */
  31653. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  31654. const char *zErr;
  31655. UNUSED_PARAMETER(NotUsed);
  31656. unixEnterMutex();
  31657. zErr = dlerror();
  31658. if( zErr ){
  31659. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  31660. }
  31661. unixLeaveMutex();
  31662. }
  31663. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  31664. /*
  31665. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  31666. ** cast into a pointer to a function. And yet the library dlsym() routine
  31667. ** returns a void* which is really a pointer to a function. So how do we
  31668. ** use dlsym() with -pedantic-errors?
  31669. **
  31670. ** Variable x below is defined to be a pointer to a function taking
  31671. ** parameters void* and const char* and returning a pointer to a function.
  31672. ** We initialize x by assigning it a pointer to the dlsym() function.
  31673. ** (That assignment requires a cast.) Then we call the function that
  31674. ** x points to.
  31675. **
  31676. ** This work-around is unlikely to work correctly on any system where
  31677. ** you really cannot cast a function pointer into void*. But then, on the
  31678. ** other hand, dlsym() will not work on such a system either, so we have
  31679. ** not really lost anything.
  31680. */
  31681. void (*(*x)(void*,const char*))(void);
  31682. UNUSED_PARAMETER(NotUsed);
  31683. x = (void(*(*)(void*,const char*))(void))dlsym;
  31684. return (*x)(p, zSym);
  31685. }
  31686. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  31687. UNUSED_PARAMETER(NotUsed);
  31688. dlclose(pHandle);
  31689. }
  31690. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  31691. #define unixDlOpen 0
  31692. #define unixDlError 0
  31693. #define unixDlSym 0
  31694. #define unixDlClose 0
  31695. #endif
  31696. /*
  31697. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  31698. */
  31699. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  31700. UNUSED_PARAMETER(NotUsed);
  31701. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  31702. /* We have to initialize zBuf to prevent valgrind from reporting
  31703. ** errors. The reports issued by valgrind are incorrect - we would
  31704. ** prefer that the randomness be increased by making use of the
  31705. ** uninitialized space in zBuf - but valgrind errors tend to worry
  31706. ** some users. Rather than argue, it seems easier just to initialize
  31707. ** the whole array and silence valgrind, even if that means less randomness
  31708. ** in the random seed.
  31709. **
  31710. ** When testing, initializing zBuf[] to zero is all we do. That means
  31711. ** that we always use the same random number sequence. This makes the
  31712. ** tests repeatable.
  31713. */
  31714. memset(zBuf, 0, nBuf);
  31715. randomnessPid = osGetpid(0);
  31716. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  31717. {
  31718. int fd, got;
  31719. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  31720. if( fd<0 ){
  31721. time_t t;
  31722. time(&t);
  31723. memcpy(zBuf, &t, sizeof(t));
  31724. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  31725. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  31726. nBuf = sizeof(t) + sizeof(randomnessPid);
  31727. }else{
  31728. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  31729. robust_close(0, fd, __LINE__);
  31730. }
  31731. }
  31732. #endif
  31733. return nBuf;
  31734. }
  31735. /*
  31736. ** Sleep for a little while. Return the amount of time slept.
  31737. ** The argument is the number of microseconds we want to sleep.
  31738. ** The return value is the number of microseconds of sleep actually
  31739. ** requested from the underlying operating system, a number which
  31740. ** might be greater than or equal to the argument, but not less
  31741. ** than the argument.
  31742. */
  31743. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  31744. #if OS_VXWORKS
  31745. struct timespec sp;
  31746. sp.tv_sec = microseconds / 1000000;
  31747. sp.tv_nsec = (microseconds % 1000000) * 1000;
  31748. nanosleep(&sp, NULL);
  31749. UNUSED_PARAMETER(NotUsed);
  31750. return microseconds;
  31751. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  31752. usleep(microseconds);
  31753. UNUSED_PARAMETER(NotUsed);
  31754. return microseconds;
  31755. #else
  31756. int seconds = (microseconds+999999)/1000000;
  31757. sleep(seconds);
  31758. UNUSED_PARAMETER(NotUsed);
  31759. return seconds*1000000;
  31760. #endif
  31761. }
  31762. /*
  31763. ** The following variable, if set to a non-zero value, is interpreted as
  31764. ** the number of seconds since 1970 and is used to set the result of
  31765. ** sqlite3OsCurrentTime() during testing.
  31766. */
  31767. #ifdef SQLITE_TEST
  31768. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  31769. #endif
  31770. /*
  31771. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  31772. ** the current time and date as a Julian Day number times 86_400_000. In
  31773. ** other words, write into *piNow the number of milliseconds since the Julian
  31774. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  31775. ** proleptic Gregorian calendar.
  31776. **
  31777. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  31778. ** cannot be found.
  31779. */
  31780. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  31781. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  31782. int rc = SQLITE_OK;
  31783. #if defined(NO_GETTOD)
  31784. time_t t;
  31785. time(&t);
  31786. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  31787. #elif OS_VXWORKS
  31788. struct timespec sNow;
  31789. clock_gettime(CLOCK_REALTIME, &sNow);
  31790. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  31791. #else
  31792. struct timeval sNow;
  31793. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  31794. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  31795. #endif
  31796. #ifdef SQLITE_TEST
  31797. if( sqlite3_current_time ){
  31798. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  31799. }
  31800. #endif
  31801. UNUSED_PARAMETER(NotUsed);
  31802. return rc;
  31803. }
  31804. #ifndef SQLITE_OMIT_DEPRECATED
  31805. /*
  31806. ** Find the current time (in Universal Coordinated Time). Write the
  31807. ** current time and date as a Julian Day number into *prNow and
  31808. ** return 0. Return 1 if the time and date cannot be found.
  31809. */
  31810. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  31811. sqlite3_int64 i = 0;
  31812. int rc;
  31813. UNUSED_PARAMETER(NotUsed);
  31814. rc = unixCurrentTimeInt64(0, &i);
  31815. *prNow = i/86400000.0;
  31816. return rc;
  31817. }
  31818. #else
  31819. # define unixCurrentTime 0
  31820. #endif
  31821. /*
  31822. ** The xGetLastError() method is designed to return a better
  31823. ** low-level error message when operating-system problems come up
  31824. ** during SQLite operation. Only the integer return code is currently
  31825. ** used.
  31826. */
  31827. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  31828. UNUSED_PARAMETER(NotUsed);
  31829. UNUSED_PARAMETER(NotUsed2);
  31830. UNUSED_PARAMETER(NotUsed3);
  31831. return errno;
  31832. }
  31833. /*
  31834. ************************ End of sqlite3_vfs methods ***************************
  31835. ******************************************************************************/
  31836. /******************************************************************************
  31837. ************************** Begin Proxy Locking ********************************
  31838. **
  31839. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  31840. ** other locking methods on secondary lock files. Proxy locking is a
  31841. ** meta-layer over top of the primitive locking implemented above. For
  31842. ** this reason, the division that implements of proxy locking is deferred
  31843. ** until late in the file (here) after all of the other I/O methods have
  31844. ** been defined - so that the primitive locking methods are available
  31845. ** as services to help with the implementation of proxy locking.
  31846. **
  31847. ****
  31848. **
  31849. ** The default locking schemes in SQLite use byte-range locks on the
  31850. ** database file to coordinate safe, concurrent access by multiple readers
  31851. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  31852. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  31853. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  31854. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  31855. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  31856. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  31857. ** address in the shared range is taken for a SHARED lock, the entire
  31858. ** shared range is taken for an EXCLUSIVE lock):
  31859. **
  31860. ** PENDING_BYTE 0x40000000
  31861. ** RESERVED_BYTE 0x40000001
  31862. ** SHARED_RANGE 0x40000002 -> 0x40000200
  31863. **
  31864. ** This works well on the local file system, but shows a nearly 100x
  31865. ** slowdown in read performance on AFP because the AFP client disables
  31866. ** the read cache when byte-range locks are present. Enabling the read
  31867. ** cache exposes a cache coherency problem that is present on all OS X
  31868. ** supported network file systems. NFS and AFP both observe the
  31869. ** close-to-open semantics for ensuring cache coherency
  31870. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  31871. ** address the requirements for concurrent database access by multiple
  31872. ** readers and writers
  31873. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  31874. **
  31875. ** To address the performance and cache coherency issues, proxy file locking
  31876. ** changes the way database access is controlled by limiting access to a
  31877. ** single host at a time and moving file locks off of the database file
  31878. ** and onto a proxy file on the local file system.
  31879. **
  31880. **
  31881. ** Using proxy locks
  31882. ** -----------------
  31883. **
  31884. ** C APIs
  31885. **
  31886. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  31887. ** <proxy_path> | ":auto:");
  31888. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  31889. ** &<proxy_path>);
  31890. **
  31891. **
  31892. ** SQL pragmas
  31893. **
  31894. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  31895. ** PRAGMA [database.]lock_proxy_file
  31896. **
  31897. ** Specifying ":auto:" means that if there is a conch file with a matching
  31898. ** host ID in it, the proxy path in the conch file will be used, otherwise
  31899. ** a proxy path based on the user's temp dir
  31900. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  31901. ** actual proxy file name is generated from the name and path of the
  31902. ** database file. For example:
  31903. **
  31904. ** For database path "/Users/me/foo.db"
  31905. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  31906. **
  31907. ** Once a lock proxy is configured for a database connection, it can not
  31908. ** be removed, however it may be switched to a different proxy path via
  31909. ** the above APIs (assuming the conch file is not being held by another
  31910. ** connection or process).
  31911. **
  31912. **
  31913. ** How proxy locking works
  31914. ** -----------------------
  31915. **
  31916. ** Proxy file locking relies primarily on two new supporting files:
  31917. **
  31918. ** * conch file to limit access to the database file to a single host
  31919. ** at a time
  31920. **
  31921. ** * proxy file to act as a proxy for the advisory locks normally
  31922. ** taken on the database
  31923. **
  31924. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  31925. ** by taking an sqlite-style shared lock on the conch file, reading the
  31926. ** contents and comparing the host's unique host ID (see below) and lock
  31927. ** proxy path against the values stored in the conch. The conch file is
  31928. ** stored in the same directory as the database file and the file name
  31929. ** is patterned after the database file name as ".<databasename>-conch".
  31930. ** If the conch file does not exist, or its contents do not match the
  31931. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  31932. ** lock and the conch file contents is updated with the host ID and proxy
  31933. ** path and the lock is downgraded to a shared lock again. If the conch
  31934. ** is held by another process (with a shared lock), the exclusive lock
  31935. ** will fail and SQLITE_BUSY is returned.
  31936. **
  31937. ** The proxy file - a single-byte file used for all advisory file locks
  31938. ** normally taken on the database file. This allows for safe sharing
  31939. ** of the database file for multiple readers and writers on the same
  31940. ** host (the conch ensures that they all use the same local lock file).
  31941. **
  31942. ** Requesting the lock proxy does not immediately take the conch, it is
  31943. ** only taken when the first request to lock database file is made.
  31944. ** This matches the semantics of the traditional locking behavior, where
  31945. ** opening a connection to a database file does not take a lock on it.
  31946. ** The shared lock and an open file descriptor are maintained until
  31947. ** the connection to the database is closed.
  31948. **
  31949. ** The proxy file and the lock file are never deleted so they only need
  31950. ** to be created the first time they are used.
  31951. **
  31952. ** Configuration options
  31953. ** ---------------------
  31954. **
  31955. ** SQLITE_PREFER_PROXY_LOCKING
  31956. **
  31957. ** Database files accessed on non-local file systems are
  31958. ** automatically configured for proxy locking, lock files are
  31959. ** named automatically using the same logic as
  31960. ** PRAGMA lock_proxy_file=":auto:"
  31961. **
  31962. ** SQLITE_PROXY_DEBUG
  31963. **
  31964. ** Enables the logging of error messages during host id file
  31965. ** retrieval and creation
  31966. **
  31967. ** LOCKPROXYDIR
  31968. **
  31969. ** Overrides the default directory used for lock proxy files that
  31970. ** are named automatically via the ":auto:" setting
  31971. **
  31972. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  31973. **
  31974. ** Permissions to use when creating a directory for storing the
  31975. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  31976. **
  31977. **
  31978. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  31979. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  31980. ** force proxy locking to be used for every database file opened, and 0
  31981. ** will force automatic proxy locking to be disabled for all database
  31982. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  31983. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  31984. */
  31985. /*
  31986. ** Proxy locking is only available on MacOSX
  31987. */
  31988. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31989. /*
  31990. ** The proxyLockingContext has the path and file structures for the remote
  31991. ** and local proxy files in it
  31992. */
  31993. typedef struct proxyLockingContext proxyLockingContext;
  31994. struct proxyLockingContext {
  31995. unixFile *conchFile; /* Open conch file */
  31996. char *conchFilePath; /* Name of the conch file */
  31997. unixFile *lockProxy; /* Open proxy lock file */
  31998. char *lockProxyPath; /* Name of the proxy lock file */
  31999. char *dbPath; /* Name of the open file */
  32000. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  32001. int nFails; /* Number of conch taking failures */
  32002. void *oldLockingContext; /* Original lockingcontext to restore on close */
  32003. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  32004. };
  32005. /*
  32006. ** The proxy lock file path for the database at dbPath is written into lPath,
  32007. ** which must point to valid, writable memory large enough for a maxLen length
  32008. ** file path.
  32009. */
  32010. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  32011. int len;
  32012. int dbLen;
  32013. int i;
  32014. #ifdef LOCKPROXYDIR
  32015. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  32016. #else
  32017. # ifdef _CS_DARWIN_USER_TEMP_DIR
  32018. {
  32019. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  32020. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  32021. lPath, errno, osGetpid(0)));
  32022. return SQLITE_IOERR_LOCK;
  32023. }
  32024. len = strlcat(lPath, "sqliteplocks", maxLen);
  32025. }
  32026. # else
  32027. len = strlcpy(lPath, "/tmp/", maxLen);
  32028. # endif
  32029. #endif
  32030. if( lPath[len-1]!='/' ){
  32031. len = strlcat(lPath, "/", maxLen);
  32032. }
  32033. /* transform the db path to a unique cache name */
  32034. dbLen = (int)strlen(dbPath);
  32035. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  32036. char c = dbPath[i];
  32037. lPath[i+len] = (c=='/')?'_':c;
  32038. }
  32039. lPath[i+len]='\0';
  32040. strlcat(lPath, ":auto:", maxLen);
  32041. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  32042. return SQLITE_OK;
  32043. }
  32044. /*
  32045. ** Creates the lock file and any missing directories in lockPath
  32046. */
  32047. static int proxyCreateLockPath(const char *lockPath){
  32048. int i, len;
  32049. char buf[MAXPATHLEN];
  32050. int start = 0;
  32051. assert(lockPath!=NULL);
  32052. /* try to create all the intermediate directories */
  32053. len = (int)strlen(lockPath);
  32054. buf[0] = lockPath[0];
  32055. for( i=1; i<len; i++ ){
  32056. if( lockPath[i] == '/' && (i - start > 0) ){
  32057. /* only mkdir if leaf dir != "." or "/" or ".." */
  32058. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  32059. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  32060. buf[i]='\0';
  32061. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  32062. int err=errno;
  32063. if( err!=EEXIST ) {
  32064. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  32065. "'%s' proxy lock path=%s pid=%d\n",
  32066. buf, strerror(err), lockPath, osGetpid(0)));
  32067. return err;
  32068. }
  32069. }
  32070. }
  32071. start=i+1;
  32072. }
  32073. buf[i] = lockPath[i];
  32074. }
  32075. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  32076. return 0;
  32077. }
  32078. /*
  32079. ** Create a new VFS file descriptor (stored in memory obtained from
  32080. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  32081. **
  32082. ** The caller is responsible not only for closing the file descriptor
  32083. ** but also for freeing the memory associated with the file descriptor.
  32084. */
  32085. static int proxyCreateUnixFile(
  32086. const char *path, /* path for the new unixFile */
  32087. unixFile **ppFile, /* unixFile created and returned by ref */
  32088. int islockfile /* if non zero missing dirs will be created */
  32089. ) {
  32090. int fd = -1;
  32091. unixFile *pNew;
  32092. int rc = SQLITE_OK;
  32093. int openFlags = O_RDWR | O_CREAT;
  32094. sqlite3_vfs dummyVfs;
  32095. int terrno = 0;
  32096. UnixUnusedFd *pUnused = NULL;
  32097. /* 1. first try to open/create the file
  32098. ** 2. if that fails, and this is a lock file (not-conch), try creating
  32099. ** the parent directories and then try again.
  32100. ** 3. if that fails, try to open the file read-only
  32101. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  32102. */
  32103. pUnused = findReusableFd(path, openFlags);
  32104. if( pUnused ){
  32105. fd = pUnused->fd;
  32106. }else{
  32107. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  32108. if( !pUnused ){
  32109. return SQLITE_NOMEM_BKPT;
  32110. }
  32111. }
  32112. if( fd<0 ){
  32113. fd = robust_open(path, openFlags, 0);
  32114. terrno = errno;
  32115. if( fd<0 && errno==ENOENT && islockfile ){
  32116. if( proxyCreateLockPath(path) == SQLITE_OK ){
  32117. fd = robust_open(path, openFlags, 0);
  32118. }
  32119. }
  32120. }
  32121. if( fd<0 ){
  32122. openFlags = O_RDONLY;
  32123. fd = robust_open(path, openFlags, 0);
  32124. terrno = errno;
  32125. }
  32126. if( fd<0 ){
  32127. if( islockfile ){
  32128. return SQLITE_BUSY;
  32129. }
  32130. switch (terrno) {
  32131. case EACCES:
  32132. return SQLITE_PERM;
  32133. case EIO:
  32134. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  32135. default:
  32136. return SQLITE_CANTOPEN_BKPT;
  32137. }
  32138. }
  32139. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  32140. if( pNew==NULL ){
  32141. rc = SQLITE_NOMEM_BKPT;
  32142. goto end_create_proxy;
  32143. }
  32144. memset(pNew, 0, sizeof(unixFile));
  32145. pNew->openFlags = openFlags;
  32146. memset(&dummyVfs, 0, sizeof(dummyVfs));
  32147. dummyVfs.pAppData = (void*)&autolockIoFinder;
  32148. dummyVfs.zName = "dummy";
  32149. pUnused->fd = fd;
  32150. pUnused->flags = openFlags;
  32151. pNew->pUnused = pUnused;
  32152. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  32153. if( rc==SQLITE_OK ){
  32154. *ppFile = pNew;
  32155. return SQLITE_OK;
  32156. }
  32157. end_create_proxy:
  32158. robust_close(pNew, fd, __LINE__);
  32159. sqlite3_free(pNew);
  32160. sqlite3_free(pUnused);
  32161. return rc;
  32162. }
  32163. #ifdef SQLITE_TEST
  32164. /* simulate multiple hosts by creating unique hostid file paths */
  32165. SQLITE_API int sqlite3_hostid_num = 0;
  32166. #endif
  32167. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  32168. #ifdef HAVE_GETHOSTUUID
  32169. /* Not always defined in the headers as it ought to be */
  32170. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  32171. #endif
  32172. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  32173. ** bytes of writable memory.
  32174. */
  32175. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  32176. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  32177. memset(pHostID, 0, PROXY_HOSTIDLEN);
  32178. #ifdef HAVE_GETHOSTUUID
  32179. {
  32180. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  32181. if( gethostuuid(pHostID, &timeout) ){
  32182. int err = errno;
  32183. if( pError ){
  32184. *pError = err;
  32185. }
  32186. return SQLITE_IOERR;
  32187. }
  32188. }
  32189. #else
  32190. UNUSED_PARAMETER(pError);
  32191. #endif
  32192. #ifdef SQLITE_TEST
  32193. /* simulate multiple hosts by creating unique hostid file paths */
  32194. if( sqlite3_hostid_num != 0){
  32195. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  32196. }
  32197. #endif
  32198. return SQLITE_OK;
  32199. }
  32200. /* The conch file contains the header, host id and lock file path
  32201. */
  32202. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  32203. #define PROXY_HEADERLEN 1 /* conch file header length */
  32204. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  32205. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  32206. /*
  32207. ** Takes an open conch file, copies the contents to a new path and then moves
  32208. ** it back. The newly created file's file descriptor is assigned to the
  32209. ** conch file structure and finally the original conch file descriptor is
  32210. ** closed. Returns zero if successful.
  32211. */
  32212. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  32213. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32214. unixFile *conchFile = pCtx->conchFile;
  32215. char tPath[MAXPATHLEN];
  32216. char buf[PROXY_MAXCONCHLEN];
  32217. char *cPath = pCtx->conchFilePath;
  32218. size_t readLen = 0;
  32219. size_t pathLen = 0;
  32220. char errmsg[64] = "";
  32221. int fd = -1;
  32222. int rc = -1;
  32223. UNUSED_PARAMETER(myHostID);
  32224. /* create a new path by replace the trailing '-conch' with '-break' */
  32225. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  32226. if( pathLen>MAXPATHLEN || pathLen<6 ||
  32227. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  32228. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  32229. goto end_breaklock;
  32230. }
  32231. /* read the conch content */
  32232. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  32233. if( readLen<PROXY_PATHINDEX ){
  32234. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  32235. goto end_breaklock;
  32236. }
  32237. /* write it out to the temporary break file */
  32238. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  32239. if( fd<0 ){
  32240. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  32241. goto end_breaklock;
  32242. }
  32243. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  32244. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  32245. goto end_breaklock;
  32246. }
  32247. if( rename(tPath, cPath) ){
  32248. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  32249. goto end_breaklock;
  32250. }
  32251. rc = 0;
  32252. fprintf(stderr, "broke stale lock on %s\n", cPath);
  32253. robust_close(pFile, conchFile->h, __LINE__);
  32254. conchFile->h = fd;
  32255. conchFile->openFlags = O_RDWR | O_CREAT;
  32256. end_breaklock:
  32257. if( rc ){
  32258. if( fd>=0 ){
  32259. osUnlink(tPath);
  32260. robust_close(pFile, fd, __LINE__);
  32261. }
  32262. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  32263. }
  32264. return rc;
  32265. }
  32266. /* Take the requested lock on the conch file and break a stale lock if the
  32267. ** host id matches.
  32268. */
  32269. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  32270. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32271. unixFile *conchFile = pCtx->conchFile;
  32272. int rc = SQLITE_OK;
  32273. int nTries = 0;
  32274. struct timespec conchModTime;
  32275. memset(&conchModTime, 0, sizeof(conchModTime));
  32276. do {
  32277. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  32278. nTries ++;
  32279. if( rc==SQLITE_BUSY ){
  32280. /* If the lock failed (busy):
  32281. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  32282. * 2nd try: fail if the mod time changed or host id is different, wait
  32283. * 10 sec and try again
  32284. * 3rd try: break the lock unless the mod time has changed.
  32285. */
  32286. struct stat buf;
  32287. if( osFstat(conchFile->h, &buf) ){
  32288. storeLastErrno(pFile, errno);
  32289. return SQLITE_IOERR_LOCK;
  32290. }
  32291. if( nTries==1 ){
  32292. conchModTime = buf.st_mtimespec;
  32293. usleep(500000); /* wait 0.5 sec and try the lock again*/
  32294. continue;
  32295. }
  32296. assert( nTries>1 );
  32297. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  32298. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  32299. return SQLITE_BUSY;
  32300. }
  32301. if( nTries==2 ){
  32302. char tBuf[PROXY_MAXCONCHLEN];
  32303. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  32304. if( len<0 ){
  32305. storeLastErrno(pFile, errno);
  32306. return SQLITE_IOERR_LOCK;
  32307. }
  32308. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  32309. /* don't break the lock if the host id doesn't match */
  32310. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  32311. return SQLITE_BUSY;
  32312. }
  32313. }else{
  32314. /* don't break the lock on short read or a version mismatch */
  32315. return SQLITE_BUSY;
  32316. }
  32317. usleep(10000000); /* wait 10 sec and try the lock again */
  32318. continue;
  32319. }
  32320. assert( nTries==3 );
  32321. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  32322. rc = SQLITE_OK;
  32323. if( lockType==EXCLUSIVE_LOCK ){
  32324. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  32325. }
  32326. if( !rc ){
  32327. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  32328. }
  32329. }
  32330. }
  32331. } while( rc==SQLITE_BUSY && nTries<3 );
  32332. return rc;
  32333. }
  32334. /* Takes the conch by taking a shared lock and read the contents conch, if
  32335. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  32336. ** lockPath means that the lockPath in the conch file will be used if the
  32337. ** host IDs match, or a new lock path will be generated automatically
  32338. ** and written to the conch file.
  32339. */
  32340. static int proxyTakeConch(unixFile *pFile){
  32341. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32342. if( pCtx->conchHeld!=0 ){
  32343. return SQLITE_OK;
  32344. }else{
  32345. unixFile *conchFile = pCtx->conchFile;
  32346. uuid_t myHostID;
  32347. int pError = 0;
  32348. char readBuf[PROXY_MAXCONCHLEN];
  32349. char lockPath[MAXPATHLEN];
  32350. char *tempLockPath = NULL;
  32351. int rc = SQLITE_OK;
  32352. int createConch = 0;
  32353. int hostIdMatch = 0;
  32354. int readLen = 0;
  32355. int tryOldLockPath = 0;
  32356. int forceNewLockPath = 0;
  32357. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  32358. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  32359. osGetpid(0)));
  32360. rc = proxyGetHostID(myHostID, &pError);
  32361. if( (rc&0xff)==SQLITE_IOERR ){
  32362. storeLastErrno(pFile, pError);
  32363. goto end_takeconch;
  32364. }
  32365. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  32366. if( rc!=SQLITE_OK ){
  32367. goto end_takeconch;
  32368. }
  32369. /* read the existing conch file */
  32370. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  32371. if( readLen<0 ){
  32372. /* I/O error: lastErrno set by seekAndRead */
  32373. storeLastErrno(pFile, conchFile->lastErrno);
  32374. rc = SQLITE_IOERR_READ;
  32375. goto end_takeconch;
  32376. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  32377. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  32378. /* a short read or version format mismatch means we need to create a new
  32379. ** conch file.
  32380. */
  32381. createConch = 1;
  32382. }
  32383. /* if the host id matches and the lock path already exists in the conch
  32384. ** we'll try to use the path there, if we can't open that path, we'll
  32385. ** retry with a new auto-generated path
  32386. */
  32387. do { /* in case we need to try again for an :auto: named lock file */
  32388. if( !createConch && !forceNewLockPath ){
  32389. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  32390. PROXY_HOSTIDLEN);
  32391. /* if the conch has data compare the contents */
  32392. if( !pCtx->lockProxyPath ){
  32393. /* for auto-named local lock file, just check the host ID and we'll
  32394. ** use the local lock file path that's already in there
  32395. */
  32396. if( hostIdMatch ){
  32397. size_t pathLen = (readLen - PROXY_PATHINDEX);
  32398. if( pathLen>=MAXPATHLEN ){
  32399. pathLen=MAXPATHLEN-1;
  32400. }
  32401. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  32402. lockPath[pathLen] = 0;
  32403. tempLockPath = lockPath;
  32404. tryOldLockPath = 1;
  32405. /* create a copy of the lock path if the conch is taken */
  32406. goto end_takeconch;
  32407. }
  32408. }else if( hostIdMatch
  32409. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  32410. readLen-PROXY_PATHINDEX)
  32411. ){
  32412. /* conch host and lock path match */
  32413. goto end_takeconch;
  32414. }
  32415. }
  32416. /* if the conch isn't writable and doesn't match, we can't take it */
  32417. if( (conchFile->openFlags&O_RDWR) == 0 ){
  32418. rc = SQLITE_BUSY;
  32419. goto end_takeconch;
  32420. }
  32421. /* either the conch didn't match or we need to create a new one */
  32422. if( !pCtx->lockProxyPath ){
  32423. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  32424. tempLockPath = lockPath;
  32425. /* create a copy of the lock path _only_ if the conch is taken */
  32426. }
  32427. /* update conch with host and path (this will fail if other process
  32428. ** has a shared lock already), if the host id matches, use the big
  32429. ** stick.
  32430. */
  32431. futimes(conchFile->h, NULL);
  32432. if( hostIdMatch && !createConch ){
  32433. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  32434. /* We are trying for an exclusive lock but another thread in this
  32435. ** same process is still holding a shared lock. */
  32436. rc = SQLITE_BUSY;
  32437. } else {
  32438. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  32439. }
  32440. }else{
  32441. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  32442. }
  32443. if( rc==SQLITE_OK ){
  32444. char writeBuffer[PROXY_MAXCONCHLEN];
  32445. int writeSize = 0;
  32446. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  32447. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  32448. if( pCtx->lockProxyPath!=NULL ){
  32449. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  32450. MAXPATHLEN);
  32451. }else{
  32452. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  32453. }
  32454. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  32455. robust_ftruncate(conchFile->h, writeSize);
  32456. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  32457. full_fsync(conchFile->h,0,0);
  32458. /* If we created a new conch file (not just updated the contents of a
  32459. ** valid conch file), try to match the permissions of the database
  32460. */
  32461. if( rc==SQLITE_OK && createConch ){
  32462. struct stat buf;
  32463. int err = osFstat(pFile->h, &buf);
  32464. if( err==0 ){
  32465. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  32466. S_IROTH|S_IWOTH);
  32467. /* try to match the database file R/W permissions, ignore failure */
  32468. #ifndef SQLITE_PROXY_DEBUG
  32469. osFchmod(conchFile->h, cmode);
  32470. #else
  32471. do{
  32472. rc = osFchmod(conchFile->h, cmode);
  32473. }while( rc==(-1) && errno==EINTR );
  32474. if( rc!=0 ){
  32475. int code = errno;
  32476. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  32477. cmode, code, strerror(code));
  32478. } else {
  32479. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  32480. }
  32481. }else{
  32482. int code = errno;
  32483. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  32484. err, code, strerror(code));
  32485. #endif
  32486. }
  32487. }
  32488. }
  32489. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  32490. end_takeconch:
  32491. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  32492. if( rc==SQLITE_OK && pFile->openFlags ){
  32493. int fd;
  32494. if( pFile->h>=0 ){
  32495. robust_close(pFile, pFile->h, __LINE__);
  32496. }
  32497. pFile->h = -1;
  32498. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  32499. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  32500. if( fd>=0 ){
  32501. pFile->h = fd;
  32502. }else{
  32503. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  32504. during locking */
  32505. }
  32506. }
  32507. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  32508. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  32509. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  32510. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  32511. /* we couldn't create the proxy lock file with the old lock file path
  32512. ** so try again via auto-naming
  32513. */
  32514. forceNewLockPath = 1;
  32515. tryOldLockPath = 0;
  32516. continue; /* go back to the do {} while start point, try again */
  32517. }
  32518. }
  32519. if( rc==SQLITE_OK ){
  32520. /* Need to make a copy of path if we extracted the value
  32521. ** from the conch file or the path was allocated on the stack
  32522. */
  32523. if( tempLockPath ){
  32524. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  32525. if( !pCtx->lockProxyPath ){
  32526. rc = SQLITE_NOMEM_BKPT;
  32527. }
  32528. }
  32529. }
  32530. if( rc==SQLITE_OK ){
  32531. pCtx->conchHeld = 1;
  32532. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  32533. afpLockingContext *afpCtx;
  32534. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  32535. afpCtx->dbPath = pCtx->lockProxyPath;
  32536. }
  32537. } else {
  32538. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  32539. }
  32540. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  32541. rc==SQLITE_OK?"ok":"failed"));
  32542. return rc;
  32543. } while (1); /* in case we need to retry the :auto: lock file -
  32544. ** we should never get here except via the 'continue' call. */
  32545. }
  32546. }
  32547. /*
  32548. ** If pFile holds a lock on a conch file, then release that lock.
  32549. */
  32550. static int proxyReleaseConch(unixFile *pFile){
  32551. int rc = SQLITE_OK; /* Subroutine return code */
  32552. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  32553. unixFile *conchFile; /* Name of the conch file */
  32554. pCtx = (proxyLockingContext *)pFile->lockingContext;
  32555. conchFile = pCtx->conchFile;
  32556. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  32557. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  32558. osGetpid(0)));
  32559. if( pCtx->conchHeld>0 ){
  32560. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  32561. }
  32562. pCtx->conchHeld = 0;
  32563. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  32564. (rc==SQLITE_OK ? "ok" : "failed")));
  32565. return rc;
  32566. }
  32567. /*
  32568. ** Given the name of a database file, compute the name of its conch file.
  32569. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  32570. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  32571. ** or SQLITE_NOMEM if unable to obtain memory.
  32572. **
  32573. ** The caller is responsible for ensuring that the allocated memory
  32574. ** space is eventually freed.
  32575. **
  32576. ** *pConchPath is set to NULL if a memory allocation error occurs.
  32577. */
  32578. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  32579. int i; /* Loop counter */
  32580. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  32581. char *conchPath; /* buffer in which to construct conch name */
  32582. /* Allocate space for the conch filename and initialize the name to
  32583. ** the name of the original database file. */
  32584. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  32585. if( conchPath==0 ){
  32586. return SQLITE_NOMEM_BKPT;
  32587. }
  32588. memcpy(conchPath, dbPath, len+1);
  32589. /* now insert a "." before the last / character */
  32590. for( i=(len-1); i>=0; i-- ){
  32591. if( conchPath[i]=='/' ){
  32592. i++;
  32593. break;
  32594. }
  32595. }
  32596. conchPath[i]='.';
  32597. while ( i<len ){
  32598. conchPath[i+1]=dbPath[i];
  32599. i++;
  32600. }
  32601. /* append the "-conch" suffix to the file */
  32602. memcpy(&conchPath[i+1], "-conch", 7);
  32603. assert( (int)strlen(conchPath) == len+7 );
  32604. return SQLITE_OK;
  32605. }
  32606. /* Takes a fully configured proxy locking-style unix file and switches
  32607. ** the local lock file path
  32608. */
  32609. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  32610. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  32611. char *oldPath = pCtx->lockProxyPath;
  32612. int rc = SQLITE_OK;
  32613. if( pFile->eFileLock!=NO_LOCK ){
  32614. return SQLITE_BUSY;
  32615. }
  32616. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  32617. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  32618. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  32619. return SQLITE_OK;
  32620. }else{
  32621. unixFile *lockProxy = pCtx->lockProxy;
  32622. pCtx->lockProxy=NULL;
  32623. pCtx->conchHeld = 0;
  32624. if( lockProxy!=NULL ){
  32625. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  32626. if( rc ) return rc;
  32627. sqlite3_free(lockProxy);
  32628. }
  32629. sqlite3_free(oldPath);
  32630. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  32631. }
  32632. return rc;
  32633. }
  32634. /*
  32635. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  32636. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  32637. **
  32638. ** This routine find the filename associated with pFile and writes it
  32639. ** int dbPath.
  32640. */
  32641. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  32642. #if defined(__APPLE__)
  32643. if( pFile->pMethod == &afpIoMethods ){
  32644. /* afp style keeps a reference to the db path in the filePath field
  32645. ** of the struct */
  32646. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  32647. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  32648. MAXPATHLEN);
  32649. } else
  32650. #endif
  32651. if( pFile->pMethod == &dotlockIoMethods ){
  32652. /* dot lock style uses the locking context to store the dot lock
  32653. ** file path */
  32654. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  32655. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  32656. }else{
  32657. /* all other styles use the locking context to store the db file path */
  32658. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  32659. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  32660. }
  32661. return SQLITE_OK;
  32662. }
  32663. /*
  32664. ** Takes an already filled in unix file and alters it so all file locking
  32665. ** will be performed on the local proxy lock file. The following fields
  32666. ** are preserved in the locking context so that they can be restored and
  32667. ** the unix structure properly cleaned up at close time:
  32668. ** ->lockingContext
  32669. ** ->pMethod
  32670. */
  32671. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  32672. proxyLockingContext *pCtx;
  32673. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  32674. char *lockPath=NULL;
  32675. int rc = SQLITE_OK;
  32676. if( pFile->eFileLock!=NO_LOCK ){
  32677. return SQLITE_BUSY;
  32678. }
  32679. proxyGetDbPathForUnixFile(pFile, dbPath);
  32680. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  32681. lockPath=NULL;
  32682. }else{
  32683. lockPath=(char *)path;
  32684. }
  32685. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  32686. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  32687. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  32688. if( pCtx==0 ){
  32689. return SQLITE_NOMEM_BKPT;
  32690. }
  32691. memset(pCtx, 0, sizeof(*pCtx));
  32692. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  32693. if( rc==SQLITE_OK ){
  32694. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  32695. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  32696. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  32697. ** (c) the file system is read-only, then enable no-locking access.
  32698. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  32699. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  32700. */
  32701. struct statfs fsInfo;
  32702. struct stat conchInfo;
  32703. int goLockless = 0;
  32704. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  32705. int err = errno;
  32706. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  32707. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  32708. }
  32709. }
  32710. if( goLockless ){
  32711. pCtx->conchHeld = -1; /* read only FS/ lockless */
  32712. rc = SQLITE_OK;
  32713. }
  32714. }
  32715. }
  32716. if( rc==SQLITE_OK && lockPath ){
  32717. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  32718. }
  32719. if( rc==SQLITE_OK ){
  32720. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  32721. if( pCtx->dbPath==NULL ){
  32722. rc = SQLITE_NOMEM_BKPT;
  32723. }
  32724. }
  32725. if( rc==SQLITE_OK ){
  32726. /* all memory is allocated, proxys are created and assigned,
  32727. ** switch the locking context and pMethod then return.
  32728. */
  32729. pCtx->oldLockingContext = pFile->lockingContext;
  32730. pFile->lockingContext = pCtx;
  32731. pCtx->pOldMethod = pFile->pMethod;
  32732. pFile->pMethod = &proxyIoMethods;
  32733. }else{
  32734. if( pCtx->conchFile ){
  32735. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  32736. sqlite3_free(pCtx->conchFile);
  32737. }
  32738. sqlite3DbFree(0, pCtx->lockProxyPath);
  32739. sqlite3_free(pCtx->conchFilePath);
  32740. sqlite3_free(pCtx);
  32741. }
  32742. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  32743. (rc==SQLITE_OK ? "ok" : "failed")));
  32744. return rc;
  32745. }
  32746. /*
  32747. ** This routine handles sqlite3_file_control() calls that are specific
  32748. ** to proxy locking.
  32749. */
  32750. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  32751. switch( op ){
  32752. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  32753. unixFile *pFile = (unixFile*)id;
  32754. if( pFile->pMethod == &proxyIoMethods ){
  32755. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  32756. proxyTakeConch(pFile);
  32757. if( pCtx->lockProxyPath ){
  32758. *(const char **)pArg = pCtx->lockProxyPath;
  32759. }else{
  32760. *(const char **)pArg = ":auto: (not held)";
  32761. }
  32762. } else {
  32763. *(const char **)pArg = NULL;
  32764. }
  32765. return SQLITE_OK;
  32766. }
  32767. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  32768. unixFile *pFile = (unixFile*)id;
  32769. int rc = SQLITE_OK;
  32770. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  32771. if( pArg==NULL || (const char *)pArg==0 ){
  32772. if( isProxyStyle ){
  32773. /* turn off proxy locking - not supported. If support is added for
  32774. ** switching proxy locking mode off then it will need to fail if
  32775. ** the journal mode is WAL mode.
  32776. */
  32777. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  32778. }else{
  32779. /* turn off proxy locking - already off - NOOP */
  32780. rc = SQLITE_OK;
  32781. }
  32782. }else{
  32783. const char *proxyPath = (const char *)pArg;
  32784. if( isProxyStyle ){
  32785. proxyLockingContext *pCtx =
  32786. (proxyLockingContext*)pFile->lockingContext;
  32787. if( !strcmp(pArg, ":auto:")
  32788. || (pCtx->lockProxyPath &&
  32789. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  32790. ){
  32791. rc = SQLITE_OK;
  32792. }else{
  32793. rc = switchLockProxyPath(pFile, proxyPath);
  32794. }
  32795. }else{
  32796. /* turn on proxy file locking */
  32797. rc = proxyTransformUnixFile(pFile, proxyPath);
  32798. }
  32799. }
  32800. return rc;
  32801. }
  32802. default: {
  32803. assert( 0 ); /* The call assures that only valid opcodes are sent */
  32804. }
  32805. }
  32806. /*NOTREACHED*/
  32807. return SQLITE_ERROR;
  32808. }
  32809. /*
  32810. ** Within this division (the proxying locking implementation) the procedures
  32811. ** above this point are all utilities. The lock-related methods of the
  32812. ** proxy-locking sqlite3_io_method object follow.
  32813. */
  32814. /*
  32815. ** This routine checks if there is a RESERVED lock held on the specified
  32816. ** file by this or any other process. If such a lock is held, set *pResOut
  32817. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32818. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32819. */
  32820. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  32821. unixFile *pFile = (unixFile*)id;
  32822. int rc = proxyTakeConch(pFile);
  32823. if( rc==SQLITE_OK ){
  32824. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32825. if( pCtx->conchHeld>0 ){
  32826. unixFile *proxy = pCtx->lockProxy;
  32827. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  32828. }else{ /* conchHeld < 0 is lockless */
  32829. pResOut=0;
  32830. }
  32831. }
  32832. return rc;
  32833. }
  32834. /*
  32835. ** Lock the file with the lock specified by parameter eFileLock - one
  32836. ** of the following:
  32837. **
  32838. ** (1) SHARED_LOCK
  32839. ** (2) RESERVED_LOCK
  32840. ** (3) PENDING_LOCK
  32841. ** (4) EXCLUSIVE_LOCK
  32842. **
  32843. ** Sometimes when requesting one lock state, additional lock states
  32844. ** are inserted in between. The locking might fail on one of the later
  32845. ** transitions leaving the lock state different from what it started but
  32846. ** still short of its goal. The following chart shows the allowed
  32847. ** transitions and the inserted intermediate states:
  32848. **
  32849. ** UNLOCKED -> SHARED
  32850. ** SHARED -> RESERVED
  32851. ** SHARED -> (PENDING) -> EXCLUSIVE
  32852. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32853. ** PENDING -> EXCLUSIVE
  32854. **
  32855. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32856. ** routine to lower a locking level.
  32857. */
  32858. static int proxyLock(sqlite3_file *id, int eFileLock) {
  32859. unixFile *pFile = (unixFile*)id;
  32860. int rc = proxyTakeConch(pFile);
  32861. if( rc==SQLITE_OK ){
  32862. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32863. if( pCtx->conchHeld>0 ){
  32864. unixFile *proxy = pCtx->lockProxy;
  32865. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  32866. pFile->eFileLock = proxy->eFileLock;
  32867. }else{
  32868. /* conchHeld < 0 is lockless */
  32869. }
  32870. }
  32871. return rc;
  32872. }
  32873. /*
  32874. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32875. ** must be either NO_LOCK or SHARED_LOCK.
  32876. **
  32877. ** If the locking level of the file descriptor is already at or below
  32878. ** the requested locking level, this routine is a no-op.
  32879. */
  32880. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  32881. unixFile *pFile = (unixFile*)id;
  32882. int rc = proxyTakeConch(pFile);
  32883. if( rc==SQLITE_OK ){
  32884. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32885. if( pCtx->conchHeld>0 ){
  32886. unixFile *proxy = pCtx->lockProxy;
  32887. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  32888. pFile->eFileLock = proxy->eFileLock;
  32889. }else{
  32890. /* conchHeld < 0 is lockless */
  32891. }
  32892. }
  32893. return rc;
  32894. }
  32895. /*
  32896. ** Close a file that uses proxy locks.
  32897. */
  32898. static int proxyClose(sqlite3_file *id) {
  32899. if( ALWAYS(id) ){
  32900. unixFile *pFile = (unixFile*)id;
  32901. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32902. unixFile *lockProxy = pCtx->lockProxy;
  32903. unixFile *conchFile = pCtx->conchFile;
  32904. int rc = SQLITE_OK;
  32905. if( lockProxy ){
  32906. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  32907. if( rc ) return rc;
  32908. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  32909. if( rc ) return rc;
  32910. sqlite3_free(lockProxy);
  32911. pCtx->lockProxy = 0;
  32912. }
  32913. if( conchFile ){
  32914. if( pCtx->conchHeld ){
  32915. rc = proxyReleaseConch(pFile);
  32916. if( rc ) return rc;
  32917. }
  32918. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  32919. if( rc ) return rc;
  32920. sqlite3_free(conchFile);
  32921. }
  32922. sqlite3DbFree(0, pCtx->lockProxyPath);
  32923. sqlite3_free(pCtx->conchFilePath);
  32924. sqlite3DbFree(0, pCtx->dbPath);
  32925. /* restore the original locking context and pMethod then close it */
  32926. pFile->lockingContext = pCtx->oldLockingContext;
  32927. pFile->pMethod = pCtx->pOldMethod;
  32928. sqlite3_free(pCtx);
  32929. return pFile->pMethod->xClose(id);
  32930. }
  32931. return SQLITE_OK;
  32932. }
  32933. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32934. /*
  32935. ** The proxy locking style is intended for use with AFP filesystems.
  32936. ** And since AFP is only supported on MacOSX, the proxy locking is also
  32937. ** restricted to MacOSX.
  32938. **
  32939. **
  32940. ******************* End of the proxy lock implementation **********************
  32941. ******************************************************************************/
  32942. /*
  32943. ** Initialize the operating system interface.
  32944. **
  32945. ** This routine registers all VFS implementations for unix-like operating
  32946. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  32947. ** should be the only routines in this file that are visible from other
  32948. ** files.
  32949. **
  32950. ** This routine is called once during SQLite initialization and by a
  32951. ** single thread. The memory allocation and mutex subsystems have not
  32952. ** necessarily been initialized when this routine is called, and so they
  32953. ** should not be used.
  32954. */
  32955. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  32956. /*
  32957. ** The following macro defines an initializer for an sqlite3_vfs object.
  32958. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  32959. ** to the "finder" function. (pAppData is a pointer to a pointer because
  32960. ** silly C90 rules prohibit a void* from being cast to a function pointer
  32961. ** and so we have to go through the intermediate pointer to avoid problems
  32962. ** when compiling with -pedantic-errors on GCC.)
  32963. **
  32964. ** The FINDER parameter to this macro is the name of the pointer to the
  32965. ** finder-function. The finder-function returns a pointer to the
  32966. ** sqlite_io_methods object that implements the desired locking
  32967. ** behaviors. See the division above that contains the IOMETHODS
  32968. ** macro for addition information on finder-functions.
  32969. **
  32970. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  32971. ** object. But the "autolockIoFinder" available on MacOSX does a little
  32972. ** more than that; it looks at the filesystem type that hosts the
  32973. ** database file and tries to choose an locking method appropriate for
  32974. ** that filesystem time.
  32975. */
  32976. #define UNIXVFS(VFSNAME, FINDER) { \
  32977. 3, /* iVersion */ \
  32978. sizeof(unixFile), /* szOsFile */ \
  32979. MAX_PATHNAME, /* mxPathname */ \
  32980. 0, /* pNext */ \
  32981. VFSNAME, /* zName */ \
  32982. (void*)&FINDER, /* pAppData */ \
  32983. unixOpen, /* xOpen */ \
  32984. unixDelete, /* xDelete */ \
  32985. unixAccess, /* xAccess */ \
  32986. unixFullPathname, /* xFullPathname */ \
  32987. unixDlOpen, /* xDlOpen */ \
  32988. unixDlError, /* xDlError */ \
  32989. unixDlSym, /* xDlSym */ \
  32990. unixDlClose, /* xDlClose */ \
  32991. unixRandomness, /* xRandomness */ \
  32992. unixSleep, /* xSleep */ \
  32993. unixCurrentTime, /* xCurrentTime */ \
  32994. unixGetLastError, /* xGetLastError */ \
  32995. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  32996. unixSetSystemCall, /* xSetSystemCall */ \
  32997. unixGetSystemCall, /* xGetSystemCall */ \
  32998. unixNextSystemCall, /* xNextSystemCall */ \
  32999. }
  33000. /*
  33001. ** All default VFSes for unix are contained in the following array.
  33002. **
  33003. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  33004. ** by the SQLite core when the VFS is registered. So the following
  33005. ** array cannot be const.
  33006. */
  33007. static sqlite3_vfs aVfs[] = {
  33008. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33009. UNIXVFS("unix", autolockIoFinder ),
  33010. #elif OS_VXWORKS
  33011. UNIXVFS("unix", vxworksIoFinder ),
  33012. #else
  33013. UNIXVFS("unix", posixIoFinder ),
  33014. #endif
  33015. UNIXVFS("unix-none", nolockIoFinder ),
  33016. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  33017. UNIXVFS("unix-excl", posixIoFinder ),
  33018. #if OS_VXWORKS
  33019. UNIXVFS("unix-namedsem", semIoFinder ),
  33020. #endif
  33021. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  33022. UNIXVFS("unix-posix", posixIoFinder ),
  33023. #endif
  33024. #if SQLITE_ENABLE_LOCKING_STYLE
  33025. UNIXVFS("unix-flock", flockIoFinder ),
  33026. #endif
  33027. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33028. UNIXVFS("unix-afp", afpIoFinder ),
  33029. UNIXVFS("unix-nfs", nfsIoFinder ),
  33030. UNIXVFS("unix-proxy", proxyIoFinder ),
  33031. #endif
  33032. };
  33033. unsigned int i; /* Loop counter */
  33034. /* Double-check that the aSyscall[] array has been constructed
  33035. ** correctly. See ticket [bb3a86e890c8e96ab] */
  33036. assert( ArraySize(aSyscall)==28 );
  33037. /* Register all VFSes defined in the aVfs[] array */
  33038. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  33039. sqlite3_vfs_register(&aVfs[i], i==0);
  33040. }
  33041. return SQLITE_OK;
  33042. }
  33043. /*
  33044. ** Shutdown the operating system interface.
  33045. **
  33046. ** Some operating systems might need to do some cleanup in this routine,
  33047. ** to release dynamically allocated objects. But not on unix.
  33048. ** This routine is a no-op for unix.
  33049. */
  33050. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  33051. return SQLITE_OK;
  33052. }
  33053. #endif /* SQLITE_OS_UNIX */
  33054. /************** End of os_unix.c *********************************************/
  33055. /************** Begin file os_win.c ******************************************/
  33056. /*
  33057. ** 2004 May 22
  33058. **
  33059. ** The author disclaims copyright to this source code. In place of
  33060. ** a legal notice, here is a blessing:
  33061. **
  33062. ** May you do good and not evil.
  33063. ** May you find forgiveness for yourself and forgive others.
  33064. ** May you share freely, never taking more than you give.
  33065. **
  33066. ******************************************************************************
  33067. **
  33068. ** This file contains code that is specific to Windows.
  33069. */
  33070. /* #include "sqliteInt.h" */
  33071. #if SQLITE_OS_WIN /* This file is used for Windows only */
  33072. /*
  33073. ** Include code that is common to all os_*.c files
  33074. */
  33075. /************** Include os_common.h in the middle of os_win.c ****************/
  33076. /************** Begin file os_common.h ***************************************/
  33077. /*
  33078. ** 2004 May 22
  33079. **
  33080. ** The author disclaims copyright to this source code. In place of
  33081. ** a legal notice, here is a blessing:
  33082. **
  33083. ** May you do good and not evil.
  33084. ** May you find forgiveness for yourself and forgive others.
  33085. ** May you share freely, never taking more than you give.
  33086. **
  33087. ******************************************************************************
  33088. **
  33089. ** This file contains macros and a little bit of code that is common to
  33090. ** all of the platform-specific files (os_*.c) and is #included into those
  33091. ** files.
  33092. **
  33093. ** This file should be #included by the os_*.c files only. It is not a
  33094. ** general purpose header file.
  33095. */
  33096. #ifndef _OS_COMMON_H_
  33097. #define _OS_COMMON_H_
  33098. /*
  33099. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  33100. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  33101. ** switch. The following code should catch this problem at compile-time.
  33102. */
  33103. #ifdef MEMORY_DEBUG
  33104. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  33105. #endif
  33106. /*
  33107. ** Macros for performance tracing. Normally turned off. Only works
  33108. ** on i486 hardware.
  33109. */
  33110. #ifdef SQLITE_PERFORMANCE_TRACE
  33111. /*
  33112. ** hwtime.h contains inline assembler code for implementing
  33113. ** high-performance timing routines.
  33114. */
  33115. /************** Include hwtime.h in the middle of os_common.h ****************/
  33116. /************** Begin file hwtime.h ******************************************/
  33117. /*
  33118. ** 2008 May 27
  33119. **
  33120. ** The author disclaims copyright to this source code. In place of
  33121. ** a legal notice, here is a blessing:
  33122. **
  33123. ** May you do good and not evil.
  33124. ** May you find forgiveness for yourself and forgive others.
  33125. ** May you share freely, never taking more than you give.
  33126. **
  33127. ******************************************************************************
  33128. **
  33129. ** This file contains inline asm code for retrieving "high-performance"
  33130. ** counters for x86 class CPUs.
  33131. */
  33132. #ifndef _HWTIME_H_
  33133. #define _HWTIME_H_
  33134. /*
  33135. ** The following routine only works on pentium-class (or newer) processors.
  33136. ** It uses the RDTSC opcode to read the cycle count value out of the
  33137. ** processor and returns that value. This can be used for high-res
  33138. ** profiling.
  33139. */
  33140. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  33141. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  33142. #if defined(__GNUC__)
  33143. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  33144. unsigned int lo, hi;
  33145. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  33146. return (sqlite_uint64)hi << 32 | lo;
  33147. }
  33148. #elif defined(_MSC_VER)
  33149. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  33150. __asm {
  33151. rdtsc
  33152. ret ; return value at EDX:EAX
  33153. }
  33154. }
  33155. #endif
  33156. #elif (defined(__GNUC__) && defined(__x86_64__))
  33157. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  33158. unsigned long val;
  33159. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  33160. return val;
  33161. }
  33162. #elif (defined(__GNUC__) && defined(__ppc__))
  33163. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  33164. unsigned long long retval;
  33165. unsigned long junk;
  33166. __asm__ __volatile__ ("\n\
  33167. 1: mftbu %1\n\
  33168. mftb %L0\n\
  33169. mftbu %0\n\
  33170. cmpw %0,%1\n\
  33171. bne 1b"
  33172. : "=r" (retval), "=r" (junk));
  33173. return retval;
  33174. }
  33175. #else
  33176. #error Need implementation of sqlite3Hwtime() for your platform.
  33177. /*
  33178. ** To compile without implementing sqlite3Hwtime() for your platform,
  33179. ** you can remove the above #error and use the following
  33180. ** stub function. You will lose timing support for many
  33181. ** of the debugging and testing utilities, but it should at
  33182. ** least compile and run.
  33183. */
  33184. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  33185. #endif
  33186. #endif /* !defined(_HWTIME_H_) */
  33187. /************** End of hwtime.h **********************************************/
  33188. /************** Continuing where we left off in os_common.h ******************/
  33189. static sqlite_uint64 g_start;
  33190. static sqlite_uint64 g_elapsed;
  33191. #define TIMER_START g_start=sqlite3Hwtime()
  33192. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  33193. #define TIMER_ELAPSED g_elapsed
  33194. #else
  33195. #define TIMER_START
  33196. #define TIMER_END
  33197. #define TIMER_ELAPSED ((sqlite_uint64)0)
  33198. #endif
  33199. /*
  33200. ** If we compile with the SQLITE_TEST macro set, then the following block
  33201. ** of code will give us the ability to simulate a disk I/O error. This
  33202. ** is used for testing the I/O recovery logic.
  33203. */
  33204. #if defined(SQLITE_TEST)
  33205. SQLITE_API extern int sqlite3_io_error_hit;
  33206. SQLITE_API extern int sqlite3_io_error_hardhit;
  33207. SQLITE_API extern int sqlite3_io_error_pending;
  33208. SQLITE_API extern int sqlite3_io_error_persist;
  33209. SQLITE_API extern int sqlite3_io_error_benign;
  33210. SQLITE_API extern int sqlite3_diskfull_pending;
  33211. SQLITE_API extern int sqlite3_diskfull;
  33212. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  33213. #define SimulateIOError(CODE) \
  33214. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  33215. || sqlite3_io_error_pending-- == 1 ) \
  33216. { local_ioerr(); CODE; }
  33217. static void local_ioerr(){
  33218. IOTRACE(("IOERR\n"));
  33219. sqlite3_io_error_hit++;
  33220. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  33221. }
  33222. #define SimulateDiskfullError(CODE) \
  33223. if( sqlite3_diskfull_pending ){ \
  33224. if( sqlite3_diskfull_pending == 1 ){ \
  33225. local_ioerr(); \
  33226. sqlite3_diskfull = 1; \
  33227. sqlite3_io_error_hit = 1; \
  33228. CODE; \
  33229. }else{ \
  33230. sqlite3_diskfull_pending--; \
  33231. } \
  33232. }
  33233. #else
  33234. #define SimulateIOErrorBenign(X)
  33235. #define SimulateIOError(A)
  33236. #define SimulateDiskfullError(A)
  33237. #endif /* defined(SQLITE_TEST) */
  33238. /*
  33239. ** When testing, keep a count of the number of open files.
  33240. */
  33241. #if defined(SQLITE_TEST)
  33242. SQLITE_API extern int sqlite3_open_file_count;
  33243. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  33244. #else
  33245. #define OpenCounter(X)
  33246. #endif /* defined(SQLITE_TEST) */
  33247. #endif /* !defined(_OS_COMMON_H_) */
  33248. /************** End of os_common.h *******************************************/
  33249. /************** Continuing where we left off in os_win.c *********************/
  33250. /*
  33251. ** Include the header file for the Windows VFS.
  33252. */
  33253. /* #include "os_win.h" */
  33254. /*
  33255. ** Compiling and using WAL mode requires several APIs that are only
  33256. ** available in Windows platforms based on the NT kernel.
  33257. */
  33258. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  33259. # error "WAL mode requires support from the Windows NT kernel, compile\
  33260. with SQLITE_OMIT_WAL."
  33261. #endif
  33262. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  33263. # error "Memory mapped files require support from the Windows NT kernel,\
  33264. compile with SQLITE_MAX_MMAP_SIZE=0."
  33265. #endif
  33266. /*
  33267. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  33268. ** based on the sub-platform)?
  33269. */
  33270. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  33271. # define SQLITE_WIN32_HAS_ANSI
  33272. #endif
  33273. /*
  33274. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  33275. ** based on the sub-platform)?
  33276. */
  33277. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  33278. !defined(SQLITE_WIN32_NO_WIDE)
  33279. # define SQLITE_WIN32_HAS_WIDE
  33280. #endif
  33281. /*
  33282. ** Make sure at least one set of Win32 APIs is available.
  33283. */
  33284. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  33285. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  33286. must be defined."
  33287. #endif
  33288. /*
  33289. ** Define the required Windows SDK version constants if they are not
  33290. ** already available.
  33291. */
  33292. #ifndef NTDDI_WIN8
  33293. # define NTDDI_WIN8 0x06020000
  33294. #endif
  33295. #ifndef NTDDI_WINBLUE
  33296. # define NTDDI_WINBLUE 0x06030000
  33297. #endif
  33298. #ifndef NTDDI_WINTHRESHOLD
  33299. # define NTDDI_WINTHRESHOLD 0x06040000
  33300. #endif
  33301. /*
  33302. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  33303. ** target system. GetVersionEx was first deprecated in Win8.1.
  33304. */
  33305. #ifndef SQLITE_WIN32_GETVERSIONEX
  33306. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  33307. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  33308. # else
  33309. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  33310. # endif
  33311. #endif
  33312. /*
  33313. ** Check to see if the CreateFileMappingA function is supported on the
  33314. ** target system. It is unavailable when using "mincore.lib" on Win10.
  33315. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  33316. */
  33317. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  33318. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  33319. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  33320. # else
  33321. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  33322. # endif
  33323. #endif
  33324. /*
  33325. ** This constant should already be defined (in the "WinDef.h" SDK file).
  33326. */
  33327. #ifndef MAX_PATH
  33328. # define MAX_PATH (260)
  33329. #endif
  33330. /*
  33331. ** Maximum pathname length (in chars) for Win32. This should normally be
  33332. ** MAX_PATH.
  33333. */
  33334. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  33335. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  33336. #endif
  33337. /*
  33338. ** This constant should already be defined (in the "WinNT.h" SDK file).
  33339. */
  33340. #ifndef UNICODE_STRING_MAX_CHARS
  33341. # define UNICODE_STRING_MAX_CHARS (32767)
  33342. #endif
  33343. /*
  33344. ** Maximum pathname length (in chars) for WinNT. This should normally be
  33345. ** UNICODE_STRING_MAX_CHARS.
  33346. */
  33347. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  33348. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  33349. #endif
  33350. /*
  33351. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  33352. ** characters, so we allocate 4 bytes per character assuming worst-case of
  33353. ** 4-bytes-per-character for UTF8.
  33354. */
  33355. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  33356. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  33357. #endif
  33358. /*
  33359. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  33360. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  33361. */
  33362. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  33363. # define SQLITE_WINNT_MAX_PATH_BYTES \
  33364. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  33365. #endif
  33366. /*
  33367. ** Maximum error message length (in chars) for WinRT.
  33368. */
  33369. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  33370. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  33371. #endif
  33372. /*
  33373. ** Returns non-zero if the character should be treated as a directory
  33374. ** separator.
  33375. */
  33376. #ifndef winIsDirSep
  33377. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  33378. #endif
  33379. /*
  33380. ** This macro is used when a local variable is set to a value that is
  33381. ** [sometimes] not used by the code (e.g. via conditional compilation).
  33382. */
  33383. #ifndef UNUSED_VARIABLE_VALUE
  33384. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  33385. #endif
  33386. /*
  33387. ** Returns the character that should be used as the directory separator.
  33388. */
  33389. #ifndef winGetDirSep
  33390. # define winGetDirSep() '\\'
  33391. #endif
  33392. /*
  33393. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  33394. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  33395. ** CE SDK; however, they are not present in the header file)?
  33396. */
  33397. #if SQLITE_WIN32_FILEMAPPING_API && \
  33398. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  33399. /*
  33400. ** Two of the file mapping APIs are different under WinRT. Figure out which
  33401. ** set we need.
  33402. */
  33403. #if SQLITE_OS_WINRT
  33404. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  33405. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  33406. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  33407. #else
  33408. #if defined(SQLITE_WIN32_HAS_ANSI)
  33409. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  33410. DWORD, DWORD, DWORD, LPCSTR);
  33411. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  33412. #if defined(SQLITE_WIN32_HAS_WIDE)
  33413. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  33414. DWORD, DWORD, DWORD, LPCWSTR);
  33415. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  33416. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  33417. #endif /* SQLITE_OS_WINRT */
  33418. /*
  33419. ** These file mapping APIs are common to both Win32 and WinRT.
  33420. */
  33421. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  33422. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  33423. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  33424. /*
  33425. ** Some Microsoft compilers lack this definition.
  33426. */
  33427. #ifndef INVALID_FILE_ATTRIBUTES
  33428. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  33429. #endif
  33430. #ifndef FILE_FLAG_MASK
  33431. # define FILE_FLAG_MASK (0xFF3C0000)
  33432. #endif
  33433. #ifndef FILE_ATTRIBUTE_MASK
  33434. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  33435. #endif
  33436. #ifndef SQLITE_OMIT_WAL
  33437. /* Forward references to structures used for WAL */
  33438. typedef struct winShm winShm; /* A connection to shared-memory */
  33439. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  33440. #endif
  33441. /*
  33442. ** WinCE lacks native support for file locking so we have to fake it
  33443. ** with some code of our own.
  33444. */
  33445. #if SQLITE_OS_WINCE
  33446. typedef struct winceLock {
  33447. int nReaders; /* Number of reader locks obtained */
  33448. BOOL bPending; /* Indicates a pending lock has been obtained */
  33449. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  33450. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  33451. } winceLock;
  33452. #endif
  33453. /*
  33454. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  33455. ** portability layer.
  33456. */
  33457. typedef struct winFile winFile;
  33458. struct winFile {
  33459. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  33460. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  33461. HANDLE h; /* Handle for accessing the file */
  33462. u8 locktype; /* Type of lock currently held on this file */
  33463. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  33464. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  33465. DWORD lastErrno; /* The Windows errno from the last I/O error */
  33466. #ifndef SQLITE_OMIT_WAL
  33467. winShm *pShm; /* Instance of shared memory on this file */
  33468. #endif
  33469. const char *zPath; /* Full pathname of this file */
  33470. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  33471. #if SQLITE_OS_WINCE
  33472. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  33473. HANDLE hMutex; /* Mutex used to control access to shared lock */
  33474. HANDLE hShared; /* Shared memory segment used for locking */
  33475. winceLock local; /* Locks obtained by this instance of winFile */
  33476. winceLock *shared; /* Global shared lock memory for the file */
  33477. #endif
  33478. #if SQLITE_MAX_MMAP_SIZE>0
  33479. int nFetchOut; /* Number of outstanding xFetch references */
  33480. HANDLE hMap; /* Handle for accessing memory mapping */
  33481. void *pMapRegion; /* Area memory mapped */
  33482. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  33483. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  33484. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  33485. #endif
  33486. };
  33487. /*
  33488. ** Allowed values for winFile.ctrlFlags
  33489. */
  33490. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  33491. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  33492. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  33493. /*
  33494. * The size of the buffer used by sqlite3_win32_write_debug().
  33495. */
  33496. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  33497. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  33498. #endif
  33499. /*
  33500. * The value used with sqlite3_win32_set_directory() to specify that
  33501. * the data directory should be changed.
  33502. */
  33503. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  33504. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  33505. #endif
  33506. /*
  33507. * The value used with sqlite3_win32_set_directory() to specify that
  33508. * the temporary directory should be changed.
  33509. */
  33510. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  33511. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  33512. #endif
  33513. /*
  33514. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  33515. * various Win32 API heap functions instead of our own.
  33516. */
  33517. #ifdef SQLITE_WIN32_MALLOC
  33518. /*
  33519. * If this is non-zero, an isolated heap will be created by the native Win32
  33520. * allocator subsystem; otherwise, the default process heap will be used. This
  33521. * setting has no effect when compiling for WinRT. By default, this is enabled
  33522. * and an isolated heap will be created to store all allocated data.
  33523. *
  33524. ******************************************************************************
  33525. * WARNING: It is important to note that when this setting is non-zero and the
  33526. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  33527. * function), all data that was allocated using the isolated heap will
  33528. * be freed immediately and any attempt to access any of that freed
  33529. * data will almost certainly result in an immediate access violation.
  33530. ******************************************************************************
  33531. */
  33532. #ifndef SQLITE_WIN32_HEAP_CREATE
  33533. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  33534. #endif
  33535. /*
  33536. * This is cache size used in the calculation of the initial size of the
  33537. * Win32-specific heap. It cannot be negative.
  33538. */
  33539. #ifndef SQLITE_WIN32_CACHE_SIZE
  33540. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  33541. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  33542. # else
  33543. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  33544. # endif
  33545. #endif
  33546. /*
  33547. * The initial size of the Win32-specific heap. This value may be zero.
  33548. */
  33549. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  33550. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  33551. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  33552. #endif
  33553. /*
  33554. * The maximum size of the Win32-specific heap. This value may be zero.
  33555. */
  33556. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  33557. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  33558. #endif
  33559. /*
  33560. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  33561. * zero for the default behavior.
  33562. */
  33563. #ifndef SQLITE_WIN32_HEAP_FLAGS
  33564. # define SQLITE_WIN32_HEAP_FLAGS (0)
  33565. #endif
  33566. /*
  33567. ** The winMemData structure stores information required by the Win32-specific
  33568. ** sqlite3_mem_methods implementation.
  33569. */
  33570. typedef struct winMemData winMemData;
  33571. struct winMemData {
  33572. #ifndef NDEBUG
  33573. u32 magic1; /* Magic number to detect structure corruption. */
  33574. #endif
  33575. HANDLE hHeap; /* The handle to our heap. */
  33576. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  33577. #ifndef NDEBUG
  33578. u32 magic2; /* Magic number to detect structure corruption. */
  33579. #endif
  33580. };
  33581. #ifndef NDEBUG
  33582. #define WINMEM_MAGIC1 0x42b2830b
  33583. #define WINMEM_MAGIC2 0xbd4d7cf4
  33584. #endif
  33585. static struct winMemData win_mem_data = {
  33586. #ifndef NDEBUG
  33587. WINMEM_MAGIC1,
  33588. #endif
  33589. NULL, FALSE
  33590. #ifndef NDEBUG
  33591. ,WINMEM_MAGIC2
  33592. #endif
  33593. };
  33594. #ifndef NDEBUG
  33595. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  33596. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  33597. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  33598. #else
  33599. #define winMemAssertMagic()
  33600. #endif
  33601. #define winMemGetDataPtr() &win_mem_data
  33602. #define winMemGetHeap() win_mem_data.hHeap
  33603. #define winMemGetOwned() win_mem_data.bOwned
  33604. static void *winMemMalloc(int nBytes);
  33605. static void winMemFree(void *pPrior);
  33606. static void *winMemRealloc(void *pPrior, int nBytes);
  33607. static int winMemSize(void *p);
  33608. static int winMemRoundup(int n);
  33609. static int winMemInit(void *pAppData);
  33610. static void winMemShutdown(void *pAppData);
  33611. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  33612. #endif /* SQLITE_WIN32_MALLOC */
  33613. /*
  33614. ** The following variable is (normally) set once and never changes
  33615. ** thereafter. It records whether the operating system is Win9x
  33616. ** or WinNT.
  33617. **
  33618. ** 0: Operating system unknown.
  33619. ** 1: Operating system is Win9x.
  33620. ** 2: Operating system is WinNT.
  33621. **
  33622. ** In order to facilitate testing on a WinNT system, the test fixture
  33623. ** can manually set this value to 1 to emulate Win98 behavior.
  33624. */
  33625. #ifdef SQLITE_TEST
  33626. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  33627. #else
  33628. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  33629. #endif
  33630. #ifndef SYSCALL
  33631. # define SYSCALL sqlite3_syscall_ptr
  33632. #endif
  33633. /*
  33634. ** This function is not available on Windows CE or WinRT.
  33635. */
  33636. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  33637. # define osAreFileApisANSI() 1
  33638. #endif
  33639. /*
  33640. ** Many system calls are accessed through pointer-to-functions so that
  33641. ** they may be overridden at runtime to facilitate fault injection during
  33642. ** testing and sandboxing. The following array holds the names and pointers
  33643. ** to all overrideable system calls.
  33644. */
  33645. static struct win_syscall {
  33646. const char *zName; /* Name of the system call */
  33647. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  33648. sqlite3_syscall_ptr pDefault; /* Default value */
  33649. } aSyscall[] = {
  33650. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33651. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  33652. #else
  33653. { "AreFileApisANSI", (SYSCALL)0, 0 },
  33654. #endif
  33655. #ifndef osAreFileApisANSI
  33656. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  33657. #endif
  33658. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  33659. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  33660. #else
  33661. { "CharLowerW", (SYSCALL)0, 0 },
  33662. #endif
  33663. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  33664. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  33665. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  33666. #else
  33667. { "CharUpperW", (SYSCALL)0, 0 },
  33668. #endif
  33669. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  33670. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  33671. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  33672. #if defined(SQLITE_WIN32_HAS_ANSI)
  33673. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  33674. #else
  33675. { "CreateFileA", (SYSCALL)0, 0 },
  33676. #endif
  33677. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  33678. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  33679. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33680. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  33681. #else
  33682. { "CreateFileW", (SYSCALL)0, 0 },
  33683. #endif
  33684. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  33685. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  33686. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  33687. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  33688. SQLITE_WIN32_CREATEFILEMAPPINGA
  33689. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  33690. #else
  33691. { "CreateFileMappingA", (SYSCALL)0, 0 },
  33692. #endif
  33693. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  33694. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  33695. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33696. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  33697. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  33698. #else
  33699. { "CreateFileMappingW", (SYSCALL)0, 0 },
  33700. #endif
  33701. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  33702. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  33703. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33704. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  33705. #else
  33706. { "CreateMutexW", (SYSCALL)0, 0 },
  33707. #endif
  33708. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  33709. LPCWSTR))aSyscall[8].pCurrent)
  33710. #if defined(SQLITE_WIN32_HAS_ANSI)
  33711. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  33712. #else
  33713. { "DeleteFileA", (SYSCALL)0, 0 },
  33714. #endif
  33715. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  33716. #if defined(SQLITE_WIN32_HAS_WIDE)
  33717. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  33718. #else
  33719. { "DeleteFileW", (SYSCALL)0, 0 },
  33720. #endif
  33721. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  33722. #if SQLITE_OS_WINCE
  33723. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  33724. #else
  33725. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  33726. #endif
  33727. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  33728. LPFILETIME))aSyscall[11].pCurrent)
  33729. #if SQLITE_OS_WINCE
  33730. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  33731. #else
  33732. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  33733. #endif
  33734. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  33735. LPSYSTEMTIME))aSyscall[12].pCurrent)
  33736. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  33737. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  33738. #if defined(SQLITE_WIN32_HAS_ANSI)
  33739. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  33740. #else
  33741. { "FormatMessageA", (SYSCALL)0, 0 },
  33742. #endif
  33743. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  33744. DWORD,va_list*))aSyscall[14].pCurrent)
  33745. #if defined(SQLITE_WIN32_HAS_WIDE)
  33746. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  33747. #else
  33748. { "FormatMessageW", (SYSCALL)0, 0 },
  33749. #endif
  33750. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  33751. DWORD,va_list*))aSyscall[15].pCurrent)
  33752. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33753. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  33754. #else
  33755. { "FreeLibrary", (SYSCALL)0, 0 },
  33756. #endif
  33757. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  33758. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  33759. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  33760. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  33761. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  33762. #else
  33763. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  33764. #endif
  33765. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  33766. LPDWORD))aSyscall[18].pCurrent)
  33767. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33768. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  33769. #else
  33770. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  33771. #endif
  33772. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  33773. LPDWORD))aSyscall[19].pCurrent)
  33774. #if defined(SQLITE_WIN32_HAS_ANSI)
  33775. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  33776. #else
  33777. { "GetFileAttributesA", (SYSCALL)0, 0 },
  33778. #endif
  33779. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  33780. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33781. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  33782. #else
  33783. { "GetFileAttributesW", (SYSCALL)0, 0 },
  33784. #endif
  33785. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  33786. #if defined(SQLITE_WIN32_HAS_WIDE)
  33787. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  33788. #else
  33789. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  33790. #endif
  33791. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  33792. LPVOID))aSyscall[22].pCurrent)
  33793. #if !SQLITE_OS_WINRT
  33794. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  33795. #else
  33796. { "GetFileSize", (SYSCALL)0, 0 },
  33797. #endif
  33798. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  33799. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  33800. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  33801. #else
  33802. { "GetFullPathNameA", (SYSCALL)0, 0 },
  33803. #endif
  33804. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  33805. LPSTR*))aSyscall[24].pCurrent)
  33806. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33807. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  33808. #else
  33809. { "GetFullPathNameW", (SYSCALL)0, 0 },
  33810. #endif
  33811. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  33812. LPWSTR*))aSyscall[25].pCurrent)
  33813. { "GetLastError", (SYSCALL)GetLastError, 0 },
  33814. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  33815. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33816. #if SQLITE_OS_WINCE
  33817. /* The GetProcAddressA() routine is only available on Windows CE. */
  33818. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  33819. #else
  33820. /* All other Windows platforms expect GetProcAddress() to take
  33821. ** an ANSI string regardless of the _UNICODE setting */
  33822. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  33823. #endif
  33824. #else
  33825. { "GetProcAddressA", (SYSCALL)0, 0 },
  33826. #endif
  33827. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  33828. LPCSTR))aSyscall[27].pCurrent)
  33829. #if !SQLITE_OS_WINRT
  33830. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  33831. #else
  33832. { "GetSystemInfo", (SYSCALL)0, 0 },
  33833. #endif
  33834. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  33835. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  33836. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  33837. #if !SQLITE_OS_WINCE
  33838. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  33839. #else
  33840. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  33841. #endif
  33842. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  33843. LPFILETIME))aSyscall[30].pCurrent)
  33844. #if defined(SQLITE_WIN32_HAS_ANSI)
  33845. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  33846. #else
  33847. { "GetTempPathA", (SYSCALL)0, 0 },
  33848. #endif
  33849. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  33850. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33851. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  33852. #else
  33853. { "GetTempPathW", (SYSCALL)0, 0 },
  33854. #endif
  33855. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  33856. #if !SQLITE_OS_WINRT
  33857. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  33858. #else
  33859. { "GetTickCount", (SYSCALL)0, 0 },
  33860. #endif
  33861. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  33862. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  33863. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  33864. #else
  33865. { "GetVersionExA", (SYSCALL)0, 0 },
  33866. #endif
  33867. #define osGetVersionExA ((BOOL(WINAPI*)( \
  33868. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  33869. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33870. SQLITE_WIN32_GETVERSIONEX
  33871. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  33872. #else
  33873. { "GetVersionExW", (SYSCALL)0, 0 },
  33874. #endif
  33875. #define osGetVersionExW ((BOOL(WINAPI*)( \
  33876. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  33877. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  33878. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  33879. SIZE_T))aSyscall[36].pCurrent)
  33880. #if !SQLITE_OS_WINRT
  33881. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  33882. #else
  33883. { "HeapCreate", (SYSCALL)0, 0 },
  33884. #endif
  33885. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  33886. SIZE_T))aSyscall[37].pCurrent)
  33887. #if !SQLITE_OS_WINRT
  33888. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  33889. #else
  33890. { "HeapDestroy", (SYSCALL)0, 0 },
  33891. #endif
  33892. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  33893. { "HeapFree", (SYSCALL)HeapFree, 0 },
  33894. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  33895. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  33896. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  33897. SIZE_T))aSyscall[40].pCurrent)
  33898. { "HeapSize", (SYSCALL)HeapSize, 0 },
  33899. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  33900. LPCVOID))aSyscall[41].pCurrent)
  33901. #if !SQLITE_OS_WINRT
  33902. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  33903. #else
  33904. { "HeapValidate", (SYSCALL)0, 0 },
  33905. #endif
  33906. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  33907. LPCVOID))aSyscall[42].pCurrent)
  33908. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33909. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  33910. #else
  33911. { "HeapCompact", (SYSCALL)0, 0 },
  33912. #endif
  33913. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  33914. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33915. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  33916. #else
  33917. { "LoadLibraryA", (SYSCALL)0, 0 },
  33918. #endif
  33919. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  33920. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33921. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33922. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  33923. #else
  33924. { "LoadLibraryW", (SYSCALL)0, 0 },
  33925. #endif
  33926. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  33927. #if !SQLITE_OS_WINRT
  33928. { "LocalFree", (SYSCALL)LocalFree, 0 },
  33929. #else
  33930. { "LocalFree", (SYSCALL)0, 0 },
  33931. #endif
  33932. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  33933. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33934. { "LockFile", (SYSCALL)LockFile, 0 },
  33935. #else
  33936. { "LockFile", (SYSCALL)0, 0 },
  33937. #endif
  33938. #ifndef osLockFile
  33939. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33940. DWORD))aSyscall[47].pCurrent)
  33941. #endif
  33942. #if !SQLITE_OS_WINCE
  33943. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  33944. #else
  33945. { "LockFileEx", (SYSCALL)0, 0 },
  33946. #endif
  33947. #ifndef osLockFileEx
  33948. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  33949. LPOVERLAPPED))aSyscall[48].pCurrent)
  33950. #endif
  33951. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  33952. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  33953. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  33954. #else
  33955. { "MapViewOfFile", (SYSCALL)0, 0 },
  33956. #endif
  33957. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33958. SIZE_T))aSyscall[49].pCurrent)
  33959. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  33960. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  33961. int))aSyscall[50].pCurrent)
  33962. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  33963. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  33964. LARGE_INTEGER*))aSyscall[51].pCurrent)
  33965. { "ReadFile", (SYSCALL)ReadFile, 0 },
  33966. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  33967. LPOVERLAPPED))aSyscall[52].pCurrent)
  33968. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  33969. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  33970. #if !SQLITE_OS_WINRT
  33971. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  33972. #else
  33973. { "SetFilePointer", (SYSCALL)0, 0 },
  33974. #endif
  33975. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  33976. DWORD))aSyscall[54].pCurrent)
  33977. #if !SQLITE_OS_WINRT
  33978. { "Sleep", (SYSCALL)Sleep, 0 },
  33979. #else
  33980. { "Sleep", (SYSCALL)0, 0 },
  33981. #endif
  33982. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  33983. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  33984. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  33985. LPFILETIME))aSyscall[56].pCurrent)
  33986. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33987. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  33988. #else
  33989. { "UnlockFile", (SYSCALL)0, 0 },
  33990. #endif
  33991. #ifndef osUnlockFile
  33992. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33993. DWORD))aSyscall[57].pCurrent)
  33994. #endif
  33995. #if !SQLITE_OS_WINCE
  33996. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  33997. #else
  33998. { "UnlockFileEx", (SYSCALL)0, 0 },
  33999. #endif
  34000. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  34001. LPOVERLAPPED))aSyscall[58].pCurrent)
  34002. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  34003. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  34004. #else
  34005. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  34006. #endif
  34007. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  34008. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  34009. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  34010. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  34011. { "WriteFile", (SYSCALL)WriteFile, 0 },
  34012. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  34013. LPOVERLAPPED))aSyscall[61].pCurrent)
  34014. #if SQLITE_OS_WINRT
  34015. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  34016. #else
  34017. { "CreateEventExW", (SYSCALL)0, 0 },
  34018. #endif
  34019. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  34020. DWORD,DWORD))aSyscall[62].pCurrent)
  34021. #if !SQLITE_OS_WINRT
  34022. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  34023. #else
  34024. { "WaitForSingleObject", (SYSCALL)0, 0 },
  34025. #endif
  34026. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  34027. DWORD))aSyscall[63].pCurrent)
  34028. #if !SQLITE_OS_WINCE
  34029. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  34030. #else
  34031. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  34032. #endif
  34033. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  34034. BOOL))aSyscall[64].pCurrent)
  34035. #if SQLITE_OS_WINRT
  34036. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  34037. #else
  34038. { "SetFilePointerEx", (SYSCALL)0, 0 },
  34039. #endif
  34040. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  34041. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  34042. #if SQLITE_OS_WINRT
  34043. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  34044. #else
  34045. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  34046. #endif
  34047. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  34048. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  34049. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  34050. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  34051. #else
  34052. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  34053. #endif
  34054. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  34055. SIZE_T))aSyscall[67].pCurrent)
  34056. #if SQLITE_OS_WINRT
  34057. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  34058. #else
  34059. { "CreateFile2", (SYSCALL)0, 0 },
  34060. #endif
  34061. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  34062. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  34063. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  34064. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  34065. #else
  34066. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  34067. #endif
  34068. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  34069. DWORD))aSyscall[69].pCurrent)
  34070. #if SQLITE_OS_WINRT
  34071. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  34072. #else
  34073. { "GetTickCount64", (SYSCALL)0, 0 },
  34074. #endif
  34075. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  34076. #if SQLITE_OS_WINRT
  34077. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  34078. #else
  34079. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  34080. #endif
  34081. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  34082. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  34083. #if defined(SQLITE_WIN32_HAS_ANSI)
  34084. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  34085. #else
  34086. { "OutputDebugStringA", (SYSCALL)0, 0 },
  34087. #endif
  34088. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  34089. #if defined(SQLITE_WIN32_HAS_WIDE)
  34090. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  34091. #else
  34092. { "OutputDebugStringW", (SYSCALL)0, 0 },
  34093. #endif
  34094. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  34095. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  34096. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  34097. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  34098. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  34099. #else
  34100. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  34101. #endif
  34102. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  34103. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  34104. /*
  34105. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  34106. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  34107. ** So do not try to make this is into a redefinable interface.
  34108. */
  34109. #if defined(InterlockedCompareExchange)
  34110. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  34111. #define osInterlockedCompareExchange InterlockedCompareExchange
  34112. #else
  34113. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  34114. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  34115. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  34116. #endif /* defined(InterlockedCompareExchange) */
  34117. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  34118. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  34119. #else
  34120. { "UuidCreate", (SYSCALL)0, 0 },
  34121. #endif
  34122. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  34123. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  34124. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  34125. #else
  34126. { "UuidCreateSequential", (SYSCALL)0, 0 },
  34127. #endif
  34128. #define osUuidCreateSequential \
  34129. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  34130. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  34131. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  34132. #else
  34133. { "FlushViewOfFile", (SYSCALL)0, 0 },
  34134. #endif
  34135. #define osFlushViewOfFile \
  34136. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  34137. }; /* End of the overrideable system calls */
  34138. /*
  34139. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  34140. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  34141. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  34142. ** system call named zName.
  34143. */
  34144. static int winSetSystemCall(
  34145. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  34146. const char *zName, /* Name of system call to override */
  34147. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  34148. ){
  34149. unsigned int i;
  34150. int rc = SQLITE_NOTFOUND;
  34151. UNUSED_PARAMETER(pNotUsed);
  34152. if( zName==0 ){
  34153. /* If no zName is given, restore all system calls to their default
  34154. ** settings and return NULL
  34155. */
  34156. rc = SQLITE_OK;
  34157. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34158. if( aSyscall[i].pDefault ){
  34159. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  34160. }
  34161. }
  34162. }else{
  34163. /* If zName is specified, operate on only the one system call
  34164. ** specified.
  34165. */
  34166. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34167. if( strcmp(zName, aSyscall[i].zName)==0 ){
  34168. if( aSyscall[i].pDefault==0 ){
  34169. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  34170. }
  34171. rc = SQLITE_OK;
  34172. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  34173. aSyscall[i].pCurrent = pNewFunc;
  34174. break;
  34175. }
  34176. }
  34177. }
  34178. return rc;
  34179. }
  34180. /*
  34181. ** Return the value of a system call. Return NULL if zName is not a
  34182. ** recognized system call name. NULL is also returned if the system call
  34183. ** is currently undefined.
  34184. */
  34185. static sqlite3_syscall_ptr winGetSystemCall(
  34186. sqlite3_vfs *pNotUsed,
  34187. const char *zName
  34188. ){
  34189. unsigned int i;
  34190. UNUSED_PARAMETER(pNotUsed);
  34191. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34192. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  34193. }
  34194. return 0;
  34195. }
  34196. /*
  34197. ** Return the name of the first system call after zName. If zName==NULL
  34198. ** then return the name of the first system call. Return NULL if zName
  34199. ** is the last system call or if zName is not the name of a valid
  34200. ** system call.
  34201. */
  34202. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  34203. int i = -1;
  34204. UNUSED_PARAMETER(p);
  34205. if( zName ){
  34206. for(i=0; i<ArraySize(aSyscall)-1; i++){
  34207. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  34208. }
  34209. }
  34210. for(i++; i<ArraySize(aSyscall); i++){
  34211. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  34212. }
  34213. return 0;
  34214. }
  34215. #ifdef SQLITE_WIN32_MALLOC
  34216. /*
  34217. ** If a Win32 native heap has been configured, this function will attempt to
  34218. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  34219. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  34220. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  34221. ** largest committed free block in the heap, in bytes.
  34222. */
  34223. SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
  34224. int rc = SQLITE_OK;
  34225. UINT nLargest = 0;
  34226. HANDLE hHeap;
  34227. winMemAssertMagic();
  34228. hHeap = winMemGetHeap();
  34229. assert( hHeap!=0 );
  34230. assert( hHeap!=INVALID_HANDLE_VALUE );
  34231. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34232. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  34233. #endif
  34234. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  34235. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  34236. DWORD lastErrno = osGetLastError();
  34237. if( lastErrno==NO_ERROR ){
  34238. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  34239. (void*)hHeap);
  34240. rc = SQLITE_NOMEM_BKPT;
  34241. }else{
  34242. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  34243. osGetLastError(), (void*)hHeap);
  34244. rc = SQLITE_ERROR;
  34245. }
  34246. }
  34247. #else
  34248. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  34249. (void*)hHeap);
  34250. rc = SQLITE_NOTFOUND;
  34251. #endif
  34252. if( pnLargest ) *pnLargest = nLargest;
  34253. return rc;
  34254. }
  34255. /*
  34256. ** If a Win32 native heap has been configured, this function will attempt to
  34257. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  34258. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  34259. ** be returned and no changes will be made to the Win32 native heap.
  34260. */
  34261. SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
  34262. int rc;
  34263. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  34264. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  34265. MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
  34266. MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
  34267. sqlite3_mutex_enter(pMaster);
  34268. sqlite3_mutex_enter(pMem);
  34269. winMemAssertMagic();
  34270. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  34271. /*
  34272. ** At this point, there should be no outstanding memory allocations on
  34273. ** the heap. Also, since both the master and memsys locks are currently
  34274. ** being held by us, no other function (i.e. from another thread) should
  34275. ** be able to even access the heap. Attempt to destroy and recreate our
  34276. ** isolated Win32 native heap now.
  34277. */
  34278. assert( winMemGetHeap()!=NULL );
  34279. assert( winMemGetOwned() );
  34280. assert( sqlite3_memory_used()==0 );
  34281. winMemShutdown(winMemGetDataPtr());
  34282. assert( winMemGetHeap()==NULL );
  34283. assert( !winMemGetOwned() );
  34284. assert( sqlite3_memory_used()==0 );
  34285. rc = winMemInit(winMemGetDataPtr());
  34286. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  34287. assert( rc!=SQLITE_OK || winMemGetOwned() );
  34288. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  34289. }else{
  34290. /*
  34291. ** The Win32 native heap cannot be modified because it may be in use.
  34292. */
  34293. rc = SQLITE_BUSY;
  34294. }
  34295. sqlite3_mutex_leave(pMem);
  34296. sqlite3_mutex_leave(pMaster);
  34297. return rc;
  34298. }
  34299. #endif /* SQLITE_WIN32_MALLOC */
  34300. /*
  34301. ** This function outputs the specified (ANSI) string to the Win32 debugger
  34302. ** (if available).
  34303. */
  34304. SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  34305. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  34306. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  34307. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  34308. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  34309. #if defined(SQLITE_WIN32_HAS_ANSI)
  34310. if( nMin>0 ){
  34311. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  34312. memcpy(zDbgBuf, zBuf, nMin);
  34313. osOutputDebugStringA(zDbgBuf);
  34314. }else{
  34315. osOutputDebugStringA(zBuf);
  34316. }
  34317. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34318. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  34319. if ( osMultiByteToWideChar(
  34320. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  34321. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  34322. return;
  34323. }
  34324. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  34325. #else
  34326. if( nMin>0 ){
  34327. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  34328. memcpy(zDbgBuf, zBuf, nMin);
  34329. fprintf(stderr, "%s", zDbgBuf);
  34330. }else{
  34331. fprintf(stderr, "%s", zBuf);
  34332. }
  34333. #endif
  34334. }
  34335. /*
  34336. ** The following routine suspends the current thread for at least ms
  34337. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  34338. */
  34339. #if SQLITE_OS_WINRT
  34340. static HANDLE sleepObj = NULL;
  34341. #endif
  34342. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
  34343. #if SQLITE_OS_WINRT
  34344. if ( sleepObj==NULL ){
  34345. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  34346. SYNCHRONIZE);
  34347. }
  34348. assert( sleepObj!=NULL );
  34349. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  34350. #else
  34351. osSleep(milliseconds);
  34352. #endif
  34353. }
  34354. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  34355. SQLITE_THREADSAFE>0
  34356. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  34357. DWORD rc;
  34358. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  34359. TRUE))==WAIT_IO_COMPLETION ){}
  34360. return rc;
  34361. }
  34362. #endif
  34363. /*
  34364. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  34365. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  34366. **
  34367. ** Here is an interesting observation: Win95, Win98, and WinME lack
  34368. ** the LockFileEx() API. But we can still statically link against that
  34369. ** API as long as we don't call it when running Win95/98/ME. A call to
  34370. ** this routine is used to determine if the host is Win95/98/ME or
  34371. ** WinNT/2K/XP so that we will know whether or not we can safely call
  34372. ** the LockFileEx() API.
  34373. */
  34374. #if !SQLITE_WIN32_GETVERSIONEX
  34375. # define osIsNT() (1)
  34376. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  34377. # define osIsNT() (1)
  34378. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  34379. # define osIsNT() (0)
  34380. #else
  34381. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  34382. #endif
  34383. /*
  34384. ** This function determines if the machine is running a version of Windows
  34385. ** based on the NT kernel.
  34386. */
  34387. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
  34388. #if SQLITE_OS_WINRT
  34389. /*
  34390. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  34391. ** kernel.
  34392. */
  34393. return 1;
  34394. #elif SQLITE_WIN32_GETVERSIONEX
  34395. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  34396. #if defined(SQLITE_WIN32_HAS_ANSI)
  34397. OSVERSIONINFOA sInfo;
  34398. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  34399. osGetVersionExA(&sInfo);
  34400. osInterlockedCompareExchange(&sqlite3_os_type,
  34401. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  34402. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34403. OSVERSIONINFOW sInfo;
  34404. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  34405. osGetVersionExW(&sInfo);
  34406. osInterlockedCompareExchange(&sqlite3_os_type,
  34407. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  34408. #endif
  34409. }
  34410. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  34411. #elif SQLITE_TEST
  34412. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  34413. #else
  34414. /*
  34415. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  34416. ** deprecated are always assumed to be based on the NT kernel.
  34417. */
  34418. return 1;
  34419. #endif
  34420. }
  34421. #ifdef SQLITE_WIN32_MALLOC
  34422. /*
  34423. ** Allocate nBytes of memory.
  34424. */
  34425. static void *winMemMalloc(int nBytes){
  34426. HANDLE hHeap;
  34427. void *p;
  34428. winMemAssertMagic();
  34429. hHeap = winMemGetHeap();
  34430. assert( hHeap!=0 );
  34431. assert( hHeap!=INVALID_HANDLE_VALUE );
  34432. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34433. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  34434. #endif
  34435. assert( nBytes>=0 );
  34436. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  34437. if( !p ){
  34438. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  34439. nBytes, osGetLastError(), (void*)hHeap);
  34440. }
  34441. return p;
  34442. }
  34443. /*
  34444. ** Free memory.
  34445. */
  34446. static void winMemFree(void *pPrior){
  34447. HANDLE hHeap;
  34448. winMemAssertMagic();
  34449. hHeap = winMemGetHeap();
  34450. assert( hHeap!=0 );
  34451. assert( hHeap!=INVALID_HANDLE_VALUE );
  34452. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34453. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  34454. #endif
  34455. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  34456. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  34457. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  34458. pPrior, osGetLastError(), (void*)hHeap);
  34459. }
  34460. }
  34461. /*
  34462. ** Change the size of an existing memory allocation
  34463. */
  34464. static void *winMemRealloc(void *pPrior, int nBytes){
  34465. HANDLE hHeap;
  34466. void *p;
  34467. winMemAssertMagic();
  34468. hHeap = winMemGetHeap();
  34469. assert( hHeap!=0 );
  34470. assert( hHeap!=INVALID_HANDLE_VALUE );
  34471. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34472. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  34473. #endif
  34474. assert( nBytes>=0 );
  34475. if( !pPrior ){
  34476. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  34477. }else{
  34478. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  34479. }
  34480. if( !p ){
  34481. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  34482. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  34483. (void*)hHeap);
  34484. }
  34485. return p;
  34486. }
  34487. /*
  34488. ** Return the size of an outstanding allocation, in bytes.
  34489. */
  34490. static int winMemSize(void *p){
  34491. HANDLE hHeap;
  34492. SIZE_T n;
  34493. winMemAssertMagic();
  34494. hHeap = winMemGetHeap();
  34495. assert( hHeap!=0 );
  34496. assert( hHeap!=INVALID_HANDLE_VALUE );
  34497. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34498. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  34499. #endif
  34500. if( !p ) return 0;
  34501. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  34502. if( n==(SIZE_T)-1 ){
  34503. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  34504. p, osGetLastError(), (void*)hHeap);
  34505. return 0;
  34506. }
  34507. return (int)n;
  34508. }
  34509. /*
  34510. ** Round up a request size to the next valid allocation size.
  34511. */
  34512. static int winMemRoundup(int n){
  34513. return n;
  34514. }
  34515. /*
  34516. ** Initialize this module.
  34517. */
  34518. static int winMemInit(void *pAppData){
  34519. winMemData *pWinMemData = (winMemData *)pAppData;
  34520. if( !pWinMemData ) return SQLITE_ERROR;
  34521. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  34522. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  34523. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  34524. if( !pWinMemData->hHeap ){
  34525. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  34526. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  34527. if( dwMaximumSize==0 ){
  34528. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  34529. }else if( dwInitialSize>dwMaximumSize ){
  34530. dwInitialSize = dwMaximumSize;
  34531. }
  34532. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  34533. dwInitialSize, dwMaximumSize);
  34534. if( !pWinMemData->hHeap ){
  34535. sqlite3_log(SQLITE_NOMEM,
  34536. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  34537. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  34538. dwMaximumSize);
  34539. return SQLITE_NOMEM_BKPT;
  34540. }
  34541. pWinMemData->bOwned = TRUE;
  34542. assert( pWinMemData->bOwned );
  34543. }
  34544. #else
  34545. pWinMemData->hHeap = osGetProcessHeap();
  34546. if( !pWinMemData->hHeap ){
  34547. sqlite3_log(SQLITE_NOMEM,
  34548. "failed to GetProcessHeap (%lu)", osGetLastError());
  34549. return SQLITE_NOMEM_BKPT;
  34550. }
  34551. pWinMemData->bOwned = FALSE;
  34552. assert( !pWinMemData->bOwned );
  34553. #endif
  34554. assert( pWinMemData->hHeap!=0 );
  34555. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  34556. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34557. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  34558. #endif
  34559. return SQLITE_OK;
  34560. }
  34561. /*
  34562. ** Deinitialize this module.
  34563. */
  34564. static void winMemShutdown(void *pAppData){
  34565. winMemData *pWinMemData = (winMemData *)pAppData;
  34566. if( !pWinMemData ) return;
  34567. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  34568. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  34569. if( pWinMemData->hHeap ){
  34570. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  34571. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34572. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  34573. #endif
  34574. if( pWinMemData->bOwned ){
  34575. if( !osHeapDestroy(pWinMemData->hHeap) ){
  34576. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  34577. osGetLastError(), (void*)pWinMemData->hHeap);
  34578. }
  34579. pWinMemData->bOwned = FALSE;
  34580. }
  34581. pWinMemData->hHeap = NULL;
  34582. }
  34583. }
  34584. /*
  34585. ** Populate the low-level memory allocation function pointers in
  34586. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  34587. ** arguments specify the block of memory to manage.
  34588. **
  34589. ** This routine is only called by sqlite3_config(), and therefore
  34590. ** is not required to be threadsafe (it is not).
  34591. */
  34592. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  34593. static const sqlite3_mem_methods winMemMethods = {
  34594. winMemMalloc,
  34595. winMemFree,
  34596. winMemRealloc,
  34597. winMemSize,
  34598. winMemRoundup,
  34599. winMemInit,
  34600. winMemShutdown,
  34601. &win_mem_data
  34602. };
  34603. return &winMemMethods;
  34604. }
  34605. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  34606. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  34607. }
  34608. #endif /* SQLITE_WIN32_MALLOC */
  34609. /*
  34610. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  34611. **
  34612. ** Space to hold the returned string is obtained from malloc.
  34613. */
  34614. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  34615. int nChar;
  34616. LPWSTR zWideFilename;
  34617. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  34618. if( nChar==0 ){
  34619. return 0;
  34620. }
  34621. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  34622. if( zWideFilename==0 ){
  34623. return 0;
  34624. }
  34625. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  34626. nChar);
  34627. if( nChar==0 ){
  34628. sqlite3_free(zWideFilename);
  34629. zWideFilename = 0;
  34630. }
  34631. return zWideFilename;
  34632. }
  34633. /*
  34634. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  34635. ** obtained from sqlite3_malloc().
  34636. */
  34637. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  34638. int nByte;
  34639. char *zFilename;
  34640. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  34641. if( nByte == 0 ){
  34642. return 0;
  34643. }
  34644. zFilename = sqlite3MallocZero( nByte );
  34645. if( zFilename==0 ){
  34646. return 0;
  34647. }
  34648. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  34649. 0, 0);
  34650. if( nByte == 0 ){
  34651. sqlite3_free(zFilename);
  34652. zFilename = 0;
  34653. }
  34654. return zFilename;
  34655. }
  34656. /*
  34657. ** Convert an ANSI string to Microsoft Unicode, based on the
  34658. ** current codepage settings for file apis.
  34659. **
  34660. ** Space to hold the returned string is obtained
  34661. ** from sqlite3_malloc.
  34662. */
  34663. static LPWSTR winMbcsToUnicode(const char *zFilename){
  34664. int nByte;
  34665. LPWSTR zMbcsFilename;
  34666. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  34667. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  34668. 0)*sizeof(WCHAR);
  34669. if( nByte==0 ){
  34670. return 0;
  34671. }
  34672. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  34673. if( zMbcsFilename==0 ){
  34674. return 0;
  34675. }
  34676. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  34677. nByte);
  34678. if( nByte==0 ){
  34679. sqlite3_free(zMbcsFilename);
  34680. zMbcsFilename = 0;
  34681. }
  34682. return zMbcsFilename;
  34683. }
  34684. /*
  34685. ** Convert Microsoft Unicode to multi-byte character string, based on the
  34686. ** user's ANSI codepage.
  34687. **
  34688. ** Space to hold the returned string is obtained from
  34689. ** sqlite3_malloc().
  34690. */
  34691. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  34692. int nByte;
  34693. char *zFilename;
  34694. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  34695. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  34696. if( nByte == 0 ){
  34697. return 0;
  34698. }
  34699. zFilename = sqlite3MallocZero( nByte );
  34700. if( zFilename==0 ){
  34701. return 0;
  34702. }
  34703. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  34704. nByte, 0, 0);
  34705. if( nByte == 0 ){
  34706. sqlite3_free(zFilename);
  34707. zFilename = 0;
  34708. }
  34709. return zFilename;
  34710. }
  34711. /*
  34712. ** Convert multibyte character string to UTF-8. Space to hold the
  34713. ** returned string is obtained from sqlite3_malloc().
  34714. */
  34715. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  34716. char *zFilenameUtf8;
  34717. LPWSTR zTmpWide;
  34718. zTmpWide = winMbcsToUnicode(zFilename);
  34719. if( zTmpWide==0 ){
  34720. return 0;
  34721. }
  34722. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  34723. sqlite3_free(zTmpWide);
  34724. return zFilenameUtf8;
  34725. }
  34726. /*
  34727. ** Convert UTF-8 to multibyte character string. Space to hold the
  34728. ** returned string is obtained from sqlite3_malloc().
  34729. */
  34730. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  34731. char *zFilenameMbcs;
  34732. LPWSTR zTmpWide;
  34733. zTmpWide = winUtf8ToUnicode(zFilename);
  34734. if( zTmpWide==0 ){
  34735. return 0;
  34736. }
  34737. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  34738. sqlite3_free(zTmpWide);
  34739. return zFilenameMbcs;
  34740. }
  34741. /*
  34742. ** This function sets the data directory or the temporary directory based on
  34743. ** the provided arguments. The type argument must be 1 in order to set the
  34744. ** data directory or 2 in order to set the temporary directory. The zValue
  34745. ** argument is the name of the directory to use. The return value will be
  34746. ** SQLITE_OK if successful.
  34747. */
  34748. SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  34749. char **ppDirectory = 0;
  34750. #ifndef SQLITE_OMIT_AUTOINIT
  34751. int rc = sqlite3_initialize();
  34752. if( rc ) return rc;
  34753. #endif
  34754. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  34755. ppDirectory = &sqlite3_data_directory;
  34756. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  34757. ppDirectory = &sqlite3_temp_directory;
  34758. }
  34759. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  34760. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  34761. );
  34762. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  34763. if( ppDirectory ){
  34764. char *zValueUtf8 = 0;
  34765. if( zValue && zValue[0] ){
  34766. zValueUtf8 = winUnicodeToUtf8(zValue);
  34767. if ( zValueUtf8==0 ){
  34768. return SQLITE_NOMEM_BKPT;
  34769. }
  34770. }
  34771. sqlite3_free(*ppDirectory);
  34772. *ppDirectory = zValueUtf8;
  34773. return SQLITE_OK;
  34774. }
  34775. return SQLITE_ERROR;
  34776. }
  34777. /*
  34778. ** The return value of winGetLastErrorMsg
  34779. ** is zero if the error message fits in the buffer, or non-zero
  34780. ** otherwise (if the message was truncated).
  34781. */
  34782. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  34783. /* FormatMessage returns 0 on failure. Otherwise it
  34784. ** returns the number of TCHARs written to the output
  34785. ** buffer, excluding the terminating null char.
  34786. */
  34787. DWORD dwLen = 0;
  34788. char *zOut = 0;
  34789. if( osIsNT() ){
  34790. #if SQLITE_OS_WINRT
  34791. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  34792. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  34793. FORMAT_MESSAGE_IGNORE_INSERTS,
  34794. NULL,
  34795. lastErrno,
  34796. 0,
  34797. zTempWide,
  34798. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  34799. 0);
  34800. #else
  34801. LPWSTR zTempWide = NULL;
  34802. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  34803. FORMAT_MESSAGE_FROM_SYSTEM |
  34804. FORMAT_MESSAGE_IGNORE_INSERTS,
  34805. NULL,
  34806. lastErrno,
  34807. 0,
  34808. (LPWSTR) &zTempWide,
  34809. 0,
  34810. 0);
  34811. #endif
  34812. if( dwLen > 0 ){
  34813. /* allocate a buffer and convert to UTF8 */
  34814. sqlite3BeginBenignMalloc();
  34815. zOut = winUnicodeToUtf8(zTempWide);
  34816. sqlite3EndBenignMalloc();
  34817. #if !SQLITE_OS_WINRT
  34818. /* free the system buffer allocated by FormatMessage */
  34819. osLocalFree(zTempWide);
  34820. #endif
  34821. }
  34822. }
  34823. #ifdef SQLITE_WIN32_HAS_ANSI
  34824. else{
  34825. char *zTemp = NULL;
  34826. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  34827. FORMAT_MESSAGE_FROM_SYSTEM |
  34828. FORMAT_MESSAGE_IGNORE_INSERTS,
  34829. NULL,
  34830. lastErrno,
  34831. 0,
  34832. (LPSTR) &zTemp,
  34833. 0,
  34834. 0);
  34835. if( dwLen > 0 ){
  34836. /* allocate a buffer and convert to UTF8 */
  34837. sqlite3BeginBenignMalloc();
  34838. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  34839. sqlite3EndBenignMalloc();
  34840. /* free the system buffer allocated by FormatMessage */
  34841. osLocalFree(zTemp);
  34842. }
  34843. }
  34844. #endif
  34845. if( 0 == dwLen ){
  34846. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  34847. }else{
  34848. /* copy a maximum of nBuf chars to output buffer */
  34849. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  34850. /* free the UTF8 buffer */
  34851. sqlite3_free(zOut);
  34852. }
  34853. return 0;
  34854. }
  34855. /*
  34856. **
  34857. ** This function - winLogErrorAtLine() - is only ever called via the macro
  34858. ** winLogError().
  34859. **
  34860. ** This routine is invoked after an error occurs in an OS function.
  34861. ** It logs a message using sqlite3_log() containing the current value of
  34862. ** error code and, if possible, the human-readable equivalent from
  34863. ** FormatMessage.
  34864. **
  34865. ** The first argument passed to the macro should be the error code that
  34866. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  34867. ** The two subsequent arguments should be the name of the OS function that
  34868. ** failed and the associated file-system path, if any.
  34869. */
  34870. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  34871. static int winLogErrorAtLine(
  34872. int errcode, /* SQLite error code */
  34873. DWORD lastErrno, /* Win32 last error */
  34874. const char *zFunc, /* Name of OS function that failed */
  34875. const char *zPath, /* File path associated with error */
  34876. int iLine /* Source line number where error occurred */
  34877. ){
  34878. char zMsg[500]; /* Human readable error text */
  34879. int i; /* Loop counter */
  34880. zMsg[0] = 0;
  34881. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  34882. assert( errcode!=SQLITE_OK );
  34883. if( zPath==0 ) zPath = "";
  34884. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  34885. zMsg[i] = 0;
  34886. sqlite3_log(errcode,
  34887. "os_win.c:%d: (%lu) %s(%s) - %s",
  34888. iLine, lastErrno, zFunc, zPath, zMsg
  34889. );
  34890. return errcode;
  34891. }
  34892. /*
  34893. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  34894. ** will be retried following a locking error - probably caused by
  34895. ** antivirus software. Also the initial delay before the first retry.
  34896. ** The delay increases linearly with each retry.
  34897. */
  34898. #ifndef SQLITE_WIN32_IOERR_RETRY
  34899. # define SQLITE_WIN32_IOERR_RETRY 10
  34900. #endif
  34901. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  34902. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  34903. #endif
  34904. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  34905. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  34906. /*
  34907. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  34908. ** error code obtained via GetLastError() is eligible to be retried. It
  34909. ** must accept the error code DWORD as its only argument and should return
  34910. ** non-zero if the error code is transient in nature and the operation
  34911. ** responsible for generating the original error might succeed upon being
  34912. ** retried. The argument to this macro should be a variable.
  34913. **
  34914. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  34915. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  34916. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  34917. ** may be used to include additional error codes in the set that should
  34918. ** result in the failing I/O operation being retried by the caller. If
  34919. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  34920. ** identical to those of the "winIoerrCanRetry1" macro.
  34921. */
  34922. #if !defined(winIoerrCanRetry1)
  34923. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  34924. ((a)==ERROR_SHARING_VIOLATION) || \
  34925. ((a)==ERROR_LOCK_VIOLATION) || \
  34926. ((a)==ERROR_DEV_NOT_EXIST) || \
  34927. ((a)==ERROR_NETNAME_DELETED) || \
  34928. ((a)==ERROR_SEM_TIMEOUT) || \
  34929. ((a)==ERROR_NETWORK_UNREACHABLE))
  34930. #endif
  34931. /*
  34932. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  34933. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  34934. ** to give up with an error.
  34935. */
  34936. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  34937. DWORD e = osGetLastError();
  34938. if( *pnRetry>=winIoerrRetry ){
  34939. if( pError ){
  34940. *pError = e;
  34941. }
  34942. return 0;
  34943. }
  34944. if( winIoerrCanRetry1(e) ){
  34945. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  34946. ++*pnRetry;
  34947. return 1;
  34948. }
  34949. #if defined(winIoerrCanRetry2)
  34950. else if( winIoerrCanRetry2(e) ){
  34951. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  34952. ++*pnRetry;
  34953. return 1;
  34954. }
  34955. #endif
  34956. if( pError ){
  34957. *pError = e;
  34958. }
  34959. return 0;
  34960. }
  34961. /*
  34962. ** Log a I/O error retry episode.
  34963. */
  34964. static void winLogIoerr(int nRetry, int lineno){
  34965. if( nRetry ){
  34966. sqlite3_log(SQLITE_NOTICE,
  34967. "delayed %dms for lock/sharing conflict at line %d",
  34968. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  34969. );
  34970. }
  34971. }
  34972. #if SQLITE_OS_WINCE
  34973. /*************************************************************************
  34974. ** This section contains code for WinCE only.
  34975. */
  34976. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  34977. /*
  34978. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  34979. ** create a substitute.
  34980. */
  34981. /* #include <time.h> */
  34982. struct tm *__cdecl localtime(const time_t *t)
  34983. {
  34984. static struct tm y;
  34985. FILETIME uTm, lTm;
  34986. SYSTEMTIME pTm;
  34987. sqlite3_int64 t64;
  34988. t64 = *t;
  34989. t64 = (t64 + 11644473600)*10000000;
  34990. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  34991. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  34992. osFileTimeToLocalFileTime(&uTm,&lTm);
  34993. osFileTimeToSystemTime(&lTm,&pTm);
  34994. y.tm_year = pTm.wYear - 1900;
  34995. y.tm_mon = pTm.wMonth - 1;
  34996. y.tm_wday = pTm.wDayOfWeek;
  34997. y.tm_mday = pTm.wDay;
  34998. y.tm_hour = pTm.wHour;
  34999. y.tm_min = pTm.wMinute;
  35000. y.tm_sec = pTm.wSecond;
  35001. return &y;
  35002. }
  35003. #endif
  35004. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  35005. /*
  35006. ** Acquire a lock on the handle h
  35007. */
  35008. static void winceMutexAcquire(HANDLE h){
  35009. DWORD dwErr;
  35010. do {
  35011. dwErr = osWaitForSingleObject(h, INFINITE);
  35012. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  35013. }
  35014. /*
  35015. ** Release a lock acquired by winceMutexAcquire()
  35016. */
  35017. #define winceMutexRelease(h) ReleaseMutex(h)
  35018. /*
  35019. ** Create the mutex and shared memory used for locking in the file
  35020. ** descriptor pFile
  35021. */
  35022. static int winceCreateLock(const char *zFilename, winFile *pFile){
  35023. LPWSTR zTok;
  35024. LPWSTR zName;
  35025. DWORD lastErrno;
  35026. BOOL bLogged = FALSE;
  35027. BOOL bInit = TRUE;
  35028. zName = winUtf8ToUnicode(zFilename);
  35029. if( zName==0 ){
  35030. /* out of memory */
  35031. return SQLITE_IOERR_NOMEM_BKPT;
  35032. }
  35033. /* Initialize the local lockdata */
  35034. memset(&pFile->local, 0, sizeof(pFile->local));
  35035. /* Replace the backslashes from the filename and lowercase it
  35036. ** to derive a mutex name. */
  35037. zTok = osCharLowerW(zName);
  35038. for (;*zTok;zTok++){
  35039. if (*zTok == '\\') *zTok = '_';
  35040. }
  35041. /* Create/open the named mutex */
  35042. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  35043. if (!pFile->hMutex){
  35044. pFile->lastErrno = osGetLastError();
  35045. sqlite3_free(zName);
  35046. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  35047. "winceCreateLock1", zFilename);
  35048. }
  35049. /* Acquire the mutex before continuing */
  35050. winceMutexAcquire(pFile->hMutex);
  35051. /* Since the names of named mutexes, semaphores, file mappings etc are
  35052. ** case-sensitive, take advantage of that by uppercasing the mutex name
  35053. ** and using that as the shared filemapping name.
  35054. */
  35055. osCharUpperW(zName);
  35056. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  35057. PAGE_READWRITE, 0, sizeof(winceLock),
  35058. zName);
  35059. /* Set a flag that indicates we're the first to create the memory so it
  35060. ** must be zero-initialized */
  35061. lastErrno = osGetLastError();
  35062. if (lastErrno == ERROR_ALREADY_EXISTS){
  35063. bInit = FALSE;
  35064. }
  35065. sqlite3_free(zName);
  35066. /* If we succeeded in making the shared memory handle, map it. */
  35067. if( pFile->hShared ){
  35068. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  35069. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  35070. /* If mapping failed, close the shared memory handle and erase it */
  35071. if( !pFile->shared ){
  35072. pFile->lastErrno = osGetLastError();
  35073. winLogError(SQLITE_IOERR, pFile->lastErrno,
  35074. "winceCreateLock2", zFilename);
  35075. bLogged = TRUE;
  35076. osCloseHandle(pFile->hShared);
  35077. pFile->hShared = NULL;
  35078. }
  35079. }
  35080. /* If shared memory could not be created, then close the mutex and fail */
  35081. if( pFile->hShared==NULL ){
  35082. if( !bLogged ){
  35083. pFile->lastErrno = lastErrno;
  35084. winLogError(SQLITE_IOERR, pFile->lastErrno,
  35085. "winceCreateLock3", zFilename);
  35086. bLogged = TRUE;
  35087. }
  35088. winceMutexRelease(pFile->hMutex);
  35089. osCloseHandle(pFile->hMutex);
  35090. pFile->hMutex = NULL;
  35091. return SQLITE_IOERR;
  35092. }
  35093. /* Initialize the shared memory if we're supposed to */
  35094. if( bInit ){
  35095. memset(pFile->shared, 0, sizeof(winceLock));
  35096. }
  35097. winceMutexRelease(pFile->hMutex);
  35098. return SQLITE_OK;
  35099. }
  35100. /*
  35101. ** Destroy the part of winFile that deals with wince locks
  35102. */
  35103. static void winceDestroyLock(winFile *pFile){
  35104. if (pFile->hMutex){
  35105. /* Acquire the mutex */
  35106. winceMutexAcquire(pFile->hMutex);
  35107. /* The following blocks should probably assert in debug mode, but they
  35108. are to cleanup in case any locks remained open */
  35109. if (pFile->local.nReaders){
  35110. pFile->shared->nReaders --;
  35111. }
  35112. if (pFile->local.bReserved){
  35113. pFile->shared->bReserved = FALSE;
  35114. }
  35115. if (pFile->local.bPending){
  35116. pFile->shared->bPending = FALSE;
  35117. }
  35118. if (pFile->local.bExclusive){
  35119. pFile->shared->bExclusive = FALSE;
  35120. }
  35121. /* De-reference and close our copy of the shared memory handle */
  35122. osUnmapViewOfFile(pFile->shared);
  35123. osCloseHandle(pFile->hShared);
  35124. /* Done with the mutex */
  35125. winceMutexRelease(pFile->hMutex);
  35126. osCloseHandle(pFile->hMutex);
  35127. pFile->hMutex = NULL;
  35128. }
  35129. }
  35130. /*
  35131. ** An implementation of the LockFile() API of Windows for CE
  35132. */
  35133. static BOOL winceLockFile(
  35134. LPHANDLE phFile,
  35135. DWORD dwFileOffsetLow,
  35136. DWORD dwFileOffsetHigh,
  35137. DWORD nNumberOfBytesToLockLow,
  35138. DWORD nNumberOfBytesToLockHigh
  35139. ){
  35140. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  35141. BOOL bReturn = FALSE;
  35142. UNUSED_PARAMETER(dwFileOffsetHigh);
  35143. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  35144. if (!pFile->hMutex) return TRUE;
  35145. winceMutexAcquire(pFile->hMutex);
  35146. /* Wanting an exclusive lock? */
  35147. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  35148. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  35149. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  35150. pFile->shared->bExclusive = TRUE;
  35151. pFile->local.bExclusive = TRUE;
  35152. bReturn = TRUE;
  35153. }
  35154. }
  35155. /* Want a read-only lock? */
  35156. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  35157. nNumberOfBytesToLockLow == 1){
  35158. if (pFile->shared->bExclusive == 0){
  35159. pFile->local.nReaders ++;
  35160. if (pFile->local.nReaders == 1){
  35161. pFile->shared->nReaders ++;
  35162. }
  35163. bReturn = TRUE;
  35164. }
  35165. }
  35166. /* Want a pending lock? */
  35167. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  35168. && nNumberOfBytesToLockLow == 1){
  35169. /* If no pending lock has been acquired, then acquire it */
  35170. if (pFile->shared->bPending == 0) {
  35171. pFile->shared->bPending = TRUE;
  35172. pFile->local.bPending = TRUE;
  35173. bReturn = TRUE;
  35174. }
  35175. }
  35176. /* Want a reserved lock? */
  35177. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  35178. && nNumberOfBytesToLockLow == 1){
  35179. if (pFile->shared->bReserved == 0) {
  35180. pFile->shared->bReserved = TRUE;
  35181. pFile->local.bReserved = TRUE;
  35182. bReturn = TRUE;
  35183. }
  35184. }
  35185. winceMutexRelease(pFile->hMutex);
  35186. return bReturn;
  35187. }
  35188. /*
  35189. ** An implementation of the UnlockFile API of Windows for CE
  35190. */
  35191. static BOOL winceUnlockFile(
  35192. LPHANDLE phFile,
  35193. DWORD dwFileOffsetLow,
  35194. DWORD dwFileOffsetHigh,
  35195. DWORD nNumberOfBytesToUnlockLow,
  35196. DWORD nNumberOfBytesToUnlockHigh
  35197. ){
  35198. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  35199. BOOL bReturn = FALSE;
  35200. UNUSED_PARAMETER(dwFileOffsetHigh);
  35201. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  35202. if (!pFile->hMutex) return TRUE;
  35203. winceMutexAcquire(pFile->hMutex);
  35204. /* Releasing a reader lock or an exclusive lock */
  35205. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  35206. /* Did we have an exclusive lock? */
  35207. if (pFile->local.bExclusive){
  35208. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  35209. pFile->local.bExclusive = FALSE;
  35210. pFile->shared->bExclusive = FALSE;
  35211. bReturn = TRUE;
  35212. }
  35213. /* Did we just have a reader lock? */
  35214. else if (pFile->local.nReaders){
  35215. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  35216. || nNumberOfBytesToUnlockLow == 1);
  35217. pFile->local.nReaders --;
  35218. if (pFile->local.nReaders == 0)
  35219. {
  35220. pFile->shared->nReaders --;
  35221. }
  35222. bReturn = TRUE;
  35223. }
  35224. }
  35225. /* Releasing a pending lock */
  35226. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  35227. && nNumberOfBytesToUnlockLow == 1){
  35228. if (pFile->local.bPending){
  35229. pFile->local.bPending = FALSE;
  35230. pFile->shared->bPending = FALSE;
  35231. bReturn = TRUE;
  35232. }
  35233. }
  35234. /* Releasing a reserved lock */
  35235. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  35236. && nNumberOfBytesToUnlockLow == 1){
  35237. if (pFile->local.bReserved) {
  35238. pFile->local.bReserved = FALSE;
  35239. pFile->shared->bReserved = FALSE;
  35240. bReturn = TRUE;
  35241. }
  35242. }
  35243. winceMutexRelease(pFile->hMutex);
  35244. return bReturn;
  35245. }
  35246. /*
  35247. ** End of the special code for wince
  35248. *****************************************************************************/
  35249. #endif /* SQLITE_OS_WINCE */
  35250. /*
  35251. ** Lock a file region.
  35252. */
  35253. static BOOL winLockFile(
  35254. LPHANDLE phFile,
  35255. DWORD flags,
  35256. DWORD offsetLow,
  35257. DWORD offsetHigh,
  35258. DWORD numBytesLow,
  35259. DWORD numBytesHigh
  35260. ){
  35261. #if SQLITE_OS_WINCE
  35262. /*
  35263. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  35264. ** API LockFile.
  35265. */
  35266. return winceLockFile(phFile, offsetLow, offsetHigh,
  35267. numBytesLow, numBytesHigh);
  35268. #else
  35269. if( osIsNT() ){
  35270. OVERLAPPED ovlp;
  35271. memset(&ovlp, 0, sizeof(OVERLAPPED));
  35272. ovlp.Offset = offsetLow;
  35273. ovlp.OffsetHigh = offsetHigh;
  35274. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  35275. }else{
  35276. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  35277. numBytesHigh);
  35278. }
  35279. #endif
  35280. }
  35281. /*
  35282. ** Unlock a file region.
  35283. */
  35284. static BOOL winUnlockFile(
  35285. LPHANDLE phFile,
  35286. DWORD offsetLow,
  35287. DWORD offsetHigh,
  35288. DWORD numBytesLow,
  35289. DWORD numBytesHigh
  35290. ){
  35291. #if SQLITE_OS_WINCE
  35292. /*
  35293. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  35294. ** API UnlockFile.
  35295. */
  35296. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  35297. numBytesLow, numBytesHigh);
  35298. #else
  35299. if( osIsNT() ){
  35300. OVERLAPPED ovlp;
  35301. memset(&ovlp, 0, sizeof(OVERLAPPED));
  35302. ovlp.Offset = offsetLow;
  35303. ovlp.OffsetHigh = offsetHigh;
  35304. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  35305. }else{
  35306. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  35307. numBytesHigh);
  35308. }
  35309. #endif
  35310. }
  35311. /*****************************************************************************
  35312. ** The next group of routines implement the I/O methods specified
  35313. ** by the sqlite3_io_methods object.
  35314. ******************************************************************************/
  35315. /*
  35316. ** Some Microsoft compilers lack this definition.
  35317. */
  35318. #ifndef INVALID_SET_FILE_POINTER
  35319. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  35320. #endif
  35321. /*
  35322. ** Move the current position of the file handle passed as the first
  35323. ** argument to offset iOffset within the file. If successful, return 0.
  35324. ** Otherwise, set pFile->lastErrno and return non-zero.
  35325. */
  35326. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  35327. #if !SQLITE_OS_WINRT
  35328. LONG upperBits; /* Most sig. 32 bits of new offset */
  35329. LONG lowerBits; /* Least sig. 32 bits of new offset */
  35330. DWORD dwRet; /* Value returned by SetFilePointer() */
  35331. DWORD lastErrno; /* Value returned by GetLastError() */
  35332. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  35333. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  35334. lowerBits = (LONG)(iOffset & 0xffffffff);
  35335. /* API oddity: If successful, SetFilePointer() returns a dword
  35336. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  35337. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  35338. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  35339. ** whether an error has actually occurred, it is also necessary to call
  35340. ** GetLastError().
  35341. */
  35342. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  35343. if( (dwRet==INVALID_SET_FILE_POINTER
  35344. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  35345. pFile->lastErrno = lastErrno;
  35346. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  35347. "winSeekFile", pFile->zPath);
  35348. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  35349. return 1;
  35350. }
  35351. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  35352. return 0;
  35353. #else
  35354. /*
  35355. ** Same as above, except that this implementation works for WinRT.
  35356. */
  35357. LARGE_INTEGER x; /* The new offset */
  35358. BOOL bRet; /* Value returned by SetFilePointerEx() */
  35359. x.QuadPart = iOffset;
  35360. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  35361. if(!bRet){
  35362. pFile->lastErrno = osGetLastError();
  35363. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  35364. "winSeekFile", pFile->zPath);
  35365. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  35366. return 1;
  35367. }
  35368. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  35369. return 0;
  35370. #endif
  35371. }
  35372. #if SQLITE_MAX_MMAP_SIZE>0
  35373. /* Forward references to VFS helper methods used for memory mapped files */
  35374. static int winMapfile(winFile*, sqlite3_int64);
  35375. static int winUnmapfile(winFile*);
  35376. #endif
  35377. /*
  35378. ** Close a file.
  35379. **
  35380. ** It is reported that an attempt to close a handle might sometimes
  35381. ** fail. This is a very unreasonable result, but Windows is notorious
  35382. ** for being unreasonable so I do not doubt that it might happen. If
  35383. ** the close fails, we pause for 100 milliseconds and try again. As
  35384. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  35385. ** giving up and returning an error.
  35386. */
  35387. #define MX_CLOSE_ATTEMPT 3
  35388. static int winClose(sqlite3_file *id){
  35389. int rc, cnt = 0;
  35390. winFile *pFile = (winFile*)id;
  35391. assert( id!=0 );
  35392. #ifndef SQLITE_OMIT_WAL
  35393. assert( pFile->pShm==0 );
  35394. #endif
  35395. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  35396. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  35397. osGetCurrentProcessId(), pFile, pFile->h));
  35398. #if SQLITE_MAX_MMAP_SIZE>0
  35399. winUnmapfile(pFile);
  35400. #endif
  35401. do{
  35402. rc = osCloseHandle(pFile->h);
  35403. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  35404. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  35405. #if SQLITE_OS_WINCE
  35406. #define WINCE_DELETION_ATTEMPTS 3
  35407. winceDestroyLock(pFile);
  35408. if( pFile->zDeleteOnClose ){
  35409. int cnt = 0;
  35410. while(
  35411. osDeleteFileW(pFile->zDeleteOnClose)==0
  35412. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  35413. && cnt++ < WINCE_DELETION_ATTEMPTS
  35414. ){
  35415. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  35416. }
  35417. sqlite3_free(pFile->zDeleteOnClose);
  35418. }
  35419. #endif
  35420. if( rc ){
  35421. pFile->h = NULL;
  35422. }
  35423. OpenCounter(-1);
  35424. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  35425. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  35426. return rc ? SQLITE_OK
  35427. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  35428. "winClose", pFile->zPath);
  35429. }
  35430. /*
  35431. ** Read data from a file into a buffer. Return SQLITE_OK if all
  35432. ** bytes were read successfully and SQLITE_IOERR if anything goes
  35433. ** wrong.
  35434. */
  35435. static int winRead(
  35436. sqlite3_file *id, /* File to read from */
  35437. void *pBuf, /* Write content into this buffer */
  35438. int amt, /* Number of bytes to read */
  35439. sqlite3_int64 offset /* Begin reading at this offset */
  35440. ){
  35441. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35442. OVERLAPPED overlapped; /* The offset for ReadFile. */
  35443. #endif
  35444. winFile *pFile = (winFile*)id; /* file handle */
  35445. DWORD nRead; /* Number of bytes actually read from file */
  35446. int nRetry = 0; /* Number of retrys */
  35447. assert( id!=0 );
  35448. assert( amt>0 );
  35449. assert( offset>=0 );
  35450. SimulateIOError(return SQLITE_IOERR_READ);
  35451. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  35452. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  35453. pFile->h, pBuf, amt, offset, pFile->locktype));
  35454. #if SQLITE_MAX_MMAP_SIZE>0
  35455. /* Deal with as much of this read request as possible by transfering
  35456. ** data from the memory mapping using memcpy(). */
  35457. if( offset<pFile->mmapSize ){
  35458. if( offset+amt <= pFile->mmapSize ){
  35459. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  35460. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35461. osGetCurrentProcessId(), pFile, pFile->h));
  35462. return SQLITE_OK;
  35463. }else{
  35464. int nCopy = (int)(pFile->mmapSize - offset);
  35465. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  35466. pBuf = &((u8 *)pBuf)[nCopy];
  35467. amt -= nCopy;
  35468. offset += nCopy;
  35469. }
  35470. }
  35471. #endif
  35472. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  35473. if( winSeekFile(pFile, offset) ){
  35474. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  35475. osGetCurrentProcessId(), pFile, pFile->h));
  35476. return SQLITE_FULL;
  35477. }
  35478. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  35479. #else
  35480. memset(&overlapped, 0, sizeof(OVERLAPPED));
  35481. overlapped.Offset = (LONG)(offset & 0xffffffff);
  35482. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  35483. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  35484. osGetLastError()!=ERROR_HANDLE_EOF ){
  35485. #endif
  35486. DWORD lastErrno;
  35487. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  35488. pFile->lastErrno = lastErrno;
  35489. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  35490. osGetCurrentProcessId(), pFile, pFile->h));
  35491. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  35492. "winRead", pFile->zPath);
  35493. }
  35494. winLogIoerr(nRetry, __LINE__);
  35495. if( nRead<(DWORD)amt ){
  35496. /* Unread parts of the buffer must be zero-filled */
  35497. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  35498. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  35499. osGetCurrentProcessId(), pFile, pFile->h));
  35500. return SQLITE_IOERR_SHORT_READ;
  35501. }
  35502. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35503. osGetCurrentProcessId(), pFile, pFile->h));
  35504. return SQLITE_OK;
  35505. }
  35506. /*
  35507. ** Write data from a buffer into a file. Return SQLITE_OK on success
  35508. ** or some other error code on failure.
  35509. */
  35510. static int winWrite(
  35511. sqlite3_file *id, /* File to write into */
  35512. const void *pBuf, /* The bytes to be written */
  35513. int amt, /* Number of bytes to write */
  35514. sqlite3_int64 offset /* Offset into the file to begin writing at */
  35515. ){
  35516. int rc = 0; /* True if error has occurred, else false */
  35517. winFile *pFile = (winFile*)id; /* File handle */
  35518. int nRetry = 0; /* Number of retries */
  35519. assert( amt>0 );
  35520. assert( pFile );
  35521. SimulateIOError(return SQLITE_IOERR_WRITE);
  35522. SimulateDiskfullError(return SQLITE_FULL);
  35523. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  35524. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  35525. pFile->h, pBuf, amt, offset, pFile->locktype));
  35526. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  35527. /* Deal with as much of this write request as possible by transfering
  35528. ** data from the memory mapping using memcpy(). */
  35529. if( offset<pFile->mmapSize ){
  35530. if( offset+amt <= pFile->mmapSize ){
  35531. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  35532. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35533. osGetCurrentProcessId(), pFile, pFile->h));
  35534. return SQLITE_OK;
  35535. }else{
  35536. int nCopy = (int)(pFile->mmapSize - offset);
  35537. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  35538. pBuf = &((u8 *)pBuf)[nCopy];
  35539. amt -= nCopy;
  35540. offset += nCopy;
  35541. }
  35542. }
  35543. #endif
  35544. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  35545. rc = winSeekFile(pFile, offset);
  35546. if( rc==0 ){
  35547. #else
  35548. {
  35549. #endif
  35550. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35551. OVERLAPPED overlapped; /* The offset for WriteFile. */
  35552. #endif
  35553. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  35554. int nRem = amt; /* Number of bytes yet to be written */
  35555. DWORD nWrite; /* Bytes written by each WriteFile() call */
  35556. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  35557. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35558. memset(&overlapped, 0, sizeof(OVERLAPPED));
  35559. overlapped.Offset = (LONG)(offset & 0xffffffff);
  35560. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  35561. #endif
  35562. while( nRem>0 ){
  35563. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  35564. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  35565. #else
  35566. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  35567. #endif
  35568. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  35569. break;
  35570. }
  35571. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  35572. if( nWrite==0 || nWrite>(DWORD)nRem ){
  35573. lastErrno = osGetLastError();
  35574. break;
  35575. }
  35576. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35577. offset += nWrite;
  35578. overlapped.Offset = (LONG)(offset & 0xffffffff);
  35579. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  35580. #endif
  35581. aRem += nWrite;
  35582. nRem -= nWrite;
  35583. }
  35584. if( nRem>0 ){
  35585. pFile->lastErrno = lastErrno;
  35586. rc = 1;
  35587. }
  35588. }
  35589. if( rc ){
  35590. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  35591. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  35592. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  35593. osGetCurrentProcessId(), pFile, pFile->h));
  35594. return winLogError(SQLITE_FULL, pFile->lastErrno,
  35595. "winWrite1", pFile->zPath);
  35596. }
  35597. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  35598. osGetCurrentProcessId(), pFile, pFile->h));
  35599. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  35600. "winWrite2", pFile->zPath);
  35601. }else{
  35602. winLogIoerr(nRetry, __LINE__);
  35603. }
  35604. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35605. osGetCurrentProcessId(), pFile, pFile->h));
  35606. return SQLITE_OK;
  35607. }
  35608. /*
  35609. ** Truncate an open file to a specified size
  35610. */
  35611. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  35612. winFile *pFile = (winFile*)id; /* File handle object */
  35613. int rc = SQLITE_OK; /* Return code for this function */
  35614. DWORD lastErrno;
  35615. assert( pFile );
  35616. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  35617. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  35618. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  35619. /* If the user has configured a chunk-size for this file, truncate the
  35620. ** file so that it consists of an integer number of chunks (i.e. the
  35621. ** actual file size after the operation may be larger than the requested
  35622. ** size).
  35623. */
  35624. if( pFile->szChunk>0 ){
  35625. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  35626. }
  35627. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  35628. if( winSeekFile(pFile, nByte) ){
  35629. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  35630. "winTruncate1", pFile->zPath);
  35631. }else if( 0==osSetEndOfFile(pFile->h) &&
  35632. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  35633. pFile->lastErrno = lastErrno;
  35634. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  35635. "winTruncate2", pFile->zPath);
  35636. }
  35637. #if SQLITE_MAX_MMAP_SIZE>0
  35638. /* If the file was truncated to a size smaller than the currently
  35639. ** mapped region, reduce the effective mapping size as well. SQLite will
  35640. ** use read() and write() to access data beyond this point from now on.
  35641. */
  35642. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  35643. pFile->mmapSize = nByte;
  35644. }
  35645. #endif
  35646. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  35647. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  35648. return rc;
  35649. }
  35650. #ifdef SQLITE_TEST
  35651. /*
  35652. ** Count the number of fullsyncs and normal syncs. This is used to test
  35653. ** that syncs and fullsyncs are occuring at the right times.
  35654. */
  35655. SQLITE_API int sqlite3_sync_count = 0;
  35656. SQLITE_API int sqlite3_fullsync_count = 0;
  35657. #endif
  35658. /*
  35659. ** Make sure all writes to a particular file are committed to disk.
  35660. */
  35661. static int winSync(sqlite3_file *id, int flags){
  35662. #ifndef SQLITE_NO_SYNC
  35663. /*
  35664. ** Used only when SQLITE_NO_SYNC is not defined.
  35665. */
  35666. BOOL rc;
  35667. #endif
  35668. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  35669. defined(SQLITE_HAVE_OS_TRACE)
  35670. /*
  35671. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  35672. ** OSTRACE() macros.
  35673. */
  35674. winFile *pFile = (winFile*)id;
  35675. #else
  35676. UNUSED_PARAMETER(id);
  35677. #endif
  35678. assert( pFile );
  35679. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  35680. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  35681. || (flags&0x0F)==SQLITE_SYNC_FULL
  35682. );
  35683. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  35684. ** line is to test that doing so does not cause any problems.
  35685. */
  35686. SimulateDiskfullError( return SQLITE_FULL );
  35687. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  35688. osGetCurrentProcessId(), pFile, pFile->h, flags,
  35689. pFile->locktype));
  35690. #ifndef SQLITE_TEST
  35691. UNUSED_PARAMETER(flags);
  35692. #else
  35693. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  35694. sqlite3_fullsync_count++;
  35695. }
  35696. sqlite3_sync_count++;
  35697. #endif
  35698. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  35699. ** no-op
  35700. */
  35701. #ifdef SQLITE_NO_SYNC
  35702. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35703. osGetCurrentProcessId(), pFile, pFile->h));
  35704. return SQLITE_OK;
  35705. #else
  35706. #if SQLITE_MAX_MMAP_SIZE>0
  35707. if( pFile->pMapRegion ){
  35708. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  35709. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  35710. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  35711. pFile, pFile->pMapRegion));
  35712. }else{
  35713. pFile->lastErrno = osGetLastError();
  35714. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  35715. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  35716. pFile, pFile->pMapRegion));
  35717. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  35718. "winSync1", pFile->zPath);
  35719. }
  35720. }
  35721. #endif
  35722. rc = osFlushFileBuffers(pFile->h);
  35723. SimulateIOError( rc=FALSE );
  35724. if( rc ){
  35725. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35726. osGetCurrentProcessId(), pFile, pFile->h));
  35727. return SQLITE_OK;
  35728. }else{
  35729. pFile->lastErrno = osGetLastError();
  35730. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  35731. osGetCurrentProcessId(), pFile, pFile->h));
  35732. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  35733. "winSync2", pFile->zPath);
  35734. }
  35735. #endif
  35736. }
  35737. /*
  35738. ** Determine the current size of a file in bytes
  35739. */
  35740. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  35741. winFile *pFile = (winFile*)id;
  35742. int rc = SQLITE_OK;
  35743. assert( id!=0 );
  35744. assert( pSize!=0 );
  35745. SimulateIOError(return SQLITE_IOERR_FSTAT);
  35746. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  35747. #if SQLITE_OS_WINRT
  35748. {
  35749. FILE_STANDARD_INFO info;
  35750. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  35751. &info, sizeof(info)) ){
  35752. *pSize = info.EndOfFile.QuadPart;
  35753. }else{
  35754. pFile->lastErrno = osGetLastError();
  35755. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  35756. "winFileSize", pFile->zPath);
  35757. }
  35758. }
  35759. #else
  35760. {
  35761. DWORD upperBits;
  35762. DWORD lowerBits;
  35763. DWORD lastErrno;
  35764. lowerBits = osGetFileSize(pFile->h, &upperBits);
  35765. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  35766. if( (lowerBits == INVALID_FILE_SIZE)
  35767. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  35768. pFile->lastErrno = lastErrno;
  35769. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  35770. "winFileSize", pFile->zPath);
  35771. }
  35772. }
  35773. #endif
  35774. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  35775. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  35776. return rc;
  35777. }
  35778. /*
  35779. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  35780. */
  35781. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  35782. # define LOCKFILE_FAIL_IMMEDIATELY 1
  35783. #endif
  35784. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  35785. # define LOCKFILE_EXCLUSIVE_LOCK 2
  35786. #endif
  35787. /*
  35788. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  35789. ** When the LockFile function was used, it was always expected to fail
  35790. ** immediately if the lock could not be obtained. Also, it always expected to
  35791. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  35792. ** and reflect those expectations; therefore, they should not be changed.
  35793. */
  35794. #ifndef SQLITE_LOCKFILE_FLAGS
  35795. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  35796. LOCKFILE_EXCLUSIVE_LOCK)
  35797. #endif
  35798. /*
  35799. ** Currently, SQLite never calls the LockFileEx function without wanting the
  35800. ** call to fail immediately if the lock cannot be obtained.
  35801. */
  35802. #ifndef SQLITE_LOCKFILEEX_FLAGS
  35803. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  35804. #endif
  35805. /*
  35806. ** Acquire a reader lock.
  35807. ** Different API routines are called depending on whether or not this
  35808. ** is Win9x or WinNT.
  35809. */
  35810. static int winGetReadLock(winFile *pFile){
  35811. int res;
  35812. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  35813. if( osIsNT() ){
  35814. #if SQLITE_OS_WINCE
  35815. /*
  35816. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  35817. ** API LockFileEx.
  35818. */
  35819. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  35820. #else
  35821. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  35822. SHARED_SIZE, 0);
  35823. #endif
  35824. }
  35825. #ifdef SQLITE_WIN32_HAS_ANSI
  35826. else{
  35827. int lk;
  35828. sqlite3_randomness(sizeof(lk), &lk);
  35829. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  35830. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  35831. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  35832. }
  35833. #endif
  35834. if( res == 0 ){
  35835. pFile->lastErrno = osGetLastError();
  35836. /* No need to log a failure to lock */
  35837. }
  35838. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  35839. return res;
  35840. }
  35841. /*
  35842. ** Undo a readlock
  35843. */
  35844. static int winUnlockReadLock(winFile *pFile){
  35845. int res;
  35846. DWORD lastErrno;
  35847. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  35848. if( osIsNT() ){
  35849. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  35850. }
  35851. #ifdef SQLITE_WIN32_HAS_ANSI
  35852. else{
  35853. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  35854. }
  35855. #endif
  35856. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  35857. pFile->lastErrno = lastErrno;
  35858. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  35859. "winUnlockReadLock", pFile->zPath);
  35860. }
  35861. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  35862. return res;
  35863. }
  35864. /*
  35865. ** Lock the file with the lock specified by parameter locktype - one
  35866. ** of the following:
  35867. **
  35868. ** (1) SHARED_LOCK
  35869. ** (2) RESERVED_LOCK
  35870. ** (3) PENDING_LOCK
  35871. ** (4) EXCLUSIVE_LOCK
  35872. **
  35873. ** Sometimes when requesting one lock state, additional lock states
  35874. ** are inserted in between. The locking might fail on one of the later
  35875. ** transitions leaving the lock state different from what it started but
  35876. ** still short of its goal. The following chart shows the allowed
  35877. ** transitions and the inserted intermediate states:
  35878. **
  35879. ** UNLOCKED -> SHARED
  35880. ** SHARED -> RESERVED
  35881. ** SHARED -> (PENDING) -> EXCLUSIVE
  35882. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35883. ** PENDING -> EXCLUSIVE
  35884. **
  35885. ** This routine will only increase a lock. The winUnlock() routine
  35886. ** erases all locks at once and returns us immediately to locking level 0.
  35887. ** It is not possible to lower the locking level one step at a time. You
  35888. ** must go straight to locking level 0.
  35889. */
  35890. static int winLock(sqlite3_file *id, int locktype){
  35891. int rc = SQLITE_OK; /* Return code from subroutines */
  35892. int res = 1; /* Result of a Windows lock call */
  35893. int newLocktype; /* Set pFile->locktype to this value before exiting */
  35894. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  35895. winFile *pFile = (winFile*)id;
  35896. DWORD lastErrno = NO_ERROR;
  35897. assert( id!=0 );
  35898. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  35899. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  35900. /* If there is already a lock of this type or more restrictive on the
  35901. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  35902. ** sqlite3OsEnterMutex() hasn't been called yet.
  35903. */
  35904. if( pFile->locktype>=locktype ){
  35905. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  35906. return SQLITE_OK;
  35907. }
  35908. /* Do not allow any kind of write-lock on a read-only database
  35909. */
  35910. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  35911. return SQLITE_IOERR_LOCK;
  35912. }
  35913. /* Make sure the locking sequence is correct
  35914. */
  35915. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  35916. assert( locktype!=PENDING_LOCK );
  35917. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  35918. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  35919. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  35920. ** the PENDING_LOCK byte is temporary.
  35921. */
  35922. newLocktype = pFile->locktype;
  35923. if( (pFile->locktype==NO_LOCK)
  35924. || ( (locktype==EXCLUSIVE_LOCK)
  35925. && (pFile->locktype==RESERVED_LOCK))
  35926. ){
  35927. int cnt = 3;
  35928. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  35929. PENDING_BYTE, 0, 1, 0))==0 ){
  35930. /* Try 3 times to get the pending lock. This is needed to work
  35931. ** around problems caused by indexing and/or anti-virus software on
  35932. ** Windows systems.
  35933. ** If you are using this code as a model for alternative VFSes, do not
  35934. ** copy this retry logic. It is a hack intended for Windows only.
  35935. */
  35936. lastErrno = osGetLastError();
  35937. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  35938. pFile->h, cnt, res));
  35939. if( lastErrno==ERROR_INVALID_HANDLE ){
  35940. pFile->lastErrno = lastErrno;
  35941. rc = SQLITE_IOERR_LOCK;
  35942. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  35943. pFile->h, cnt, sqlite3ErrName(rc)));
  35944. return rc;
  35945. }
  35946. if( cnt ) sqlite3_win32_sleep(1);
  35947. }
  35948. gotPendingLock = res;
  35949. if( !res ){
  35950. lastErrno = osGetLastError();
  35951. }
  35952. }
  35953. /* Acquire a shared lock
  35954. */
  35955. if( locktype==SHARED_LOCK && res ){
  35956. assert( pFile->locktype==NO_LOCK );
  35957. res = winGetReadLock(pFile);
  35958. if( res ){
  35959. newLocktype = SHARED_LOCK;
  35960. }else{
  35961. lastErrno = osGetLastError();
  35962. }
  35963. }
  35964. /* Acquire a RESERVED lock
  35965. */
  35966. if( locktype==RESERVED_LOCK && res ){
  35967. assert( pFile->locktype==SHARED_LOCK );
  35968. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  35969. if( res ){
  35970. newLocktype = RESERVED_LOCK;
  35971. }else{
  35972. lastErrno = osGetLastError();
  35973. }
  35974. }
  35975. /* Acquire a PENDING lock
  35976. */
  35977. if( locktype==EXCLUSIVE_LOCK && res ){
  35978. newLocktype = PENDING_LOCK;
  35979. gotPendingLock = 0;
  35980. }
  35981. /* Acquire an EXCLUSIVE lock
  35982. */
  35983. if( locktype==EXCLUSIVE_LOCK && res ){
  35984. assert( pFile->locktype>=SHARED_LOCK );
  35985. res = winUnlockReadLock(pFile);
  35986. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  35987. SHARED_SIZE, 0);
  35988. if( res ){
  35989. newLocktype = EXCLUSIVE_LOCK;
  35990. }else{
  35991. lastErrno = osGetLastError();
  35992. winGetReadLock(pFile);
  35993. }
  35994. }
  35995. /* If we are holding a PENDING lock that ought to be released, then
  35996. ** release it now.
  35997. */
  35998. if( gotPendingLock && locktype==SHARED_LOCK ){
  35999. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  36000. }
  36001. /* Update the state of the lock has held in the file descriptor then
  36002. ** return the appropriate result code.
  36003. */
  36004. if( res ){
  36005. rc = SQLITE_OK;
  36006. }else{
  36007. pFile->lastErrno = lastErrno;
  36008. rc = SQLITE_BUSY;
  36009. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  36010. pFile->h, locktype, newLocktype));
  36011. }
  36012. pFile->locktype = (u8)newLocktype;
  36013. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  36014. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  36015. return rc;
  36016. }
  36017. /*
  36018. ** This routine checks if there is a RESERVED lock held on the specified
  36019. ** file by this or any other process. If such a lock is held, return
  36020. ** non-zero, otherwise zero.
  36021. */
  36022. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  36023. int res;
  36024. winFile *pFile = (winFile*)id;
  36025. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  36026. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  36027. assert( id!=0 );
  36028. if( pFile->locktype>=RESERVED_LOCK ){
  36029. res = 1;
  36030. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  36031. }else{
  36032. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  36033. if( res ){
  36034. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  36035. }
  36036. res = !res;
  36037. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  36038. }
  36039. *pResOut = res;
  36040. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  36041. pFile->h, pResOut, *pResOut));
  36042. return SQLITE_OK;
  36043. }
  36044. /*
  36045. ** Lower the locking level on file descriptor id to locktype. locktype
  36046. ** must be either NO_LOCK or SHARED_LOCK.
  36047. **
  36048. ** If the locking level of the file descriptor is already at or below
  36049. ** the requested locking level, this routine is a no-op.
  36050. **
  36051. ** It is not possible for this routine to fail if the second argument
  36052. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  36053. ** might return SQLITE_IOERR;
  36054. */
  36055. static int winUnlock(sqlite3_file *id, int locktype){
  36056. int type;
  36057. winFile *pFile = (winFile*)id;
  36058. int rc = SQLITE_OK;
  36059. assert( pFile!=0 );
  36060. assert( locktype<=SHARED_LOCK );
  36061. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  36062. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  36063. type = pFile->locktype;
  36064. if( type>=EXCLUSIVE_LOCK ){
  36065. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  36066. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  36067. /* This should never happen. We should always be able to
  36068. ** reacquire the read lock */
  36069. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  36070. "winUnlock", pFile->zPath);
  36071. }
  36072. }
  36073. if( type>=RESERVED_LOCK ){
  36074. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  36075. }
  36076. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  36077. winUnlockReadLock(pFile);
  36078. }
  36079. if( type>=PENDING_LOCK ){
  36080. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  36081. }
  36082. pFile->locktype = (u8)locktype;
  36083. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  36084. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  36085. return rc;
  36086. }
  36087. /*
  36088. ** If *pArg is initially negative then this is a query. Set *pArg to
  36089. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  36090. **
  36091. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  36092. */
  36093. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  36094. if( *pArg<0 ){
  36095. *pArg = (pFile->ctrlFlags & mask)!=0;
  36096. }else if( (*pArg)==0 ){
  36097. pFile->ctrlFlags &= ~mask;
  36098. }else{
  36099. pFile->ctrlFlags |= mask;
  36100. }
  36101. }
  36102. /* Forward references to VFS helper methods used for temporary files */
  36103. static int winGetTempname(sqlite3_vfs *, char **);
  36104. static int winIsDir(const void *);
  36105. static BOOL winIsDriveLetterAndColon(const char *);
  36106. /*
  36107. ** Control and query of the open file handle.
  36108. */
  36109. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  36110. winFile *pFile = (winFile*)id;
  36111. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  36112. switch( op ){
  36113. case SQLITE_FCNTL_LOCKSTATE: {
  36114. *(int*)pArg = pFile->locktype;
  36115. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36116. return SQLITE_OK;
  36117. }
  36118. case SQLITE_FCNTL_LAST_ERRNO: {
  36119. *(int*)pArg = (int)pFile->lastErrno;
  36120. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36121. return SQLITE_OK;
  36122. }
  36123. case SQLITE_FCNTL_CHUNK_SIZE: {
  36124. pFile->szChunk = *(int *)pArg;
  36125. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36126. return SQLITE_OK;
  36127. }
  36128. case SQLITE_FCNTL_SIZE_HINT: {
  36129. if( pFile->szChunk>0 ){
  36130. sqlite3_int64 oldSz;
  36131. int rc = winFileSize(id, &oldSz);
  36132. if( rc==SQLITE_OK ){
  36133. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  36134. if( newSz>oldSz ){
  36135. SimulateIOErrorBenign(1);
  36136. rc = winTruncate(id, newSz);
  36137. SimulateIOErrorBenign(0);
  36138. }
  36139. }
  36140. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  36141. return rc;
  36142. }
  36143. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36144. return SQLITE_OK;
  36145. }
  36146. case SQLITE_FCNTL_PERSIST_WAL: {
  36147. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  36148. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36149. return SQLITE_OK;
  36150. }
  36151. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  36152. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  36153. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36154. return SQLITE_OK;
  36155. }
  36156. case SQLITE_FCNTL_VFSNAME: {
  36157. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  36158. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36159. return SQLITE_OK;
  36160. }
  36161. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  36162. int *a = (int*)pArg;
  36163. if( a[0]>0 ){
  36164. winIoerrRetry = a[0];
  36165. }else{
  36166. a[0] = winIoerrRetry;
  36167. }
  36168. if( a[1]>0 ){
  36169. winIoerrRetryDelay = a[1];
  36170. }else{
  36171. a[1] = winIoerrRetryDelay;
  36172. }
  36173. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  36174. return SQLITE_OK;
  36175. }
  36176. #ifdef SQLITE_TEST
  36177. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  36178. LPHANDLE phFile = (LPHANDLE)pArg;
  36179. HANDLE hOldFile = pFile->h;
  36180. pFile->h = *phFile;
  36181. *phFile = hOldFile;
  36182. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  36183. hOldFile, pFile->h));
  36184. return SQLITE_OK;
  36185. }
  36186. #endif
  36187. case SQLITE_FCNTL_TEMPFILENAME: {
  36188. char *zTFile = 0;
  36189. int rc = winGetTempname(pFile->pVfs, &zTFile);
  36190. if( rc==SQLITE_OK ){
  36191. *(char**)pArg = zTFile;
  36192. }
  36193. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  36194. return rc;
  36195. }
  36196. #if SQLITE_MAX_MMAP_SIZE>0
  36197. case SQLITE_FCNTL_MMAP_SIZE: {
  36198. i64 newLimit = *(i64*)pArg;
  36199. int rc = SQLITE_OK;
  36200. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  36201. newLimit = sqlite3GlobalConfig.mxMmap;
  36202. }
  36203. *(i64*)pArg = pFile->mmapSizeMax;
  36204. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  36205. pFile->mmapSizeMax = newLimit;
  36206. if( pFile->mmapSize>0 ){
  36207. winUnmapfile(pFile);
  36208. rc = winMapfile(pFile, -1);
  36209. }
  36210. }
  36211. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  36212. return rc;
  36213. }
  36214. #endif
  36215. }
  36216. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  36217. return SQLITE_NOTFOUND;
  36218. }
  36219. /*
  36220. ** Return the sector size in bytes of the underlying block device for
  36221. ** the specified file. This is almost always 512 bytes, but may be
  36222. ** larger for some devices.
  36223. **
  36224. ** SQLite code assumes this function cannot fail. It also assumes that
  36225. ** if two files are created in the same file-system directory (i.e.
  36226. ** a database and its journal file) that the sector size will be the
  36227. ** same for both.
  36228. */
  36229. static int winSectorSize(sqlite3_file *id){
  36230. (void)id;
  36231. return SQLITE_DEFAULT_SECTOR_SIZE;
  36232. }
  36233. /*
  36234. ** Return a vector of device characteristics.
  36235. */
  36236. static int winDeviceCharacteristics(sqlite3_file *id){
  36237. winFile *p = (winFile*)id;
  36238. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  36239. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  36240. }
  36241. /*
  36242. ** Windows will only let you create file view mappings
  36243. ** on allocation size granularity boundaries.
  36244. ** During sqlite3_os_init() we do a GetSystemInfo()
  36245. ** to get the granularity size.
  36246. */
  36247. static SYSTEM_INFO winSysInfo;
  36248. #ifndef SQLITE_OMIT_WAL
  36249. /*
  36250. ** Helper functions to obtain and relinquish the global mutex. The
  36251. ** global mutex is used to protect the winLockInfo objects used by
  36252. ** this file, all of which may be shared by multiple threads.
  36253. **
  36254. ** Function winShmMutexHeld() is used to assert() that the global mutex
  36255. ** is held when required. This function is only used as part of assert()
  36256. ** statements. e.g.
  36257. **
  36258. ** winShmEnterMutex()
  36259. ** assert( winShmMutexHeld() );
  36260. ** winShmLeaveMutex()
  36261. */
  36262. static void winShmEnterMutex(void){
  36263. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  36264. }
  36265. static void winShmLeaveMutex(void){
  36266. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  36267. }
  36268. #ifndef NDEBUG
  36269. static int winShmMutexHeld(void) {
  36270. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  36271. }
  36272. #endif
  36273. /*
  36274. ** Object used to represent a single file opened and mmapped to provide
  36275. ** shared memory. When multiple threads all reference the same
  36276. ** log-summary, each thread has its own winFile object, but they all
  36277. ** point to a single instance of this object. In other words, each
  36278. ** log-summary is opened only once per process.
  36279. **
  36280. ** winShmMutexHeld() must be true when creating or destroying
  36281. ** this object or while reading or writing the following fields:
  36282. **
  36283. ** nRef
  36284. ** pNext
  36285. **
  36286. ** The following fields are read-only after the object is created:
  36287. **
  36288. ** fid
  36289. ** zFilename
  36290. **
  36291. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  36292. ** winShmMutexHeld() is true when reading or writing any other field
  36293. ** in this structure.
  36294. **
  36295. */
  36296. struct winShmNode {
  36297. sqlite3_mutex *mutex; /* Mutex to access this object */
  36298. char *zFilename; /* Name of the file */
  36299. winFile hFile; /* File handle from winOpen */
  36300. int szRegion; /* Size of shared-memory regions */
  36301. int nRegion; /* Size of array apRegion */
  36302. struct ShmRegion {
  36303. HANDLE hMap; /* File handle from CreateFileMapping */
  36304. void *pMap;
  36305. } *aRegion;
  36306. DWORD lastErrno; /* The Windows errno from the last I/O error */
  36307. int nRef; /* Number of winShm objects pointing to this */
  36308. winShm *pFirst; /* All winShm objects pointing to this */
  36309. winShmNode *pNext; /* Next in list of all winShmNode objects */
  36310. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  36311. u8 nextShmId; /* Next available winShm.id value */
  36312. #endif
  36313. };
  36314. /*
  36315. ** A global array of all winShmNode objects.
  36316. **
  36317. ** The winShmMutexHeld() must be true while reading or writing this list.
  36318. */
  36319. static winShmNode *winShmNodeList = 0;
  36320. /*
  36321. ** Structure used internally by this VFS to record the state of an
  36322. ** open shared memory connection.
  36323. **
  36324. ** The following fields are initialized when this object is created and
  36325. ** are read-only thereafter:
  36326. **
  36327. ** winShm.pShmNode
  36328. ** winShm.id
  36329. **
  36330. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  36331. ** while accessing any read/write fields.
  36332. */
  36333. struct winShm {
  36334. winShmNode *pShmNode; /* The underlying winShmNode object */
  36335. winShm *pNext; /* Next winShm with the same winShmNode */
  36336. u8 hasMutex; /* True if holding the winShmNode mutex */
  36337. u16 sharedMask; /* Mask of shared locks held */
  36338. u16 exclMask; /* Mask of exclusive locks held */
  36339. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  36340. u8 id; /* Id of this connection with its winShmNode */
  36341. #endif
  36342. };
  36343. /*
  36344. ** Constants used for locking
  36345. */
  36346. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  36347. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  36348. /*
  36349. ** Apply advisory locks for all n bytes beginning at ofst.
  36350. */
  36351. #define _SHM_UNLCK 1
  36352. #define _SHM_RDLCK 2
  36353. #define _SHM_WRLCK 3
  36354. static int winShmSystemLock(
  36355. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  36356. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  36357. int ofst, /* Offset to first byte to be locked/unlocked */
  36358. int nByte /* Number of bytes to lock or unlock */
  36359. ){
  36360. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  36361. /* Access to the winShmNode object is serialized by the caller */
  36362. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  36363. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  36364. pFile->hFile.h, lockType, ofst, nByte));
  36365. /* Release/Acquire the system-level lock */
  36366. if( lockType==_SHM_UNLCK ){
  36367. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  36368. }else{
  36369. /* Initialize the locking parameters */
  36370. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  36371. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  36372. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  36373. }
  36374. if( rc!= 0 ){
  36375. rc = SQLITE_OK;
  36376. }else{
  36377. pFile->lastErrno = osGetLastError();
  36378. rc = SQLITE_BUSY;
  36379. }
  36380. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  36381. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  36382. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  36383. return rc;
  36384. }
  36385. /* Forward references to VFS methods */
  36386. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  36387. static int winDelete(sqlite3_vfs *,const char*,int);
  36388. /*
  36389. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  36390. **
  36391. ** This is not a VFS shared-memory method; it is a utility function called
  36392. ** by VFS shared-memory methods.
  36393. */
  36394. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  36395. winShmNode **pp;
  36396. winShmNode *p;
  36397. assert( winShmMutexHeld() );
  36398. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  36399. osGetCurrentProcessId(), deleteFlag));
  36400. pp = &winShmNodeList;
  36401. while( (p = *pp)!=0 ){
  36402. if( p->nRef==0 ){
  36403. int i;
  36404. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  36405. for(i=0; i<p->nRegion; i++){
  36406. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  36407. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  36408. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  36409. UNUSED_VARIABLE_VALUE(bRc);
  36410. bRc = osCloseHandle(p->aRegion[i].hMap);
  36411. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  36412. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  36413. UNUSED_VARIABLE_VALUE(bRc);
  36414. }
  36415. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  36416. SimulateIOErrorBenign(1);
  36417. winClose((sqlite3_file *)&p->hFile);
  36418. SimulateIOErrorBenign(0);
  36419. }
  36420. if( deleteFlag ){
  36421. SimulateIOErrorBenign(1);
  36422. sqlite3BeginBenignMalloc();
  36423. winDelete(pVfs, p->zFilename, 0);
  36424. sqlite3EndBenignMalloc();
  36425. SimulateIOErrorBenign(0);
  36426. }
  36427. *pp = p->pNext;
  36428. sqlite3_free(p->aRegion);
  36429. sqlite3_free(p);
  36430. }else{
  36431. pp = &p->pNext;
  36432. }
  36433. }
  36434. }
  36435. /*
  36436. ** Open the shared-memory area associated with database file pDbFd.
  36437. **
  36438. ** When opening a new shared-memory file, if no other instances of that
  36439. ** file are currently open, in this process or in other processes, then
  36440. ** the file must be truncated to zero length or have its header cleared.
  36441. */
  36442. static int winOpenSharedMemory(winFile *pDbFd){
  36443. struct winShm *p; /* The connection to be opened */
  36444. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  36445. int rc; /* Result code */
  36446. struct winShmNode *pNew; /* Newly allocated winShmNode */
  36447. int nName; /* Size of zName in bytes */
  36448. assert( pDbFd->pShm==0 ); /* Not previously opened */
  36449. /* Allocate space for the new sqlite3_shm object. Also speculatively
  36450. ** allocate space for a new winShmNode and filename.
  36451. */
  36452. p = sqlite3MallocZero( sizeof(*p) );
  36453. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  36454. nName = sqlite3Strlen30(pDbFd->zPath);
  36455. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  36456. if( pNew==0 ){
  36457. sqlite3_free(p);
  36458. return SQLITE_IOERR_NOMEM_BKPT;
  36459. }
  36460. pNew->zFilename = (char*)&pNew[1];
  36461. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  36462. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  36463. /* Look to see if there is an existing winShmNode that can be used.
  36464. ** If no matching winShmNode currently exists, create a new one.
  36465. */
  36466. winShmEnterMutex();
  36467. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  36468. /* TBD need to come up with better match here. Perhaps
  36469. ** use FILE_ID_BOTH_DIR_INFO Structure.
  36470. */
  36471. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  36472. }
  36473. if( pShmNode ){
  36474. sqlite3_free(pNew);
  36475. }else{
  36476. pShmNode = pNew;
  36477. pNew = 0;
  36478. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  36479. pShmNode->pNext = winShmNodeList;
  36480. winShmNodeList = pShmNode;
  36481. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  36482. if( pShmNode->mutex==0 ){
  36483. rc = SQLITE_IOERR_NOMEM_BKPT;
  36484. goto shm_open_err;
  36485. }
  36486. rc = winOpen(pDbFd->pVfs,
  36487. pShmNode->zFilename, /* Name of the file (UTF-8) */
  36488. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  36489. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  36490. 0);
  36491. if( SQLITE_OK!=rc ){
  36492. goto shm_open_err;
  36493. }
  36494. /* Check to see if another process is holding the dead-man switch.
  36495. ** If not, truncate the file to zero length.
  36496. */
  36497. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  36498. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  36499. if( rc!=SQLITE_OK ){
  36500. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  36501. "winOpenShm", pDbFd->zPath);
  36502. }
  36503. }
  36504. if( rc==SQLITE_OK ){
  36505. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  36506. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  36507. }
  36508. if( rc ) goto shm_open_err;
  36509. }
  36510. /* Make the new connection a child of the winShmNode */
  36511. p->pShmNode = pShmNode;
  36512. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  36513. p->id = pShmNode->nextShmId++;
  36514. #endif
  36515. pShmNode->nRef++;
  36516. pDbFd->pShm = p;
  36517. winShmLeaveMutex();
  36518. /* The reference count on pShmNode has already been incremented under
  36519. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  36520. ** new (struct winShm) object to the pShmNode has been set. All that is
  36521. ** left to do is to link the new object into the linked list starting
  36522. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  36523. ** mutex.
  36524. */
  36525. sqlite3_mutex_enter(pShmNode->mutex);
  36526. p->pNext = pShmNode->pFirst;
  36527. pShmNode->pFirst = p;
  36528. sqlite3_mutex_leave(pShmNode->mutex);
  36529. return SQLITE_OK;
  36530. /* Jump here on any error */
  36531. shm_open_err:
  36532. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  36533. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  36534. sqlite3_free(p);
  36535. sqlite3_free(pNew);
  36536. winShmLeaveMutex();
  36537. return rc;
  36538. }
  36539. /*
  36540. ** Close a connection to shared-memory. Delete the underlying
  36541. ** storage if deleteFlag is true.
  36542. */
  36543. static int winShmUnmap(
  36544. sqlite3_file *fd, /* Database holding shared memory */
  36545. int deleteFlag /* Delete after closing if true */
  36546. ){
  36547. winFile *pDbFd; /* Database holding shared-memory */
  36548. winShm *p; /* The connection to be closed */
  36549. winShmNode *pShmNode; /* The underlying shared-memory file */
  36550. winShm **pp; /* For looping over sibling connections */
  36551. pDbFd = (winFile*)fd;
  36552. p = pDbFd->pShm;
  36553. if( p==0 ) return SQLITE_OK;
  36554. pShmNode = p->pShmNode;
  36555. /* Remove connection p from the set of connections associated
  36556. ** with pShmNode */
  36557. sqlite3_mutex_enter(pShmNode->mutex);
  36558. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  36559. *pp = p->pNext;
  36560. /* Free the connection p */
  36561. sqlite3_free(p);
  36562. pDbFd->pShm = 0;
  36563. sqlite3_mutex_leave(pShmNode->mutex);
  36564. /* If pShmNode->nRef has reached 0, then close the underlying
  36565. ** shared-memory file, too */
  36566. winShmEnterMutex();
  36567. assert( pShmNode->nRef>0 );
  36568. pShmNode->nRef--;
  36569. if( pShmNode->nRef==0 ){
  36570. winShmPurge(pDbFd->pVfs, deleteFlag);
  36571. }
  36572. winShmLeaveMutex();
  36573. return SQLITE_OK;
  36574. }
  36575. /*
  36576. ** Change the lock state for a shared-memory segment.
  36577. */
  36578. static int winShmLock(
  36579. sqlite3_file *fd, /* Database file holding the shared memory */
  36580. int ofst, /* First lock to acquire or release */
  36581. int n, /* Number of locks to acquire or release */
  36582. int flags /* What to do with the lock */
  36583. ){
  36584. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  36585. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  36586. winShm *pX; /* For looping over all siblings */
  36587. winShmNode *pShmNode = p->pShmNode;
  36588. int rc = SQLITE_OK; /* Result code */
  36589. u16 mask; /* Mask of locks to take or release */
  36590. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  36591. assert( n>=1 );
  36592. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  36593. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  36594. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  36595. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  36596. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  36597. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  36598. assert( n>1 || mask==(1<<ofst) );
  36599. sqlite3_mutex_enter(pShmNode->mutex);
  36600. if( flags & SQLITE_SHM_UNLOCK ){
  36601. u16 allMask = 0; /* Mask of locks held by siblings */
  36602. /* See if any siblings hold this same lock */
  36603. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36604. if( pX==p ) continue;
  36605. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  36606. allMask |= pX->sharedMask;
  36607. }
  36608. /* Unlock the system-level locks */
  36609. if( (mask & allMask)==0 ){
  36610. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  36611. }else{
  36612. rc = SQLITE_OK;
  36613. }
  36614. /* Undo the local locks */
  36615. if( rc==SQLITE_OK ){
  36616. p->exclMask &= ~mask;
  36617. p->sharedMask &= ~mask;
  36618. }
  36619. }else if( flags & SQLITE_SHM_SHARED ){
  36620. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  36621. /* Find out which shared locks are already held by sibling connections.
  36622. ** If any sibling already holds an exclusive lock, go ahead and return
  36623. ** SQLITE_BUSY.
  36624. */
  36625. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36626. if( (pX->exclMask & mask)!=0 ){
  36627. rc = SQLITE_BUSY;
  36628. break;
  36629. }
  36630. allShared |= pX->sharedMask;
  36631. }
  36632. /* Get shared locks at the system level, if necessary */
  36633. if( rc==SQLITE_OK ){
  36634. if( (allShared & mask)==0 ){
  36635. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  36636. }else{
  36637. rc = SQLITE_OK;
  36638. }
  36639. }
  36640. /* Get the local shared locks */
  36641. if( rc==SQLITE_OK ){
  36642. p->sharedMask |= mask;
  36643. }
  36644. }else{
  36645. /* Make sure no sibling connections hold locks that will block this
  36646. ** lock. If any do, return SQLITE_BUSY right away.
  36647. */
  36648. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36649. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  36650. rc = SQLITE_BUSY;
  36651. break;
  36652. }
  36653. }
  36654. /* Get the exclusive locks at the system level. Then if successful
  36655. ** also mark the local connection as being locked.
  36656. */
  36657. if( rc==SQLITE_OK ){
  36658. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  36659. if( rc==SQLITE_OK ){
  36660. assert( (p->sharedMask & mask)==0 );
  36661. p->exclMask |= mask;
  36662. }
  36663. }
  36664. }
  36665. sqlite3_mutex_leave(pShmNode->mutex);
  36666. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  36667. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  36668. sqlite3ErrName(rc)));
  36669. return rc;
  36670. }
  36671. /*
  36672. ** Implement a memory barrier or memory fence on shared memory.
  36673. **
  36674. ** All loads and stores begun before the barrier must complete before
  36675. ** any load or store begun after the barrier.
  36676. */
  36677. static void winShmBarrier(
  36678. sqlite3_file *fd /* Database holding the shared memory */
  36679. ){
  36680. UNUSED_PARAMETER(fd);
  36681. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  36682. winShmEnterMutex(); /* Also mutex, for redundancy */
  36683. winShmLeaveMutex();
  36684. }
  36685. /*
  36686. ** This function is called to obtain a pointer to region iRegion of the
  36687. ** shared-memory associated with the database file fd. Shared-memory regions
  36688. ** are numbered starting from zero. Each shared-memory region is szRegion
  36689. ** bytes in size.
  36690. **
  36691. ** If an error occurs, an error code is returned and *pp is set to NULL.
  36692. **
  36693. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  36694. ** region has not been allocated (by any client, including one running in a
  36695. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  36696. ** isWrite is non-zero and the requested shared-memory region has not yet
  36697. ** been allocated, it is allocated by this function.
  36698. **
  36699. ** If the shared-memory region has already been allocated or is allocated by
  36700. ** this call as described above, then it is mapped into this processes
  36701. ** address space (if it is not already), *pp is set to point to the mapped
  36702. ** memory and SQLITE_OK returned.
  36703. */
  36704. static int winShmMap(
  36705. sqlite3_file *fd, /* Handle open on database file */
  36706. int iRegion, /* Region to retrieve */
  36707. int szRegion, /* Size of regions */
  36708. int isWrite, /* True to extend file if necessary */
  36709. void volatile **pp /* OUT: Mapped memory */
  36710. ){
  36711. winFile *pDbFd = (winFile*)fd;
  36712. winShm *pShm = pDbFd->pShm;
  36713. winShmNode *pShmNode;
  36714. int rc = SQLITE_OK;
  36715. if( !pShm ){
  36716. rc = winOpenSharedMemory(pDbFd);
  36717. if( rc!=SQLITE_OK ) return rc;
  36718. pShm = pDbFd->pShm;
  36719. }
  36720. pShmNode = pShm->pShmNode;
  36721. sqlite3_mutex_enter(pShmNode->mutex);
  36722. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  36723. if( pShmNode->nRegion<=iRegion ){
  36724. struct ShmRegion *apNew; /* New aRegion[] array */
  36725. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  36726. sqlite3_int64 sz; /* Current size of wal-index file */
  36727. pShmNode->szRegion = szRegion;
  36728. /* The requested region is not mapped into this processes address space.
  36729. ** Check to see if it has been allocated (i.e. if the wal-index file is
  36730. ** large enough to contain the requested region).
  36731. */
  36732. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  36733. if( rc!=SQLITE_OK ){
  36734. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  36735. "winShmMap1", pDbFd->zPath);
  36736. goto shmpage_out;
  36737. }
  36738. if( sz<nByte ){
  36739. /* The requested memory region does not exist. If isWrite is set to
  36740. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  36741. **
  36742. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  36743. ** the requested memory region.
  36744. */
  36745. if( !isWrite ) goto shmpage_out;
  36746. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  36747. if( rc!=SQLITE_OK ){
  36748. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  36749. "winShmMap2", pDbFd->zPath);
  36750. goto shmpage_out;
  36751. }
  36752. }
  36753. /* Map the requested memory region into this processes address space. */
  36754. apNew = (struct ShmRegion *)sqlite3_realloc64(
  36755. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  36756. );
  36757. if( !apNew ){
  36758. rc = SQLITE_IOERR_NOMEM_BKPT;
  36759. goto shmpage_out;
  36760. }
  36761. pShmNode->aRegion = apNew;
  36762. while( pShmNode->nRegion<=iRegion ){
  36763. HANDLE hMap = NULL; /* file-mapping handle */
  36764. void *pMap = 0; /* Mapped memory region */
  36765. #if SQLITE_OS_WINRT
  36766. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  36767. NULL, PAGE_READWRITE, nByte, NULL
  36768. );
  36769. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36770. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  36771. NULL, PAGE_READWRITE, 0, nByte, NULL
  36772. );
  36773. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  36774. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  36775. NULL, PAGE_READWRITE, 0, nByte, NULL
  36776. );
  36777. #endif
  36778. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  36779. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  36780. hMap ? "ok" : "failed"));
  36781. if( hMap ){
  36782. int iOffset = pShmNode->nRegion*szRegion;
  36783. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  36784. #if SQLITE_OS_WINRT
  36785. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  36786. iOffset - iOffsetShift, szRegion + iOffsetShift
  36787. );
  36788. #else
  36789. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  36790. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  36791. );
  36792. #endif
  36793. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  36794. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  36795. szRegion, pMap ? "ok" : "failed"));
  36796. }
  36797. if( !pMap ){
  36798. pShmNode->lastErrno = osGetLastError();
  36799. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  36800. "winShmMap3", pDbFd->zPath);
  36801. if( hMap ) osCloseHandle(hMap);
  36802. goto shmpage_out;
  36803. }
  36804. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  36805. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  36806. pShmNode->nRegion++;
  36807. }
  36808. }
  36809. shmpage_out:
  36810. if( pShmNode->nRegion>iRegion ){
  36811. int iOffset = iRegion*szRegion;
  36812. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  36813. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  36814. *pp = (void *)&p[iOffsetShift];
  36815. }else{
  36816. *pp = 0;
  36817. }
  36818. sqlite3_mutex_leave(pShmNode->mutex);
  36819. return rc;
  36820. }
  36821. #else
  36822. # define winShmMap 0
  36823. # define winShmLock 0
  36824. # define winShmBarrier 0
  36825. # define winShmUnmap 0
  36826. #endif /* #ifndef SQLITE_OMIT_WAL */
  36827. /*
  36828. ** Cleans up the mapped region of the specified file, if any.
  36829. */
  36830. #if SQLITE_MAX_MMAP_SIZE>0
  36831. static int winUnmapfile(winFile *pFile){
  36832. assert( pFile!=0 );
  36833. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  36834. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  36835. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  36836. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  36837. if( pFile->pMapRegion ){
  36838. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  36839. pFile->lastErrno = osGetLastError();
  36840. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  36841. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  36842. pFile->pMapRegion));
  36843. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  36844. "winUnmapfile1", pFile->zPath);
  36845. }
  36846. pFile->pMapRegion = 0;
  36847. pFile->mmapSize = 0;
  36848. pFile->mmapSizeActual = 0;
  36849. }
  36850. if( pFile->hMap!=NULL ){
  36851. if( !osCloseHandle(pFile->hMap) ){
  36852. pFile->lastErrno = osGetLastError();
  36853. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  36854. osGetCurrentProcessId(), pFile, pFile->hMap));
  36855. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  36856. "winUnmapfile2", pFile->zPath);
  36857. }
  36858. pFile->hMap = NULL;
  36859. }
  36860. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36861. osGetCurrentProcessId(), pFile));
  36862. return SQLITE_OK;
  36863. }
  36864. /*
  36865. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  36866. ** is already mapped, the existing mapping is replaced by the new). Or, if
  36867. ** there already exists a mapping for this file, and there are still
  36868. ** outstanding xFetch() references to it, this function is a no-op.
  36869. **
  36870. ** If parameter nByte is non-negative, then it is the requested size of
  36871. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  36872. ** requested size is the size of the file on disk. The actual size of the
  36873. ** created mapping is either the requested size or the value configured
  36874. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  36875. **
  36876. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  36877. ** recreated as a result of outstanding references) or an SQLite error
  36878. ** code otherwise.
  36879. */
  36880. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  36881. sqlite3_int64 nMap = nByte;
  36882. int rc;
  36883. assert( nMap>=0 || pFd->nFetchOut==0 );
  36884. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  36885. osGetCurrentProcessId(), pFd, nByte));
  36886. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  36887. if( nMap<0 ){
  36888. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  36889. if( rc ){
  36890. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  36891. osGetCurrentProcessId(), pFd));
  36892. return SQLITE_IOERR_FSTAT;
  36893. }
  36894. }
  36895. if( nMap>pFd->mmapSizeMax ){
  36896. nMap = pFd->mmapSizeMax;
  36897. }
  36898. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  36899. if( nMap==0 && pFd->mmapSize>0 ){
  36900. winUnmapfile(pFd);
  36901. }
  36902. if( nMap!=pFd->mmapSize ){
  36903. void *pNew = 0;
  36904. DWORD protect = PAGE_READONLY;
  36905. DWORD flags = FILE_MAP_READ;
  36906. winUnmapfile(pFd);
  36907. #ifdef SQLITE_MMAP_READWRITE
  36908. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  36909. protect = PAGE_READWRITE;
  36910. flags |= FILE_MAP_WRITE;
  36911. }
  36912. #endif
  36913. #if SQLITE_OS_WINRT
  36914. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  36915. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36916. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  36917. (DWORD)((nMap>>32) & 0xffffffff),
  36918. (DWORD)(nMap & 0xffffffff), NULL);
  36919. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  36920. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  36921. (DWORD)((nMap>>32) & 0xffffffff),
  36922. (DWORD)(nMap & 0xffffffff), NULL);
  36923. #endif
  36924. if( pFd->hMap==NULL ){
  36925. pFd->lastErrno = osGetLastError();
  36926. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  36927. "winMapfile1", pFd->zPath);
  36928. /* Log the error, but continue normal operation using xRead/xWrite */
  36929. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  36930. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36931. return SQLITE_OK;
  36932. }
  36933. assert( (nMap % winSysInfo.dwPageSize)==0 );
  36934. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  36935. #if SQLITE_OS_WINRT
  36936. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  36937. #else
  36938. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  36939. #endif
  36940. if( pNew==NULL ){
  36941. osCloseHandle(pFd->hMap);
  36942. pFd->hMap = NULL;
  36943. pFd->lastErrno = osGetLastError();
  36944. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  36945. "winMapfile2", pFd->zPath);
  36946. /* Log the error, but continue normal operation using xRead/xWrite */
  36947. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  36948. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36949. return SQLITE_OK;
  36950. }
  36951. pFd->pMapRegion = pNew;
  36952. pFd->mmapSize = nMap;
  36953. pFd->mmapSizeActual = nMap;
  36954. }
  36955. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36956. osGetCurrentProcessId(), pFd));
  36957. return SQLITE_OK;
  36958. }
  36959. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  36960. /*
  36961. ** If possible, return a pointer to a mapping of file fd starting at offset
  36962. ** iOff. The mapping must be valid for at least nAmt bytes.
  36963. **
  36964. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  36965. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  36966. ** Finally, if an error does occur, return an SQLite error code. The final
  36967. ** value of *pp is undefined in this case.
  36968. **
  36969. ** If this function does return a pointer, the caller must eventually
  36970. ** release the reference by calling winUnfetch().
  36971. */
  36972. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  36973. #if SQLITE_MAX_MMAP_SIZE>0
  36974. winFile *pFd = (winFile*)fd; /* The underlying database file */
  36975. #endif
  36976. *pp = 0;
  36977. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  36978. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  36979. #if SQLITE_MAX_MMAP_SIZE>0
  36980. if( pFd->mmapSizeMax>0 ){
  36981. if( pFd->pMapRegion==0 ){
  36982. int rc = winMapfile(pFd, -1);
  36983. if( rc!=SQLITE_OK ){
  36984. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  36985. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36986. return rc;
  36987. }
  36988. }
  36989. if( pFd->mmapSize >= iOff+nAmt ){
  36990. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  36991. pFd->nFetchOut++;
  36992. }
  36993. }
  36994. #endif
  36995. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  36996. osGetCurrentProcessId(), fd, pp, *pp));
  36997. return SQLITE_OK;
  36998. }
  36999. /*
  37000. ** If the third argument is non-NULL, then this function releases a
  37001. ** reference obtained by an earlier call to winFetch(). The second
  37002. ** argument passed to this function must be the same as the corresponding
  37003. ** argument that was passed to the winFetch() invocation.
  37004. **
  37005. ** Or, if the third argument is NULL, then this function is being called
  37006. ** to inform the VFS layer that, according to POSIX, any existing mapping
  37007. ** may now be invalid and should be unmapped.
  37008. */
  37009. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  37010. #if SQLITE_MAX_MMAP_SIZE>0
  37011. winFile *pFd = (winFile*)fd; /* The underlying database file */
  37012. /* If p==0 (unmap the entire file) then there must be no outstanding
  37013. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  37014. ** then there must be at least one outstanding. */
  37015. assert( (p==0)==(pFd->nFetchOut==0) );
  37016. /* If p!=0, it must match the iOff value. */
  37017. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  37018. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  37019. osGetCurrentProcessId(), pFd, iOff, p));
  37020. if( p ){
  37021. pFd->nFetchOut--;
  37022. }else{
  37023. /* FIXME: If Windows truly always prevents truncating or deleting a
  37024. ** file while a mapping is held, then the following winUnmapfile() call
  37025. ** is unnecessary can be omitted - potentially improving
  37026. ** performance. */
  37027. winUnmapfile(pFd);
  37028. }
  37029. assert( pFd->nFetchOut>=0 );
  37030. #endif
  37031. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  37032. osGetCurrentProcessId(), fd));
  37033. return SQLITE_OK;
  37034. }
  37035. /*
  37036. ** Here ends the implementation of all sqlite3_file methods.
  37037. **
  37038. ********************** End sqlite3_file Methods *******************************
  37039. ******************************************************************************/
  37040. /*
  37041. ** This vector defines all the methods that can operate on an
  37042. ** sqlite3_file for win32.
  37043. */
  37044. static const sqlite3_io_methods winIoMethod = {
  37045. 3, /* iVersion */
  37046. winClose, /* xClose */
  37047. winRead, /* xRead */
  37048. winWrite, /* xWrite */
  37049. winTruncate, /* xTruncate */
  37050. winSync, /* xSync */
  37051. winFileSize, /* xFileSize */
  37052. winLock, /* xLock */
  37053. winUnlock, /* xUnlock */
  37054. winCheckReservedLock, /* xCheckReservedLock */
  37055. winFileControl, /* xFileControl */
  37056. winSectorSize, /* xSectorSize */
  37057. winDeviceCharacteristics, /* xDeviceCharacteristics */
  37058. winShmMap, /* xShmMap */
  37059. winShmLock, /* xShmLock */
  37060. winShmBarrier, /* xShmBarrier */
  37061. winShmUnmap, /* xShmUnmap */
  37062. winFetch, /* xFetch */
  37063. winUnfetch /* xUnfetch */
  37064. };
  37065. /****************************************************************************
  37066. **************************** sqlite3_vfs methods ****************************
  37067. **
  37068. ** This division contains the implementation of methods on the
  37069. ** sqlite3_vfs object.
  37070. */
  37071. #if defined(__CYGWIN__)
  37072. /*
  37073. ** Convert a filename from whatever the underlying operating system
  37074. ** supports for filenames into UTF-8. Space to hold the result is
  37075. ** obtained from malloc and must be freed by the calling function.
  37076. */
  37077. static char *winConvertToUtf8Filename(const void *zFilename){
  37078. char *zConverted = 0;
  37079. if( osIsNT() ){
  37080. zConverted = winUnicodeToUtf8(zFilename);
  37081. }
  37082. #ifdef SQLITE_WIN32_HAS_ANSI
  37083. else{
  37084. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  37085. }
  37086. #endif
  37087. /* caller will handle out of memory */
  37088. return zConverted;
  37089. }
  37090. #endif
  37091. /*
  37092. ** Convert a UTF-8 filename into whatever form the underlying
  37093. ** operating system wants filenames in. Space to hold the result
  37094. ** is obtained from malloc and must be freed by the calling
  37095. ** function.
  37096. */
  37097. static void *winConvertFromUtf8Filename(const char *zFilename){
  37098. void *zConverted = 0;
  37099. if( osIsNT() ){
  37100. zConverted = winUtf8ToUnicode(zFilename);
  37101. }
  37102. #ifdef SQLITE_WIN32_HAS_ANSI
  37103. else{
  37104. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  37105. }
  37106. #endif
  37107. /* caller will handle out of memory */
  37108. return zConverted;
  37109. }
  37110. /*
  37111. ** This function returns non-zero if the specified UTF-8 string buffer
  37112. ** ends with a directory separator character or one was successfully
  37113. ** added to it.
  37114. */
  37115. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  37116. if( zBuf ){
  37117. int nLen = sqlite3Strlen30(zBuf);
  37118. if( nLen>0 ){
  37119. if( winIsDirSep(zBuf[nLen-1]) ){
  37120. return 1;
  37121. }else if( nLen+1<nBuf ){
  37122. zBuf[nLen] = winGetDirSep();
  37123. zBuf[nLen+1] = '\0';
  37124. return 1;
  37125. }
  37126. }
  37127. }
  37128. return 0;
  37129. }
  37130. /*
  37131. ** Create a temporary file name and store the resulting pointer into pzBuf.
  37132. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  37133. */
  37134. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  37135. static char zChars[] =
  37136. "abcdefghijklmnopqrstuvwxyz"
  37137. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  37138. "0123456789";
  37139. size_t i, j;
  37140. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  37141. int nMax, nBuf, nDir, nLen;
  37142. char *zBuf;
  37143. /* It's odd to simulate an io-error here, but really this is just
  37144. ** using the io-error infrastructure to test that SQLite handles this
  37145. ** function failing.
  37146. */
  37147. SimulateIOError( return SQLITE_IOERR );
  37148. /* Allocate a temporary buffer to store the fully qualified file
  37149. ** name for the temporary file. If this fails, we cannot continue.
  37150. */
  37151. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  37152. zBuf = sqlite3MallocZero( nBuf );
  37153. if( !zBuf ){
  37154. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37155. return SQLITE_IOERR_NOMEM_BKPT;
  37156. }
  37157. /* Figure out the effective temporary directory. First, check if one
  37158. ** has been explicitly set by the application; otherwise, use the one
  37159. ** configured by the operating system.
  37160. */
  37161. nDir = nMax - (nPre + 15);
  37162. assert( nDir>0 );
  37163. if( sqlite3_temp_directory ){
  37164. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  37165. if( nDirLen>0 ){
  37166. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  37167. nDirLen++;
  37168. }
  37169. if( nDirLen>nDir ){
  37170. sqlite3_free(zBuf);
  37171. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  37172. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  37173. }
  37174. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  37175. }
  37176. }
  37177. #if defined(__CYGWIN__)
  37178. else{
  37179. static const char *azDirs[] = {
  37180. 0, /* getenv("SQLITE_TMPDIR") */
  37181. 0, /* getenv("TMPDIR") */
  37182. 0, /* getenv("TMP") */
  37183. 0, /* getenv("TEMP") */
  37184. 0, /* getenv("USERPROFILE") */
  37185. "/var/tmp",
  37186. "/usr/tmp",
  37187. "/tmp",
  37188. ".",
  37189. 0 /* List terminator */
  37190. };
  37191. unsigned int i;
  37192. const char *zDir = 0;
  37193. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  37194. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  37195. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  37196. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  37197. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  37198. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  37199. void *zConverted;
  37200. if( zDir==0 ) continue;
  37201. /* If the path starts with a drive letter followed by the colon
  37202. ** character, assume it is already a native Win32 path; otherwise,
  37203. ** it must be converted to a native Win32 path via the Cygwin API
  37204. ** prior to using it.
  37205. */
  37206. if( winIsDriveLetterAndColon(zDir) ){
  37207. zConverted = winConvertFromUtf8Filename(zDir);
  37208. if( !zConverted ){
  37209. sqlite3_free(zBuf);
  37210. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37211. return SQLITE_IOERR_NOMEM_BKPT;
  37212. }
  37213. if( winIsDir(zConverted) ){
  37214. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  37215. sqlite3_free(zConverted);
  37216. break;
  37217. }
  37218. sqlite3_free(zConverted);
  37219. }else{
  37220. zConverted = sqlite3MallocZero( nMax+1 );
  37221. if( !zConverted ){
  37222. sqlite3_free(zBuf);
  37223. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37224. return SQLITE_IOERR_NOMEM_BKPT;
  37225. }
  37226. if( cygwin_conv_path(
  37227. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  37228. zConverted, nMax+1)<0 ){
  37229. sqlite3_free(zConverted);
  37230. sqlite3_free(zBuf);
  37231. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  37232. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  37233. "winGetTempname2", zDir);
  37234. }
  37235. if( winIsDir(zConverted) ){
  37236. /* At this point, we know the candidate directory exists and should
  37237. ** be used. However, we may need to convert the string containing
  37238. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  37239. */
  37240. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  37241. if( !zUtf8 ){
  37242. sqlite3_free(zConverted);
  37243. sqlite3_free(zBuf);
  37244. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37245. return SQLITE_IOERR_NOMEM_BKPT;
  37246. }
  37247. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  37248. sqlite3_free(zUtf8);
  37249. sqlite3_free(zConverted);
  37250. break;
  37251. }
  37252. sqlite3_free(zConverted);
  37253. }
  37254. }
  37255. }
  37256. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  37257. else if( osIsNT() ){
  37258. char *zMulti;
  37259. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  37260. if( !zWidePath ){
  37261. sqlite3_free(zBuf);
  37262. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37263. return SQLITE_IOERR_NOMEM_BKPT;
  37264. }
  37265. if( osGetTempPathW(nMax, zWidePath)==0 ){
  37266. sqlite3_free(zWidePath);
  37267. sqlite3_free(zBuf);
  37268. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  37269. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  37270. "winGetTempname2", 0);
  37271. }
  37272. zMulti = winUnicodeToUtf8(zWidePath);
  37273. if( zMulti ){
  37274. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  37275. sqlite3_free(zMulti);
  37276. sqlite3_free(zWidePath);
  37277. }else{
  37278. sqlite3_free(zWidePath);
  37279. sqlite3_free(zBuf);
  37280. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37281. return SQLITE_IOERR_NOMEM_BKPT;
  37282. }
  37283. }
  37284. #ifdef SQLITE_WIN32_HAS_ANSI
  37285. else{
  37286. char *zUtf8;
  37287. char *zMbcsPath = sqlite3MallocZero( nMax );
  37288. if( !zMbcsPath ){
  37289. sqlite3_free(zBuf);
  37290. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37291. return SQLITE_IOERR_NOMEM_BKPT;
  37292. }
  37293. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  37294. sqlite3_free(zBuf);
  37295. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  37296. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  37297. "winGetTempname3", 0);
  37298. }
  37299. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  37300. if( zUtf8 ){
  37301. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  37302. sqlite3_free(zUtf8);
  37303. }else{
  37304. sqlite3_free(zBuf);
  37305. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  37306. return SQLITE_IOERR_NOMEM_BKPT;
  37307. }
  37308. }
  37309. #endif /* SQLITE_WIN32_HAS_ANSI */
  37310. #endif /* !SQLITE_OS_WINRT */
  37311. /*
  37312. ** Check to make sure the temporary directory ends with an appropriate
  37313. ** separator. If it does not and there is not enough space left to add
  37314. ** one, fail.
  37315. */
  37316. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  37317. sqlite3_free(zBuf);
  37318. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  37319. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  37320. }
  37321. /*
  37322. ** Check that the output buffer is large enough for the temporary file
  37323. ** name in the following format:
  37324. **
  37325. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  37326. **
  37327. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  37328. ** account for the space used by the 15 character random suffix and the
  37329. ** two trailing NUL characters. The final directory separator character
  37330. ** has already added if it was not already present.
  37331. */
  37332. nLen = sqlite3Strlen30(zBuf);
  37333. if( (nLen + nPre + 17) > nBuf ){
  37334. sqlite3_free(zBuf);
  37335. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  37336. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  37337. }
  37338. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  37339. j = sqlite3Strlen30(zBuf);
  37340. sqlite3_randomness(15, &zBuf[j]);
  37341. for(i=0; i<15; i++, j++){
  37342. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  37343. }
  37344. zBuf[j] = 0;
  37345. zBuf[j+1] = 0;
  37346. *pzBuf = zBuf;
  37347. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  37348. return SQLITE_OK;
  37349. }
  37350. /*
  37351. ** Return TRUE if the named file is really a directory. Return false if
  37352. ** it is something other than a directory, or if there is any kind of memory
  37353. ** allocation failure.
  37354. */
  37355. static int winIsDir(const void *zConverted){
  37356. DWORD attr;
  37357. int rc = 0;
  37358. DWORD lastErrno;
  37359. if( osIsNT() ){
  37360. int cnt = 0;
  37361. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  37362. memset(&sAttrData, 0, sizeof(sAttrData));
  37363. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  37364. GetFileExInfoStandard,
  37365. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  37366. if( !rc ){
  37367. return 0; /* Invalid name? */
  37368. }
  37369. attr = sAttrData.dwFileAttributes;
  37370. #if SQLITE_OS_WINCE==0
  37371. }else{
  37372. attr = osGetFileAttributesA((char*)zConverted);
  37373. #endif
  37374. }
  37375. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  37376. }
  37377. /*
  37378. ** Open a file.
  37379. */
  37380. static int winOpen(
  37381. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  37382. const char *zName, /* Name of the file (UTF-8) */
  37383. sqlite3_file *id, /* Write the SQLite file handle here */
  37384. int flags, /* Open mode flags */
  37385. int *pOutFlags /* Status return flags */
  37386. ){
  37387. HANDLE h;
  37388. DWORD lastErrno = 0;
  37389. DWORD dwDesiredAccess;
  37390. DWORD dwShareMode;
  37391. DWORD dwCreationDisposition;
  37392. DWORD dwFlagsAndAttributes = 0;
  37393. #if SQLITE_OS_WINCE
  37394. int isTemp = 0;
  37395. #endif
  37396. winFile *pFile = (winFile*)id;
  37397. void *zConverted; /* Filename in OS encoding */
  37398. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  37399. int cnt = 0;
  37400. /* If argument zPath is a NULL pointer, this function is required to open
  37401. ** a temporary file. Use this buffer to store the file name in.
  37402. */
  37403. char *zTmpname = 0; /* For temporary filename, if necessary. */
  37404. int rc = SQLITE_OK; /* Function Return Code */
  37405. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  37406. int eType = flags&0xFFFFFF00; /* Type of file to open */
  37407. #endif
  37408. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  37409. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  37410. int isCreate = (flags & SQLITE_OPEN_CREATE);
  37411. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  37412. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  37413. #ifndef NDEBUG
  37414. int isOpenJournal = (isCreate && (
  37415. eType==SQLITE_OPEN_MASTER_JOURNAL
  37416. || eType==SQLITE_OPEN_MAIN_JOURNAL
  37417. || eType==SQLITE_OPEN_WAL
  37418. ));
  37419. #endif
  37420. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  37421. zUtf8Name, id, flags, pOutFlags));
  37422. /* Check the following statements are true:
  37423. **
  37424. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  37425. ** (b) if CREATE is set, then READWRITE must also be set, and
  37426. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  37427. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  37428. */
  37429. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  37430. assert(isCreate==0 || isReadWrite);
  37431. assert(isExclusive==0 || isCreate);
  37432. assert(isDelete==0 || isCreate);
  37433. /* The main DB, main journal, WAL file and master journal are never
  37434. ** automatically deleted. Nor are they ever temporary files. */
  37435. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  37436. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  37437. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  37438. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  37439. /* Assert that the upper layer has set one of the "file-type" flags. */
  37440. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  37441. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  37442. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  37443. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  37444. );
  37445. assert( pFile!=0 );
  37446. memset(pFile, 0, sizeof(winFile));
  37447. pFile->h = INVALID_HANDLE_VALUE;
  37448. #if SQLITE_OS_WINRT
  37449. if( !zUtf8Name && !sqlite3_temp_directory ){
  37450. sqlite3_log(SQLITE_ERROR,
  37451. "sqlite3_temp_directory variable should be set for WinRT");
  37452. }
  37453. #endif
  37454. /* If the second argument to this function is NULL, generate a
  37455. ** temporary file name to use
  37456. */
  37457. if( !zUtf8Name ){
  37458. assert( isDelete && !isOpenJournal );
  37459. rc = winGetTempname(pVfs, &zTmpname);
  37460. if( rc!=SQLITE_OK ){
  37461. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  37462. return rc;
  37463. }
  37464. zUtf8Name = zTmpname;
  37465. }
  37466. /* Database filenames are double-zero terminated if they are not
  37467. ** URIs with parameters. Hence, they can always be passed into
  37468. ** sqlite3_uri_parameter().
  37469. */
  37470. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  37471. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  37472. /* Convert the filename to the system encoding. */
  37473. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  37474. if( zConverted==0 ){
  37475. sqlite3_free(zTmpname);
  37476. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  37477. return SQLITE_IOERR_NOMEM_BKPT;
  37478. }
  37479. if( winIsDir(zConverted) ){
  37480. sqlite3_free(zConverted);
  37481. sqlite3_free(zTmpname);
  37482. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  37483. return SQLITE_CANTOPEN_ISDIR;
  37484. }
  37485. if( isReadWrite ){
  37486. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  37487. }else{
  37488. dwDesiredAccess = GENERIC_READ;
  37489. }
  37490. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  37491. ** created. SQLite doesn't use it to indicate "exclusive access"
  37492. ** as it is usually understood.
  37493. */
  37494. if( isExclusive ){
  37495. /* Creates a new file, only if it does not already exist. */
  37496. /* If the file exists, it fails. */
  37497. dwCreationDisposition = CREATE_NEW;
  37498. }else if( isCreate ){
  37499. /* Open existing file, or create if it doesn't exist */
  37500. dwCreationDisposition = OPEN_ALWAYS;
  37501. }else{
  37502. /* Opens a file, only if it exists. */
  37503. dwCreationDisposition = OPEN_EXISTING;
  37504. }
  37505. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  37506. if( isDelete ){
  37507. #if SQLITE_OS_WINCE
  37508. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  37509. isTemp = 1;
  37510. #else
  37511. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  37512. | FILE_ATTRIBUTE_HIDDEN
  37513. | FILE_FLAG_DELETE_ON_CLOSE;
  37514. #endif
  37515. }else{
  37516. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  37517. }
  37518. /* Reports from the internet are that performance is always
  37519. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  37520. #if SQLITE_OS_WINCE
  37521. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  37522. #endif
  37523. if( osIsNT() ){
  37524. #if SQLITE_OS_WINRT
  37525. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  37526. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  37527. extendedParameters.dwFileAttributes =
  37528. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  37529. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  37530. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  37531. extendedParameters.lpSecurityAttributes = NULL;
  37532. extendedParameters.hTemplateFile = NULL;
  37533. while( (h = osCreateFile2((LPCWSTR)zConverted,
  37534. dwDesiredAccess,
  37535. dwShareMode,
  37536. dwCreationDisposition,
  37537. &extendedParameters))==INVALID_HANDLE_VALUE &&
  37538. winRetryIoerr(&cnt, &lastErrno) ){
  37539. /* Noop */
  37540. }
  37541. #else
  37542. while( (h = osCreateFileW((LPCWSTR)zConverted,
  37543. dwDesiredAccess,
  37544. dwShareMode, NULL,
  37545. dwCreationDisposition,
  37546. dwFlagsAndAttributes,
  37547. NULL))==INVALID_HANDLE_VALUE &&
  37548. winRetryIoerr(&cnt, &lastErrno) ){
  37549. /* Noop */
  37550. }
  37551. #endif
  37552. }
  37553. #ifdef SQLITE_WIN32_HAS_ANSI
  37554. else{
  37555. while( (h = osCreateFileA((LPCSTR)zConverted,
  37556. dwDesiredAccess,
  37557. dwShareMode, NULL,
  37558. dwCreationDisposition,
  37559. dwFlagsAndAttributes,
  37560. NULL))==INVALID_HANDLE_VALUE &&
  37561. winRetryIoerr(&cnt, &lastErrno) ){
  37562. /* Noop */
  37563. }
  37564. }
  37565. #endif
  37566. winLogIoerr(cnt, __LINE__);
  37567. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  37568. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  37569. if( h==INVALID_HANDLE_VALUE ){
  37570. pFile->lastErrno = lastErrno;
  37571. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  37572. sqlite3_free(zConverted);
  37573. sqlite3_free(zTmpname);
  37574. if( isReadWrite && !isExclusive ){
  37575. return winOpen(pVfs, zName, id,
  37576. ((flags|SQLITE_OPEN_READONLY) &
  37577. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  37578. pOutFlags);
  37579. }else{
  37580. return SQLITE_CANTOPEN_BKPT;
  37581. }
  37582. }
  37583. if( pOutFlags ){
  37584. if( isReadWrite ){
  37585. *pOutFlags = SQLITE_OPEN_READWRITE;
  37586. }else{
  37587. *pOutFlags = SQLITE_OPEN_READONLY;
  37588. }
  37589. }
  37590. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  37591. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  37592. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  37593. #if SQLITE_OS_WINCE
  37594. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  37595. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  37596. ){
  37597. osCloseHandle(h);
  37598. sqlite3_free(zConverted);
  37599. sqlite3_free(zTmpname);
  37600. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  37601. return rc;
  37602. }
  37603. if( isTemp ){
  37604. pFile->zDeleteOnClose = zConverted;
  37605. }else
  37606. #endif
  37607. {
  37608. sqlite3_free(zConverted);
  37609. }
  37610. sqlite3_free(zTmpname);
  37611. pFile->pMethod = &winIoMethod;
  37612. pFile->pVfs = pVfs;
  37613. pFile->h = h;
  37614. if( isReadonly ){
  37615. pFile->ctrlFlags |= WINFILE_RDONLY;
  37616. }
  37617. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  37618. pFile->ctrlFlags |= WINFILE_PSOW;
  37619. }
  37620. pFile->lastErrno = NO_ERROR;
  37621. pFile->zPath = zName;
  37622. #if SQLITE_MAX_MMAP_SIZE>0
  37623. pFile->hMap = NULL;
  37624. pFile->pMapRegion = 0;
  37625. pFile->mmapSize = 0;
  37626. pFile->mmapSizeActual = 0;
  37627. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  37628. #endif
  37629. OpenCounter(+1);
  37630. return rc;
  37631. }
  37632. /*
  37633. ** Delete the named file.
  37634. **
  37635. ** Note that Windows does not allow a file to be deleted if some other
  37636. ** process has it open. Sometimes a virus scanner or indexing program
  37637. ** will open a journal file shortly after it is created in order to do
  37638. ** whatever it does. While this other process is holding the
  37639. ** file open, we will be unable to delete it. To work around this
  37640. ** problem, we delay 100 milliseconds and try to delete again. Up
  37641. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  37642. ** up and returning an error.
  37643. */
  37644. static int winDelete(
  37645. sqlite3_vfs *pVfs, /* Not used on win32 */
  37646. const char *zFilename, /* Name of file to delete */
  37647. int syncDir /* Not used on win32 */
  37648. ){
  37649. int cnt = 0;
  37650. int rc;
  37651. DWORD attr;
  37652. DWORD lastErrno = 0;
  37653. void *zConverted;
  37654. UNUSED_PARAMETER(pVfs);
  37655. UNUSED_PARAMETER(syncDir);
  37656. SimulateIOError(return SQLITE_IOERR_DELETE);
  37657. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  37658. zConverted = winConvertFromUtf8Filename(zFilename);
  37659. if( zConverted==0 ){
  37660. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  37661. return SQLITE_IOERR_NOMEM_BKPT;
  37662. }
  37663. if( osIsNT() ){
  37664. do {
  37665. #if SQLITE_OS_WINRT
  37666. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  37667. memset(&sAttrData, 0, sizeof(sAttrData));
  37668. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  37669. &sAttrData) ){
  37670. attr = sAttrData.dwFileAttributes;
  37671. }else{
  37672. lastErrno = osGetLastError();
  37673. if( lastErrno==ERROR_FILE_NOT_FOUND
  37674. || lastErrno==ERROR_PATH_NOT_FOUND ){
  37675. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  37676. }else{
  37677. rc = SQLITE_ERROR;
  37678. }
  37679. break;
  37680. }
  37681. #else
  37682. attr = osGetFileAttributesW(zConverted);
  37683. #endif
  37684. if ( attr==INVALID_FILE_ATTRIBUTES ){
  37685. lastErrno = osGetLastError();
  37686. if( lastErrno==ERROR_FILE_NOT_FOUND
  37687. || lastErrno==ERROR_PATH_NOT_FOUND ){
  37688. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  37689. }else{
  37690. rc = SQLITE_ERROR;
  37691. }
  37692. break;
  37693. }
  37694. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  37695. rc = SQLITE_ERROR; /* Files only. */
  37696. break;
  37697. }
  37698. if ( osDeleteFileW(zConverted) ){
  37699. rc = SQLITE_OK; /* Deleted OK. */
  37700. break;
  37701. }
  37702. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  37703. rc = SQLITE_ERROR; /* No more retries. */
  37704. break;
  37705. }
  37706. } while(1);
  37707. }
  37708. #ifdef SQLITE_WIN32_HAS_ANSI
  37709. else{
  37710. do {
  37711. attr = osGetFileAttributesA(zConverted);
  37712. if ( attr==INVALID_FILE_ATTRIBUTES ){
  37713. lastErrno = osGetLastError();
  37714. if( lastErrno==ERROR_FILE_NOT_FOUND
  37715. || lastErrno==ERROR_PATH_NOT_FOUND ){
  37716. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  37717. }else{
  37718. rc = SQLITE_ERROR;
  37719. }
  37720. break;
  37721. }
  37722. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  37723. rc = SQLITE_ERROR; /* Files only. */
  37724. break;
  37725. }
  37726. if ( osDeleteFileA(zConverted) ){
  37727. rc = SQLITE_OK; /* Deleted OK. */
  37728. break;
  37729. }
  37730. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  37731. rc = SQLITE_ERROR; /* No more retries. */
  37732. break;
  37733. }
  37734. } while(1);
  37735. }
  37736. #endif
  37737. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  37738. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  37739. }else{
  37740. winLogIoerr(cnt, __LINE__);
  37741. }
  37742. sqlite3_free(zConverted);
  37743. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  37744. return rc;
  37745. }
  37746. /*
  37747. ** Check the existence and status of a file.
  37748. */
  37749. static int winAccess(
  37750. sqlite3_vfs *pVfs, /* Not used on win32 */
  37751. const char *zFilename, /* Name of file to check */
  37752. int flags, /* Type of test to make on this file */
  37753. int *pResOut /* OUT: Result */
  37754. ){
  37755. DWORD attr;
  37756. int rc = 0;
  37757. DWORD lastErrno = 0;
  37758. void *zConverted;
  37759. UNUSED_PARAMETER(pVfs);
  37760. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  37761. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  37762. zFilename, flags, pResOut));
  37763. zConverted = winConvertFromUtf8Filename(zFilename);
  37764. if( zConverted==0 ){
  37765. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  37766. return SQLITE_IOERR_NOMEM_BKPT;
  37767. }
  37768. if( osIsNT() ){
  37769. int cnt = 0;
  37770. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  37771. memset(&sAttrData, 0, sizeof(sAttrData));
  37772. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  37773. GetFileExInfoStandard,
  37774. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  37775. if( rc ){
  37776. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  37777. ** as if it does not exist.
  37778. */
  37779. if( flags==SQLITE_ACCESS_EXISTS
  37780. && sAttrData.nFileSizeHigh==0
  37781. && sAttrData.nFileSizeLow==0 ){
  37782. attr = INVALID_FILE_ATTRIBUTES;
  37783. }else{
  37784. attr = sAttrData.dwFileAttributes;
  37785. }
  37786. }else{
  37787. winLogIoerr(cnt, __LINE__);
  37788. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  37789. sqlite3_free(zConverted);
  37790. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  37791. zFilename);
  37792. }else{
  37793. attr = INVALID_FILE_ATTRIBUTES;
  37794. }
  37795. }
  37796. }
  37797. #ifdef SQLITE_WIN32_HAS_ANSI
  37798. else{
  37799. attr = osGetFileAttributesA((char*)zConverted);
  37800. }
  37801. #endif
  37802. sqlite3_free(zConverted);
  37803. switch( flags ){
  37804. case SQLITE_ACCESS_READ:
  37805. case SQLITE_ACCESS_EXISTS:
  37806. rc = attr!=INVALID_FILE_ATTRIBUTES;
  37807. break;
  37808. case SQLITE_ACCESS_READWRITE:
  37809. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  37810. (attr & FILE_ATTRIBUTE_READONLY)==0;
  37811. break;
  37812. default:
  37813. assert(!"Invalid flags argument");
  37814. }
  37815. *pResOut = rc;
  37816. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  37817. zFilename, pResOut, *pResOut));
  37818. return SQLITE_OK;
  37819. }
  37820. /*
  37821. ** Returns non-zero if the specified path name starts with a drive letter
  37822. ** followed by a colon character.
  37823. */
  37824. static BOOL winIsDriveLetterAndColon(
  37825. const char *zPathname
  37826. ){
  37827. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  37828. }
  37829. /*
  37830. ** Returns non-zero if the specified path name should be used verbatim. If
  37831. ** non-zero is returned from this function, the calling function must simply
  37832. ** use the provided path name verbatim -OR- resolve it into a full path name
  37833. ** using the GetFullPathName Win32 API function (if available).
  37834. */
  37835. static BOOL winIsVerbatimPathname(
  37836. const char *zPathname
  37837. ){
  37838. /*
  37839. ** If the path name starts with a forward slash or a backslash, it is either
  37840. ** a legal UNC name, a volume relative path, or an absolute path name in the
  37841. ** "Unix" format on Windows. There is no easy way to differentiate between
  37842. ** the final two cases; therefore, we return the safer return value of TRUE
  37843. ** so that callers of this function will simply use it verbatim.
  37844. */
  37845. if ( winIsDirSep(zPathname[0]) ){
  37846. return TRUE;
  37847. }
  37848. /*
  37849. ** If the path name starts with a letter and a colon it is either a volume
  37850. ** relative path or an absolute path. Callers of this function must not
  37851. ** attempt to treat it as a relative path name (i.e. they should simply use
  37852. ** it verbatim).
  37853. */
  37854. if ( winIsDriveLetterAndColon(zPathname) ){
  37855. return TRUE;
  37856. }
  37857. /*
  37858. ** If we get to this point, the path name should almost certainly be a purely
  37859. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  37860. */
  37861. return FALSE;
  37862. }
  37863. /*
  37864. ** Turn a relative pathname into a full pathname. Write the full
  37865. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  37866. ** bytes in size.
  37867. */
  37868. static int winFullPathname(
  37869. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  37870. const char *zRelative, /* Possibly relative input path */
  37871. int nFull, /* Size of output buffer in bytes */
  37872. char *zFull /* Output buffer */
  37873. ){
  37874. #if defined(__CYGWIN__)
  37875. SimulateIOError( return SQLITE_ERROR );
  37876. UNUSED_PARAMETER(nFull);
  37877. assert( nFull>=pVfs->mxPathname );
  37878. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37879. /*
  37880. ** NOTE: We are dealing with a relative path name and the data
  37881. ** directory has been set. Therefore, use it as the basis
  37882. ** for converting the relative path name to an absolute
  37883. ** one by prepending the data directory and a slash.
  37884. */
  37885. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  37886. if( !zOut ){
  37887. return SQLITE_IOERR_NOMEM_BKPT;
  37888. }
  37889. if( cygwin_conv_path(
  37890. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  37891. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  37892. sqlite3_free(zOut);
  37893. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  37894. "winFullPathname1", zRelative);
  37895. }else{
  37896. char *zUtf8 = winConvertToUtf8Filename(zOut);
  37897. if( !zUtf8 ){
  37898. sqlite3_free(zOut);
  37899. return SQLITE_IOERR_NOMEM_BKPT;
  37900. }
  37901. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37902. sqlite3_data_directory, winGetDirSep(), zUtf8);
  37903. sqlite3_free(zUtf8);
  37904. sqlite3_free(zOut);
  37905. }
  37906. }else{
  37907. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  37908. if( !zOut ){
  37909. return SQLITE_IOERR_NOMEM_BKPT;
  37910. }
  37911. if( cygwin_conv_path(
  37912. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  37913. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  37914. sqlite3_free(zOut);
  37915. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  37916. "winFullPathname2", zRelative);
  37917. }else{
  37918. char *zUtf8 = winConvertToUtf8Filename(zOut);
  37919. if( !zUtf8 ){
  37920. sqlite3_free(zOut);
  37921. return SQLITE_IOERR_NOMEM_BKPT;
  37922. }
  37923. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  37924. sqlite3_free(zUtf8);
  37925. sqlite3_free(zOut);
  37926. }
  37927. }
  37928. return SQLITE_OK;
  37929. #endif
  37930. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  37931. SimulateIOError( return SQLITE_ERROR );
  37932. /* WinCE has no concept of a relative pathname, or so I am told. */
  37933. /* WinRT has no way to convert a relative path to an absolute one. */
  37934. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37935. /*
  37936. ** NOTE: We are dealing with a relative path name and the data
  37937. ** directory has been set. Therefore, use it as the basis
  37938. ** for converting the relative path name to an absolute
  37939. ** one by prepending the data directory and a backslash.
  37940. */
  37941. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37942. sqlite3_data_directory, winGetDirSep(), zRelative);
  37943. }else{
  37944. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  37945. }
  37946. return SQLITE_OK;
  37947. #endif
  37948. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  37949. DWORD nByte;
  37950. void *zConverted;
  37951. char *zOut;
  37952. /* If this path name begins with "/X:", where "X" is any alphabetic
  37953. ** character, discard the initial "/" from the pathname.
  37954. */
  37955. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  37956. zRelative++;
  37957. }
  37958. /* It's odd to simulate an io-error here, but really this is just
  37959. ** using the io-error infrastructure to test that SQLite handles this
  37960. ** function failing. This function could fail if, for example, the
  37961. ** current working directory has been unlinked.
  37962. */
  37963. SimulateIOError( return SQLITE_ERROR );
  37964. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37965. /*
  37966. ** NOTE: We are dealing with a relative path name and the data
  37967. ** directory has been set. Therefore, use it as the basis
  37968. ** for converting the relative path name to an absolute
  37969. ** one by prepending the data directory and a backslash.
  37970. */
  37971. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37972. sqlite3_data_directory, winGetDirSep(), zRelative);
  37973. return SQLITE_OK;
  37974. }
  37975. zConverted = winConvertFromUtf8Filename(zRelative);
  37976. if( zConverted==0 ){
  37977. return SQLITE_IOERR_NOMEM_BKPT;
  37978. }
  37979. if( osIsNT() ){
  37980. LPWSTR zTemp;
  37981. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  37982. if( nByte==0 ){
  37983. sqlite3_free(zConverted);
  37984. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37985. "winFullPathname1", zRelative);
  37986. }
  37987. nByte += 3;
  37988. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  37989. if( zTemp==0 ){
  37990. sqlite3_free(zConverted);
  37991. return SQLITE_IOERR_NOMEM_BKPT;
  37992. }
  37993. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  37994. if( nByte==0 ){
  37995. sqlite3_free(zConverted);
  37996. sqlite3_free(zTemp);
  37997. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37998. "winFullPathname2", zRelative);
  37999. }
  38000. sqlite3_free(zConverted);
  38001. zOut = winUnicodeToUtf8(zTemp);
  38002. sqlite3_free(zTemp);
  38003. }
  38004. #ifdef SQLITE_WIN32_HAS_ANSI
  38005. else{
  38006. char *zTemp;
  38007. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  38008. if( nByte==0 ){
  38009. sqlite3_free(zConverted);
  38010. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  38011. "winFullPathname3", zRelative);
  38012. }
  38013. nByte += 3;
  38014. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  38015. if( zTemp==0 ){
  38016. sqlite3_free(zConverted);
  38017. return SQLITE_IOERR_NOMEM_BKPT;
  38018. }
  38019. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  38020. if( nByte==0 ){
  38021. sqlite3_free(zConverted);
  38022. sqlite3_free(zTemp);
  38023. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  38024. "winFullPathname4", zRelative);
  38025. }
  38026. sqlite3_free(zConverted);
  38027. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  38028. sqlite3_free(zTemp);
  38029. }
  38030. #endif
  38031. if( zOut ){
  38032. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  38033. sqlite3_free(zOut);
  38034. return SQLITE_OK;
  38035. }else{
  38036. return SQLITE_IOERR_NOMEM_BKPT;
  38037. }
  38038. #endif
  38039. }
  38040. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  38041. /*
  38042. ** Interfaces for opening a shared library, finding entry points
  38043. ** within the shared library, and closing the shared library.
  38044. */
  38045. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  38046. HANDLE h;
  38047. #if defined(__CYGWIN__)
  38048. int nFull = pVfs->mxPathname+1;
  38049. char *zFull = sqlite3MallocZero( nFull );
  38050. void *zConverted = 0;
  38051. if( zFull==0 ){
  38052. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  38053. return 0;
  38054. }
  38055. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  38056. sqlite3_free(zFull);
  38057. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  38058. return 0;
  38059. }
  38060. zConverted = winConvertFromUtf8Filename(zFull);
  38061. sqlite3_free(zFull);
  38062. #else
  38063. void *zConverted = winConvertFromUtf8Filename(zFilename);
  38064. UNUSED_PARAMETER(pVfs);
  38065. #endif
  38066. if( zConverted==0 ){
  38067. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  38068. return 0;
  38069. }
  38070. if( osIsNT() ){
  38071. #if SQLITE_OS_WINRT
  38072. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  38073. #else
  38074. h = osLoadLibraryW((LPCWSTR)zConverted);
  38075. #endif
  38076. }
  38077. #ifdef SQLITE_WIN32_HAS_ANSI
  38078. else{
  38079. h = osLoadLibraryA((char*)zConverted);
  38080. }
  38081. #endif
  38082. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  38083. sqlite3_free(zConverted);
  38084. return (void*)h;
  38085. }
  38086. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  38087. UNUSED_PARAMETER(pVfs);
  38088. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  38089. }
  38090. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  38091. FARPROC proc;
  38092. UNUSED_PARAMETER(pVfs);
  38093. proc = osGetProcAddressA((HANDLE)pH, zSym);
  38094. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  38095. (void*)pH, zSym, (void*)proc));
  38096. return (void(*)(void))proc;
  38097. }
  38098. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  38099. UNUSED_PARAMETER(pVfs);
  38100. osFreeLibrary((HANDLE)pHandle);
  38101. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  38102. }
  38103. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  38104. #define winDlOpen 0
  38105. #define winDlError 0
  38106. #define winDlSym 0
  38107. #define winDlClose 0
  38108. #endif
  38109. /* State information for the randomness gatherer. */
  38110. typedef struct EntropyGatherer EntropyGatherer;
  38111. struct EntropyGatherer {
  38112. unsigned char *a; /* Gather entropy into this buffer */
  38113. int na; /* Size of a[] in bytes */
  38114. int i; /* XOR next input into a[i] */
  38115. int nXor; /* Number of XOR operations done */
  38116. };
  38117. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  38118. /* Mix sz bytes of entropy into p. */
  38119. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  38120. int j, k;
  38121. for(j=0, k=p->i; j<sz; j++){
  38122. p->a[k++] ^= x[j];
  38123. if( k>=p->na ) k = 0;
  38124. }
  38125. p->i = k;
  38126. p->nXor += sz;
  38127. }
  38128. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  38129. /*
  38130. ** Write up to nBuf bytes of randomness into zBuf.
  38131. */
  38132. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  38133. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  38134. UNUSED_PARAMETER(pVfs);
  38135. memset(zBuf, 0, nBuf);
  38136. return nBuf;
  38137. #else
  38138. EntropyGatherer e;
  38139. UNUSED_PARAMETER(pVfs);
  38140. memset(zBuf, 0, nBuf);
  38141. #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
  38142. rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
  38143. #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
  38144. e.a = (unsigned char*)zBuf;
  38145. e.na = nBuf;
  38146. e.nXor = 0;
  38147. e.i = 0;
  38148. {
  38149. SYSTEMTIME x;
  38150. osGetSystemTime(&x);
  38151. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  38152. }
  38153. {
  38154. DWORD pid = osGetCurrentProcessId();
  38155. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  38156. }
  38157. #if SQLITE_OS_WINRT
  38158. {
  38159. ULONGLONG cnt = osGetTickCount64();
  38160. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  38161. }
  38162. #else
  38163. {
  38164. DWORD cnt = osGetTickCount();
  38165. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  38166. }
  38167. #endif /* SQLITE_OS_WINRT */
  38168. {
  38169. LARGE_INTEGER i;
  38170. osQueryPerformanceCounter(&i);
  38171. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  38172. }
  38173. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  38174. {
  38175. UUID id;
  38176. memset(&id, 0, sizeof(UUID));
  38177. osUuidCreate(&id);
  38178. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  38179. memset(&id, 0, sizeof(UUID));
  38180. osUuidCreateSequential(&id);
  38181. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  38182. }
  38183. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  38184. return e.nXor>nBuf ? nBuf : e.nXor;
  38185. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  38186. }
  38187. /*
  38188. ** Sleep for a little while. Return the amount of time slept.
  38189. */
  38190. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  38191. sqlite3_win32_sleep((microsec+999)/1000);
  38192. UNUSED_PARAMETER(pVfs);
  38193. return ((microsec+999)/1000)*1000;
  38194. }
  38195. /*
  38196. ** The following variable, if set to a non-zero value, is interpreted as
  38197. ** the number of seconds since 1970 and is used to set the result of
  38198. ** sqlite3OsCurrentTime() during testing.
  38199. */
  38200. #ifdef SQLITE_TEST
  38201. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  38202. #endif
  38203. /*
  38204. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  38205. ** the current time and date as a Julian Day number times 86_400_000. In
  38206. ** other words, write into *piNow the number of milliseconds since the Julian
  38207. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  38208. ** proleptic Gregorian calendar.
  38209. **
  38210. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  38211. ** cannot be found.
  38212. */
  38213. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  38214. /* FILETIME structure is a 64-bit value representing the number of
  38215. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  38216. */
  38217. FILETIME ft;
  38218. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  38219. #ifdef SQLITE_TEST
  38220. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  38221. #endif
  38222. /* 2^32 - to avoid use of LL and warnings in gcc */
  38223. static const sqlite3_int64 max32BitValue =
  38224. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  38225. (sqlite3_int64)294967296;
  38226. #if SQLITE_OS_WINCE
  38227. SYSTEMTIME time;
  38228. osGetSystemTime(&time);
  38229. /* if SystemTimeToFileTime() fails, it returns zero. */
  38230. if (!osSystemTimeToFileTime(&time,&ft)){
  38231. return SQLITE_ERROR;
  38232. }
  38233. #else
  38234. osGetSystemTimeAsFileTime( &ft );
  38235. #endif
  38236. *piNow = winFiletimeEpoch +
  38237. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  38238. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  38239. #ifdef SQLITE_TEST
  38240. if( sqlite3_current_time ){
  38241. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  38242. }
  38243. #endif
  38244. UNUSED_PARAMETER(pVfs);
  38245. return SQLITE_OK;
  38246. }
  38247. /*
  38248. ** Find the current time (in Universal Coordinated Time). Write the
  38249. ** current time and date as a Julian Day number into *prNow and
  38250. ** return 0. Return 1 if the time and date cannot be found.
  38251. */
  38252. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  38253. int rc;
  38254. sqlite3_int64 i;
  38255. rc = winCurrentTimeInt64(pVfs, &i);
  38256. if( !rc ){
  38257. *prNow = i/86400000.0;
  38258. }
  38259. return rc;
  38260. }
  38261. /*
  38262. ** The idea is that this function works like a combination of
  38263. ** GetLastError() and FormatMessage() on Windows (or errno and
  38264. ** strerror_r() on Unix). After an error is returned by an OS
  38265. ** function, SQLite calls this function with zBuf pointing to
  38266. ** a buffer of nBuf bytes. The OS layer should populate the
  38267. ** buffer with a nul-terminated UTF-8 encoded error message
  38268. ** describing the last IO error to have occurred within the calling
  38269. ** thread.
  38270. **
  38271. ** If the error message is too large for the supplied buffer,
  38272. ** it should be truncated. The return value of xGetLastError
  38273. ** is zero if the error message fits in the buffer, or non-zero
  38274. ** otherwise (if the message was truncated). If non-zero is returned,
  38275. ** then it is not necessary to include the nul-terminator character
  38276. ** in the output buffer.
  38277. **
  38278. ** Not supplying an error message will have no adverse effect
  38279. ** on SQLite. It is fine to have an implementation that never
  38280. ** returns an error message:
  38281. **
  38282. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  38283. ** assert(zBuf[0]=='\0');
  38284. ** return 0;
  38285. ** }
  38286. **
  38287. ** However if an error message is supplied, it will be incorporated
  38288. ** by sqlite into the error message available to the user using
  38289. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  38290. */
  38291. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  38292. DWORD e = osGetLastError();
  38293. UNUSED_PARAMETER(pVfs);
  38294. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  38295. return e;
  38296. }
  38297. /*
  38298. ** Initialize and deinitialize the operating system interface.
  38299. */
  38300. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  38301. static sqlite3_vfs winVfs = {
  38302. 3, /* iVersion */
  38303. sizeof(winFile), /* szOsFile */
  38304. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  38305. 0, /* pNext */
  38306. "win32", /* zName */
  38307. 0, /* pAppData */
  38308. winOpen, /* xOpen */
  38309. winDelete, /* xDelete */
  38310. winAccess, /* xAccess */
  38311. winFullPathname, /* xFullPathname */
  38312. winDlOpen, /* xDlOpen */
  38313. winDlError, /* xDlError */
  38314. winDlSym, /* xDlSym */
  38315. winDlClose, /* xDlClose */
  38316. winRandomness, /* xRandomness */
  38317. winSleep, /* xSleep */
  38318. winCurrentTime, /* xCurrentTime */
  38319. winGetLastError, /* xGetLastError */
  38320. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  38321. winSetSystemCall, /* xSetSystemCall */
  38322. winGetSystemCall, /* xGetSystemCall */
  38323. winNextSystemCall, /* xNextSystemCall */
  38324. };
  38325. #if defined(SQLITE_WIN32_HAS_WIDE)
  38326. static sqlite3_vfs winLongPathVfs = {
  38327. 3, /* iVersion */
  38328. sizeof(winFile), /* szOsFile */
  38329. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  38330. 0, /* pNext */
  38331. "win32-longpath", /* zName */
  38332. 0, /* pAppData */
  38333. winOpen, /* xOpen */
  38334. winDelete, /* xDelete */
  38335. winAccess, /* xAccess */
  38336. winFullPathname, /* xFullPathname */
  38337. winDlOpen, /* xDlOpen */
  38338. winDlError, /* xDlError */
  38339. winDlSym, /* xDlSym */
  38340. winDlClose, /* xDlClose */
  38341. winRandomness, /* xRandomness */
  38342. winSleep, /* xSleep */
  38343. winCurrentTime, /* xCurrentTime */
  38344. winGetLastError, /* xGetLastError */
  38345. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  38346. winSetSystemCall, /* xSetSystemCall */
  38347. winGetSystemCall, /* xGetSystemCall */
  38348. winNextSystemCall, /* xNextSystemCall */
  38349. };
  38350. #endif
  38351. /* Double-check that the aSyscall[] array has been constructed
  38352. ** correctly. See ticket [bb3a86e890c8e96ab] */
  38353. assert( ArraySize(aSyscall)==80 );
  38354. /* get memory map allocation granularity */
  38355. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  38356. #if SQLITE_OS_WINRT
  38357. osGetNativeSystemInfo(&winSysInfo);
  38358. #else
  38359. osGetSystemInfo(&winSysInfo);
  38360. #endif
  38361. assert( winSysInfo.dwAllocationGranularity>0 );
  38362. assert( winSysInfo.dwPageSize>0 );
  38363. sqlite3_vfs_register(&winVfs, 1);
  38364. #if defined(SQLITE_WIN32_HAS_WIDE)
  38365. sqlite3_vfs_register(&winLongPathVfs, 0);
  38366. #endif
  38367. return SQLITE_OK;
  38368. }
  38369. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  38370. #if SQLITE_OS_WINRT
  38371. if( sleepObj!=NULL ){
  38372. osCloseHandle(sleepObj);
  38373. sleepObj = NULL;
  38374. }
  38375. #endif
  38376. return SQLITE_OK;
  38377. }
  38378. #endif /* SQLITE_OS_WIN */
  38379. /************** End of os_win.c **********************************************/
  38380. /************** Begin file bitvec.c ******************************************/
  38381. /*
  38382. ** 2008 February 16
  38383. **
  38384. ** The author disclaims copyright to this source code. In place of
  38385. ** a legal notice, here is a blessing:
  38386. **
  38387. ** May you do good and not evil.
  38388. ** May you find forgiveness for yourself and forgive others.
  38389. ** May you share freely, never taking more than you give.
  38390. **
  38391. *************************************************************************
  38392. ** This file implements an object that represents a fixed-length
  38393. ** bitmap. Bits are numbered starting with 1.
  38394. **
  38395. ** A bitmap is used to record which pages of a database file have been
  38396. ** journalled during a transaction, or which pages have the "dont-write"
  38397. ** property. Usually only a few pages are meet either condition.
  38398. ** So the bitmap is usually sparse and has low cardinality.
  38399. ** But sometimes (for example when during a DROP of a large table) most
  38400. ** or all of the pages in a database can get journalled. In those cases,
  38401. ** the bitmap becomes dense with high cardinality. The algorithm needs
  38402. ** to handle both cases well.
  38403. **
  38404. ** The size of the bitmap is fixed when the object is created.
  38405. **
  38406. ** All bits are clear when the bitmap is created. Individual bits
  38407. ** may be set or cleared one at a time.
  38408. **
  38409. ** Test operations are about 100 times more common that set operations.
  38410. ** Clear operations are exceedingly rare. There are usually between
  38411. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  38412. ** sometimes grow into tens of thousands or larger. The size of the
  38413. ** Bitvec object is the number of pages in the database file at the
  38414. ** start of a transaction, and is thus usually less than a few thousand,
  38415. ** but can be as large as 2 billion for a really big database.
  38416. */
  38417. /* #include "sqliteInt.h" */
  38418. /* Size of the Bitvec structure in bytes. */
  38419. #define BITVEC_SZ 512
  38420. /* Round the union size down to the nearest pointer boundary, since that's how
  38421. ** it will be aligned within the Bitvec struct. */
  38422. #define BITVEC_USIZE \
  38423. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  38424. /* Type of the array "element" for the bitmap representation.
  38425. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  38426. ** Setting this to the "natural word" size of your CPU may improve
  38427. ** performance. */
  38428. #define BITVEC_TELEM u8
  38429. /* Size, in bits, of the bitmap element. */
  38430. #define BITVEC_SZELEM 8
  38431. /* Number of elements in a bitmap array. */
  38432. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  38433. /* Number of bits in the bitmap array. */
  38434. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  38435. /* Number of u32 values in hash table. */
  38436. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  38437. /* Maximum number of entries in hash table before
  38438. ** sub-dividing and re-hashing. */
  38439. #define BITVEC_MXHASH (BITVEC_NINT/2)
  38440. /* Hashing function for the aHash representation.
  38441. ** Empirical testing showed that the *37 multiplier
  38442. ** (an arbitrary prime)in the hash function provided
  38443. ** no fewer collisions than the no-op *1. */
  38444. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  38445. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  38446. /*
  38447. ** A bitmap is an instance of the following structure.
  38448. **
  38449. ** This bitmap records the existence of zero or more bits
  38450. ** with values between 1 and iSize, inclusive.
  38451. **
  38452. ** There are three possible representations of the bitmap.
  38453. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  38454. ** bitmap. The least significant bit is bit 1.
  38455. **
  38456. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  38457. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  38458. **
  38459. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  38460. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  38461. ** handles up to iDivisor separate values of i. apSub[0] holds
  38462. ** values between 1 and iDivisor. apSub[1] holds values between
  38463. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  38464. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  38465. ** to hold deal with values between 1 and iDivisor.
  38466. */
  38467. struct Bitvec {
  38468. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  38469. u32 nSet; /* Number of bits that are set - only valid for aHash
  38470. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  38471. ** this would be 125. */
  38472. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  38473. /* Should >=0 for apSub element. */
  38474. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  38475. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  38476. union {
  38477. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  38478. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  38479. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  38480. } u;
  38481. };
  38482. /*
  38483. ** Create a new bitmap object able to handle bits between 0 and iSize,
  38484. ** inclusive. Return a pointer to the new object. Return NULL if
  38485. ** malloc fails.
  38486. */
  38487. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  38488. Bitvec *p;
  38489. assert( sizeof(*p)==BITVEC_SZ );
  38490. p = sqlite3MallocZero( sizeof(*p) );
  38491. if( p ){
  38492. p->iSize = iSize;
  38493. }
  38494. return p;
  38495. }
  38496. /*
  38497. ** Check to see if the i-th bit is set. Return true or false.
  38498. ** If p is NULL (if the bitmap has not been created) or if
  38499. ** i is out of range, then return false.
  38500. */
  38501. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  38502. assert( p!=0 );
  38503. i--;
  38504. if( i>=p->iSize ) return 0;
  38505. while( p->iDivisor ){
  38506. u32 bin = i/p->iDivisor;
  38507. i = i%p->iDivisor;
  38508. p = p->u.apSub[bin];
  38509. if (!p) {
  38510. return 0;
  38511. }
  38512. }
  38513. if( p->iSize<=BITVEC_NBIT ){
  38514. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  38515. } else{
  38516. u32 h = BITVEC_HASH(i++);
  38517. while( p->u.aHash[h] ){
  38518. if( p->u.aHash[h]==i ) return 1;
  38519. h = (h+1) % BITVEC_NINT;
  38520. }
  38521. return 0;
  38522. }
  38523. }
  38524. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  38525. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  38526. }
  38527. /*
  38528. ** Set the i-th bit. Return 0 on success and an error code if
  38529. ** anything goes wrong.
  38530. **
  38531. ** This routine might cause sub-bitmaps to be allocated. Failing
  38532. ** to get the memory needed to hold the sub-bitmap is the only
  38533. ** that can go wrong with an insert, assuming p and i are valid.
  38534. **
  38535. ** The calling function must ensure that p is a valid Bitvec object
  38536. ** and that the value for "i" is within range of the Bitvec object.
  38537. ** Otherwise the behavior is undefined.
  38538. */
  38539. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  38540. u32 h;
  38541. if( p==0 ) return SQLITE_OK;
  38542. assert( i>0 );
  38543. assert( i<=p->iSize );
  38544. i--;
  38545. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  38546. u32 bin = i/p->iDivisor;
  38547. i = i%p->iDivisor;
  38548. if( p->u.apSub[bin]==0 ){
  38549. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  38550. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  38551. }
  38552. p = p->u.apSub[bin];
  38553. }
  38554. if( p->iSize<=BITVEC_NBIT ){
  38555. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  38556. return SQLITE_OK;
  38557. }
  38558. h = BITVEC_HASH(i++);
  38559. /* if there wasn't a hash collision, and this doesn't */
  38560. /* completely fill the hash, then just add it without */
  38561. /* worring about sub-dividing and re-hashing. */
  38562. if( !p->u.aHash[h] ){
  38563. if (p->nSet<(BITVEC_NINT-1)) {
  38564. goto bitvec_set_end;
  38565. } else {
  38566. goto bitvec_set_rehash;
  38567. }
  38568. }
  38569. /* there was a collision, check to see if it's already */
  38570. /* in hash, if not, try to find a spot for it */
  38571. do {
  38572. if( p->u.aHash[h]==i ) return SQLITE_OK;
  38573. h++;
  38574. if( h>=BITVEC_NINT ) h = 0;
  38575. } while( p->u.aHash[h] );
  38576. /* we didn't find it in the hash. h points to the first */
  38577. /* available free spot. check to see if this is going to */
  38578. /* make our hash too "full". */
  38579. bitvec_set_rehash:
  38580. if( p->nSet>=BITVEC_MXHASH ){
  38581. unsigned int j;
  38582. int rc;
  38583. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  38584. if( aiValues==0 ){
  38585. return SQLITE_NOMEM_BKPT;
  38586. }else{
  38587. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  38588. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  38589. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  38590. rc = sqlite3BitvecSet(p, i);
  38591. for(j=0; j<BITVEC_NINT; j++){
  38592. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  38593. }
  38594. sqlite3StackFree(0, aiValues);
  38595. return rc;
  38596. }
  38597. }
  38598. bitvec_set_end:
  38599. p->nSet++;
  38600. p->u.aHash[h] = i;
  38601. return SQLITE_OK;
  38602. }
  38603. /*
  38604. ** Clear the i-th bit.
  38605. **
  38606. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  38607. ** that BitvecClear can use to rebuilt its hash table.
  38608. */
  38609. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  38610. if( p==0 ) return;
  38611. assert( i>0 );
  38612. i--;
  38613. while( p->iDivisor ){
  38614. u32 bin = i/p->iDivisor;
  38615. i = i%p->iDivisor;
  38616. p = p->u.apSub[bin];
  38617. if (!p) {
  38618. return;
  38619. }
  38620. }
  38621. if( p->iSize<=BITVEC_NBIT ){
  38622. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  38623. }else{
  38624. unsigned int j;
  38625. u32 *aiValues = pBuf;
  38626. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  38627. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  38628. p->nSet = 0;
  38629. for(j=0; j<BITVEC_NINT; j++){
  38630. if( aiValues[j] && aiValues[j]!=(i+1) ){
  38631. u32 h = BITVEC_HASH(aiValues[j]-1);
  38632. p->nSet++;
  38633. while( p->u.aHash[h] ){
  38634. h++;
  38635. if( h>=BITVEC_NINT ) h = 0;
  38636. }
  38637. p->u.aHash[h] = aiValues[j];
  38638. }
  38639. }
  38640. }
  38641. }
  38642. /*
  38643. ** Destroy a bitmap object. Reclaim all memory used.
  38644. */
  38645. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  38646. if( p==0 ) return;
  38647. if( p->iDivisor ){
  38648. unsigned int i;
  38649. for(i=0; i<BITVEC_NPTR; i++){
  38650. sqlite3BitvecDestroy(p->u.apSub[i]);
  38651. }
  38652. }
  38653. sqlite3_free(p);
  38654. }
  38655. /*
  38656. ** Return the value of the iSize parameter specified when Bitvec *p
  38657. ** was created.
  38658. */
  38659. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  38660. return p->iSize;
  38661. }
  38662. #ifndef SQLITE_OMIT_BUILTIN_TEST
  38663. /*
  38664. ** Let V[] be an array of unsigned characters sufficient to hold
  38665. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  38666. ** Then the following macros can be used to set, clear, or test
  38667. ** individual bits within V.
  38668. */
  38669. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  38670. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  38671. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  38672. /*
  38673. ** This routine runs an extensive test of the Bitvec code.
  38674. **
  38675. ** The input is an array of integers that acts as a program
  38676. ** to test the Bitvec. The integers are opcodes followed
  38677. ** by 0, 1, or 3 operands, depending on the opcode. Another
  38678. ** opcode follows immediately after the last operand.
  38679. **
  38680. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  38681. ** "halt" opcode and causes the test to end.
  38682. **
  38683. ** 0 Halt and return the number of errors
  38684. ** 1 N S X Set N bits beginning with S and incrementing by X
  38685. ** 2 N S X Clear N bits beginning with S and incrementing by X
  38686. ** 3 N Set N randomly chosen bits
  38687. ** 4 N Clear N randomly chosen bits
  38688. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  38689. **
  38690. ** The opcodes 1 through 4 perform set and clear operations are performed
  38691. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  38692. ** Opcode 5 works on the linear array only, not on the Bitvec.
  38693. ** Opcode 5 is used to deliberately induce a fault in order to
  38694. ** confirm that error detection works.
  38695. **
  38696. ** At the conclusion of the test the linear array is compared
  38697. ** against the Bitvec object. If there are any differences,
  38698. ** an error is returned. If they are the same, zero is returned.
  38699. **
  38700. ** If a memory allocation error occurs, return -1.
  38701. */
  38702. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  38703. Bitvec *pBitvec = 0;
  38704. unsigned char *pV = 0;
  38705. int rc = -1;
  38706. int i, nx, pc, op;
  38707. void *pTmpSpace;
  38708. /* Allocate the Bitvec to be tested and a linear array of
  38709. ** bits to act as the reference */
  38710. pBitvec = sqlite3BitvecCreate( sz );
  38711. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  38712. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  38713. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  38714. /* NULL pBitvec tests */
  38715. sqlite3BitvecSet(0, 1);
  38716. sqlite3BitvecClear(0, 1, pTmpSpace);
  38717. /* Run the program */
  38718. pc = 0;
  38719. while( (op = aOp[pc])!=0 ){
  38720. switch( op ){
  38721. case 1:
  38722. case 2:
  38723. case 5: {
  38724. nx = 4;
  38725. i = aOp[pc+2] - 1;
  38726. aOp[pc+2] += aOp[pc+3];
  38727. break;
  38728. }
  38729. case 3:
  38730. case 4:
  38731. default: {
  38732. nx = 2;
  38733. sqlite3_randomness(sizeof(i), &i);
  38734. break;
  38735. }
  38736. }
  38737. if( (--aOp[pc+1]) > 0 ) nx = 0;
  38738. pc += nx;
  38739. i = (i & 0x7fffffff)%sz;
  38740. if( (op & 1)!=0 ){
  38741. SETBIT(pV, (i+1));
  38742. if( op!=5 ){
  38743. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  38744. }
  38745. }else{
  38746. CLEARBIT(pV, (i+1));
  38747. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  38748. }
  38749. }
  38750. /* Test to make sure the linear array exactly matches the
  38751. ** Bitvec object. Start with the assumption that they do
  38752. ** match (rc==0). Change rc to non-zero if a discrepancy
  38753. ** is found.
  38754. */
  38755. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  38756. + sqlite3BitvecTest(pBitvec, 0)
  38757. + (sqlite3BitvecSize(pBitvec) - sz);
  38758. for(i=1; i<=sz; i++){
  38759. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  38760. rc = i;
  38761. break;
  38762. }
  38763. }
  38764. /* Free allocated structure */
  38765. bitvec_end:
  38766. sqlite3_free(pTmpSpace);
  38767. sqlite3_free(pV);
  38768. sqlite3BitvecDestroy(pBitvec);
  38769. return rc;
  38770. }
  38771. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  38772. /************** End of bitvec.c **********************************************/
  38773. /************** Begin file pcache.c ******************************************/
  38774. /*
  38775. ** 2008 August 05
  38776. **
  38777. ** The author disclaims copyright to this source code. In place of
  38778. ** a legal notice, here is a blessing:
  38779. **
  38780. ** May you do good and not evil.
  38781. ** May you find forgiveness for yourself and forgive others.
  38782. ** May you share freely, never taking more than you give.
  38783. **
  38784. *************************************************************************
  38785. ** This file implements that page cache.
  38786. */
  38787. /* #include "sqliteInt.h" */
  38788. /*
  38789. ** A complete page cache is an instance of this structure.
  38790. */
  38791. struct PCache {
  38792. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  38793. PgHdr *pSynced; /* Last synced page in dirty page list */
  38794. int nRefSum; /* Sum of ref counts over all pages */
  38795. int szCache; /* Configured cache size */
  38796. int szSpill; /* Size before spilling occurs */
  38797. int szPage; /* Size of every page in this cache */
  38798. int szExtra; /* Size of extra space for each page */
  38799. u8 bPurgeable; /* True if pages are on backing store */
  38800. u8 eCreate; /* eCreate value for for xFetch() */
  38801. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  38802. void *pStress; /* Argument to xStress */
  38803. sqlite3_pcache *pCache; /* Pluggable cache module */
  38804. };
  38805. /********************************** Linked List Management ********************/
  38806. /* Allowed values for second argument to pcacheManageDirtyList() */
  38807. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  38808. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  38809. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  38810. /*
  38811. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  38812. ** argument determines what operation to do. The 0x01 bit means first
  38813. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  38814. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  38815. */
  38816. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  38817. PCache *p = pPage->pCache;
  38818. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  38819. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  38820. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  38821. /* Update the PCache1.pSynced variable if necessary. */
  38822. if( p->pSynced==pPage ){
  38823. PgHdr *pSynced = pPage->pDirtyPrev;
  38824. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  38825. pSynced = pSynced->pDirtyPrev;
  38826. }
  38827. p->pSynced = pSynced;
  38828. }
  38829. if( pPage->pDirtyNext ){
  38830. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  38831. }else{
  38832. assert( pPage==p->pDirtyTail );
  38833. p->pDirtyTail = pPage->pDirtyPrev;
  38834. }
  38835. if( pPage->pDirtyPrev ){
  38836. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  38837. }else{
  38838. assert( pPage==p->pDirty );
  38839. p->pDirty = pPage->pDirtyNext;
  38840. if( p->pDirty==0 && p->bPurgeable ){
  38841. assert( p->eCreate==1 );
  38842. p->eCreate = 2;
  38843. }
  38844. }
  38845. pPage->pDirtyNext = 0;
  38846. pPage->pDirtyPrev = 0;
  38847. }
  38848. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  38849. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  38850. pPage->pDirtyNext = p->pDirty;
  38851. if( pPage->pDirtyNext ){
  38852. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  38853. pPage->pDirtyNext->pDirtyPrev = pPage;
  38854. }else{
  38855. p->pDirtyTail = pPage;
  38856. if( p->bPurgeable ){
  38857. assert( p->eCreate==2 );
  38858. p->eCreate = 1;
  38859. }
  38860. }
  38861. p->pDirty = pPage;
  38862. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  38863. p->pSynced = pPage;
  38864. }
  38865. }
  38866. }
  38867. /*
  38868. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  38869. ** being used for an in-memory database, this function is a no-op.
  38870. */
  38871. static void pcacheUnpin(PgHdr *p){
  38872. if( p->pCache->bPurgeable ){
  38873. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  38874. }
  38875. }
  38876. /*
  38877. ** Compute the number of pages of cache requested. p->szCache is the
  38878. ** cache size requested by the "PRAGMA cache_size" statement.
  38879. */
  38880. static int numberOfCachePages(PCache *p){
  38881. if( p->szCache>=0 ){
  38882. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  38883. ** suggested cache size is set to N. */
  38884. return p->szCache;
  38885. }else{
  38886. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  38887. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  38888. ** bytes of memory. */
  38889. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  38890. }
  38891. }
  38892. /*************************************************** General Interfaces ******
  38893. **
  38894. ** Initialize and shutdown the page cache subsystem. Neither of these
  38895. ** functions are threadsafe.
  38896. */
  38897. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  38898. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  38899. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  38900. ** built-in default page cache is used instead of the application defined
  38901. ** page cache. */
  38902. sqlite3PCacheSetDefault();
  38903. }
  38904. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  38905. }
  38906. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  38907. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  38908. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  38909. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  38910. }
  38911. }
  38912. /*
  38913. ** Return the size in bytes of a PCache object.
  38914. */
  38915. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  38916. /*
  38917. ** Create a new PCache object. Storage space to hold the object
  38918. ** has already been allocated and is passed in as the p pointer.
  38919. ** The caller discovers how much space needs to be allocated by
  38920. ** calling sqlite3PcacheSize().
  38921. */
  38922. SQLITE_PRIVATE int sqlite3PcacheOpen(
  38923. int szPage, /* Size of every page */
  38924. int szExtra, /* Extra space associated with each page */
  38925. int bPurgeable, /* True if pages are on backing store */
  38926. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  38927. void *pStress, /* Argument to xStress */
  38928. PCache *p /* Preallocated space for the PCache */
  38929. ){
  38930. memset(p, 0, sizeof(PCache));
  38931. p->szPage = 1;
  38932. p->szExtra = szExtra;
  38933. p->bPurgeable = bPurgeable;
  38934. p->eCreate = 2;
  38935. p->xStress = xStress;
  38936. p->pStress = pStress;
  38937. p->szCache = 100;
  38938. p->szSpill = 1;
  38939. return sqlite3PcacheSetPageSize(p, szPage);
  38940. }
  38941. /*
  38942. ** Change the page size for PCache object. The caller must ensure that there
  38943. ** are no outstanding page references when this function is called.
  38944. */
  38945. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  38946. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  38947. if( pCache->szPage ){
  38948. sqlite3_pcache *pNew;
  38949. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  38950. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  38951. pCache->bPurgeable
  38952. );
  38953. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  38954. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  38955. if( pCache->pCache ){
  38956. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  38957. }
  38958. pCache->pCache = pNew;
  38959. pCache->szPage = szPage;
  38960. }
  38961. return SQLITE_OK;
  38962. }
  38963. /*
  38964. ** Try to obtain a page from the cache.
  38965. **
  38966. ** This routine returns a pointer to an sqlite3_pcache_page object if
  38967. ** such an object is already in cache, or if a new one is created.
  38968. ** This routine returns a NULL pointer if the object was not in cache
  38969. ** and could not be created.
  38970. **
  38971. ** The createFlags should be 0 to check for existing pages and should
  38972. ** be 3 (not 1, but 3) to try to create a new page.
  38973. **
  38974. ** If the createFlag is 0, then NULL is always returned if the page
  38975. ** is not already in the cache. If createFlag is 1, then a new page
  38976. ** is created only if that can be done without spilling dirty pages
  38977. ** and without exceeding the cache size limit.
  38978. **
  38979. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  38980. ** initialize the sqlite3_pcache_page object and convert it into a
  38981. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  38982. ** routines are split this way for performance reasons. When separated
  38983. ** they can both (usually) operate without having to push values to
  38984. ** the stack on entry and pop them back off on exit, which saves a
  38985. ** lot of pushing and popping.
  38986. */
  38987. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  38988. PCache *pCache, /* Obtain the page from this cache */
  38989. Pgno pgno, /* Page number to obtain */
  38990. int createFlag /* If true, create page if it does not exist already */
  38991. ){
  38992. int eCreate;
  38993. assert( pCache!=0 );
  38994. assert( pCache->pCache!=0 );
  38995. assert( createFlag==3 || createFlag==0 );
  38996. assert( pgno>0 );
  38997. /* eCreate defines what to do if the page does not exist.
  38998. ** 0 Do not allocate a new page. (createFlag==0)
  38999. ** 1 Allocate a new page if doing so is inexpensive.
  39000. ** (createFlag==1 AND bPurgeable AND pDirty)
  39001. ** 2 Allocate a new page even it doing so is difficult.
  39002. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  39003. */
  39004. eCreate = createFlag & pCache->eCreate;
  39005. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  39006. assert( createFlag==0 || pCache->eCreate==eCreate );
  39007. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  39008. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  39009. }
  39010. /*
  39011. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  39012. ** page because new clean pages are available for reuse and the cache
  39013. ** size limit has been reached, then this routine can be invoked to
  39014. ** try harder to allocate a page. This routine might invoke the stress
  39015. ** callback to spill dirty pages to the journal. It will then try to
  39016. ** allocate the new page and will only fail to allocate a new page on
  39017. ** an OOM error.
  39018. **
  39019. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  39020. */
  39021. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  39022. PCache *pCache, /* Obtain the page from this cache */
  39023. Pgno pgno, /* Page number to obtain */
  39024. sqlite3_pcache_page **ppPage /* Write result here */
  39025. ){
  39026. PgHdr *pPg;
  39027. if( pCache->eCreate==2 ) return 0;
  39028. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  39029. /* Find a dirty page to write-out and recycle. First try to find a
  39030. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  39031. ** cleared), but if that is not possible settle for any other
  39032. ** unreferenced dirty page.
  39033. */
  39034. for(pPg=pCache->pSynced;
  39035. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  39036. pPg=pPg->pDirtyPrev
  39037. );
  39038. pCache->pSynced = pPg;
  39039. if( !pPg ){
  39040. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  39041. }
  39042. if( pPg ){
  39043. int rc;
  39044. #ifdef SQLITE_LOG_CACHE_SPILL
  39045. sqlite3_log(SQLITE_FULL,
  39046. "spill page %d making room for %d - cache used: %d/%d",
  39047. pPg->pgno, pgno,
  39048. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  39049. numberOfCachePages(pCache));
  39050. #endif
  39051. rc = pCache->xStress(pCache->pStress, pPg);
  39052. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  39053. return rc;
  39054. }
  39055. }
  39056. }
  39057. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  39058. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  39059. }
  39060. /*
  39061. ** This is a helper routine for sqlite3PcacheFetchFinish()
  39062. **
  39063. ** In the uncommon case where the page being fetched has not been
  39064. ** initialized, this routine is invoked to do the initialization.
  39065. ** This routine is broken out into a separate function since it
  39066. ** requires extra stack manipulation that can be avoided in the common
  39067. ** case.
  39068. */
  39069. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  39070. PCache *pCache, /* Obtain the page from this cache */
  39071. Pgno pgno, /* Page number obtained */
  39072. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  39073. ){
  39074. PgHdr *pPgHdr;
  39075. assert( pPage!=0 );
  39076. pPgHdr = (PgHdr*)pPage->pExtra;
  39077. assert( pPgHdr->pPage==0 );
  39078. memset(pPgHdr, 0, sizeof(PgHdr));
  39079. pPgHdr->pPage = pPage;
  39080. pPgHdr->pData = pPage->pBuf;
  39081. pPgHdr->pExtra = (void *)&pPgHdr[1];
  39082. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  39083. pPgHdr->pCache = pCache;
  39084. pPgHdr->pgno = pgno;
  39085. pPgHdr->flags = PGHDR_CLEAN;
  39086. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  39087. }
  39088. /*
  39089. ** This routine converts the sqlite3_pcache_page object returned by
  39090. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  39091. ** must be called after sqlite3PcacheFetch() in order to get a usable
  39092. ** result.
  39093. */
  39094. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  39095. PCache *pCache, /* Obtain the page from this cache */
  39096. Pgno pgno, /* Page number obtained */
  39097. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  39098. ){
  39099. PgHdr *pPgHdr;
  39100. assert( pPage!=0 );
  39101. pPgHdr = (PgHdr *)pPage->pExtra;
  39102. if( !pPgHdr->pPage ){
  39103. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  39104. }
  39105. pCache->nRefSum++;
  39106. pPgHdr->nRef++;
  39107. return pPgHdr;
  39108. }
  39109. /*
  39110. ** Decrement the reference count on a page. If the page is clean and the
  39111. ** reference count drops to 0, then it is made eligible for recycling.
  39112. */
  39113. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  39114. assert( p->nRef>0 );
  39115. p->pCache->nRefSum--;
  39116. if( (--p->nRef)==0 ){
  39117. if( p->flags&PGHDR_CLEAN ){
  39118. pcacheUnpin(p);
  39119. }else if( p->pDirtyPrev!=0 ){
  39120. /* Move the page to the head of the dirty list. */
  39121. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  39122. }
  39123. }
  39124. }
  39125. /*
  39126. ** Increase the reference count of a supplied page by 1.
  39127. */
  39128. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  39129. assert(p->nRef>0);
  39130. p->nRef++;
  39131. p->pCache->nRefSum++;
  39132. }
  39133. /*
  39134. ** Drop a page from the cache. There must be exactly one reference to the
  39135. ** page. This function deletes that reference, so after it returns the
  39136. ** page pointed to by p is invalid.
  39137. */
  39138. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  39139. assert( p->nRef==1 );
  39140. if( p->flags&PGHDR_DIRTY ){
  39141. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  39142. }
  39143. p->pCache->nRefSum--;
  39144. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  39145. }
  39146. /*
  39147. ** Make sure the page is marked as dirty. If it isn't dirty already,
  39148. ** make it so.
  39149. */
  39150. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  39151. assert( p->nRef>0 );
  39152. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
  39153. p->flags &= ~PGHDR_DONT_WRITE;
  39154. if( p->flags & PGHDR_CLEAN ){
  39155. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  39156. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  39157. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  39158. }
  39159. }
  39160. }
  39161. /*
  39162. ** Make sure the page is marked as clean. If it isn't clean already,
  39163. ** make it so.
  39164. */
  39165. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  39166. if( (p->flags & PGHDR_DIRTY) ){
  39167. assert( (p->flags & PGHDR_CLEAN)==0 );
  39168. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  39169. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  39170. p->flags |= PGHDR_CLEAN;
  39171. if( p->nRef==0 ){
  39172. pcacheUnpin(p);
  39173. }
  39174. }
  39175. }
  39176. /*
  39177. ** Make every page in the cache clean.
  39178. */
  39179. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  39180. PgHdr *p;
  39181. while( (p = pCache->pDirty)!=0 ){
  39182. sqlite3PcacheMakeClean(p);
  39183. }
  39184. }
  39185. /*
  39186. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  39187. */
  39188. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  39189. PgHdr *p;
  39190. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  39191. p->flags &= ~PGHDR_NEED_SYNC;
  39192. }
  39193. pCache->pSynced = pCache->pDirtyTail;
  39194. }
  39195. /*
  39196. ** Change the page number of page p to newPgno.
  39197. */
  39198. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  39199. PCache *pCache = p->pCache;
  39200. assert( p->nRef>0 );
  39201. assert( newPgno>0 );
  39202. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  39203. p->pgno = newPgno;
  39204. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  39205. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  39206. }
  39207. }
  39208. /*
  39209. ** Drop every cache entry whose page number is greater than "pgno". The
  39210. ** caller must ensure that there are no outstanding references to any pages
  39211. ** other than page 1 with a page number greater than pgno.
  39212. **
  39213. ** If there is a reference to page 1 and the pgno parameter passed to this
  39214. ** function is 0, then the data area associated with page 1 is zeroed, but
  39215. ** the page object is not dropped.
  39216. */
  39217. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  39218. if( pCache->pCache ){
  39219. PgHdr *p;
  39220. PgHdr *pNext;
  39221. for(p=pCache->pDirty; p; p=pNext){
  39222. pNext = p->pDirtyNext;
  39223. /* This routine never gets call with a positive pgno except right
  39224. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  39225. ** it must be that pgno==0.
  39226. */
  39227. assert( p->pgno>0 );
  39228. if( ALWAYS(p->pgno>pgno) ){
  39229. assert( p->flags&PGHDR_DIRTY );
  39230. sqlite3PcacheMakeClean(p);
  39231. }
  39232. }
  39233. if( pgno==0 && pCache->nRefSum ){
  39234. sqlite3_pcache_page *pPage1;
  39235. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  39236. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  39237. ** pCache->nRefSum>0 */
  39238. memset(pPage1->pBuf, 0, pCache->szPage);
  39239. pgno = 1;
  39240. }
  39241. }
  39242. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  39243. }
  39244. }
  39245. /*
  39246. ** Close a cache.
  39247. */
  39248. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  39249. assert( pCache->pCache!=0 );
  39250. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  39251. }
  39252. /*
  39253. ** Discard the contents of the cache.
  39254. */
  39255. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  39256. sqlite3PcacheTruncate(pCache, 0);
  39257. }
  39258. /*
  39259. ** Merge two lists of pages connected by pDirty and in pgno order.
  39260. ** Do not both fixing the pDirtyPrev pointers.
  39261. */
  39262. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  39263. PgHdr result, *pTail;
  39264. pTail = &result;
  39265. while( pA && pB ){
  39266. if( pA->pgno<pB->pgno ){
  39267. pTail->pDirty = pA;
  39268. pTail = pA;
  39269. pA = pA->pDirty;
  39270. }else{
  39271. pTail->pDirty = pB;
  39272. pTail = pB;
  39273. pB = pB->pDirty;
  39274. }
  39275. }
  39276. if( pA ){
  39277. pTail->pDirty = pA;
  39278. }else if( pB ){
  39279. pTail->pDirty = pB;
  39280. }else{
  39281. pTail->pDirty = 0;
  39282. }
  39283. return result.pDirty;
  39284. }
  39285. /*
  39286. ** Sort the list of pages in accending order by pgno. Pages are
  39287. ** connected by pDirty pointers. The pDirtyPrev pointers are
  39288. ** corrupted by this sort.
  39289. **
  39290. ** Since there cannot be more than 2^31 distinct pages in a database,
  39291. ** there cannot be more than 31 buckets required by the merge sorter.
  39292. ** One extra bucket is added to catch overflow in case something
  39293. ** ever changes to make the previous sentence incorrect.
  39294. */
  39295. #define N_SORT_BUCKET 32
  39296. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  39297. PgHdr *a[N_SORT_BUCKET], *p;
  39298. int i;
  39299. memset(a, 0, sizeof(a));
  39300. while( pIn ){
  39301. p = pIn;
  39302. pIn = p->pDirty;
  39303. p->pDirty = 0;
  39304. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  39305. if( a[i]==0 ){
  39306. a[i] = p;
  39307. break;
  39308. }else{
  39309. p = pcacheMergeDirtyList(a[i], p);
  39310. a[i] = 0;
  39311. }
  39312. }
  39313. if( NEVER(i==N_SORT_BUCKET-1) ){
  39314. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  39315. ** the input list. But that is impossible.
  39316. */
  39317. a[i] = pcacheMergeDirtyList(a[i], p);
  39318. }
  39319. }
  39320. p = a[0];
  39321. for(i=1; i<N_SORT_BUCKET; i++){
  39322. p = pcacheMergeDirtyList(p, a[i]);
  39323. }
  39324. return p;
  39325. }
  39326. /*
  39327. ** Return a list of all dirty pages in the cache, sorted by page number.
  39328. */
  39329. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  39330. PgHdr *p;
  39331. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  39332. p->pDirty = p->pDirtyNext;
  39333. }
  39334. return pcacheSortDirtyList(pCache->pDirty);
  39335. }
  39336. /*
  39337. ** Return the total number of references to all pages held by the cache.
  39338. **
  39339. ** This is not the total number of pages referenced, but the sum of the
  39340. ** reference count for all pages.
  39341. */
  39342. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  39343. return pCache->nRefSum;
  39344. }
  39345. /*
  39346. ** Return the number of references to the page supplied as an argument.
  39347. */
  39348. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  39349. return p->nRef;
  39350. }
  39351. /*
  39352. ** Return the total number of pages in the cache.
  39353. */
  39354. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  39355. assert( pCache->pCache!=0 );
  39356. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  39357. }
  39358. #ifdef SQLITE_TEST
  39359. /*
  39360. ** Get the suggested cache-size value.
  39361. */
  39362. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  39363. return numberOfCachePages(pCache);
  39364. }
  39365. #endif
  39366. /*
  39367. ** Set the suggested cache-size value.
  39368. */
  39369. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  39370. assert( pCache->pCache!=0 );
  39371. pCache->szCache = mxPage;
  39372. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  39373. numberOfCachePages(pCache));
  39374. }
  39375. /*
  39376. ** Set the suggested cache-spill value. Make no changes if if the
  39377. ** argument is zero. Return the effective cache-spill size, which will
  39378. ** be the larger of the szSpill and szCache.
  39379. */
  39380. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  39381. int res;
  39382. assert( p->pCache!=0 );
  39383. if( mxPage ){
  39384. if( mxPage<0 ){
  39385. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  39386. }
  39387. p->szSpill = mxPage;
  39388. }
  39389. res = numberOfCachePages(p);
  39390. if( res<p->szSpill ) res = p->szSpill;
  39391. return res;
  39392. }
  39393. /*
  39394. ** Free up as much memory as possible from the page cache.
  39395. */
  39396. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  39397. assert( pCache->pCache!=0 );
  39398. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  39399. }
  39400. /*
  39401. ** Return the size of the header added by this middleware layer
  39402. ** in the page-cache hierarchy.
  39403. */
  39404. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  39405. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  39406. /*
  39407. ** For all dirty pages currently in the cache, invoke the specified
  39408. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  39409. ** defined.
  39410. */
  39411. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  39412. PgHdr *pDirty;
  39413. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  39414. xIter(pDirty);
  39415. }
  39416. }
  39417. #endif
  39418. /************** End of pcache.c **********************************************/
  39419. /************** Begin file pcache1.c *****************************************/
  39420. /*
  39421. ** 2008 November 05
  39422. **
  39423. ** The author disclaims copyright to this source code. In place of
  39424. ** a legal notice, here is a blessing:
  39425. **
  39426. ** May you do good and not evil.
  39427. ** May you find forgiveness for yourself and forgive others.
  39428. ** May you share freely, never taking more than you give.
  39429. **
  39430. *************************************************************************
  39431. **
  39432. ** This file implements the default page cache implementation (the
  39433. ** sqlite3_pcache interface). It also contains part of the implementation
  39434. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  39435. ** If the default page cache implementation is overridden, then neither of
  39436. ** these two features are available.
  39437. **
  39438. ** A Page cache line looks like this:
  39439. **
  39440. ** -------------------------------------------------------------
  39441. ** | database page content | PgHdr1 | MemPage | PgHdr |
  39442. ** -------------------------------------------------------------
  39443. **
  39444. ** The database page content is up front (so that buffer overreads tend to
  39445. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  39446. ** is the extension added by the btree.c module containing information such
  39447. ** as the database page number and how that database page is used. PgHdr
  39448. ** is added by the pcache.c layer and contains information used to keep track
  39449. ** of which pages are "dirty". PgHdr1 is an extension added by this
  39450. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  39451. ** PgHdr1 contains information needed to look up a page by its page number.
  39452. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  39453. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  39454. **
  39455. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  39456. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  39457. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  39458. ** size can vary according to architecture, compile-time options, and
  39459. ** SQLite library version number.
  39460. **
  39461. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  39462. ** using a separate memory allocation from the database page content. This
  39463. ** seeks to overcome the "clownshoe" problem (also called "internal
  39464. ** fragmentation" in academic literature) of allocating a few bytes more
  39465. ** than a power of two with the memory allocator rounding up to the next
  39466. ** power of two, and leaving the rounded-up space unused.
  39467. **
  39468. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  39469. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  39470. **
  39471. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  39472. ** The btree.c module deals with pointers to MemPage objects.
  39473. **
  39474. ** SOURCE OF PAGE CACHE MEMORY:
  39475. **
  39476. ** Memory for a page might come from any of three sources:
  39477. **
  39478. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  39479. ** (2) Global page-cache memory provided using sqlite3_config() with
  39480. ** SQLITE_CONFIG_PAGECACHE.
  39481. ** (3) PCache-local bulk allocation.
  39482. **
  39483. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  39484. ** that is allocated when the page cache is created. The size of the local
  39485. ** bulk allocation can be adjusted using
  39486. **
  39487. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  39488. **
  39489. ** If N is positive, then N pages worth of memory are allocated using a single
  39490. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  39491. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  39492. ** for as many pages as can be accomodated.
  39493. **
  39494. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  39495. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  39496. ** memory allocator (1).
  39497. **
  39498. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  39499. ** show that method (3) with N==100 provides about a 5% performance boost for
  39500. ** common workloads.
  39501. */
  39502. /* #include "sqliteInt.h" */
  39503. typedef struct PCache1 PCache1;
  39504. typedef struct PgHdr1 PgHdr1;
  39505. typedef struct PgFreeslot PgFreeslot;
  39506. typedef struct PGroup PGroup;
  39507. /*
  39508. ** Each cache entry is represented by an instance of the following
  39509. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  39510. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  39511. ** in memory.
  39512. */
  39513. struct PgHdr1 {
  39514. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  39515. unsigned int iKey; /* Key value (page number) */
  39516. u8 isPinned; /* Page in use, not on the LRU list */
  39517. u8 isBulkLocal; /* This page from bulk local storage */
  39518. u8 isAnchor; /* This is the PGroup.lru element */
  39519. PgHdr1 *pNext; /* Next in hash table chain */
  39520. PCache1 *pCache; /* Cache that currently owns this page */
  39521. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  39522. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  39523. };
  39524. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  39525. ** of one or more PCaches that are able to recycle each other's unpinned
  39526. ** pages when they are under memory pressure. A PGroup is an instance of
  39527. ** the following object.
  39528. **
  39529. ** This page cache implementation works in one of two modes:
  39530. **
  39531. ** (1) Every PCache is the sole member of its own PGroup. There is
  39532. ** one PGroup per PCache.
  39533. **
  39534. ** (2) There is a single global PGroup that all PCaches are a member
  39535. ** of.
  39536. **
  39537. ** Mode 1 uses more memory (since PCache instances are not able to rob
  39538. ** unused pages from other PCaches) but it also operates without a mutex,
  39539. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  39540. ** threadsafe, but recycles pages more efficiently.
  39541. **
  39542. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  39543. ** PGroup which is the pcache1.grp global variable and its mutex is
  39544. ** SQLITE_MUTEX_STATIC_LRU.
  39545. */
  39546. struct PGroup {
  39547. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  39548. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  39549. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  39550. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  39551. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  39552. PgHdr1 lru; /* The beginning and end of the LRU list */
  39553. };
  39554. /* Each page cache is an instance of the following object. Every
  39555. ** open database file (including each in-memory database and each
  39556. ** temporary or transient database) has a single page cache which
  39557. ** is an instance of this object.
  39558. **
  39559. ** Pointers to structures of this type are cast and returned as
  39560. ** opaque sqlite3_pcache* handles.
  39561. */
  39562. struct PCache1 {
  39563. /* Cache configuration parameters. Page size (szPage) and the purgeable
  39564. ** flag (bPurgeable) are set when the cache is created. nMax may be
  39565. ** modified at any time by a call to the pcache1Cachesize() method.
  39566. ** The PGroup mutex must be held when accessing nMax.
  39567. */
  39568. PGroup *pGroup; /* PGroup this cache belongs to */
  39569. int szPage; /* Size of database content section */
  39570. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  39571. int szAlloc; /* Total size of one pcache line */
  39572. int bPurgeable; /* True if cache is purgeable */
  39573. unsigned int nMin; /* Minimum number of pages reserved */
  39574. unsigned int nMax; /* Configured "cache_size" value */
  39575. unsigned int n90pct; /* nMax*9/10 */
  39576. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  39577. /* Hash table of all pages. The following variables may only be accessed
  39578. ** when the accessor is holding the PGroup mutex.
  39579. */
  39580. unsigned int nRecyclable; /* Number of pages in the LRU list */
  39581. unsigned int nPage; /* Total number of pages in apHash */
  39582. unsigned int nHash; /* Number of slots in apHash[] */
  39583. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  39584. PgHdr1 *pFree; /* List of unused pcache-local pages */
  39585. void *pBulk; /* Bulk memory used by pcache-local */
  39586. };
  39587. /*
  39588. ** Free slots in the allocator used to divide up the global page cache
  39589. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  39590. */
  39591. struct PgFreeslot {
  39592. PgFreeslot *pNext; /* Next free slot */
  39593. };
  39594. /*
  39595. ** Global data used by this cache.
  39596. */
  39597. static SQLITE_WSD struct PCacheGlobal {
  39598. PGroup grp; /* The global PGroup for mode (2) */
  39599. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  39600. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  39601. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  39602. ** The nFreeSlot and pFree values do require mutex protection.
  39603. */
  39604. int isInit; /* True if initialized */
  39605. int separateCache; /* Use a new PGroup for each PCache */
  39606. int nInitPage; /* Initial bulk allocation size */
  39607. int szSlot; /* Size of each free slot */
  39608. int nSlot; /* The number of pcache slots */
  39609. int nReserve; /* Try to keep nFreeSlot above this */
  39610. void *pStart, *pEnd; /* Bounds of global page cache memory */
  39611. /* Above requires no mutex. Use mutex below for variable that follow. */
  39612. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  39613. PgFreeslot *pFree; /* Free page blocks */
  39614. int nFreeSlot; /* Number of unused pcache slots */
  39615. /* The following value requires a mutex to change. We skip the mutex on
  39616. ** reading because (1) most platforms read a 32-bit integer atomically and
  39617. ** (2) even if an incorrect value is read, no great harm is done since this
  39618. ** is really just an optimization. */
  39619. int bUnderPressure; /* True if low on PAGECACHE memory */
  39620. } pcache1_g;
  39621. /*
  39622. ** All code in this file should access the global structure above via the
  39623. ** alias "pcache1". This ensures that the WSD emulation is used when
  39624. ** compiling for systems that do not support real WSD.
  39625. */
  39626. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  39627. /*
  39628. ** Macros to enter and leave the PCache LRU mutex.
  39629. */
  39630. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  39631. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  39632. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  39633. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  39634. #else
  39635. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  39636. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  39637. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  39638. #endif
  39639. /******************************************************************************/
  39640. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  39641. /*
  39642. ** This function is called during initialization if a static buffer is
  39643. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  39644. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  39645. ** enough to contain 'n' buffers of 'sz' bytes each.
  39646. **
  39647. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  39648. ** to be serialized already. There is no need for further mutexing.
  39649. */
  39650. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  39651. if( pcache1.isInit ){
  39652. PgFreeslot *p;
  39653. if( pBuf==0 ) sz = n = 0;
  39654. sz = ROUNDDOWN8(sz);
  39655. pcache1.szSlot = sz;
  39656. pcache1.nSlot = pcache1.nFreeSlot = n;
  39657. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  39658. pcache1.pStart = pBuf;
  39659. pcache1.pFree = 0;
  39660. pcache1.bUnderPressure = 0;
  39661. while( n-- ){
  39662. p = (PgFreeslot*)pBuf;
  39663. p->pNext = pcache1.pFree;
  39664. pcache1.pFree = p;
  39665. pBuf = (void*)&((char*)pBuf)[sz];
  39666. }
  39667. pcache1.pEnd = pBuf;
  39668. }
  39669. }
  39670. /*
  39671. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  39672. ** true if pCache->pFree ends up containing one or more free pages.
  39673. */
  39674. static int pcache1InitBulk(PCache1 *pCache){
  39675. i64 szBulk;
  39676. char *zBulk;
  39677. if( pcache1.nInitPage==0 ) return 0;
  39678. /* Do not bother with a bulk allocation if the cache size very small */
  39679. if( pCache->nMax<3 ) return 0;
  39680. sqlite3BeginBenignMalloc();
  39681. if( pcache1.nInitPage>0 ){
  39682. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  39683. }else{
  39684. szBulk = -1024 * (i64)pcache1.nInitPage;
  39685. }
  39686. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  39687. szBulk = pCache->szAlloc*pCache->nMax;
  39688. }
  39689. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  39690. sqlite3EndBenignMalloc();
  39691. if( zBulk ){
  39692. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  39693. int i;
  39694. for(i=0; i<nBulk; i++){
  39695. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  39696. pX->page.pBuf = zBulk;
  39697. pX->page.pExtra = &pX[1];
  39698. pX->isBulkLocal = 1;
  39699. pX->isAnchor = 0;
  39700. pX->pNext = pCache->pFree;
  39701. pCache->pFree = pX;
  39702. zBulk += pCache->szAlloc;
  39703. }
  39704. }
  39705. return pCache->pFree!=0;
  39706. }
  39707. /*
  39708. ** Malloc function used within this file to allocate space from the buffer
  39709. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  39710. ** such buffer exists or there is no space left in it, this function falls
  39711. ** back to sqlite3Malloc().
  39712. **
  39713. ** Multiple threads can run this routine at the same time. Global variables
  39714. ** in pcache1 need to be protected via mutex.
  39715. */
  39716. static void *pcache1Alloc(int nByte){
  39717. void *p = 0;
  39718. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  39719. if( nByte<=pcache1.szSlot ){
  39720. sqlite3_mutex_enter(pcache1.mutex);
  39721. p = (PgHdr1 *)pcache1.pFree;
  39722. if( p ){
  39723. pcache1.pFree = pcache1.pFree->pNext;
  39724. pcache1.nFreeSlot--;
  39725. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  39726. assert( pcache1.nFreeSlot>=0 );
  39727. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  39728. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  39729. }
  39730. sqlite3_mutex_leave(pcache1.mutex);
  39731. }
  39732. if( p==0 ){
  39733. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  39734. ** it from sqlite3Malloc instead.
  39735. */
  39736. p = sqlite3Malloc(nByte);
  39737. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  39738. if( p ){
  39739. int sz = sqlite3MallocSize(p);
  39740. sqlite3_mutex_enter(pcache1.mutex);
  39741. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  39742. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  39743. sqlite3_mutex_leave(pcache1.mutex);
  39744. }
  39745. #endif
  39746. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  39747. }
  39748. return p;
  39749. }
  39750. /*
  39751. ** Free an allocated buffer obtained from pcache1Alloc().
  39752. */
  39753. static void pcache1Free(void *p){
  39754. if( p==0 ) return;
  39755. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  39756. PgFreeslot *pSlot;
  39757. sqlite3_mutex_enter(pcache1.mutex);
  39758. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  39759. pSlot = (PgFreeslot*)p;
  39760. pSlot->pNext = pcache1.pFree;
  39761. pcache1.pFree = pSlot;
  39762. pcache1.nFreeSlot++;
  39763. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  39764. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  39765. sqlite3_mutex_leave(pcache1.mutex);
  39766. }else{
  39767. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  39768. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  39769. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  39770. {
  39771. int nFreed = 0;
  39772. nFreed = sqlite3MallocSize(p);
  39773. sqlite3_mutex_enter(pcache1.mutex);
  39774. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  39775. sqlite3_mutex_leave(pcache1.mutex);
  39776. }
  39777. #endif
  39778. sqlite3_free(p);
  39779. }
  39780. }
  39781. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39782. /*
  39783. ** Return the size of a pcache allocation
  39784. */
  39785. static int pcache1MemSize(void *p){
  39786. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  39787. return pcache1.szSlot;
  39788. }else{
  39789. int iSize;
  39790. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  39791. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  39792. iSize = sqlite3MallocSize(p);
  39793. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  39794. return iSize;
  39795. }
  39796. }
  39797. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  39798. /*
  39799. ** Allocate a new page object initially associated with cache pCache.
  39800. */
  39801. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  39802. PgHdr1 *p = 0;
  39803. void *pPg;
  39804. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39805. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  39806. p = pCache->pFree;
  39807. pCache->pFree = p->pNext;
  39808. p->pNext = 0;
  39809. }else{
  39810. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39811. /* The group mutex must be released before pcache1Alloc() is called. This
  39812. ** is because it might call sqlite3_release_memory(), which assumes that
  39813. ** this mutex is not held. */
  39814. assert( pcache1.separateCache==0 );
  39815. assert( pCache->pGroup==&pcache1.grp );
  39816. pcache1LeaveMutex(pCache->pGroup);
  39817. #endif
  39818. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  39819. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  39820. pPg = pcache1Alloc(pCache->szPage);
  39821. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  39822. if( !pPg || !p ){
  39823. pcache1Free(pPg);
  39824. sqlite3_free(p);
  39825. pPg = 0;
  39826. }
  39827. #else
  39828. pPg = pcache1Alloc(pCache->szAlloc);
  39829. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  39830. #endif
  39831. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  39832. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39833. pcache1EnterMutex(pCache->pGroup);
  39834. #endif
  39835. if( pPg==0 ) return 0;
  39836. p->page.pBuf = pPg;
  39837. p->page.pExtra = &p[1];
  39838. p->isBulkLocal = 0;
  39839. p->isAnchor = 0;
  39840. }
  39841. if( pCache->bPurgeable ){
  39842. pCache->pGroup->nCurrentPage++;
  39843. }
  39844. return p;
  39845. }
  39846. /*
  39847. ** Free a page object allocated by pcache1AllocPage().
  39848. */
  39849. static void pcache1FreePage(PgHdr1 *p){
  39850. PCache1 *pCache;
  39851. assert( p!=0 );
  39852. pCache = p->pCache;
  39853. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  39854. if( p->isBulkLocal ){
  39855. p->pNext = pCache->pFree;
  39856. pCache->pFree = p;
  39857. }else{
  39858. pcache1Free(p->page.pBuf);
  39859. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  39860. sqlite3_free(p);
  39861. #endif
  39862. }
  39863. if( pCache->bPurgeable ){
  39864. pCache->pGroup->nCurrentPage--;
  39865. }
  39866. }
  39867. /*
  39868. ** Malloc function used by SQLite to obtain space from the buffer configured
  39869. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  39870. ** exists, this function falls back to sqlite3Malloc().
  39871. */
  39872. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  39873. return pcache1Alloc(sz);
  39874. }
  39875. /*
  39876. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  39877. */
  39878. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  39879. pcache1Free(p);
  39880. }
  39881. /*
  39882. ** Return true if it desirable to avoid allocating a new page cache
  39883. ** entry.
  39884. **
  39885. ** If memory was allocated specifically to the page cache using
  39886. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  39887. ** it is desirable to avoid allocating a new page cache entry because
  39888. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  39889. ** for all page cache needs and we should not need to spill the
  39890. ** allocation onto the heap.
  39891. **
  39892. ** Or, the heap is used for all page cache memory but the heap is
  39893. ** under memory pressure, then again it is desirable to avoid
  39894. ** allocating a new page cache entry in order to avoid stressing
  39895. ** the heap even further.
  39896. */
  39897. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  39898. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  39899. return pcache1.bUnderPressure;
  39900. }else{
  39901. return sqlite3HeapNearlyFull();
  39902. }
  39903. }
  39904. /******************************************************************************/
  39905. /******** General Implementation Functions ************************************/
  39906. /*
  39907. ** This function is used to resize the hash table used by the cache passed
  39908. ** as the first argument.
  39909. **
  39910. ** The PCache mutex must be held when this function is called.
  39911. */
  39912. static void pcache1ResizeHash(PCache1 *p){
  39913. PgHdr1 **apNew;
  39914. unsigned int nNew;
  39915. unsigned int i;
  39916. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  39917. nNew = p->nHash*2;
  39918. if( nNew<256 ){
  39919. nNew = 256;
  39920. }
  39921. pcache1LeaveMutex(p->pGroup);
  39922. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  39923. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  39924. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  39925. pcache1EnterMutex(p->pGroup);
  39926. if( apNew ){
  39927. for(i=0; i<p->nHash; i++){
  39928. PgHdr1 *pPage;
  39929. PgHdr1 *pNext = p->apHash[i];
  39930. while( (pPage = pNext)!=0 ){
  39931. unsigned int h = pPage->iKey % nNew;
  39932. pNext = pPage->pNext;
  39933. pPage->pNext = apNew[h];
  39934. apNew[h] = pPage;
  39935. }
  39936. }
  39937. sqlite3_free(p->apHash);
  39938. p->apHash = apNew;
  39939. p->nHash = nNew;
  39940. }
  39941. }
  39942. /*
  39943. ** This function is used internally to remove the page pPage from the
  39944. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  39945. ** LRU list, then this function is a no-op.
  39946. **
  39947. ** The PGroup mutex must be held when this function is called.
  39948. */
  39949. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  39950. PCache1 *pCache;
  39951. assert( pPage!=0 );
  39952. assert( pPage->isPinned==0 );
  39953. pCache = pPage->pCache;
  39954. assert( pPage->pLruNext );
  39955. assert( pPage->pLruPrev );
  39956. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39957. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  39958. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  39959. pPage->pLruNext = 0;
  39960. pPage->pLruPrev = 0;
  39961. pPage->isPinned = 1;
  39962. assert( pPage->isAnchor==0 );
  39963. assert( pCache->pGroup->lru.isAnchor==1 );
  39964. pCache->nRecyclable--;
  39965. return pPage;
  39966. }
  39967. /*
  39968. ** Remove the page supplied as an argument from the hash table
  39969. ** (PCache1.apHash structure) that it is currently stored in.
  39970. ** Also free the page if freePage is true.
  39971. **
  39972. ** The PGroup mutex must be held when this function is called.
  39973. */
  39974. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  39975. unsigned int h;
  39976. PCache1 *pCache = pPage->pCache;
  39977. PgHdr1 **pp;
  39978. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39979. h = pPage->iKey % pCache->nHash;
  39980. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  39981. *pp = (*pp)->pNext;
  39982. pCache->nPage--;
  39983. if( freeFlag ) pcache1FreePage(pPage);
  39984. }
  39985. /*
  39986. ** If there are currently more than nMaxPage pages allocated, try
  39987. ** to recycle pages to reduce the number allocated to nMaxPage.
  39988. */
  39989. static void pcache1EnforceMaxPage(PCache1 *pCache){
  39990. PGroup *pGroup = pCache->pGroup;
  39991. PgHdr1 *p;
  39992. assert( sqlite3_mutex_held(pGroup->mutex) );
  39993. while( pGroup->nCurrentPage>pGroup->nMaxPage
  39994. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  39995. ){
  39996. assert( p->pCache->pGroup==pGroup );
  39997. assert( p->isPinned==0 );
  39998. pcache1PinPage(p);
  39999. pcache1RemoveFromHash(p, 1);
  40000. }
  40001. if( pCache->nPage==0 && pCache->pBulk ){
  40002. sqlite3_free(pCache->pBulk);
  40003. pCache->pBulk = pCache->pFree = 0;
  40004. }
  40005. }
  40006. /*
  40007. ** Discard all pages from cache pCache with a page number (key value)
  40008. ** greater than or equal to iLimit. Any pinned pages that meet this
  40009. ** criteria are unpinned before they are discarded.
  40010. **
  40011. ** The PCache mutex must be held when this function is called.
  40012. */
  40013. static void pcache1TruncateUnsafe(
  40014. PCache1 *pCache, /* The cache to truncate */
  40015. unsigned int iLimit /* Drop pages with this pgno or larger */
  40016. ){
  40017. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  40018. unsigned int h;
  40019. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  40020. for(h=0; h<pCache->nHash; h++){
  40021. PgHdr1 **pp = &pCache->apHash[h];
  40022. PgHdr1 *pPage;
  40023. while( (pPage = *pp)!=0 ){
  40024. if( pPage->iKey>=iLimit ){
  40025. pCache->nPage--;
  40026. *pp = pPage->pNext;
  40027. if( !pPage->isPinned ) pcache1PinPage(pPage);
  40028. pcache1FreePage(pPage);
  40029. }else{
  40030. pp = &pPage->pNext;
  40031. TESTONLY( nPage++; )
  40032. }
  40033. }
  40034. }
  40035. assert( pCache->nPage==nPage );
  40036. }
  40037. /******************************************************************************/
  40038. /******** sqlite3_pcache Methods **********************************************/
  40039. /*
  40040. ** Implementation of the sqlite3_pcache.xInit method.
  40041. */
  40042. static int pcache1Init(void *NotUsed){
  40043. UNUSED_PARAMETER(NotUsed);
  40044. assert( pcache1.isInit==0 );
  40045. memset(&pcache1, 0, sizeof(pcache1));
  40046. /*
  40047. ** The pcache1.separateCache variable is true if each PCache has its own
  40048. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  40049. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  40050. **
  40051. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  40052. **
  40053. ** * Use a unified cache in single-threaded applications that have
  40054. ** configured a start-time buffer for use as page-cache memory using
  40055. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  40056. ** pBuf argument.
  40057. **
  40058. ** * Otherwise use separate caches (mode-1)
  40059. */
  40060. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  40061. pcache1.separateCache = 0;
  40062. #elif SQLITE_THREADSAFE
  40063. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  40064. || sqlite3GlobalConfig.bCoreMutex>0;
  40065. #else
  40066. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  40067. #endif
  40068. #if SQLITE_THREADSAFE
  40069. if( sqlite3GlobalConfig.bCoreMutex ){
  40070. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  40071. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  40072. }
  40073. #endif
  40074. if( pcache1.separateCache
  40075. && sqlite3GlobalConfig.nPage!=0
  40076. && sqlite3GlobalConfig.pPage==0
  40077. ){
  40078. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  40079. }else{
  40080. pcache1.nInitPage = 0;
  40081. }
  40082. pcache1.grp.mxPinned = 10;
  40083. pcache1.isInit = 1;
  40084. return SQLITE_OK;
  40085. }
  40086. /*
  40087. ** Implementation of the sqlite3_pcache.xShutdown method.
  40088. ** Note that the static mutex allocated in xInit does
  40089. ** not need to be freed.
  40090. */
  40091. static void pcache1Shutdown(void *NotUsed){
  40092. UNUSED_PARAMETER(NotUsed);
  40093. assert( pcache1.isInit!=0 );
  40094. memset(&pcache1, 0, sizeof(pcache1));
  40095. }
  40096. /* forward declaration */
  40097. static void pcache1Destroy(sqlite3_pcache *p);
  40098. /*
  40099. ** Implementation of the sqlite3_pcache.xCreate method.
  40100. **
  40101. ** Allocate a new cache.
  40102. */
  40103. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  40104. PCache1 *pCache; /* The newly created page cache */
  40105. PGroup *pGroup; /* The group the new page cache will belong to */
  40106. int sz; /* Bytes of memory required to allocate the new cache */
  40107. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  40108. assert( szExtra < 300 );
  40109. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  40110. pCache = (PCache1 *)sqlite3MallocZero(sz);
  40111. if( pCache ){
  40112. if( pcache1.separateCache ){
  40113. pGroup = (PGroup*)&pCache[1];
  40114. pGroup->mxPinned = 10;
  40115. }else{
  40116. pGroup = &pcache1.grp;
  40117. }
  40118. if( pGroup->lru.isAnchor==0 ){
  40119. pGroup->lru.isAnchor = 1;
  40120. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  40121. }
  40122. pCache->pGroup = pGroup;
  40123. pCache->szPage = szPage;
  40124. pCache->szExtra = szExtra;
  40125. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  40126. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  40127. pcache1EnterMutex(pGroup);
  40128. pcache1ResizeHash(pCache);
  40129. if( bPurgeable ){
  40130. pCache->nMin = 10;
  40131. pGroup->nMinPage += pCache->nMin;
  40132. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  40133. }
  40134. pcache1LeaveMutex(pGroup);
  40135. if( pCache->nHash==0 ){
  40136. pcache1Destroy((sqlite3_pcache*)pCache);
  40137. pCache = 0;
  40138. }
  40139. }
  40140. return (sqlite3_pcache *)pCache;
  40141. }
  40142. /*
  40143. ** Implementation of the sqlite3_pcache.xCachesize method.
  40144. **
  40145. ** Configure the cache_size limit for a cache.
  40146. */
  40147. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  40148. PCache1 *pCache = (PCache1 *)p;
  40149. if( pCache->bPurgeable ){
  40150. PGroup *pGroup = pCache->pGroup;
  40151. pcache1EnterMutex(pGroup);
  40152. pGroup->nMaxPage += (nMax - pCache->nMax);
  40153. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  40154. pCache->nMax = nMax;
  40155. pCache->n90pct = pCache->nMax*9/10;
  40156. pcache1EnforceMaxPage(pCache);
  40157. pcache1LeaveMutex(pGroup);
  40158. }
  40159. }
  40160. /*
  40161. ** Implementation of the sqlite3_pcache.xShrink method.
  40162. **
  40163. ** Free up as much memory as possible.
  40164. */
  40165. static void pcache1Shrink(sqlite3_pcache *p){
  40166. PCache1 *pCache = (PCache1*)p;
  40167. if( pCache->bPurgeable ){
  40168. PGroup *pGroup = pCache->pGroup;
  40169. int savedMaxPage;
  40170. pcache1EnterMutex(pGroup);
  40171. savedMaxPage = pGroup->nMaxPage;
  40172. pGroup->nMaxPage = 0;
  40173. pcache1EnforceMaxPage(pCache);
  40174. pGroup->nMaxPage = savedMaxPage;
  40175. pcache1LeaveMutex(pGroup);
  40176. }
  40177. }
  40178. /*
  40179. ** Implementation of the sqlite3_pcache.xPagecount method.
  40180. */
  40181. static int pcache1Pagecount(sqlite3_pcache *p){
  40182. int n;
  40183. PCache1 *pCache = (PCache1*)p;
  40184. pcache1EnterMutex(pCache->pGroup);
  40185. n = pCache->nPage;
  40186. pcache1LeaveMutex(pCache->pGroup);
  40187. return n;
  40188. }
  40189. /*
  40190. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  40191. ** in the header of the pcache1Fetch() procedure.
  40192. **
  40193. ** This steps are broken out into a separate procedure because they are
  40194. ** usually not needed, and by avoiding the stack initialization required
  40195. ** for these steps, the main pcache1Fetch() procedure can run faster.
  40196. */
  40197. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  40198. PCache1 *pCache,
  40199. unsigned int iKey,
  40200. int createFlag
  40201. ){
  40202. unsigned int nPinned;
  40203. PGroup *pGroup = pCache->pGroup;
  40204. PgHdr1 *pPage = 0;
  40205. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  40206. assert( pCache->nPage >= pCache->nRecyclable );
  40207. nPinned = pCache->nPage - pCache->nRecyclable;
  40208. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  40209. assert( pCache->n90pct == pCache->nMax*9/10 );
  40210. if( createFlag==1 && (
  40211. nPinned>=pGroup->mxPinned
  40212. || nPinned>=pCache->n90pct
  40213. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  40214. )){
  40215. return 0;
  40216. }
  40217. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  40218. assert( pCache->nHash>0 && pCache->apHash );
  40219. /* Step 4. Try to recycle a page. */
  40220. if( pCache->bPurgeable
  40221. && !pGroup->lru.pLruPrev->isAnchor
  40222. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  40223. ){
  40224. PCache1 *pOther;
  40225. pPage = pGroup->lru.pLruPrev;
  40226. assert( pPage->isPinned==0 );
  40227. pcache1RemoveFromHash(pPage, 0);
  40228. pcache1PinPage(pPage);
  40229. pOther = pPage->pCache;
  40230. if( pOther->szAlloc != pCache->szAlloc ){
  40231. pcache1FreePage(pPage);
  40232. pPage = 0;
  40233. }else{
  40234. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  40235. }
  40236. }
  40237. /* Step 5. If a usable page buffer has still not been found,
  40238. ** attempt to allocate a new one.
  40239. */
  40240. if( !pPage ){
  40241. pPage = pcache1AllocPage(pCache, createFlag==1);
  40242. }
  40243. if( pPage ){
  40244. unsigned int h = iKey % pCache->nHash;
  40245. pCache->nPage++;
  40246. pPage->iKey = iKey;
  40247. pPage->pNext = pCache->apHash[h];
  40248. pPage->pCache = pCache;
  40249. pPage->pLruPrev = 0;
  40250. pPage->pLruNext = 0;
  40251. pPage->isPinned = 1;
  40252. *(void **)pPage->page.pExtra = 0;
  40253. pCache->apHash[h] = pPage;
  40254. if( iKey>pCache->iMaxKey ){
  40255. pCache->iMaxKey = iKey;
  40256. }
  40257. }
  40258. return pPage;
  40259. }
  40260. /*
  40261. ** Implementation of the sqlite3_pcache.xFetch method.
  40262. **
  40263. ** Fetch a page by key value.
  40264. **
  40265. ** Whether or not a new page may be allocated by this function depends on
  40266. ** the value of the createFlag argument. 0 means do not allocate a new
  40267. ** page. 1 means allocate a new page if space is easily available. 2
  40268. ** means to try really hard to allocate a new page.
  40269. **
  40270. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  40271. ** database) there is really no difference between createFlag 1 and 2. So
  40272. ** the calling function (pcache.c) will never have a createFlag of 1 on
  40273. ** a non-purgeable cache.
  40274. **
  40275. ** There are three different approaches to obtaining space for a page,
  40276. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  40277. **
  40278. ** 1. Regardless of the value of createFlag, the cache is searched for a
  40279. ** copy of the requested page. If one is found, it is returned.
  40280. **
  40281. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  40282. ** returned.
  40283. **
  40284. ** 3. If createFlag is 1, and the page is not already in the cache, then
  40285. ** return NULL (do not allocate a new page) if any of the following
  40286. ** conditions are true:
  40287. **
  40288. ** (a) the number of pages pinned by the cache is greater than
  40289. ** PCache1.nMax, or
  40290. **
  40291. ** (b) the number of pages pinned by the cache is greater than
  40292. ** the sum of nMax for all purgeable caches, less the sum of
  40293. ** nMin for all other purgeable caches, or
  40294. **
  40295. ** 4. If none of the first three conditions apply and the cache is marked
  40296. ** as purgeable, and if one of the following is true:
  40297. **
  40298. ** (a) The number of pages allocated for the cache is already
  40299. ** PCache1.nMax, or
  40300. **
  40301. ** (b) The number of pages allocated for all purgeable caches is
  40302. ** already equal to or greater than the sum of nMax for all
  40303. ** purgeable caches,
  40304. **
  40305. ** (c) The system is under memory pressure and wants to avoid
  40306. ** unnecessary pages cache entry allocations
  40307. **
  40308. ** then attempt to recycle a page from the LRU list. If it is the right
  40309. ** size, return the recycled buffer. Otherwise, free the buffer and
  40310. ** proceed to step 5.
  40311. **
  40312. ** 5. Otherwise, allocate and return a new page buffer.
  40313. **
  40314. ** There are two versions of this routine. pcache1FetchWithMutex() is
  40315. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  40316. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  40317. ** invokes the appropriate routine.
  40318. */
  40319. static PgHdr1 *pcache1FetchNoMutex(
  40320. sqlite3_pcache *p,
  40321. unsigned int iKey,
  40322. int createFlag
  40323. ){
  40324. PCache1 *pCache = (PCache1 *)p;
  40325. PgHdr1 *pPage = 0;
  40326. /* Step 1: Search the hash table for an existing entry. */
  40327. pPage = pCache->apHash[iKey % pCache->nHash];
  40328. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  40329. /* Step 2: If the page was found in the hash table, then return it.
  40330. ** If the page was not in the hash table and createFlag is 0, abort.
  40331. ** Otherwise (page not in hash and createFlag!=0) continue with
  40332. ** subsequent steps to try to create the page. */
  40333. if( pPage ){
  40334. if( !pPage->isPinned ){
  40335. return pcache1PinPage(pPage);
  40336. }else{
  40337. return pPage;
  40338. }
  40339. }else if( createFlag ){
  40340. /* Steps 3, 4, and 5 implemented by this subroutine */
  40341. return pcache1FetchStage2(pCache, iKey, createFlag);
  40342. }else{
  40343. return 0;
  40344. }
  40345. }
  40346. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  40347. static PgHdr1 *pcache1FetchWithMutex(
  40348. sqlite3_pcache *p,
  40349. unsigned int iKey,
  40350. int createFlag
  40351. ){
  40352. PCache1 *pCache = (PCache1 *)p;
  40353. PgHdr1 *pPage;
  40354. pcache1EnterMutex(pCache->pGroup);
  40355. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  40356. assert( pPage==0 || pCache->iMaxKey>=iKey );
  40357. pcache1LeaveMutex(pCache->pGroup);
  40358. return pPage;
  40359. }
  40360. #endif
  40361. static sqlite3_pcache_page *pcache1Fetch(
  40362. sqlite3_pcache *p,
  40363. unsigned int iKey,
  40364. int createFlag
  40365. ){
  40366. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  40367. PCache1 *pCache = (PCache1 *)p;
  40368. #endif
  40369. assert( offsetof(PgHdr1,page)==0 );
  40370. assert( pCache->bPurgeable || createFlag!=1 );
  40371. assert( pCache->bPurgeable || pCache->nMin==0 );
  40372. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  40373. assert( pCache->nMin==0 || pCache->bPurgeable );
  40374. assert( pCache->nHash>0 );
  40375. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  40376. if( pCache->pGroup->mutex ){
  40377. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  40378. }else
  40379. #endif
  40380. {
  40381. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  40382. }
  40383. }
  40384. /*
  40385. ** Implementation of the sqlite3_pcache.xUnpin method.
  40386. **
  40387. ** Mark a page as unpinned (eligible for asynchronous recycling).
  40388. */
  40389. static void pcache1Unpin(
  40390. sqlite3_pcache *p,
  40391. sqlite3_pcache_page *pPg,
  40392. int reuseUnlikely
  40393. ){
  40394. PCache1 *pCache = (PCache1 *)p;
  40395. PgHdr1 *pPage = (PgHdr1 *)pPg;
  40396. PGroup *pGroup = pCache->pGroup;
  40397. assert( pPage->pCache==pCache );
  40398. pcache1EnterMutex(pGroup);
  40399. /* It is an error to call this function if the page is already
  40400. ** part of the PGroup LRU list.
  40401. */
  40402. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  40403. assert( pPage->isPinned==1 );
  40404. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  40405. pcache1RemoveFromHash(pPage, 1);
  40406. }else{
  40407. /* Add the page to the PGroup LRU list. */
  40408. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  40409. pPage->pLruPrev = &pGroup->lru;
  40410. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  40411. *ppFirst = pPage;
  40412. pCache->nRecyclable++;
  40413. pPage->isPinned = 0;
  40414. }
  40415. pcache1LeaveMutex(pCache->pGroup);
  40416. }
  40417. /*
  40418. ** Implementation of the sqlite3_pcache.xRekey method.
  40419. */
  40420. static void pcache1Rekey(
  40421. sqlite3_pcache *p,
  40422. sqlite3_pcache_page *pPg,
  40423. unsigned int iOld,
  40424. unsigned int iNew
  40425. ){
  40426. PCache1 *pCache = (PCache1 *)p;
  40427. PgHdr1 *pPage = (PgHdr1 *)pPg;
  40428. PgHdr1 **pp;
  40429. unsigned int h;
  40430. assert( pPage->iKey==iOld );
  40431. assert( pPage->pCache==pCache );
  40432. pcache1EnterMutex(pCache->pGroup);
  40433. h = iOld%pCache->nHash;
  40434. pp = &pCache->apHash[h];
  40435. while( (*pp)!=pPage ){
  40436. pp = &(*pp)->pNext;
  40437. }
  40438. *pp = pPage->pNext;
  40439. h = iNew%pCache->nHash;
  40440. pPage->iKey = iNew;
  40441. pPage->pNext = pCache->apHash[h];
  40442. pCache->apHash[h] = pPage;
  40443. if( iNew>pCache->iMaxKey ){
  40444. pCache->iMaxKey = iNew;
  40445. }
  40446. pcache1LeaveMutex(pCache->pGroup);
  40447. }
  40448. /*
  40449. ** Implementation of the sqlite3_pcache.xTruncate method.
  40450. **
  40451. ** Discard all unpinned pages in the cache with a page number equal to
  40452. ** or greater than parameter iLimit. Any pinned pages with a page number
  40453. ** equal to or greater than iLimit are implicitly unpinned.
  40454. */
  40455. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  40456. PCache1 *pCache = (PCache1 *)p;
  40457. pcache1EnterMutex(pCache->pGroup);
  40458. if( iLimit<=pCache->iMaxKey ){
  40459. pcache1TruncateUnsafe(pCache, iLimit);
  40460. pCache->iMaxKey = iLimit-1;
  40461. }
  40462. pcache1LeaveMutex(pCache->pGroup);
  40463. }
  40464. /*
  40465. ** Implementation of the sqlite3_pcache.xDestroy method.
  40466. **
  40467. ** Destroy a cache allocated using pcache1Create().
  40468. */
  40469. static void pcache1Destroy(sqlite3_pcache *p){
  40470. PCache1 *pCache = (PCache1 *)p;
  40471. PGroup *pGroup = pCache->pGroup;
  40472. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  40473. pcache1EnterMutex(pGroup);
  40474. pcache1TruncateUnsafe(pCache, 0);
  40475. assert( pGroup->nMaxPage >= pCache->nMax );
  40476. pGroup->nMaxPage -= pCache->nMax;
  40477. assert( pGroup->nMinPage >= pCache->nMin );
  40478. pGroup->nMinPage -= pCache->nMin;
  40479. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  40480. pcache1EnforceMaxPage(pCache);
  40481. pcache1LeaveMutex(pGroup);
  40482. sqlite3_free(pCache->pBulk);
  40483. sqlite3_free(pCache->apHash);
  40484. sqlite3_free(pCache);
  40485. }
  40486. /*
  40487. ** This function is called during initialization (sqlite3_initialize()) to
  40488. ** install the default pluggable cache module, assuming the user has not
  40489. ** already provided an alternative.
  40490. */
  40491. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  40492. static const sqlite3_pcache_methods2 defaultMethods = {
  40493. 1, /* iVersion */
  40494. 0, /* pArg */
  40495. pcache1Init, /* xInit */
  40496. pcache1Shutdown, /* xShutdown */
  40497. pcache1Create, /* xCreate */
  40498. pcache1Cachesize, /* xCachesize */
  40499. pcache1Pagecount, /* xPagecount */
  40500. pcache1Fetch, /* xFetch */
  40501. pcache1Unpin, /* xUnpin */
  40502. pcache1Rekey, /* xRekey */
  40503. pcache1Truncate, /* xTruncate */
  40504. pcache1Destroy, /* xDestroy */
  40505. pcache1Shrink /* xShrink */
  40506. };
  40507. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  40508. }
  40509. /*
  40510. ** Return the size of the header on each page of this PCACHE implementation.
  40511. */
  40512. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  40513. /*
  40514. ** Return the global mutex used by this PCACHE implementation. The
  40515. ** sqlite3_status() routine needs access to this mutex.
  40516. */
  40517. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  40518. return pcache1.mutex;
  40519. }
  40520. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  40521. /*
  40522. ** This function is called to free superfluous dynamically allocated memory
  40523. ** held by the pager system. Memory in use by any SQLite pager allocated
  40524. ** by the current thread may be sqlite3_free()ed.
  40525. **
  40526. ** nReq is the number of bytes of memory required. Once this much has
  40527. ** been released, the function returns. The return value is the total number
  40528. ** of bytes of memory released.
  40529. */
  40530. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  40531. int nFree = 0;
  40532. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  40533. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  40534. if( sqlite3GlobalConfig.nPage==0 ){
  40535. PgHdr1 *p;
  40536. pcache1EnterMutex(&pcache1.grp);
  40537. while( (nReq<0 || nFree<nReq)
  40538. && (p=pcache1.grp.lru.pLruPrev)!=0
  40539. && p->isAnchor==0
  40540. ){
  40541. nFree += pcache1MemSize(p->page.pBuf);
  40542. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  40543. nFree += sqlite3MemSize(p);
  40544. #endif
  40545. assert( p->isPinned==0 );
  40546. pcache1PinPage(p);
  40547. pcache1RemoveFromHash(p, 1);
  40548. }
  40549. pcache1LeaveMutex(&pcache1.grp);
  40550. }
  40551. return nFree;
  40552. }
  40553. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  40554. #ifdef SQLITE_TEST
  40555. /*
  40556. ** This function is used by test procedures to inspect the internal state
  40557. ** of the global cache.
  40558. */
  40559. SQLITE_PRIVATE void sqlite3PcacheStats(
  40560. int *pnCurrent, /* OUT: Total number of pages cached */
  40561. int *pnMax, /* OUT: Global maximum cache size */
  40562. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  40563. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  40564. ){
  40565. PgHdr1 *p;
  40566. int nRecyclable = 0;
  40567. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  40568. assert( p->isPinned==0 );
  40569. nRecyclable++;
  40570. }
  40571. *pnCurrent = pcache1.grp.nCurrentPage;
  40572. *pnMax = (int)pcache1.grp.nMaxPage;
  40573. *pnMin = (int)pcache1.grp.nMinPage;
  40574. *pnRecyclable = nRecyclable;
  40575. }
  40576. #endif
  40577. /************** End of pcache1.c *********************************************/
  40578. /************** Begin file rowset.c ******************************************/
  40579. /*
  40580. ** 2008 December 3
  40581. **
  40582. ** The author disclaims copyright to this source code. In place of
  40583. ** a legal notice, here is a blessing:
  40584. **
  40585. ** May you do good and not evil.
  40586. ** May you find forgiveness for yourself and forgive others.
  40587. ** May you share freely, never taking more than you give.
  40588. **
  40589. *************************************************************************
  40590. **
  40591. ** This module implements an object we call a "RowSet".
  40592. **
  40593. ** The RowSet object is a collection of rowids. Rowids
  40594. ** are inserted into the RowSet in an arbitrary order. Inserts
  40595. ** can be intermixed with tests to see if a given rowid has been
  40596. ** previously inserted into the RowSet.
  40597. **
  40598. ** After all inserts are finished, it is possible to extract the
  40599. ** elements of the RowSet in sorted order. Once this extraction
  40600. ** process has started, no new elements may be inserted.
  40601. **
  40602. ** Hence, the primitive operations for a RowSet are:
  40603. **
  40604. ** CREATE
  40605. ** INSERT
  40606. ** TEST
  40607. ** SMALLEST
  40608. ** DESTROY
  40609. **
  40610. ** The CREATE and DESTROY primitives are the constructor and destructor,
  40611. ** obviously. The INSERT primitive adds a new element to the RowSet.
  40612. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  40613. ** extracts the least value from the RowSet.
  40614. **
  40615. ** The INSERT primitive might allocate additional memory. Memory is
  40616. ** allocated in chunks so most INSERTs do no allocation. There is an
  40617. ** upper bound on the size of allocated memory. No memory is freed
  40618. ** until DESTROY.
  40619. **
  40620. ** The TEST primitive includes a "batch" number. The TEST primitive
  40621. ** will only see elements that were inserted before the last change
  40622. ** in the batch number. In other words, if an INSERT occurs between
  40623. ** two TESTs where the TESTs have the same batch nubmer, then the
  40624. ** value added by the INSERT will not be visible to the second TEST.
  40625. ** The initial batch number is zero, so if the very first TEST contains
  40626. ** a non-zero batch number, it will see all prior INSERTs.
  40627. **
  40628. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  40629. ** that is attempted.
  40630. **
  40631. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  40632. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  40633. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  40634. ** The cost of a TEST using the same batch number is O(logN). The cost
  40635. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  40636. ** primitives are constant time. The cost of DESTROY is O(N).
  40637. **
  40638. ** There is an added cost of O(N) when switching between TEST and
  40639. ** SMALLEST primitives.
  40640. */
  40641. /* #include "sqliteInt.h" */
  40642. /*
  40643. ** Target size for allocation chunks.
  40644. */
  40645. #define ROWSET_ALLOCATION_SIZE 1024
  40646. /*
  40647. ** The number of rowset entries per allocation chunk.
  40648. */
  40649. #define ROWSET_ENTRY_PER_CHUNK \
  40650. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  40651. /*
  40652. ** Each entry in a RowSet is an instance of the following object.
  40653. **
  40654. ** This same object is reused to store a linked list of trees of RowSetEntry
  40655. ** objects. In that alternative use, pRight points to the next entry
  40656. ** in the list, pLeft points to the tree, and v is unused. The
  40657. ** RowSet.pForest value points to the head of this forest list.
  40658. */
  40659. struct RowSetEntry {
  40660. i64 v; /* ROWID value for this entry */
  40661. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  40662. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  40663. };
  40664. /*
  40665. ** RowSetEntry objects are allocated in large chunks (instances of the
  40666. ** following structure) to reduce memory allocation overhead. The
  40667. ** chunks are kept on a linked list so that they can be deallocated
  40668. ** when the RowSet is destroyed.
  40669. */
  40670. struct RowSetChunk {
  40671. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  40672. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  40673. };
  40674. /*
  40675. ** A RowSet in an instance of the following structure.
  40676. **
  40677. ** A typedef of this structure if found in sqliteInt.h.
  40678. */
  40679. struct RowSet {
  40680. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  40681. sqlite3 *db; /* The database connection */
  40682. struct RowSetEntry *pEntry; /* List of entries using pRight */
  40683. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  40684. struct RowSetEntry *pFresh; /* Source of new entry objects */
  40685. struct RowSetEntry *pForest; /* List of binary trees of entries */
  40686. u16 nFresh; /* Number of objects on pFresh */
  40687. u16 rsFlags; /* Various flags */
  40688. int iBatch; /* Current insert batch */
  40689. };
  40690. /*
  40691. ** Allowed values for RowSet.rsFlags
  40692. */
  40693. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  40694. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  40695. /*
  40696. ** Turn bulk memory into a RowSet object. N bytes of memory
  40697. ** are available at pSpace. The db pointer is used as a memory context
  40698. ** for any subsequent allocations that need to occur.
  40699. ** Return a pointer to the new RowSet object.
  40700. **
  40701. ** It must be the case that N is sufficient to make a Rowset. If not
  40702. ** an assertion fault occurs.
  40703. **
  40704. ** If N is larger than the minimum, use the surplus as an initial
  40705. ** allocation of entries available to be filled.
  40706. */
  40707. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  40708. RowSet *p;
  40709. assert( N >= ROUND8(sizeof(*p)) );
  40710. p = pSpace;
  40711. p->pChunk = 0;
  40712. p->db = db;
  40713. p->pEntry = 0;
  40714. p->pLast = 0;
  40715. p->pForest = 0;
  40716. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  40717. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  40718. p->rsFlags = ROWSET_SORTED;
  40719. p->iBatch = 0;
  40720. return p;
  40721. }
  40722. /*
  40723. ** Deallocate all chunks from a RowSet. This frees all memory that
  40724. ** the RowSet has allocated over its lifetime. This routine is
  40725. ** the destructor for the RowSet.
  40726. */
  40727. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  40728. struct RowSetChunk *pChunk, *pNextChunk;
  40729. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  40730. pNextChunk = pChunk->pNextChunk;
  40731. sqlite3DbFree(p->db, pChunk);
  40732. }
  40733. p->pChunk = 0;
  40734. p->nFresh = 0;
  40735. p->pEntry = 0;
  40736. p->pLast = 0;
  40737. p->pForest = 0;
  40738. p->rsFlags = ROWSET_SORTED;
  40739. }
  40740. /*
  40741. ** Allocate a new RowSetEntry object that is associated with the
  40742. ** given RowSet. Return a pointer to the new and completely uninitialized
  40743. ** objected.
  40744. **
  40745. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  40746. ** routine returns NULL.
  40747. */
  40748. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  40749. assert( p!=0 );
  40750. if( p->nFresh==0 ){
  40751. struct RowSetChunk *pNew;
  40752. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  40753. if( pNew==0 ){
  40754. return 0;
  40755. }
  40756. pNew->pNextChunk = p->pChunk;
  40757. p->pChunk = pNew;
  40758. p->pFresh = pNew->aEntry;
  40759. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  40760. }
  40761. p->nFresh--;
  40762. return p->pFresh++;
  40763. }
  40764. /*
  40765. ** Insert a new value into a RowSet.
  40766. **
  40767. ** The mallocFailed flag of the database connection is set if a
  40768. ** memory allocation fails.
  40769. */
  40770. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  40771. struct RowSetEntry *pEntry; /* The new entry */
  40772. struct RowSetEntry *pLast; /* The last prior entry */
  40773. /* This routine is never called after sqlite3RowSetNext() */
  40774. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  40775. pEntry = rowSetEntryAlloc(p);
  40776. if( pEntry==0 ) return;
  40777. pEntry->v = rowid;
  40778. pEntry->pRight = 0;
  40779. pLast = p->pLast;
  40780. if( pLast ){
  40781. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  40782. p->rsFlags &= ~ROWSET_SORTED;
  40783. }
  40784. pLast->pRight = pEntry;
  40785. }else{
  40786. p->pEntry = pEntry;
  40787. }
  40788. p->pLast = pEntry;
  40789. }
  40790. /*
  40791. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  40792. **
  40793. ** The input lists are connected via pRight pointers and are
  40794. ** assumed to each already be in sorted order.
  40795. */
  40796. static struct RowSetEntry *rowSetEntryMerge(
  40797. struct RowSetEntry *pA, /* First sorted list to be merged */
  40798. struct RowSetEntry *pB /* Second sorted list to be merged */
  40799. ){
  40800. struct RowSetEntry head;
  40801. struct RowSetEntry *pTail;
  40802. pTail = &head;
  40803. while( pA && pB ){
  40804. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  40805. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  40806. if( pA->v<pB->v ){
  40807. pTail->pRight = pA;
  40808. pA = pA->pRight;
  40809. pTail = pTail->pRight;
  40810. }else if( pB->v<pA->v ){
  40811. pTail->pRight = pB;
  40812. pB = pB->pRight;
  40813. pTail = pTail->pRight;
  40814. }else{
  40815. pA = pA->pRight;
  40816. }
  40817. }
  40818. if( pA ){
  40819. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  40820. pTail->pRight = pA;
  40821. }else{
  40822. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  40823. pTail->pRight = pB;
  40824. }
  40825. return head.pRight;
  40826. }
  40827. /*
  40828. ** Sort all elements on the list of RowSetEntry objects into order of
  40829. ** increasing v.
  40830. */
  40831. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  40832. unsigned int i;
  40833. struct RowSetEntry *pNext, *aBucket[40];
  40834. memset(aBucket, 0, sizeof(aBucket));
  40835. while( pIn ){
  40836. pNext = pIn->pRight;
  40837. pIn->pRight = 0;
  40838. for(i=0; aBucket[i]; i++){
  40839. pIn = rowSetEntryMerge(aBucket[i], pIn);
  40840. aBucket[i] = 0;
  40841. }
  40842. aBucket[i] = pIn;
  40843. pIn = pNext;
  40844. }
  40845. pIn = 0;
  40846. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  40847. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  40848. }
  40849. return pIn;
  40850. }
  40851. /*
  40852. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  40853. ** Convert this tree into a linked list connected by the pRight pointers
  40854. ** and return pointers to the first and last elements of the new list.
  40855. */
  40856. static void rowSetTreeToList(
  40857. struct RowSetEntry *pIn, /* Root of the input tree */
  40858. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  40859. struct RowSetEntry **ppLast /* Write tail of the output list here */
  40860. ){
  40861. assert( pIn!=0 );
  40862. if( pIn->pLeft ){
  40863. struct RowSetEntry *p;
  40864. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  40865. p->pRight = pIn;
  40866. }else{
  40867. *ppFirst = pIn;
  40868. }
  40869. if( pIn->pRight ){
  40870. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  40871. }else{
  40872. *ppLast = pIn;
  40873. }
  40874. assert( (*ppLast)->pRight==0 );
  40875. }
  40876. /*
  40877. ** Convert a sorted list of elements (connected by pRight) into a binary
  40878. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  40879. ** node taken from the head of *ppList. A depth of 2 means a tree with
  40880. ** three nodes. And so forth.
  40881. **
  40882. ** Use as many entries from the input list as required and update the
  40883. ** *ppList to point to the unused elements of the list. If the input
  40884. ** list contains too few elements, then construct an incomplete tree
  40885. ** and leave *ppList set to NULL.
  40886. **
  40887. ** Return a pointer to the root of the constructed binary tree.
  40888. */
  40889. static struct RowSetEntry *rowSetNDeepTree(
  40890. struct RowSetEntry **ppList,
  40891. int iDepth
  40892. ){
  40893. struct RowSetEntry *p; /* Root of the new tree */
  40894. struct RowSetEntry *pLeft; /* Left subtree */
  40895. if( *ppList==0 ){
  40896. return 0;
  40897. }
  40898. if( iDepth==1 ){
  40899. p = *ppList;
  40900. *ppList = p->pRight;
  40901. p->pLeft = p->pRight = 0;
  40902. return p;
  40903. }
  40904. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  40905. p = *ppList;
  40906. if( p==0 ){
  40907. return pLeft;
  40908. }
  40909. p->pLeft = pLeft;
  40910. *ppList = p->pRight;
  40911. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  40912. return p;
  40913. }
  40914. /*
  40915. ** Convert a sorted list of elements into a binary tree. Make the tree
  40916. ** as deep as it needs to be in order to contain the entire list.
  40917. */
  40918. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  40919. int iDepth; /* Depth of the tree so far */
  40920. struct RowSetEntry *p; /* Current tree root */
  40921. struct RowSetEntry *pLeft; /* Left subtree */
  40922. assert( pList!=0 );
  40923. p = pList;
  40924. pList = p->pRight;
  40925. p->pLeft = p->pRight = 0;
  40926. for(iDepth=1; pList; iDepth++){
  40927. pLeft = p;
  40928. p = pList;
  40929. pList = p->pRight;
  40930. p->pLeft = pLeft;
  40931. p->pRight = rowSetNDeepTree(&pList, iDepth);
  40932. }
  40933. return p;
  40934. }
  40935. /*
  40936. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  40937. ** sort them all together into one big ordered list on p->pEntry.
  40938. **
  40939. ** This routine should only be called once in the life of a RowSet.
  40940. */
  40941. static void rowSetToList(RowSet *p){
  40942. /* This routine is called only once */
  40943. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  40944. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  40945. p->pEntry = rowSetEntrySort(p->pEntry);
  40946. }
  40947. /* While this module could theoretically support it, sqlite3RowSetNext()
  40948. ** is never called after sqlite3RowSetText() for the same RowSet. So
  40949. ** there is never a forest to deal with. Should this change, simply
  40950. ** remove the assert() and the #if 0. */
  40951. assert( p->pForest==0 );
  40952. #if 0
  40953. while( p->pForest ){
  40954. struct RowSetEntry *pTree = p->pForest->pLeft;
  40955. if( pTree ){
  40956. struct RowSetEntry *pHead, *pTail;
  40957. rowSetTreeToList(pTree, &pHead, &pTail);
  40958. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  40959. }
  40960. p->pForest = p->pForest->pRight;
  40961. }
  40962. #endif
  40963. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  40964. }
  40965. /*
  40966. ** Extract the smallest element from the RowSet.
  40967. ** Write the element into *pRowid. Return 1 on success. Return
  40968. ** 0 if the RowSet is already empty.
  40969. **
  40970. ** After this routine has been called, the sqlite3RowSetInsert()
  40971. ** routine may not be called again.
  40972. */
  40973. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  40974. assert( p!=0 );
  40975. /* Merge the forest into a single sorted list on first call */
  40976. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  40977. /* Return the next entry on the list */
  40978. if( p->pEntry ){
  40979. *pRowid = p->pEntry->v;
  40980. p->pEntry = p->pEntry->pRight;
  40981. if( p->pEntry==0 ){
  40982. sqlite3RowSetClear(p);
  40983. }
  40984. return 1;
  40985. }else{
  40986. return 0;
  40987. }
  40988. }
  40989. /*
  40990. ** Check to see if element iRowid was inserted into the rowset as
  40991. ** part of any insert batch prior to iBatch. Return 1 or 0.
  40992. **
  40993. ** If this is the first test of a new batch and if there exist entries
  40994. ** on pRowSet->pEntry, then sort those entries into the forest at
  40995. ** pRowSet->pForest so that they can be tested.
  40996. */
  40997. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  40998. struct RowSetEntry *p, *pTree;
  40999. /* This routine is never called after sqlite3RowSetNext() */
  41000. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  41001. /* Sort entries into the forest on the first test of a new batch
  41002. */
  41003. if( iBatch!=pRowSet->iBatch ){
  41004. p = pRowSet->pEntry;
  41005. if( p ){
  41006. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  41007. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  41008. p = rowSetEntrySort(p);
  41009. }
  41010. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  41011. ppPrevTree = &pTree->pRight;
  41012. if( pTree->pLeft==0 ){
  41013. pTree->pLeft = rowSetListToTree(p);
  41014. break;
  41015. }else{
  41016. struct RowSetEntry *pAux, *pTail;
  41017. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  41018. pTree->pLeft = 0;
  41019. p = rowSetEntryMerge(pAux, p);
  41020. }
  41021. }
  41022. if( pTree==0 ){
  41023. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  41024. if( pTree ){
  41025. pTree->v = 0;
  41026. pTree->pRight = 0;
  41027. pTree->pLeft = rowSetListToTree(p);
  41028. }
  41029. }
  41030. pRowSet->pEntry = 0;
  41031. pRowSet->pLast = 0;
  41032. pRowSet->rsFlags |= ROWSET_SORTED;
  41033. }
  41034. pRowSet->iBatch = iBatch;
  41035. }
  41036. /* Test to see if the iRowid value appears anywhere in the forest.
  41037. ** Return 1 if it does and 0 if not.
  41038. */
  41039. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  41040. p = pTree->pLeft;
  41041. while( p ){
  41042. if( p->v<iRowid ){
  41043. p = p->pRight;
  41044. }else if( p->v>iRowid ){
  41045. p = p->pLeft;
  41046. }else{
  41047. return 1;
  41048. }
  41049. }
  41050. }
  41051. return 0;
  41052. }
  41053. /************** End of rowset.c **********************************************/
  41054. /************** Begin file pager.c *******************************************/
  41055. /*
  41056. ** 2001 September 15
  41057. **
  41058. ** The author disclaims copyright to this source code. In place of
  41059. ** a legal notice, here is a blessing:
  41060. **
  41061. ** May you do good and not evil.
  41062. ** May you find forgiveness for yourself and forgive others.
  41063. ** May you share freely, never taking more than you give.
  41064. **
  41065. *************************************************************************
  41066. ** This is the implementation of the page cache subsystem or "pager".
  41067. **
  41068. ** The pager is used to access a database disk file. It implements
  41069. ** atomic commit and rollback through the use of a journal file that
  41070. ** is separate from the database file. The pager also implements file
  41071. ** locking to prevent two processes from writing the same database
  41072. ** file simultaneously, or one process from reading the database while
  41073. ** another is writing.
  41074. */
  41075. #ifndef SQLITE_OMIT_DISKIO
  41076. /* #include "sqliteInt.h" */
  41077. /************** Include wal.h in the middle of pager.c ***********************/
  41078. /************** Begin file wal.h *********************************************/
  41079. /*
  41080. ** 2010 February 1
  41081. **
  41082. ** The author disclaims copyright to this source code. In place of
  41083. ** a legal notice, here is a blessing:
  41084. **
  41085. ** May you do good and not evil.
  41086. ** May you find forgiveness for yourself and forgive others.
  41087. ** May you share freely, never taking more than you give.
  41088. **
  41089. *************************************************************************
  41090. ** This header file defines the interface to the write-ahead logging
  41091. ** system. Refer to the comments below and the header comment attached to
  41092. ** the implementation of each function in log.c for further details.
  41093. */
  41094. #ifndef _WAL_H_
  41095. #define _WAL_H_
  41096. /* #include "sqliteInt.h" */
  41097. /* Additional values that can be added to the sync_flags argument of
  41098. ** sqlite3WalFrames():
  41099. */
  41100. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  41101. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  41102. #ifdef SQLITE_OMIT_WAL
  41103. # define sqlite3WalOpen(x,y,z) 0
  41104. # define sqlite3WalLimit(x,y)
  41105. # define sqlite3WalClose(w,x,y,z) 0
  41106. # define sqlite3WalBeginReadTransaction(y,z) 0
  41107. # define sqlite3WalEndReadTransaction(z)
  41108. # define sqlite3WalDbsize(y) 0
  41109. # define sqlite3WalBeginWriteTransaction(y) 0
  41110. # define sqlite3WalEndWriteTransaction(x) 0
  41111. # define sqlite3WalUndo(x,y,z) 0
  41112. # define sqlite3WalSavepoint(y,z)
  41113. # define sqlite3WalSavepointUndo(y,z) 0
  41114. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  41115. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  41116. # define sqlite3WalCallback(z) 0
  41117. # define sqlite3WalExclusiveMode(y,z) 0
  41118. # define sqlite3WalHeapMemory(z) 0
  41119. # define sqlite3WalFramesize(z) 0
  41120. # define sqlite3WalFindFrame(x,y,z) 0
  41121. # define sqlite3WalFile(x) 0
  41122. #else
  41123. #define WAL_SAVEPOINT_NDATA 4
  41124. /* Connection to a write-ahead log (WAL) file.
  41125. ** There is one object of this type for each pager.
  41126. */
  41127. typedef struct Wal Wal;
  41128. /* Open and close a connection to a write-ahead log. */
  41129. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  41130. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  41131. /* Set the limiting size of a WAL file. */
  41132. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  41133. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  41134. ** snapshot is like a read-transaction. It is the state of the database
  41135. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  41136. ** preserves the current state even if the other threads or processes
  41137. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  41138. ** transaction and releases the lock.
  41139. */
  41140. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  41141. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  41142. /* Read a page from the write-ahead log, if it is present. */
  41143. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  41144. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  41145. /* If the WAL is not empty, return the size of the database. */
  41146. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  41147. /* Obtain or release the WRITER lock. */
  41148. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  41149. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  41150. /* Undo any frames written (but not committed) to the log */
  41151. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  41152. /* Return an integer that records the current (uncommitted) write
  41153. ** position in the WAL */
  41154. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  41155. /* Move the write position of the WAL back to iFrame. Called in
  41156. ** response to a ROLLBACK TO command. */
  41157. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  41158. /* Write a frame or frames to the log. */
  41159. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  41160. /* Copy pages from the log to the database file */
  41161. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  41162. Wal *pWal, /* Write-ahead log connection */
  41163. int eMode, /* One of PASSIVE, FULL and RESTART */
  41164. int (*xBusy)(void*), /* Function to call when busy */
  41165. void *pBusyArg, /* Context argument for xBusyHandler */
  41166. int sync_flags, /* Flags to sync db file with (or 0) */
  41167. int nBuf, /* Size of buffer nBuf */
  41168. u8 *zBuf, /* Temporary buffer to use */
  41169. int *pnLog, /* OUT: Number of frames in WAL */
  41170. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  41171. );
  41172. /* Return the value to pass to a sqlite3_wal_hook callback, the
  41173. ** number of frames in the WAL at the point of the last commit since
  41174. ** sqlite3WalCallback() was called. If no commits have occurred since
  41175. ** the last call, then return 0.
  41176. */
  41177. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  41178. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  41179. ** by the pager layer on the database file.
  41180. */
  41181. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  41182. /* Return true if the argument is non-NULL and the WAL module is using
  41183. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  41184. ** WAL module is using shared-memory, return false.
  41185. */
  41186. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  41187. #ifdef SQLITE_ENABLE_SNAPSHOT
  41188. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  41189. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  41190. #endif
  41191. #ifdef SQLITE_ENABLE_ZIPVFS
  41192. /* If the WAL file is not empty, return the number of bytes of content
  41193. ** stored in each frame (i.e. the db page-size when the WAL was created).
  41194. */
  41195. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  41196. #endif
  41197. /* Return the sqlite3_file object for the WAL file */
  41198. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  41199. #endif /* ifndef SQLITE_OMIT_WAL */
  41200. #endif /* _WAL_H_ */
  41201. /************** End of wal.h *************************************************/
  41202. /************** Continuing where we left off in pager.c **********************/
  41203. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  41204. **
  41205. ** This comment block describes invariants that hold when using a rollback
  41206. ** journal. These invariants do not apply for journal_mode=WAL,
  41207. ** journal_mode=MEMORY, or journal_mode=OFF.
  41208. **
  41209. ** Within this comment block, a page is deemed to have been synced
  41210. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  41211. ** Otherwise, the page is not synced until the xSync method of the VFS
  41212. ** is called successfully on the file containing the page.
  41213. **
  41214. ** Definition: A page of the database file is said to be "overwriteable" if
  41215. ** one or more of the following are true about the page:
  41216. **
  41217. ** (a) The original content of the page as it was at the beginning of
  41218. ** the transaction has been written into the rollback journal and
  41219. ** synced.
  41220. **
  41221. ** (b) The page was a freelist leaf page at the start of the transaction.
  41222. **
  41223. ** (c) The page number is greater than the largest page that existed in
  41224. ** the database file at the start of the transaction.
  41225. **
  41226. ** (1) A page of the database file is never overwritten unless one of the
  41227. ** following are true:
  41228. **
  41229. ** (a) The page and all other pages on the same sector are overwriteable.
  41230. **
  41231. ** (b) The atomic page write optimization is enabled, and the entire
  41232. ** transaction other than the update of the transaction sequence
  41233. ** number consists of a single page change.
  41234. **
  41235. ** (2) The content of a page written into the rollback journal exactly matches
  41236. ** both the content in the database when the rollback journal was written
  41237. ** and the content in the database at the beginning of the current
  41238. ** transaction.
  41239. **
  41240. ** (3) Writes to the database file are an integer multiple of the page size
  41241. ** in length and are aligned on a page boundary.
  41242. **
  41243. ** (4) Reads from the database file are either aligned on a page boundary and
  41244. ** an integer multiple of the page size in length or are taken from the
  41245. ** first 100 bytes of the database file.
  41246. **
  41247. ** (5) All writes to the database file are synced prior to the rollback journal
  41248. ** being deleted, truncated, or zeroed.
  41249. **
  41250. ** (6) If a master journal file is used, then all writes to the database file
  41251. ** are synced prior to the master journal being deleted.
  41252. **
  41253. ** Definition: Two databases (or the same database at two points it time)
  41254. ** are said to be "logically equivalent" if they give the same answer to
  41255. ** all queries. Note in particular the content of freelist leaf
  41256. ** pages can be changed arbitrarily without affecting the logical equivalence
  41257. ** of the database.
  41258. **
  41259. ** (7) At any time, if any subset, including the empty set and the total set,
  41260. ** of the unsynced changes to a rollback journal are removed and the
  41261. ** journal is rolled back, the resulting database file will be logically
  41262. ** equivalent to the database file at the beginning of the transaction.
  41263. **
  41264. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  41265. ** is called to restore the database file to the same size it was at
  41266. ** the beginning of the transaction. (In some VFSes, the xTruncate
  41267. ** method is a no-op, but that does not change the fact the SQLite will
  41268. ** invoke it.)
  41269. **
  41270. ** (9) Whenever the database file is modified, at least one bit in the range
  41271. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  41272. ** the EXCLUSIVE lock, thus signaling other connections on the same
  41273. ** database to flush their caches.
  41274. **
  41275. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  41276. ** than one billion transactions.
  41277. **
  41278. ** (11) A database file is well-formed at the beginning and at the conclusion
  41279. ** of every transaction.
  41280. **
  41281. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  41282. ** the database file.
  41283. **
  41284. ** (13) A SHARED lock is held on the database file while reading any
  41285. ** content out of the database file.
  41286. **
  41287. ******************************************************************************/
  41288. /*
  41289. ** Macros for troubleshooting. Normally turned off
  41290. */
  41291. #if 0
  41292. int sqlite3PagerTrace=1; /* True to enable tracing */
  41293. #define sqlite3DebugPrintf printf
  41294. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  41295. #else
  41296. #define PAGERTRACE(X)
  41297. #endif
  41298. /*
  41299. ** The following two macros are used within the PAGERTRACE() macros above
  41300. ** to print out file-descriptors.
  41301. **
  41302. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  41303. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  41304. ** struct as its argument.
  41305. */
  41306. #define PAGERID(p) ((int)(p->fd))
  41307. #define FILEHANDLEID(fd) ((int)fd)
  41308. /*
  41309. ** The Pager.eState variable stores the current 'state' of a pager. A
  41310. ** pager may be in any one of the seven states shown in the following
  41311. ** state diagram.
  41312. **
  41313. ** OPEN <------+------+
  41314. ** | | |
  41315. ** V | |
  41316. ** +---------> READER-------+ |
  41317. ** | | |
  41318. ** | V |
  41319. ** |<-------WRITER_LOCKED------> ERROR
  41320. ** | | ^
  41321. ** | V |
  41322. ** |<------WRITER_CACHEMOD-------->|
  41323. ** | | |
  41324. ** | V |
  41325. ** |<-------WRITER_DBMOD---------->|
  41326. ** | | |
  41327. ** | V |
  41328. ** +<------WRITER_FINISHED-------->+
  41329. **
  41330. **
  41331. ** List of state transitions and the C [function] that performs each:
  41332. **
  41333. ** OPEN -> READER [sqlite3PagerSharedLock]
  41334. ** READER -> OPEN [pager_unlock]
  41335. **
  41336. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  41337. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  41338. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  41339. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  41340. ** WRITER_*** -> READER [pager_end_transaction]
  41341. **
  41342. ** WRITER_*** -> ERROR [pager_error]
  41343. ** ERROR -> OPEN [pager_unlock]
  41344. **
  41345. **
  41346. ** OPEN:
  41347. **
  41348. ** The pager starts up in this state. Nothing is guaranteed in this
  41349. ** state - the file may or may not be locked and the database size is
  41350. ** unknown. The database may not be read or written.
  41351. **
  41352. ** * No read or write transaction is active.
  41353. ** * Any lock, or no lock at all, may be held on the database file.
  41354. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  41355. **
  41356. ** READER:
  41357. **
  41358. ** In this state all the requirements for reading the database in
  41359. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  41360. ** was) in exclusive-locking mode, a user-level read transaction is
  41361. ** open. The database size is known in this state.
  41362. **
  41363. ** A connection running with locking_mode=normal enters this state when
  41364. ** it opens a read-transaction on the database and returns to state
  41365. ** OPEN after the read-transaction is completed. However a connection
  41366. ** running in locking_mode=exclusive (including temp databases) remains in
  41367. ** this state even after the read-transaction is closed. The only way
  41368. ** a locking_mode=exclusive connection can transition from READER to OPEN
  41369. ** is via the ERROR state (see below).
  41370. **
  41371. ** * A read transaction may be active (but a write-transaction cannot).
  41372. ** * A SHARED or greater lock is held on the database file.
  41373. ** * The dbSize variable may be trusted (even if a user-level read
  41374. ** transaction is not active). The dbOrigSize and dbFileSize variables
  41375. ** may not be trusted at this point.
  41376. ** * If the database is a WAL database, then the WAL connection is open.
  41377. ** * Even if a read-transaction is not open, it is guaranteed that
  41378. ** there is no hot-journal in the file-system.
  41379. **
  41380. ** WRITER_LOCKED:
  41381. **
  41382. ** The pager moves to this state from READER when a write-transaction
  41383. ** is first opened on the database. In WRITER_LOCKED state, all locks
  41384. ** required to start a write-transaction are held, but no actual
  41385. ** modifications to the cache or database have taken place.
  41386. **
  41387. ** In rollback mode, a RESERVED or (if the transaction was opened with
  41388. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  41389. ** moving to this state, but the journal file is not written to or opened
  41390. ** to in this state. If the transaction is committed or rolled back while
  41391. ** in WRITER_LOCKED state, all that is required is to unlock the database
  41392. ** file.
  41393. **
  41394. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  41395. ** If the connection is running with locking_mode=exclusive, an attempt
  41396. ** is made to obtain an EXCLUSIVE lock on the database file.
  41397. **
  41398. ** * A write transaction is active.
  41399. ** * If the connection is open in rollback-mode, a RESERVED or greater
  41400. ** lock is held on the database file.
  41401. ** * If the connection is open in WAL-mode, a WAL write transaction
  41402. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  41403. ** called).
  41404. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  41405. ** * The contents of the pager cache have not been modified.
  41406. ** * The journal file may or may not be open.
  41407. ** * Nothing (not even the first header) has been written to the journal.
  41408. **
  41409. ** WRITER_CACHEMOD:
  41410. **
  41411. ** A pager moves from WRITER_LOCKED state to this state when a page is
  41412. ** first modified by the upper layer. In rollback mode the journal file
  41413. ** is opened (if it is not already open) and a header written to the
  41414. ** start of it. The database file on disk has not been modified.
  41415. **
  41416. ** * A write transaction is active.
  41417. ** * A RESERVED or greater lock is held on the database file.
  41418. ** * The journal file is open and the first header has been written
  41419. ** to it, but the header has not been synced to disk.
  41420. ** * The contents of the page cache have been modified.
  41421. **
  41422. ** WRITER_DBMOD:
  41423. **
  41424. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  41425. ** when it modifies the contents of the database file. WAL connections
  41426. ** never enter this state (since they do not modify the database file,
  41427. ** just the log file).
  41428. **
  41429. ** * A write transaction is active.
  41430. ** * An EXCLUSIVE or greater lock is held on the database file.
  41431. ** * The journal file is open and the first header has been written
  41432. ** and synced to disk.
  41433. ** * The contents of the page cache have been modified (and possibly
  41434. ** written to disk).
  41435. **
  41436. ** WRITER_FINISHED:
  41437. **
  41438. ** It is not possible for a WAL connection to enter this state.
  41439. **
  41440. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  41441. ** state after the entire transaction has been successfully written into the
  41442. ** database file. In this state the transaction may be committed simply
  41443. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  41444. ** not possible to modify the database further. At this point, the upper
  41445. ** layer must either commit or rollback the transaction.
  41446. **
  41447. ** * A write transaction is active.
  41448. ** * An EXCLUSIVE or greater lock is held on the database file.
  41449. ** * All writing and syncing of journal and database data has finished.
  41450. ** If no error occurred, all that remains is to finalize the journal to
  41451. ** commit the transaction. If an error did occur, the caller will need
  41452. ** to rollback the transaction.
  41453. **
  41454. ** ERROR:
  41455. **
  41456. ** The ERROR state is entered when an IO or disk-full error (including
  41457. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  41458. ** difficult to be sure that the in-memory pager state (cache contents,
  41459. ** db size etc.) are consistent with the contents of the file-system.
  41460. **
  41461. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  41462. ** cannot.
  41463. **
  41464. ** For example, if an IO error occurs while performing a rollback,
  41465. ** the contents of the page-cache may be left in an inconsistent state.
  41466. ** At this point it would be dangerous to change back to READER state
  41467. ** (as usually happens after a rollback). Any subsequent readers might
  41468. ** report database corruption (due to the inconsistent cache), and if
  41469. ** they upgrade to writers, they may inadvertently corrupt the database
  41470. ** file. To avoid this hazard, the pager switches into the ERROR state
  41471. ** instead of READER following such an error.
  41472. **
  41473. ** Once it has entered the ERROR state, any attempt to use the pager
  41474. ** to read or write data returns an error. Eventually, once all
  41475. ** outstanding transactions have been abandoned, the pager is able to
  41476. ** transition back to OPEN state, discarding the contents of the
  41477. ** page-cache and any other in-memory state at the same time. Everything
  41478. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  41479. ** when a read-transaction is next opened on the pager (transitioning
  41480. ** the pager into READER state). At that point the system has recovered
  41481. ** from the error.
  41482. **
  41483. ** Specifically, the pager jumps into the ERROR state if:
  41484. **
  41485. ** 1. An error occurs while attempting a rollback. This happens in
  41486. ** function sqlite3PagerRollback().
  41487. **
  41488. ** 2. An error occurs while attempting to finalize a journal file
  41489. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  41490. **
  41491. ** 3. An error occurs while attempting to write to the journal or
  41492. ** database file in function pagerStress() in order to free up
  41493. ** memory.
  41494. **
  41495. ** In other cases, the error is returned to the b-tree layer. The b-tree
  41496. ** layer then attempts a rollback operation. If the error condition
  41497. ** persists, the pager enters the ERROR state via condition (1) above.
  41498. **
  41499. ** Condition (3) is necessary because it can be triggered by a read-only
  41500. ** statement executed within a transaction. In this case, if the error
  41501. ** code were simply returned to the user, the b-tree layer would not
  41502. ** automatically attempt a rollback, as it assumes that an error in a
  41503. ** read-only statement cannot leave the pager in an internally inconsistent
  41504. ** state.
  41505. **
  41506. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  41507. ** * There are one or more outstanding references to pages (after the
  41508. ** last reference is dropped the pager should move back to OPEN state).
  41509. ** * The pager is not an in-memory pager.
  41510. **
  41511. **
  41512. ** Notes:
  41513. **
  41514. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  41515. ** connection is open in WAL mode. A WAL connection is always in one
  41516. ** of the first four states.
  41517. **
  41518. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  41519. ** state. There are two exceptions: immediately after exclusive-mode has
  41520. ** been turned on (and before any read or write transactions are
  41521. ** executed), and when the pager is leaving the "error state".
  41522. **
  41523. ** * See also: assert_pager_state().
  41524. */
  41525. #define PAGER_OPEN 0
  41526. #define PAGER_READER 1
  41527. #define PAGER_WRITER_LOCKED 2
  41528. #define PAGER_WRITER_CACHEMOD 3
  41529. #define PAGER_WRITER_DBMOD 4
  41530. #define PAGER_WRITER_FINISHED 5
  41531. #define PAGER_ERROR 6
  41532. /*
  41533. ** The Pager.eLock variable is almost always set to one of the
  41534. ** following locking-states, according to the lock currently held on
  41535. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  41536. ** This variable is kept up to date as locks are taken and released by
  41537. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  41538. **
  41539. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  41540. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  41541. ** the operation was successful. In these circumstances pagerLockDb() and
  41542. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  41543. ** when unlocking the file, and only updated when locking the file if the
  41544. ** VFS call is successful. This way, the Pager.eLock variable may be set
  41545. ** to a less exclusive (lower) value than the lock that is actually held
  41546. ** at the system level, but it is never set to a more exclusive value.
  41547. **
  41548. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  41549. ** be a few redundant xLock() calls or a lock may be held for longer than
  41550. ** required, but nothing really goes wrong.
  41551. **
  41552. ** The exception is when the database file is unlocked as the pager moves
  41553. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  41554. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  41555. ** transition, by the same pager or any other). If the call to xUnlock()
  41556. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  41557. ** can confuse the call to xCheckReservedLock() call made later as part
  41558. ** of hot-journal detection.
  41559. **
  41560. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  41561. ** lock held by this process or any others". So xCheckReservedLock may
  41562. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  41563. ** doesn't know it because of a previous error in xUnlock). If this happens
  41564. ** a hot-journal may be mistaken for a journal being created by an active
  41565. ** transaction in another process, causing SQLite to read from the database
  41566. ** without rolling it back.
  41567. **
  41568. ** To work around this, if a call to xUnlock() fails when unlocking the
  41569. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  41570. ** is only changed back to a real locking state after a successful call
  41571. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  41572. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  41573. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  41574. ** lock on the database file before attempting to roll it back. See function
  41575. ** PagerSharedLock() for more detail.
  41576. **
  41577. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  41578. ** PAGER_OPEN state.
  41579. */
  41580. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  41581. /*
  41582. ** A macro used for invoking the codec if there is one
  41583. */
  41584. #ifdef SQLITE_HAS_CODEC
  41585. # define CODEC1(P,D,N,X,E) \
  41586. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  41587. # define CODEC2(P,D,N,X,E,O) \
  41588. if( P->xCodec==0 ){ O=(char*)D; }else \
  41589. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  41590. #else
  41591. # define CODEC1(P,D,N,X,E) /* NO-OP */
  41592. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  41593. #endif
  41594. /*
  41595. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  41596. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  41597. ** This could conceivably cause corruption following a power failure on
  41598. ** such a system. This is currently an undocumented limit.
  41599. */
  41600. #define MAX_SECTOR_SIZE 0x10000
  41601. /*
  41602. ** An instance of the following structure is allocated for each active
  41603. ** savepoint and statement transaction in the system. All such structures
  41604. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  41605. ** resized using sqlite3Realloc().
  41606. **
  41607. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  41608. ** set to 0. If a journal-header is written into the main journal while
  41609. ** the savepoint is active, then iHdrOffset is set to the byte offset
  41610. ** immediately following the last journal record written into the main
  41611. ** journal before the journal-header. This is required during savepoint
  41612. ** rollback (see pagerPlaybackSavepoint()).
  41613. */
  41614. typedef struct PagerSavepoint PagerSavepoint;
  41615. struct PagerSavepoint {
  41616. i64 iOffset; /* Starting offset in main journal */
  41617. i64 iHdrOffset; /* See above */
  41618. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  41619. Pgno nOrig; /* Original number of pages in file */
  41620. Pgno iSubRec; /* Index of first record in sub-journal */
  41621. #ifndef SQLITE_OMIT_WAL
  41622. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  41623. #endif
  41624. };
  41625. /*
  41626. ** Bits of the Pager.doNotSpill flag. See further description below.
  41627. */
  41628. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  41629. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  41630. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  41631. /*
  41632. ** An open page cache is an instance of struct Pager. A description of
  41633. ** some of the more important member variables follows:
  41634. **
  41635. ** eState
  41636. **
  41637. ** The current 'state' of the pager object. See the comment and state
  41638. ** diagram above for a description of the pager state.
  41639. **
  41640. ** eLock
  41641. **
  41642. ** For a real on-disk database, the current lock held on the database file -
  41643. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  41644. **
  41645. ** For a temporary or in-memory database (neither of which require any
  41646. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  41647. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  41648. ** logic into thinking that it already has all the locks it will ever
  41649. ** need (and no reason to release them).
  41650. **
  41651. ** In some (obscure) circumstances, this variable may also be set to
  41652. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  41653. ** details.
  41654. **
  41655. ** changeCountDone
  41656. **
  41657. ** This boolean variable is used to make sure that the change-counter
  41658. ** (the 4-byte header field at byte offset 24 of the database file) is
  41659. ** not updated more often than necessary.
  41660. **
  41661. ** It is set to true when the change-counter field is updated, which
  41662. ** can only happen if an exclusive lock is held on the database file.
  41663. ** It is cleared (set to false) whenever an exclusive lock is
  41664. ** relinquished on the database file. Each time a transaction is committed,
  41665. ** The changeCountDone flag is inspected. If it is true, the work of
  41666. ** updating the change-counter is omitted for the current transaction.
  41667. **
  41668. ** This mechanism means that when running in exclusive mode, a connection
  41669. ** need only update the change-counter once, for the first transaction
  41670. ** committed.
  41671. **
  41672. ** setMaster
  41673. **
  41674. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  41675. ** (or may not) specify a master-journal name to be written into the
  41676. ** journal file before it is synced to disk.
  41677. **
  41678. ** Whether or not a journal file contains a master-journal pointer affects
  41679. ** the way in which the journal file is finalized after the transaction is
  41680. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  41681. ** If a journal file does not contain a master-journal pointer, it is
  41682. ** finalized by overwriting the first journal header with zeroes. If
  41683. ** it does contain a master-journal pointer the journal file is finalized
  41684. ** by truncating it to zero bytes, just as if the connection were
  41685. ** running in "journal_mode=truncate" mode.
  41686. **
  41687. ** Journal files that contain master journal pointers cannot be finalized
  41688. ** simply by overwriting the first journal-header with zeroes, as the
  41689. ** master journal pointer could interfere with hot-journal rollback of any
  41690. ** subsequently interrupted transaction that reuses the journal file.
  41691. **
  41692. ** The flag is cleared as soon as the journal file is finalized (either
  41693. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  41694. ** journal file from being successfully finalized, the setMaster flag
  41695. ** is cleared anyway (and the pager will move to ERROR state).
  41696. **
  41697. ** doNotSpill
  41698. **
  41699. ** This variables control the behavior of cache-spills (calls made by
  41700. ** the pcache module to the pagerStress() routine to write cached data
  41701. ** to the file-system in order to free up memory).
  41702. **
  41703. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  41704. ** writing to the database from pagerStress() is disabled altogether.
  41705. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  41706. ** comes up during savepoint rollback that requires the pcache module
  41707. ** to allocate a new page to prevent the journal file from being written
  41708. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  41709. ** case is a user preference.
  41710. **
  41711. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  41712. ** pagerStress() is permitted, but syncing the journal file is not.
  41713. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  41714. ** is larger than the database page-size in order to prevent a journal sync
  41715. ** from happening in between the journalling of two pages on the same sector.
  41716. **
  41717. ** subjInMemory
  41718. **
  41719. ** This is a boolean variable. If true, then any required sub-journal
  41720. ** is opened as an in-memory journal file. If false, then in-memory
  41721. ** sub-journals are only used for in-memory pager files.
  41722. **
  41723. ** This variable is updated by the upper layer each time a new
  41724. ** write-transaction is opened.
  41725. **
  41726. ** dbSize, dbOrigSize, dbFileSize
  41727. **
  41728. ** Variable dbSize is set to the number of pages in the database file.
  41729. ** It is valid in PAGER_READER and higher states (all states except for
  41730. ** OPEN and ERROR).
  41731. **
  41732. ** dbSize is set based on the size of the database file, which may be
  41733. ** larger than the size of the database (the value stored at offset
  41734. ** 28 of the database header by the btree). If the size of the file
  41735. ** is not an integer multiple of the page-size, the value stored in
  41736. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  41737. ** Except, any file that is greater than 0 bytes in size is considered
  41738. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  41739. ** to dbSize==1).
  41740. **
  41741. ** During a write-transaction, if pages with page-numbers greater than
  41742. ** dbSize are modified in the cache, dbSize is updated accordingly.
  41743. ** Similarly, if the database is truncated using PagerTruncateImage(),
  41744. ** dbSize is updated.
  41745. **
  41746. ** Variables dbOrigSize and dbFileSize are valid in states
  41747. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  41748. ** variable at the start of the transaction. It is used during rollback,
  41749. ** and to determine whether or not pages need to be journalled before
  41750. ** being modified.
  41751. **
  41752. ** Throughout a write-transaction, dbFileSize contains the size of
  41753. ** the file on disk in pages. It is set to a copy of dbSize when the
  41754. ** write-transaction is first opened, and updated when VFS calls are made
  41755. ** to write or truncate the database file on disk.
  41756. **
  41757. ** The only reason the dbFileSize variable is required is to suppress
  41758. ** unnecessary calls to xTruncate() after committing a transaction. If,
  41759. ** when a transaction is committed, the dbFileSize variable indicates
  41760. ** that the database file is larger than the database image (Pager.dbSize),
  41761. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  41762. ** to measure the database file on disk, and then truncates it if required.
  41763. ** dbFileSize is not used when rolling back a transaction. In this case
  41764. ** pager_truncate() is called unconditionally (which means there may be
  41765. ** a call to xFilesize() that is not strictly required). In either case,
  41766. ** pager_truncate() may cause the file to become smaller or larger.
  41767. **
  41768. ** dbHintSize
  41769. **
  41770. ** The dbHintSize variable is used to limit the number of calls made to
  41771. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  41772. **
  41773. ** dbHintSize is set to a copy of the dbSize variable when a
  41774. ** write-transaction is opened (at the same time as dbFileSize and
  41775. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  41776. ** dbHintSize is increased to the number of pages that correspond to the
  41777. ** size-hint passed to the method call. See pager_write_pagelist() for
  41778. ** details.
  41779. **
  41780. ** errCode
  41781. **
  41782. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  41783. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  41784. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  41785. ** sub-codes.
  41786. */
  41787. struct Pager {
  41788. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  41789. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  41790. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  41791. u8 useJournal; /* Use a rollback journal on this file */
  41792. u8 noSync; /* Do not sync the journal if true */
  41793. u8 fullSync; /* Do extra syncs of the journal for robustness */
  41794. u8 extraSync; /* sync directory after journal delete */
  41795. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  41796. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  41797. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  41798. u8 tempFile; /* zFilename is a temporary or immutable file */
  41799. u8 noLock; /* Do not lock (except in WAL mode) */
  41800. u8 readOnly; /* True for a read-only database */
  41801. u8 memDb; /* True to inhibit all file I/O */
  41802. /**************************************************************************
  41803. ** The following block contains those class members that change during
  41804. ** routine operation. Class members not in this block are either fixed
  41805. ** when the pager is first created or else only change when there is a
  41806. ** significant mode change (such as changing the page_size, locking_mode,
  41807. ** or the journal_mode). From another view, these class members describe
  41808. ** the "state" of the pager, while other class members describe the
  41809. ** "configuration" of the pager.
  41810. */
  41811. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  41812. u8 eLock; /* Current lock held on database file */
  41813. u8 changeCountDone; /* Set after incrementing the change-counter */
  41814. u8 setMaster; /* True if a m-j name has been written to jrnl */
  41815. u8 doNotSpill; /* Do not spill the cache when non-zero */
  41816. u8 subjInMemory; /* True to use in-memory sub-journals */
  41817. u8 bUseFetch; /* True to use xFetch() */
  41818. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  41819. Pgno dbSize; /* Number of pages in the database */
  41820. Pgno dbOrigSize; /* dbSize before the current transaction */
  41821. Pgno dbFileSize; /* Number of pages in the database file */
  41822. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  41823. int errCode; /* One of several kinds of errors */
  41824. int nRec; /* Pages journalled since last j-header written */
  41825. u32 cksumInit; /* Quasi-random value added to every checksum */
  41826. u32 nSubRec; /* Number of records written to sub-journal */
  41827. Bitvec *pInJournal; /* One bit for each page in the database file */
  41828. sqlite3_file *fd; /* File descriptor for database */
  41829. sqlite3_file *jfd; /* File descriptor for main journal */
  41830. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  41831. i64 journalOff; /* Current write offset in the journal file */
  41832. i64 journalHdr; /* Byte offset to previous journal header */
  41833. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  41834. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  41835. int nSavepoint; /* Number of elements in aSavepoint[] */
  41836. u32 iDataVersion; /* Changes whenever database content changes */
  41837. char dbFileVers[16]; /* Changes whenever database file changes */
  41838. int nMmapOut; /* Number of mmap pages currently outstanding */
  41839. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  41840. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  41841. /*
  41842. ** End of the routinely-changing class members
  41843. ***************************************************************************/
  41844. u16 nExtra; /* Add this many bytes to each in-memory page */
  41845. i16 nReserve; /* Number of unused bytes at end of each page */
  41846. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  41847. u32 sectorSize; /* Assumed sector size during rollback */
  41848. int pageSize; /* Number of bytes in a page */
  41849. Pgno mxPgno; /* Maximum allowed size of the database */
  41850. i64 journalSizeLimit; /* Size limit for persistent journal files */
  41851. char *zFilename; /* Name of the database file */
  41852. char *zJournal; /* Name of the journal file */
  41853. int (*xBusyHandler)(void*); /* Function to call when busy */
  41854. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  41855. int aStat[3]; /* Total cache hits, misses and writes */
  41856. #ifdef SQLITE_TEST
  41857. int nRead; /* Database pages read */
  41858. #endif
  41859. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  41860. #ifdef SQLITE_HAS_CODEC
  41861. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  41862. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  41863. void (*xCodecFree)(void*); /* Destructor for the codec */
  41864. void *pCodec; /* First argument to xCodec... methods */
  41865. #endif
  41866. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  41867. PCache *pPCache; /* Pointer to page cache object */
  41868. #ifndef SQLITE_OMIT_WAL
  41869. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  41870. char *zWal; /* File name for write-ahead log */
  41871. #endif
  41872. };
  41873. /*
  41874. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  41875. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  41876. ** or CACHE_WRITE to sqlite3_db_status().
  41877. */
  41878. #define PAGER_STAT_HIT 0
  41879. #define PAGER_STAT_MISS 1
  41880. #define PAGER_STAT_WRITE 2
  41881. /*
  41882. ** The following global variables hold counters used for
  41883. ** testing purposes only. These variables do not exist in
  41884. ** a non-testing build. These variables are not thread-safe.
  41885. */
  41886. #ifdef SQLITE_TEST
  41887. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  41888. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  41889. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  41890. # define PAGER_INCR(v) v++
  41891. #else
  41892. # define PAGER_INCR(v)
  41893. #endif
  41894. /*
  41895. ** Journal files begin with the following magic string. The data
  41896. ** was obtained from /dev/random. It is used only as a sanity check.
  41897. **
  41898. ** Since version 2.8.0, the journal format contains additional sanity
  41899. ** checking information. If the power fails while the journal is being
  41900. ** written, semi-random garbage data might appear in the journal
  41901. ** file after power is restored. If an attempt is then made
  41902. ** to roll the journal back, the database could be corrupted. The additional
  41903. ** sanity checking data is an attempt to discover the garbage in the
  41904. ** journal and ignore it.
  41905. **
  41906. ** The sanity checking information for the new journal format consists
  41907. ** of a 32-bit checksum on each page of data. The checksum covers both
  41908. ** the page number and the pPager->pageSize bytes of data for the page.
  41909. ** This cksum is initialized to a 32-bit random value that appears in the
  41910. ** journal file right after the header. The random initializer is important,
  41911. ** because garbage data that appears at the end of a journal is likely
  41912. ** data that was once in other files that have now been deleted. If the
  41913. ** garbage data came from an obsolete journal file, the checksums might
  41914. ** be correct. But by initializing the checksum to random value which
  41915. ** is different for every journal, we minimize that risk.
  41916. */
  41917. static const unsigned char aJournalMagic[] = {
  41918. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  41919. };
  41920. /*
  41921. ** The size of the of each page record in the journal is given by
  41922. ** the following macro.
  41923. */
  41924. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  41925. /*
  41926. ** The journal header size for this pager. This is usually the same
  41927. ** size as a single disk sector. See also setSectorSize().
  41928. */
  41929. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  41930. /*
  41931. ** The macro MEMDB is true if we are dealing with an in-memory database.
  41932. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  41933. ** the value of MEMDB will be a constant and the compiler will optimize
  41934. ** out code that would never execute.
  41935. */
  41936. #ifdef SQLITE_OMIT_MEMORYDB
  41937. # define MEMDB 0
  41938. #else
  41939. # define MEMDB pPager->memDb
  41940. #endif
  41941. /*
  41942. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  41943. ** interfaces to access the database using memory-mapped I/O.
  41944. */
  41945. #if SQLITE_MAX_MMAP_SIZE>0
  41946. # define USEFETCH(x) ((x)->bUseFetch)
  41947. #else
  41948. # define USEFETCH(x) 0
  41949. #endif
  41950. /*
  41951. ** The maximum legal page number is (2^31 - 1).
  41952. */
  41953. #define PAGER_MAX_PGNO 2147483647
  41954. /*
  41955. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  41956. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  41957. **
  41958. ** This is so that expressions can be written as:
  41959. **
  41960. ** if( isOpen(pPager->jfd) ){ ...
  41961. **
  41962. ** instead of
  41963. **
  41964. ** if( pPager->jfd->pMethods ){ ...
  41965. */
  41966. #define isOpen(pFd) ((pFd)->pMethods!=0)
  41967. /*
  41968. ** Return true if this pager uses a write-ahead log instead of the usual
  41969. ** rollback journal. Otherwise false.
  41970. */
  41971. #ifndef SQLITE_OMIT_WAL
  41972. static int pagerUseWal(Pager *pPager){
  41973. return (pPager->pWal!=0);
  41974. }
  41975. #else
  41976. # define pagerUseWal(x) 0
  41977. # define pagerRollbackWal(x) 0
  41978. # define pagerWalFrames(v,w,x,y) 0
  41979. # define pagerOpenWalIfPresent(z) SQLITE_OK
  41980. # define pagerBeginReadTransaction(z) SQLITE_OK
  41981. #endif
  41982. #ifndef NDEBUG
  41983. /*
  41984. ** Usage:
  41985. **
  41986. ** assert( assert_pager_state(pPager) );
  41987. **
  41988. ** This function runs many asserts to try to find inconsistencies in
  41989. ** the internal state of the Pager object.
  41990. */
  41991. static int assert_pager_state(Pager *p){
  41992. Pager *pPager = p;
  41993. /* State must be valid. */
  41994. assert( p->eState==PAGER_OPEN
  41995. || p->eState==PAGER_READER
  41996. || p->eState==PAGER_WRITER_LOCKED
  41997. || p->eState==PAGER_WRITER_CACHEMOD
  41998. || p->eState==PAGER_WRITER_DBMOD
  41999. || p->eState==PAGER_WRITER_FINISHED
  42000. || p->eState==PAGER_ERROR
  42001. );
  42002. /* Regardless of the current state, a temp-file connection always behaves
  42003. ** as if it has an exclusive lock on the database file. It never updates
  42004. ** the change-counter field, so the changeCountDone flag is always set.
  42005. */
  42006. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  42007. assert( p->tempFile==0 || pPager->changeCountDone );
  42008. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  42009. ** And if the journal-mode is "OFF", the journal file must not be open.
  42010. */
  42011. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  42012. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  42013. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  42014. ** this means an in-memory pager performs no IO at all, it cannot encounter
  42015. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  42016. ** a journal file. (although the in-memory journal implementation may
  42017. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  42018. ** is therefore not possible for an in-memory pager to enter the ERROR
  42019. ** state.
  42020. */
  42021. if( MEMDB ){
  42022. assert( p->noSync );
  42023. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  42024. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  42025. );
  42026. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  42027. assert( pagerUseWal(p)==0 );
  42028. }
  42029. /* If changeCountDone is set, a RESERVED lock or greater must be held
  42030. ** on the file.
  42031. */
  42032. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  42033. assert( p->eLock!=PENDING_LOCK );
  42034. switch( p->eState ){
  42035. case PAGER_OPEN:
  42036. assert( !MEMDB );
  42037. assert( pPager->errCode==SQLITE_OK );
  42038. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  42039. break;
  42040. case PAGER_READER:
  42041. assert( pPager->errCode==SQLITE_OK );
  42042. assert( p->eLock!=UNKNOWN_LOCK );
  42043. assert( p->eLock>=SHARED_LOCK );
  42044. break;
  42045. case PAGER_WRITER_LOCKED:
  42046. assert( p->eLock!=UNKNOWN_LOCK );
  42047. assert( pPager->errCode==SQLITE_OK );
  42048. if( !pagerUseWal(pPager) ){
  42049. assert( p->eLock>=RESERVED_LOCK );
  42050. }
  42051. assert( pPager->dbSize==pPager->dbOrigSize );
  42052. assert( pPager->dbOrigSize==pPager->dbFileSize );
  42053. assert( pPager->dbOrigSize==pPager->dbHintSize );
  42054. assert( pPager->setMaster==0 );
  42055. break;
  42056. case PAGER_WRITER_CACHEMOD:
  42057. assert( p->eLock!=UNKNOWN_LOCK );
  42058. assert( pPager->errCode==SQLITE_OK );
  42059. if( !pagerUseWal(pPager) ){
  42060. /* It is possible that if journal_mode=wal here that neither the
  42061. ** journal file nor the WAL file are open. This happens during
  42062. ** a rollback transaction that switches from journal_mode=off
  42063. ** to journal_mode=wal.
  42064. */
  42065. assert( p->eLock>=RESERVED_LOCK );
  42066. assert( isOpen(p->jfd)
  42067. || p->journalMode==PAGER_JOURNALMODE_OFF
  42068. || p->journalMode==PAGER_JOURNALMODE_WAL
  42069. );
  42070. }
  42071. assert( pPager->dbOrigSize==pPager->dbFileSize );
  42072. assert( pPager->dbOrigSize==pPager->dbHintSize );
  42073. break;
  42074. case PAGER_WRITER_DBMOD:
  42075. assert( p->eLock==EXCLUSIVE_LOCK );
  42076. assert( pPager->errCode==SQLITE_OK );
  42077. assert( !pagerUseWal(pPager) );
  42078. assert( p->eLock>=EXCLUSIVE_LOCK );
  42079. assert( isOpen(p->jfd)
  42080. || p->journalMode==PAGER_JOURNALMODE_OFF
  42081. || p->journalMode==PAGER_JOURNALMODE_WAL
  42082. );
  42083. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  42084. break;
  42085. case PAGER_WRITER_FINISHED:
  42086. assert( p->eLock==EXCLUSIVE_LOCK );
  42087. assert( pPager->errCode==SQLITE_OK );
  42088. assert( !pagerUseWal(pPager) );
  42089. assert( isOpen(p->jfd)
  42090. || p->journalMode==PAGER_JOURNALMODE_OFF
  42091. || p->journalMode==PAGER_JOURNALMODE_WAL
  42092. );
  42093. break;
  42094. case PAGER_ERROR:
  42095. /* There must be at least one outstanding reference to the pager if
  42096. ** in ERROR state. Otherwise the pager should have already dropped
  42097. ** back to OPEN state.
  42098. */
  42099. assert( pPager->errCode!=SQLITE_OK );
  42100. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  42101. break;
  42102. }
  42103. return 1;
  42104. }
  42105. #endif /* ifndef NDEBUG */
  42106. #ifdef SQLITE_DEBUG
  42107. /*
  42108. ** Return a pointer to a human readable string in a static buffer
  42109. ** containing the state of the Pager object passed as an argument. This
  42110. ** is intended to be used within debuggers. For example, as an alternative
  42111. ** to "print *pPager" in gdb:
  42112. **
  42113. ** (gdb) printf "%s", print_pager_state(pPager)
  42114. */
  42115. static char *print_pager_state(Pager *p){
  42116. static char zRet[1024];
  42117. sqlite3_snprintf(1024, zRet,
  42118. "Filename: %s\n"
  42119. "State: %s errCode=%d\n"
  42120. "Lock: %s\n"
  42121. "Locking mode: locking_mode=%s\n"
  42122. "Journal mode: journal_mode=%s\n"
  42123. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  42124. "Journal: journalOff=%lld journalHdr=%lld\n"
  42125. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  42126. , p->zFilename
  42127. , p->eState==PAGER_OPEN ? "OPEN" :
  42128. p->eState==PAGER_READER ? "READER" :
  42129. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  42130. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  42131. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  42132. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  42133. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  42134. , (int)p->errCode
  42135. , p->eLock==NO_LOCK ? "NO_LOCK" :
  42136. p->eLock==RESERVED_LOCK ? "RESERVED" :
  42137. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  42138. p->eLock==SHARED_LOCK ? "SHARED" :
  42139. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  42140. , p->exclusiveMode ? "exclusive" : "normal"
  42141. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  42142. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  42143. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  42144. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  42145. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  42146. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  42147. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  42148. , p->journalOff, p->journalHdr
  42149. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  42150. );
  42151. return zRet;
  42152. }
  42153. #endif
  42154. /*
  42155. ** Return true if it is necessary to write page *pPg into the sub-journal.
  42156. ** A page needs to be written into the sub-journal if there exists one
  42157. ** or more open savepoints for which:
  42158. **
  42159. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  42160. ** * The bit corresponding to the page-number is not set in
  42161. ** PagerSavepoint.pInSavepoint.
  42162. */
  42163. static int subjRequiresPage(PgHdr *pPg){
  42164. Pager *pPager = pPg->pPager;
  42165. PagerSavepoint *p;
  42166. Pgno pgno = pPg->pgno;
  42167. int i;
  42168. for(i=0; i<pPager->nSavepoint; i++){
  42169. p = &pPager->aSavepoint[i];
  42170. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  42171. return 1;
  42172. }
  42173. }
  42174. return 0;
  42175. }
  42176. #ifdef SQLITE_DEBUG
  42177. /*
  42178. ** Return true if the page is already in the journal file.
  42179. */
  42180. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  42181. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  42182. }
  42183. #endif
  42184. /*
  42185. ** Read a 32-bit integer from the given file descriptor. Store the integer
  42186. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  42187. ** error code is something goes wrong.
  42188. **
  42189. ** All values are stored on disk as big-endian.
  42190. */
  42191. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  42192. unsigned char ac[4];
  42193. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  42194. if( rc==SQLITE_OK ){
  42195. *pRes = sqlite3Get4byte(ac);
  42196. }
  42197. return rc;
  42198. }
  42199. /*
  42200. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  42201. */
  42202. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  42203. /*
  42204. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  42205. ** on success or an error code is something goes wrong.
  42206. */
  42207. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  42208. char ac[4];
  42209. put32bits(ac, val);
  42210. return sqlite3OsWrite(fd, ac, 4, offset);
  42211. }
  42212. /*
  42213. ** Unlock the database file to level eLock, which must be either NO_LOCK
  42214. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  42215. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  42216. **
  42217. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  42218. ** called, do not modify it. See the comment above the #define of
  42219. ** UNKNOWN_LOCK for an explanation of this.
  42220. */
  42221. static int pagerUnlockDb(Pager *pPager, int eLock){
  42222. int rc = SQLITE_OK;
  42223. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  42224. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  42225. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  42226. if( isOpen(pPager->fd) ){
  42227. assert( pPager->eLock>=eLock );
  42228. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  42229. if( pPager->eLock!=UNKNOWN_LOCK ){
  42230. pPager->eLock = (u8)eLock;
  42231. }
  42232. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  42233. }
  42234. return rc;
  42235. }
  42236. /*
  42237. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  42238. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  42239. ** Pager.eLock variable to the new locking state.
  42240. **
  42241. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  42242. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  42243. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  42244. ** of this.
  42245. */
  42246. static int pagerLockDb(Pager *pPager, int eLock){
  42247. int rc = SQLITE_OK;
  42248. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  42249. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  42250. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  42251. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  42252. pPager->eLock = (u8)eLock;
  42253. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  42254. }
  42255. }
  42256. return rc;
  42257. }
  42258. /*
  42259. ** This function determines whether or not the atomic-write optimization
  42260. ** can be used with this pager. The optimization can be used if:
  42261. **
  42262. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  42263. ** a database page may be written atomically, and
  42264. ** (b) the value returned by OsSectorSize() is less than or equal
  42265. ** to the page size.
  42266. **
  42267. ** The optimization is also always enabled for temporary files. It is
  42268. ** an error to call this function if pPager is opened on an in-memory
  42269. ** database.
  42270. **
  42271. ** If the optimization cannot be used, 0 is returned. If it can be used,
  42272. ** then the value returned is the size of the journal file when it
  42273. ** contains rollback data for exactly one page.
  42274. */
  42275. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  42276. static int jrnlBufferSize(Pager *pPager){
  42277. assert( !MEMDB );
  42278. if( !pPager->tempFile ){
  42279. int dc; /* Device characteristics */
  42280. int nSector; /* Sector size */
  42281. int szPage; /* Page size */
  42282. assert( isOpen(pPager->fd) );
  42283. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42284. nSector = pPager->sectorSize;
  42285. szPage = pPager->pageSize;
  42286. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  42287. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  42288. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  42289. return 0;
  42290. }
  42291. }
  42292. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  42293. }
  42294. #endif
  42295. /*
  42296. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  42297. ** on the cache using a hash function. This is used for testing
  42298. ** and debugging only.
  42299. */
  42300. #ifdef SQLITE_CHECK_PAGES
  42301. /*
  42302. ** Return a 32-bit hash of the page data for pPage.
  42303. */
  42304. static u32 pager_datahash(int nByte, unsigned char *pData){
  42305. u32 hash = 0;
  42306. int i;
  42307. for(i=0; i<nByte; i++){
  42308. hash = (hash*1039) + pData[i];
  42309. }
  42310. return hash;
  42311. }
  42312. static u32 pager_pagehash(PgHdr *pPage){
  42313. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  42314. }
  42315. static void pager_set_pagehash(PgHdr *pPage){
  42316. pPage->pageHash = pager_pagehash(pPage);
  42317. }
  42318. /*
  42319. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  42320. ** is defined, and NDEBUG is not defined, an assert() statement checks
  42321. ** that the page is either dirty or still matches the calculated page-hash.
  42322. */
  42323. #define CHECK_PAGE(x) checkPage(x)
  42324. static void checkPage(PgHdr *pPg){
  42325. Pager *pPager = pPg->pPager;
  42326. assert( pPager->eState!=PAGER_ERROR );
  42327. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  42328. }
  42329. #else
  42330. #define pager_datahash(X,Y) 0
  42331. #define pager_pagehash(X) 0
  42332. #define pager_set_pagehash(X)
  42333. #define CHECK_PAGE(x)
  42334. #endif /* SQLITE_CHECK_PAGES */
  42335. /*
  42336. ** When this is called the journal file for pager pPager must be open.
  42337. ** This function attempts to read a master journal file name from the
  42338. ** end of the file and, if successful, copies it into memory supplied
  42339. ** by the caller. See comments above writeMasterJournal() for the format
  42340. ** used to store a master journal file name at the end of a journal file.
  42341. **
  42342. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  42343. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  42344. ** enough space to write the master journal name). If the master journal
  42345. ** name in the journal is longer than nMaster bytes (including a
  42346. ** nul-terminator), then this is handled as if no master journal name
  42347. ** were present in the journal.
  42348. **
  42349. ** If a master journal file name is present at the end of the journal
  42350. ** file, then it is copied into the buffer pointed to by zMaster. A
  42351. ** nul-terminator byte is appended to the buffer following the master
  42352. ** journal file name.
  42353. **
  42354. ** If it is determined that no master journal file name is present
  42355. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  42356. **
  42357. ** If an error occurs while reading from the journal file, an SQLite
  42358. ** error code is returned.
  42359. */
  42360. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  42361. int rc; /* Return code */
  42362. u32 len; /* Length in bytes of master journal name */
  42363. i64 szJ; /* Total size in bytes of journal file pJrnl */
  42364. u32 cksum; /* MJ checksum value read from journal */
  42365. u32 u; /* Unsigned loop counter */
  42366. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  42367. zMaster[0] = '\0';
  42368. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  42369. || szJ<16
  42370. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  42371. || len>=nMaster
  42372. || len==0
  42373. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  42374. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  42375. || memcmp(aMagic, aJournalMagic, 8)
  42376. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  42377. ){
  42378. return rc;
  42379. }
  42380. /* See if the checksum matches the master journal name */
  42381. for(u=0; u<len; u++){
  42382. cksum -= zMaster[u];
  42383. }
  42384. if( cksum ){
  42385. /* If the checksum doesn't add up, then one or more of the disk sectors
  42386. ** containing the master journal filename is corrupted. This means
  42387. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  42388. ** master-journal filename.
  42389. */
  42390. len = 0;
  42391. }
  42392. zMaster[len] = '\0';
  42393. return SQLITE_OK;
  42394. }
  42395. /*
  42396. ** Return the offset of the sector boundary at or immediately
  42397. ** following the value in pPager->journalOff, assuming a sector
  42398. ** size of pPager->sectorSize bytes.
  42399. **
  42400. ** i.e for a sector size of 512:
  42401. **
  42402. ** Pager.journalOff Return value
  42403. ** ---------------------------------------
  42404. ** 0 0
  42405. ** 512 512
  42406. ** 100 512
  42407. ** 2000 2048
  42408. **
  42409. */
  42410. static i64 journalHdrOffset(Pager *pPager){
  42411. i64 offset = 0;
  42412. i64 c = pPager->journalOff;
  42413. if( c ){
  42414. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  42415. }
  42416. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  42417. assert( offset>=c );
  42418. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  42419. return offset;
  42420. }
  42421. /*
  42422. ** The journal file must be open when this function is called.
  42423. **
  42424. ** This function is a no-op if the journal file has not been written to
  42425. ** within the current transaction (i.e. if Pager.journalOff==0).
  42426. **
  42427. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  42428. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  42429. ** zero the 28-byte header at the start of the journal file. In either case,
  42430. ** if the pager is not in no-sync mode, sync the journal file immediately
  42431. ** after writing or truncating it.
  42432. **
  42433. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  42434. ** following the truncation or zeroing described above the size of the
  42435. ** journal file in bytes is larger than this value, then truncate the
  42436. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  42437. ** not need to be synced following this operation.
  42438. **
  42439. ** If an IO error occurs, abandon processing and return the IO error code.
  42440. ** Otherwise, return SQLITE_OK.
  42441. */
  42442. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  42443. int rc = SQLITE_OK; /* Return code */
  42444. assert( isOpen(pPager->jfd) );
  42445. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  42446. if( pPager->journalOff ){
  42447. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  42448. IOTRACE(("JZEROHDR %p\n", pPager))
  42449. if( doTruncate || iLimit==0 ){
  42450. rc = sqlite3OsTruncate(pPager->jfd, 0);
  42451. }else{
  42452. static const char zeroHdr[28] = {0};
  42453. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  42454. }
  42455. if( rc==SQLITE_OK && !pPager->noSync ){
  42456. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  42457. }
  42458. /* At this point the transaction is committed but the write lock
  42459. ** is still held on the file. If there is a size limit configured for
  42460. ** the persistent journal and the journal file currently consumes more
  42461. ** space than that limit allows for, truncate it now. There is no need
  42462. ** to sync the file following this operation.
  42463. */
  42464. if( rc==SQLITE_OK && iLimit>0 ){
  42465. i64 sz;
  42466. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  42467. if( rc==SQLITE_OK && sz>iLimit ){
  42468. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  42469. }
  42470. }
  42471. }
  42472. return rc;
  42473. }
  42474. /*
  42475. ** The journal file must be open when this routine is called. A journal
  42476. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  42477. ** current location.
  42478. **
  42479. ** The format for the journal header is as follows:
  42480. ** - 8 bytes: Magic identifying journal format.
  42481. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  42482. ** - 4 bytes: Random number used for page hash.
  42483. ** - 4 bytes: Initial database page count.
  42484. ** - 4 bytes: Sector size used by the process that wrote this journal.
  42485. ** - 4 bytes: Database page size.
  42486. **
  42487. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  42488. */
  42489. static int writeJournalHdr(Pager *pPager){
  42490. int rc = SQLITE_OK; /* Return code */
  42491. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  42492. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  42493. u32 nWrite; /* Bytes of header sector written */
  42494. int ii; /* Loop counter */
  42495. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  42496. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  42497. nHeader = JOURNAL_HDR_SZ(pPager);
  42498. }
  42499. /* If there are active savepoints and any of them were created
  42500. ** since the most recent journal header was written, update the
  42501. ** PagerSavepoint.iHdrOffset fields now.
  42502. */
  42503. for(ii=0; ii<pPager->nSavepoint; ii++){
  42504. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  42505. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  42506. }
  42507. }
  42508. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  42509. /*
  42510. ** Write the nRec Field - the number of page records that follow this
  42511. ** journal header. Normally, zero is written to this value at this time.
  42512. ** After the records are added to the journal (and the journal synced,
  42513. ** if in full-sync mode), the zero is overwritten with the true number
  42514. ** of records (see syncJournal()).
  42515. **
  42516. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  42517. ** reading the journal this value tells SQLite to assume that the
  42518. ** rest of the journal file contains valid page records. This assumption
  42519. ** is dangerous, as if a failure occurred whilst writing to the journal
  42520. ** file it may contain some garbage data. There are two scenarios
  42521. ** where this risk can be ignored:
  42522. **
  42523. ** * When the pager is in no-sync mode. Corruption can follow a
  42524. ** power failure in this case anyway.
  42525. **
  42526. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  42527. ** that garbage data is never appended to the journal file.
  42528. */
  42529. assert( isOpen(pPager->fd) || pPager->noSync );
  42530. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  42531. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  42532. ){
  42533. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  42534. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  42535. }else{
  42536. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  42537. }
  42538. /* The random check-hash initializer */
  42539. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  42540. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  42541. /* The initial database size */
  42542. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  42543. /* The assumed sector size for this process */
  42544. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  42545. /* The page size */
  42546. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  42547. /* Initializing the tail of the buffer is not necessary. Everything
  42548. ** works find if the following memset() is omitted. But initializing
  42549. ** the memory prevents valgrind from complaining, so we are willing to
  42550. ** take the performance hit.
  42551. */
  42552. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  42553. nHeader-(sizeof(aJournalMagic)+20));
  42554. /* In theory, it is only necessary to write the 28 bytes that the
  42555. ** journal header consumes to the journal file here. Then increment the
  42556. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  42557. ** record is written to the following sector (leaving a gap in the file
  42558. ** that will be implicitly filled in by the OS).
  42559. **
  42560. ** However it has been discovered that on some systems this pattern can
  42561. ** be significantly slower than contiguously writing data to the file,
  42562. ** even if that means explicitly writing data to the block of
  42563. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  42564. ** is done.
  42565. **
  42566. ** The loop is required here in case the sector-size is larger than the
  42567. ** database page size. Since the zHeader buffer is only Pager.pageSize
  42568. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  42569. ** to populate the entire journal header sector.
  42570. */
  42571. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  42572. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  42573. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  42574. assert( pPager->journalHdr <= pPager->journalOff );
  42575. pPager->journalOff += nHeader;
  42576. }
  42577. return rc;
  42578. }
  42579. /*
  42580. ** The journal file must be open when this is called. A journal header file
  42581. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  42582. ** file. The current location in the journal file is given by
  42583. ** pPager->journalOff. See comments above function writeJournalHdr() for
  42584. ** a description of the journal header format.
  42585. **
  42586. ** If the header is read successfully, *pNRec is set to the number of
  42587. ** page records following this header and *pDbSize is set to the size of the
  42588. ** database before the transaction began, in pages. Also, pPager->cksumInit
  42589. ** is set to the value read from the journal header. SQLITE_OK is returned
  42590. ** in this case.
  42591. **
  42592. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  42593. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  42594. ** cannot be read from the journal file an error code is returned.
  42595. */
  42596. static int readJournalHdr(
  42597. Pager *pPager, /* Pager object */
  42598. int isHot,
  42599. i64 journalSize, /* Size of the open journal file in bytes */
  42600. u32 *pNRec, /* OUT: Value read from the nRec field */
  42601. u32 *pDbSize /* OUT: Value of original database size field */
  42602. ){
  42603. int rc; /* Return code */
  42604. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  42605. i64 iHdrOff; /* Offset of journal header being read */
  42606. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  42607. /* Advance Pager.journalOff to the start of the next sector. If the
  42608. ** journal file is too small for there to be a header stored at this
  42609. ** point, return SQLITE_DONE.
  42610. */
  42611. pPager->journalOff = journalHdrOffset(pPager);
  42612. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  42613. return SQLITE_DONE;
  42614. }
  42615. iHdrOff = pPager->journalOff;
  42616. /* Read in the first 8 bytes of the journal header. If they do not match
  42617. ** the magic string found at the start of each journal header, return
  42618. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  42619. ** proceed.
  42620. */
  42621. if( isHot || iHdrOff!=pPager->journalHdr ){
  42622. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  42623. if( rc ){
  42624. return rc;
  42625. }
  42626. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  42627. return SQLITE_DONE;
  42628. }
  42629. }
  42630. /* Read the first three 32-bit fields of the journal header: The nRec
  42631. ** field, the checksum-initializer and the database size at the start
  42632. ** of the transaction. Return an error code if anything goes wrong.
  42633. */
  42634. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  42635. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  42636. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  42637. ){
  42638. return rc;
  42639. }
  42640. if( pPager->journalOff==0 ){
  42641. u32 iPageSize; /* Page-size field of journal header */
  42642. u32 iSectorSize; /* Sector-size field of journal header */
  42643. /* Read the page-size and sector-size journal header fields. */
  42644. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  42645. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  42646. ){
  42647. return rc;
  42648. }
  42649. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  42650. ** journal header to zero. In this case, assume that the Pager.pageSize
  42651. ** variable is already set to the correct page size.
  42652. */
  42653. if( iPageSize==0 ){
  42654. iPageSize = pPager->pageSize;
  42655. }
  42656. /* Check that the values read from the page-size and sector-size fields
  42657. ** are within range. To be 'in range', both values need to be a power
  42658. ** of two greater than or equal to 512 or 32, and not greater than their
  42659. ** respective compile time maximum limits.
  42660. */
  42661. if( iPageSize<512 || iSectorSize<32
  42662. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  42663. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  42664. ){
  42665. /* If the either the page-size or sector-size in the journal-header is
  42666. ** invalid, then the process that wrote the journal-header must have
  42667. ** crashed before the header was synced. In this case stop reading
  42668. ** the journal file here.
  42669. */
  42670. return SQLITE_DONE;
  42671. }
  42672. /* Update the page-size to match the value read from the journal.
  42673. ** Use a testcase() macro to make sure that malloc failure within
  42674. ** PagerSetPagesize() is tested.
  42675. */
  42676. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  42677. testcase( rc!=SQLITE_OK );
  42678. /* Update the assumed sector-size to match the value used by
  42679. ** the process that created this journal. If this journal was
  42680. ** created by a process other than this one, then this routine
  42681. ** is being called from within pager_playback(). The local value
  42682. ** of Pager.sectorSize is restored at the end of that routine.
  42683. */
  42684. pPager->sectorSize = iSectorSize;
  42685. }
  42686. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  42687. return rc;
  42688. }
  42689. /*
  42690. ** Write the supplied master journal name into the journal file for pager
  42691. ** pPager at the current location. The master journal name must be the last
  42692. ** thing written to a journal file. If the pager is in full-sync mode, the
  42693. ** journal file descriptor is advanced to the next sector boundary before
  42694. ** anything is written. The format is:
  42695. **
  42696. ** + 4 bytes: PAGER_MJ_PGNO.
  42697. ** + N bytes: Master journal filename in utf-8.
  42698. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  42699. ** + 4 bytes: Master journal name checksum.
  42700. ** + 8 bytes: aJournalMagic[].
  42701. **
  42702. ** The master journal page checksum is the sum of the bytes in the master
  42703. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  42704. **
  42705. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  42706. ** this call is a no-op.
  42707. */
  42708. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  42709. int rc; /* Return code */
  42710. int nMaster; /* Length of string zMaster */
  42711. i64 iHdrOff; /* Offset of header in journal file */
  42712. i64 jrnlSize; /* Size of journal file on disk */
  42713. u32 cksum = 0; /* Checksum of string zMaster */
  42714. assert( pPager->setMaster==0 );
  42715. assert( !pagerUseWal(pPager) );
  42716. if( !zMaster
  42717. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  42718. || !isOpen(pPager->jfd)
  42719. ){
  42720. return SQLITE_OK;
  42721. }
  42722. pPager->setMaster = 1;
  42723. assert( pPager->journalHdr <= pPager->journalOff );
  42724. /* Calculate the length in bytes and the checksum of zMaster */
  42725. for(nMaster=0; zMaster[nMaster]; nMaster++){
  42726. cksum += zMaster[nMaster];
  42727. }
  42728. /* If in full-sync mode, advance to the next disk sector before writing
  42729. ** the master journal name. This is in case the previous page written to
  42730. ** the journal has already been synced.
  42731. */
  42732. if( pPager->fullSync ){
  42733. pPager->journalOff = journalHdrOffset(pPager);
  42734. }
  42735. iHdrOff = pPager->journalOff;
  42736. /* Write the master journal data to the end of the journal file. If
  42737. ** an error occurs, return the error code to the caller.
  42738. */
  42739. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  42740. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  42741. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  42742. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  42743. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  42744. iHdrOff+4+nMaster+8)))
  42745. ){
  42746. return rc;
  42747. }
  42748. pPager->journalOff += (nMaster+20);
  42749. /* If the pager is in peristent-journal mode, then the physical
  42750. ** journal-file may extend past the end of the master-journal name
  42751. ** and 8 bytes of magic data just written to the file. This is
  42752. ** dangerous because the code to rollback a hot-journal file
  42753. ** will not be able to find the master-journal name to determine
  42754. ** whether or not the journal is hot.
  42755. **
  42756. ** Easiest thing to do in this scenario is to truncate the journal
  42757. ** file to the required size.
  42758. */
  42759. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  42760. && jrnlSize>pPager->journalOff
  42761. ){
  42762. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  42763. }
  42764. return rc;
  42765. }
  42766. /*
  42767. ** Discard the entire contents of the in-memory page-cache.
  42768. */
  42769. static void pager_reset(Pager *pPager){
  42770. pPager->iDataVersion++;
  42771. sqlite3BackupRestart(pPager->pBackup);
  42772. sqlite3PcacheClear(pPager->pPCache);
  42773. }
  42774. /*
  42775. ** Return the pPager->iDataVersion value
  42776. */
  42777. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  42778. assert( pPager->eState>PAGER_OPEN );
  42779. return pPager->iDataVersion;
  42780. }
  42781. /*
  42782. ** Free all structures in the Pager.aSavepoint[] array and set both
  42783. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  42784. ** if it is open and the pager is not in exclusive mode.
  42785. */
  42786. static void releaseAllSavepoints(Pager *pPager){
  42787. int ii; /* Iterator for looping through Pager.aSavepoint */
  42788. for(ii=0; ii<pPager->nSavepoint; ii++){
  42789. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  42790. }
  42791. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  42792. sqlite3OsClose(pPager->sjfd);
  42793. }
  42794. sqlite3_free(pPager->aSavepoint);
  42795. pPager->aSavepoint = 0;
  42796. pPager->nSavepoint = 0;
  42797. pPager->nSubRec = 0;
  42798. }
  42799. /*
  42800. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  42801. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  42802. ** or SQLITE_NOMEM if a malloc failure occurs.
  42803. */
  42804. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  42805. int ii; /* Loop counter */
  42806. int rc = SQLITE_OK; /* Result code */
  42807. for(ii=0; ii<pPager->nSavepoint; ii++){
  42808. PagerSavepoint *p = &pPager->aSavepoint[ii];
  42809. if( pgno<=p->nOrig ){
  42810. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  42811. testcase( rc==SQLITE_NOMEM );
  42812. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  42813. }
  42814. }
  42815. return rc;
  42816. }
  42817. /*
  42818. ** This function is a no-op if the pager is in exclusive mode and not
  42819. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  42820. ** state.
  42821. **
  42822. ** If the pager is not in exclusive-access mode, the database file is
  42823. ** completely unlocked. If the file is unlocked and the file-system does
  42824. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  42825. ** closed (if it is open).
  42826. **
  42827. ** If the pager is in ERROR state when this function is called, the
  42828. ** contents of the pager cache are discarded before switching back to
  42829. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  42830. ** or not, any journal file left in the file-system will be treated
  42831. ** as a hot-journal and rolled back the next time a read-transaction
  42832. ** is opened (by this or by any other connection).
  42833. */
  42834. static void pager_unlock(Pager *pPager){
  42835. assert( pPager->eState==PAGER_READER
  42836. || pPager->eState==PAGER_OPEN
  42837. || pPager->eState==PAGER_ERROR
  42838. );
  42839. sqlite3BitvecDestroy(pPager->pInJournal);
  42840. pPager->pInJournal = 0;
  42841. releaseAllSavepoints(pPager);
  42842. if( pagerUseWal(pPager) ){
  42843. assert( !isOpen(pPager->jfd) );
  42844. sqlite3WalEndReadTransaction(pPager->pWal);
  42845. pPager->eState = PAGER_OPEN;
  42846. }else if( !pPager->exclusiveMode ){
  42847. int rc; /* Error code returned by pagerUnlockDb() */
  42848. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  42849. /* If the operating system support deletion of open files, then
  42850. ** close the journal file when dropping the database lock. Otherwise
  42851. ** another connection with journal_mode=delete might delete the file
  42852. ** out from under us.
  42853. */
  42854. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  42855. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  42856. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  42857. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  42858. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  42859. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  42860. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  42861. || 1!=(pPager->journalMode & 5)
  42862. ){
  42863. sqlite3OsClose(pPager->jfd);
  42864. }
  42865. /* If the pager is in the ERROR state and the call to unlock the database
  42866. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  42867. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  42868. ** is necessary.
  42869. */
  42870. rc = pagerUnlockDb(pPager, NO_LOCK);
  42871. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  42872. pPager->eLock = UNKNOWN_LOCK;
  42873. }
  42874. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  42875. ** without clearing the error code. This is intentional - the error
  42876. ** code is cleared and the cache reset in the block below.
  42877. */
  42878. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  42879. pPager->changeCountDone = 0;
  42880. pPager->eState = PAGER_OPEN;
  42881. }
  42882. /* If Pager.errCode is set, the contents of the pager cache cannot be
  42883. ** trusted. Now that there are no outstanding references to the pager,
  42884. ** it can safely move back to PAGER_OPEN state. This happens in both
  42885. ** normal and exclusive-locking mode.
  42886. */
  42887. if( pPager->errCode ){
  42888. assert( !MEMDB );
  42889. pager_reset(pPager);
  42890. pPager->changeCountDone = pPager->tempFile;
  42891. pPager->eState = PAGER_OPEN;
  42892. pPager->errCode = SQLITE_OK;
  42893. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  42894. }
  42895. pPager->journalOff = 0;
  42896. pPager->journalHdr = 0;
  42897. pPager->setMaster = 0;
  42898. }
  42899. /*
  42900. ** This function is called whenever an IOERR or FULL error that requires
  42901. ** the pager to transition into the ERROR state may ahve occurred.
  42902. ** The first argument is a pointer to the pager structure, the second
  42903. ** the error-code about to be returned by a pager API function. The
  42904. ** value returned is a copy of the second argument to this function.
  42905. **
  42906. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  42907. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  42908. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  42909. ** all major API calls on the Pager will immediately return Pager.errCode.
  42910. **
  42911. ** The ERROR state indicates that the contents of the pager-cache
  42912. ** cannot be trusted. This state can be cleared by completely discarding
  42913. ** the contents of the pager-cache. If a transaction was active when
  42914. ** the persistent error occurred, then the rollback journal may need
  42915. ** to be replayed to restore the contents of the database file (as if
  42916. ** it were a hot-journal).
  42917. */
  42918. static int pager_error(Pager *pPager, int rc){
  42919. int rc2 = rc & 0xff;
  42920. assert( rc==SQLITE_OK || !MEMDB );
  42921. assert(
  42922. pPager->errCode==SQLITE_FULL ||
  42923. pPager->errCode==SQLITE_OK ||
  42924. (pPager->errCode & 0xff)==SQLITE_IOERR
  42925. );
  42926. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  42927. pPager->errCode = rc;
  42928. pPager->eState = PAGER_ERROR;
  42929. }
  42930. return rc;
  42931. }
  42932. static int pager_truncate(Pager *pPager, Pgno nPage);
  42933. /*
  42934. ** This routine ends a transaction. A transaction is usually ended by
  42935. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  42936. ** after rollback of a hot-journal, or if an error occurs while opening
  42937. ** the journal file or writing the very first journal-header of a
  42938. ** database transaction.
  42939. **
  42940. ** This routine is never called in PAGER_ERROR state. If it is called
  42941. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  42942. ** exclusive than a RESERVED lock, it is a no-op.
  42943. **
  42944. ** Otherwise, any active savepoints are released.
  42945. **
  42946. ** If the journal file is open, then it is "finalized". Once a journal
  42947. ** file has been finalized it is not possible to use it to roll back a
  42948. ** transaction. Nor will it be considered to be a hot-journal by this
  42949. ** or any other database connection. Exactly how a journal is finalized
  42950. ** depends on whether or not the pager is running in exclusive mode and
  42951. ** the current journal-mode (Pager.journalMode value), as follows:
  42952. **
  42953. ** journalMode==MEMORY
  42954. ** Journal file descriptor is simply closed. This destroys an
  42955. ** in-memory journal.
  42956. **
  42957. ** journalMode==TRUNCATE
  42958. ** Journal file is truncated to zero bytes in size.
  42959. **
  42960. ** journalMode==PERSIST
  42961. ** The first 28 bytes of the journal file are zeroed. This invalidates
  42962. ** the first journal header in the file, and hence the entire journal
  42963. ** file. An invalid journal file cannot be rolled back.
  42964. **
  42965. ** journalMode==DELETE
  42966. ** The journal file is closed and deleted using sqlite3OsDelete().
  42967. **
  42968. ** If the pager is running in exclusive mode, this method of finalizing
  42969. ** the journal file is never used. Instead, if the journalMode is
  42970. ** DELETE and the pager is in exclusive mode, the method described under
  42971. ** journalMode==PERSIST is used instead.
  42972. **
  42973. ** After the journal is finalized, the pager moves to PAGER_READER state.
  42974. ** If running in non-exclusive rollback mode, the lock on the file is
  42975. ** downgraded to a SHARED_LOCK.
  42976. **
  42977. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  42978. ** any of the IO operations to finalize the journal file or unlock the
  42979. ** database then the IO error code is returned to the user. If the
  42980. ** operation to finalize the journal file fails, then the code still
  42981. ** tries to unlock the database file if not in exclusive mode. If the
  42982. ** unlock operation fails as well, then the first error code related
  42983. ** to the first error encountered (the journal finalization one) is
  42984. ** returned.
  42985. */
  42986. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  42987. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  42988. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  42989. /* Do nothing if the pager does not have an open write transaction
  42990. ** or at least a RESERVED lock. This function may be called when there
  42991. ** is no write-transaction active but a RESERVED or greater lock is
  42992. ** held under two circumstances:
  42993. **
  42994. ** 1. After a successful hot-journal rollback, it is called with
  42995. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  42996. **
  42997. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  42998. ** lock switches back to locking_mode=normal and then executes a
  42999. ** read-transaction, this function is called with eState==PAGER_READER
  43000. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  43001. */
  43002. assert( assert_pager_state(pPager) );
  43003. assert( pPager->eState!=PAGER_ERROR );
  43004. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  43005. return SQLITE_OK;
  43006. }
  43007. releaseAllSavepoints(pPager);
  43008. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  43009. if( isOpen(pPager->jfd) ){
  43010. assert( !pagerUseWal(pPager) );
  43011. /* Finalize the journal file. */
  43012. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  43013. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  43014. sqlite3OsClose(pPager->jfd);
  43015. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  43016. if( pPager->journalOff==0 ){
  43017. rc = SQLITE_OK;
  43018. }else{
  43019. rc = sqlite3OsTruncate(pPager->jfd, 0);
  43020. if( rc==SQLITE_OK && pPager->fullSync ){
  43021. /* Make sure the new file size is written into the inode right away.
  43022. ** Otherwise the journal might resurrect following a power loss and
  43023. ** cause the last transaction to roll back. See
  43024. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  43025. */
  43026. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  43027. }
  43028. }
  43029. pPager->journalOff = 0;
  43030. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  43031. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  43032. ){
  43033. rc = zeroJournalHdr(pPager, hasMaster);
  43034. pPager->journalOff = 0;
  43035. }else{
  43036. /* This branch may be executed with Pager.journalMode==MEMORY if
  43037. ** a hot-journal was just rolled back. In this case the journal
  43038. ** file should be closed and deleted. If this connection writes to
  43039. ** the database file, it will do so using an in-memory journal.
  43040. */
  43041. int bDelete = !pPager->tempFile;
  43042. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  43043. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  43044. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  43045. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  43046. );
  43047. sqlite3OsClose(pPager->jfd);
  43048. if( bDelete ){
  43049. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  43050. }
  43051. }
  43052. }
  43053. #ifdef SQLITE_CHECK_PAGES
  43054. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  43055. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  43056. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  43057. if( p ){
  43058. p->pageHash = 0;
  43059. sqlite3PagerUnrefNotNull(p);
  43060. }
  43061. }
  43062. #endif
  43063. sqlite3BitvecDestroy(pPager->pInJournal);
  43064. pPager->pInJournal = 0;
  43065. pPager->nRec = 0;
  43066. sqlite3PcacheCleanAll(pPager->pPCache);
  43067. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  43068. if( pagerUseWal(pPager) ){
  43069. /* Drop the WAL write-lock, if any. Also, if the connection was in
  43070. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  43071. ** lock held on the database file.
  43072. */
  43073. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  43074. assert( rc2==SQLITE_OK );
  43075. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  43076. /* This branch is taken when committing a transaction in rollback-journal
  43077. ** mode if the database file on disk is larger than the database image.
  43078. ** At this point the journal has been finalized and the transaction
  43079. ** successfully committed, but the EXCLUSIVE lock is still held on the
  43080. ** file. So it is safe to truncate the database file to its minimum
  43081. ** required size. */
  43082. assert( pPager->eLock==EXCLUSIVE_LOCK );
  43083. rc = pager_truncate(pPager, pPager->dbSize);
  43084. }
  43085. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  43086. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  43087. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  43088. }
  43089. if( !pPager->exclusiveMode
  43090. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  43091. ){
  43092. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  43093. pPager->changeCountDone = 0;
  43094. }
  43095. pPager->eState = PAGER_READER;
  43096. pPager->setMaster = 0;
  43097. return (rc==SQLITE_OK?rc2:rc);
  43098. }
  43099. /*
  43100. ** Execute a rollback if a transaction is active and unlock the
  43101. ** database file.
  43102. **
  43103. ** If the pager has already entered the ERROR state, do not attempt
  43104. ** the rollback at this time. Instead, pager_unlock() is called. The
  43105. ** call to pager_unlock() will discard all in-memory pages, unlock
  43106. ** the database file and move the pager back to OPEN state. If this
  43107. ** means that there is a hot-journal left in the file-system, the next
  43108. ** connection to obtain a shared lock on the pager (which may be this one)
  43109. ** will roll it back.
  43110. **
  43111. ** If the pager has not already entered the ERROR state, but an IO or
  43112. ** malloc error occurs during a rollback, then this will itself cause
  43113. ** the pager to enter the ERROR state. Which will be cleared by the
  43114. ** call to pager_unlock(), as described above.
  43115. */
  43116. static void pagerUnlockAndRollback(Pager *pPager){
  43117. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  43118. assert( assert_pager_state(pPager) );
  43119. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  43120. sqlite3BeginBenignMalloc();
  43121. sqlite3PagerRollback(pPager);
  43122. sqlite3EndBenignMalloc();
  43123. }else if( !pPager->exclusiveMode ){
  43124. assert( pPager->eState==PAGER_READER );
  43125. pager_end_transaction(pPager, 0, 0);
  43126. }
  43127. }
  43128. pager_unlock(pPager);
  43129. }
  43130. /*
  43131. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  43132. ** of data. Compute and return a checksum based ont the contents of the
  43133. ** page of data and the current value of pPager->cksumInit.
  43134. **
  43135. ** This is not a real checksum. It is really just the sum of the
  43136. ** random initial value (pPager->cksumInit) and every 200th byte
  43137. ** of the page data, starting with byte offset (pPager->pageSize%200).
  43138. ** Each byte is interpreted as an 8-bit unsigned integer.
  43139. **
  43140. ** Changing the formula used to compute this checksum results in an
  43141. ** incompatible journal file format.
  43142. **
  43143. ** If journal corruption occurs due to a power failure, the most likely
  43144. ** scenario is that one end or the other of the record will be changed.
  43145. ** It is much less likely that the two ends of the journal record will be
  43146. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  43147. ** though fast and simple, catches the mostly likely kind of corruption.
  43148. */
  43149. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  43150. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  43151. int i = pPager->pageSize-200; /* Loop counter */
  43152. while( i>0 ){
  43153. cksum += aData[i];
  43154. i -= 200;
  43155. }
  43156. return cksum;
  43157. }
  43158. /*
  43159. ** Report the current page size and number of reserved bytes back
  43160. ** to the codec.
  43161. */
  43162. #ifdef SQLITE_HAS_CODEC
  43163. static void pagerReportSize(Pager *pPager){
  43164. if( pPager->xCodecSizeChng ){
  43165. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  43166. (int)pPager->nReserve);
  43167. }
  43168. }
  43169. #else
  43170. # define pagerReportSize(X) /* No-op if we do not support a codec */
  43171. #endif
  43172. #ifdef SQLITE_HAS_CODEC
  43173. /*
  43174. ** Make sure the number of reserved bits is the same in the destination
  43175. ** pager as it is in the source. This comes up when a VACUUM changes the
  43176. ** number of reserved bits to the "optimal" amount.
  43177. */
  43178. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  43179. if( pDest->nReserve!=pSrc->nReserve ){
  43180. pDest->nReserve = pSrc->nReserve;
  43181. pagerReportSize(pDest);
  43182. }
  43183. }
  43184. #endif
  43185. /*
  43186. ** Read a single page from either the journal file (if isMainJrnl==1) or
  43187. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  43188. ** The page begins at offset *pOffset into the file. The *pOffset
  43189. ** value is increased to the start of the next page in the journal.
  43190. **
  43191. ** The main rollback journal uses checksums - the statement journal does
  43192. ** not.
  43193. **
  43194. ** If the page number of the page record read from the (sub-)journal file
  43195. ** is greater than the current value of Pager.dbSize, then playback is
  43196. ** skipped and SQLITE_OK is returned.
  43197. **
  43198. ** If pDone is not NULL, then it is a record of pages that have already
  43199. ** been played back. If the page at *pOffset has already been played back
  43200. ** (if the corresponding pDone bit is set) then skip the playback.
  43201. ** Make sure the pDone bit corresponding to the *pOffset page is set
  43202. ** prior to returning.
  43203. **
  43204. ** If the page record is successfully read from the (sub-)journal file
  43205. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  43206. ** while reading the record from the (sub-)journal file or while writing
  43207. ** to the database file, then the IO error code is returned. If data
  43208. ** is successfully read from the (sub-)journal file but appears to be
  43209. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  43210. ** two circumstances:
  43211. **
  43212. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  43213. ** * If the record is being rolled back from the main journal file
  43214. ** and the checksum field does not match the record content.
  43215. **
  43216. ** Neither of these two scenarios are possible during a savepoint rollback.
  43217. **
  43218. ** If this is a savepoint rollback, then memory may have to be dynamically
  43219. ** allocated by this function. If this is the case and an allocation fails,
  43220. ** SQLITE_NOMEM is returned.
  43221. */
  43222. static int pager_playback_one_page(
  43223. Pager *pPager, /* The pager being played back */
  43224. i64 *pOffset, /* Offset of record to playback */
  43225. Bitvec *pDone, /* Bitvec of pages already played back */
  43226. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  43227. int isSavepnt /* True for a savepoint rollback */
  43228. ){
  43229. int rc;
  43230. PgHdr *pPg; /* An existing page in the cache */
  43231. Pgno pgno; /* The page number of a page in journal */
  43232. u32 cksum; /* Checksum used for sanity checking */
  43233. char *aData; /* Temporary storage for the page */
  43234. sqlite3_file *jfd; /* The file descriptor for the journal file */
  43235. int isSynced; /* True if journal page is synced */
  43236. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  43237. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  43238. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  43239. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  43240. aData = pPager->pTmpSpace;
  43241. assert( aData ); /* Temp storage must have already been allocated */
  43242. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  43243. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  43244. ** or savepoint rollback done at the request of the caller) or this is
  43245. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  43246. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  43247. ** only reads from the main journal, not the sub-journal.
  43248. */
  43249. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  43250. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  43251. );
  43252. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  43253. /* Read the page number and page data from the journal or sub-journal
  43254. ** file. Return an error code to the caller if an IO error occurs.
  43255. */
  43256. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  43257. rc = read32bits(jfd, *pOffset, &pgno);
  43258. if( rc!=SQLITE_OK ) return rc;
  43259. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  43260. if( rc!=SQLITE_OK ) return rc;
  43261. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  43262. /* Sanity checking on the page. This is more important that I originally
  43263. ** thought. If a power failure occurs while the journal is being written,
  43264. ** it could cause invalid data to be written into the journal. We need to
  43265. ** detect this invalid data (with high probability) and ignore it.
  43266. */
  43267. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  43268. assert( !isSavepnt );
  43269. return SQLITE_DONE;
  43270. }
  43271. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  43272. return SQLITE_OK;
  43273. }
  43274. if( isMainJrnl ){
  43275. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  43276. if( rc ) return rc;
  43277. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  43278. return SQLITE_DONE;
  43279. }
  43280. }
  43281. /* If this page has already been played back before during the current
  43282. ** rollback, then don't bother to play it back again.
  43283. */
  43284. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  43285. return rc;
  43286. }
  43287. /* When playing back page 1, restore the nReserve setting
  43288. */
  43289. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  43290. pPager->nReserve = ((u8*)aData)[20];
  43291. pagerReportSize(pPager);
  43292. }
  43293. /* If the pager is in CACHEMOD state, then there must be a copy of this
  43294. ** page in the pager cache. In this case just update the pager cache,
  43295. ** not the database file. The page is left marked dirty in this case.
  43296. **
  43297. ** An exception to the above rule: If the database is in no-sync mode
  43298. ** and a page is moved during an incremental vacuum then the page may
  43299. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  43300. ** during a Movepage() call, then the page may not be in the cache
  43301. ** either. So the condition described in the above paragraph is not
  43302. ** assert()able.
  43303. **
  43304. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  43305. ** pager cache if it exists and the main file. The page is then marked
  43306. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  43307. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  43308. ** if the pager is in OPEN state.
  43309. **
  43310. ** Ticket #1171: The statement journal might contain page content that is
  43311. ** different from the page content at the start of the transaction.
  43312. ** This occurs when a page is changed prior to the start of a statement
  43313. ** then changed again within the statement. When rolling back such a
  43314. ** statement we must not write to the original database unless we know
  43315. ** for certain that original page contents are synced into the main rollback
  43316. ** journal. Otherwise, a power loss might leave modified data in the
  43317. ** database file without an entry in the rollback journal that can
  43318. ** restore the database to its original form. Two conditions must be
  43319. ** met before writing to the database files. (1) the database must be
  43320. ** locked. (2) we know that the original page content is fully synced
  43321. ** in the main journal either because the page is not in cache or else
  43322. ** the page is marked as needSync==0.
  43323. **
  43324. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  43325. ** is possible to fail a statement on a database that does not yet exist.
  43326. ** Do not attempt to write if database file has never been opened.
  43327. */
  43328. if( pagerUseWal(pPager) ){
  43329. pPg = 0;
  43330. }else{
  43331. pPg = sqlite3PagerLookup(pPager, pgno);
  43332. }
  43333. assert( pPg || !MEMDB );
  43334. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  43335. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  43336. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  43337. (isMainJrnl?"main-journal":"sub-journal")
  43338. ));
  43339. if( isMainJrnl ){
  43340. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  43341. }else{
  43342. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  43343. }
  43344. if( isOpen(pPager->fd)
  43345. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  43346. && isSynced
  43347. ){
  43348. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  43349. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  43350. assert( !pagerUseWal(pPager) );
  43351. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  43352. if( pgno>pPager->dbFileSize ){
  43353. pPager->dbFileSize = pgno;
  43354. }
  43355. if( pPager->pBackup ){
  43356. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  43357. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  43358. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  43359. }
  43360. }else if( !isMainJrnl && pPg==0 ){
  43361. /* If this is a rollback of a savepoint and data was not written to
  43362. ** the database and the page is not in-memory, there is a potential
  43363. ** problem. When the page is next fetched by the b-tree layer, it
  43364. ** will be read from the database file, which may or may not be
  43365. ** current.
  43366. **
  43367. ** There are a couple of different ways this can happen. All are quite
  43368. ** obscure. When running in synchronous mode, this can only happen
  43369. ** if the page is on the free-list at the start of the transaction, then
  43370. ** populated, then moved using sqlite3PagerMovepage().
  43371. **
  43372. ** The solution is to add an in-memory page to the cache containing
  43373. ** the data just read from the sub-journal. Mark the page as dirty
  43374. ** and if the pager requires a journal-sync, then mark the page as
  43375. ** requiring a journal-sync before it is written.
  43376. */
  43377. assert( isSavepnt );
  43378. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  43379. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  43380. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  43381. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  43382. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  43383. if( rc!=SQLITE_OK ) return rc;
  43384. pPg->flags &= ~PGHDR_NEED_READ;
  43385. sqlite3PcacheMakeDirty(pPg);
  43386. }
  43387. if( pPg ){
  43388. /* No page should ever be explicitly rolled back that is in use, except
  43389. ** for page 1 which is held in use in order to keep the lock on the
  43390. ** database active. However such a page may be rolled back as a result
  43391. ** of an internal error resulting in an automatic call to
  43392. ** sqlite3PagerRollback().
  43393. */
  43394. void *pData;
  43395. pData = pPg->pData;
  43396. memcpy(pData, (u8*)aData, pPager->pageSize);
  43397. pPager->xReiniter(pPg);
  43398. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  43399. /* If the contents of this page were just restored from the main
  43400. ** journal file, then its content must be as they were when the
  43401. ** transaction was first opened. In this case we can mark the page
  43402. ** as clean, since there will be no need to write it out to the
  43403. ** database.
  43404. **
  43405. ** There is one exception to this rule. If the page is being rolled
  43406. ** back as part of a savepoint (or statement) rollback from an
  43407. ** unsynced portion of the main journal file, then it is not safe
  43408. ** to mark the page as clean. This is because marking the page as
  43409. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  43410. ** already in the journal file (recorded in Pager.pInJournal) and
  43411. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  43412. ** again within this transaction, it will be marked as dirty but
  43413. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  43414. ** be written out into the database file before its journal file
  43415. ** segment is synced. If a crash occurs during or following this,
  43416. ** database corruption may ensue.
  43417. */
  43418. assert( !pagerUseWal(pPager) );
  43419. sqlite3PcacheMakeClean(pPg);
  43420. }
  43421. pager_set_pagehash(pPg);
  43422. /* If this was page 1, then restore the value of Pager.dbFileVers.
  43423. ** Do this before any decoding. */
  43424. if( pgno==1 ){
  43425. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  43426. }
  43427. /* Decode the page just read from disk */
  43428. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
  43429. sqlite3PcacheRelease(pPg);
  43430. }
  43431. return rc;
  43432. }
  43433. /*
  43434. ** Parameter zMaster is the name of a master journal file. A single journal
  43435. ** file that referred to the master journal file has just been rolled back.
  43436. ** This routine checks if it is possible to delete the master journal file,
  43437. ** and does so if it is.
  43438. **
  43439. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  43440. ** available for use within this function.
  43441. **
  43442. ** When a master journal file is created, it is populated with the names
  43443. ** of all of its child journals, one after another, formatted as utf-8
  43444. ** encoded text. The end of each child journal file is marked with a
  43445. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  43446. ** file for a transaction involving two databases might be:
  43447. **
  43448. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  43449. **
  43450. ** A master journal file may only be deleted once all of its child
  43451. ** journals have been rolled back.
  43452. **
  43453. ** This function reads the contents of the master-journal file into
  43454. ** memory and loops through each of the child journal names. For
  43455. ** each child journal, it checks if:
  43456. **
  43457. ** * if the child journal exists, and if so
  43458. ** * if the child journal contains a reference to master journal
  43459. ** file zMaster
  43460. **
  43461. ** If a child journal can be found that matches both of the criteria
  43462. ** above, this function returns without doing anything. Otherwise, if
  43463. ** no such child journal can be found, file zMaster is deleted from
  43464. ** the file-system using sqlite3OsDelete().
  43465. **
  43466. ** If an IO error within this function, an error code is returned. This
  43467. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  43468. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  43469. ** occur, SQLITE_OK is returned.
  43470. **
  43471. ** TODO: This function allocates a single block of memory to load
  43472. ** the entire contents of the master journal file. This could be
  43473. ** a couple of kilobytes or so - potentially larger than the page
  43474. ** size.
  43475. */
  43476. static int pager_delmaster(Pager *pPager, const char *zMaster){
  43477. sqlite3_vfs *pVfs = pPager->pVfs;
  43478. int rc; /* Return code */
  43479. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  43480. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  43481. char *zMasterJournal = 0; /* Contents of master journal file */
  43482. i64 nMasterJournal; /* Size of master journal file */
  43483. char *zJournal; /* Pointer to one journal within MJ file */
  43484. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  43485. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  43486. /* Allocate space for both the pJournal and pMaster file descriptors.
  43487. ** If successful, open the master journal file for reading.
  43488. */
  43489. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  43490. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  43491. if( !pMaster ){
  43492. rc = SQLITE_NOMEM_BKPT;
  43493. }else{
  43494. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  43495. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  43496. }
  43497. if( rc!=SQLITE_OK ) goto delmaster_out;
  43498. /* Load the entire master journal file into space obtained from
  43499. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  43500. ** sufficient space (in zMasterPtr) to hold the names of master
  43501. ** journal files extracted from regular rollback-journals.
  43502. */
  43503. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  43504. if( rc!=SQLITE_OK ) goto delmaster_out;
  43505. nMasterPtr = pVfs->mxPathname+1;
  43506. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  43507. if( !zMasterJournal ){
  43508. rc = SQLITE_NOMEM_BKPT;
  43509. goto delmaster_out;
  43510. }
  43511. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  43512. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  43513. if( rc!=SQLITE_OK ) goto delmaster_out;
  43514. zMasterJournal[nMasterJournal] = 0;
  43515. zJournal = zMasterJournal;
  43516. while( (zJournal-zMasterJournal)<nMasterJournal ){
  43517. int exists;
  43518. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  43519. if( rc!=SQLITE_OK ){
  43520. goto delmaster_out;
  43521. }
  43522. if( exists ){
  43523. /* One of the journals pointed to by the master journal exists.
  43524. ** Open it and check if it points at the master journal. If
  43525. ** so, return without deleting the master journal file.
  43526. */
  43527. int c;
  43528. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  43529. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  43530. if( rc!=SQLITE_OK ){
  43531. goto delmaster_out;
  43532. }
  43533. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  43534. sqlite3OsClose(pJournal);
  43535. if( rc!=SQLITE_OK ){
  43536. goto delmaster_out;
  43537. }
  43538. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  43539. if( c ){
  43540. /* We have a match. Do not delete the master journal file. */
  43541. goto delmaster_out;
  43542. }
  43543. }
  43544. zJournal += (sqlite3Strlen30(zJournal)+1);
  43545. }
  43546. sqlite3OsClose(pMaster);
  43547. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  43548. delmaster_out:
  43549. sqlite3_free(zMasterJournal);
  43550. if( pMaster ){
  43551. sqlite3OsClose(pMaster);
  43552. assert( !isOpen(pJournal) );
  43553. sqlite3_free(pMaster);
  43554. }
  43555. return rc;
  43556. }
  43557. /*
  43558. ** This function is used to change the actual size of the database
  43559. ** file in the file-system. This only happens when committing a transaction,
  43560. ** or rolling back a transaction (including rolling back a hot-journal).
  43561. **
  43562. ** If the main database file is not open, or the pager is not in either
  43563. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  43564. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  43565. ** If the file on disk is currently larger than nPage pages, then use the VFS
  43566. ** xTruncate() method to truncate it.
  43567. **
  43568. ** Or, it might be the case that the file on disk is smaller than
  43569. ** nPage pages. Some operating system implementations can get confused if
  43570. ** you try to truncate a file to some size that is larger than it
  43571. ** currently is, so detect this case and write a single zero byte to
  43572. ** the end of the new file instead.
  43573. **
  43574. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  43575. ** the database file, return the error code to the caller.
  43576. */
  43577. static int pager_truncate(Pager *pPager, Pgno nPage){
  43578. int rc = SQLITE_OK;
  43579. assert( pPager->eState!=PAGER_ERROR );
  43580. assert( pPager->eState!=PAGER_READER );
  43581. if( isOpen(pPager->fd)
  43582. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  43583. ){
  43584. i64 currentSize, newSize;
  43585. int szPage = pPager->pageSize;
  43586. assert( pPager->eLock==EXCLUSIVE_LOCK );
  43587. /* TODO: Is it safe to use Pager.dbFileSize here? */
  43588. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  43589. newSize = szPage*(i64)nPage;
  43590. if( rc==SQLITE_OK && currentSize!=newSize ){
  43591. if( currentSize>newSize ){
  43592. rc = sqlite3OsTruncate(pPager->fd, newSize);
  43593. }else if( (currentSize+szPage)<=newSize ){
  43594. char *pTmp = pPager->pTmpSpace;
  43595. memset(pTmp, 0, szPage);
  43596. testcase( (newSize-szPage) == currentSize );
  43597. testcase( (newSize-szPage) > currentSize );
  43598. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  43599. }
  43600. if( rc==SQLITE_OK ){
  43601. pPager->dbFileSize = nPage;
  43602. }
  43603. }
  43604. }
  43605. return rc;
  43606. }
  43607. /*
  43608. ** Return a sanitized version of the sector-size of OS file pFile. The
  43609. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  43610. */
  43611. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  43612. int iRet = sqlite3OsSectorSize(pFile);
  43613. if( iRet<32 ){
  43614. iRet = 512;
  43615. }else if( iRet>MAX_SECTOR_SIZE ){
  43616. assert( MAX_SECTOR_SIZE>=512 );
  43617. iRet = MAX_SECTOR_SIZE;
  43618. }
  43619. return iRet;
  43620. }
  43621. /*
  43622. ** Set the value of the Pager.sectorSize variable for the given
  43623. ** pager based on the value returned by the xSectorSize method
  43624. ** of the open database file. The sector size will be used
  43625. ** to determine the size and alignment of journal header and
  43626. ** master journal pointers within created journal files.
  43627. **
  43628. ** For temporary files the effective sector size is always 512 bytes.
  43629. **
  43630. ** Otherwise, for non-temporary files, the effective sector size is
  43631. ** the value returned by the xSectorSize() method rounded up to 32 if
  43632. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  43633. ** is greater than MAX_SECTOR_SIZE.
  43634. **
  43635. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  43636. ** the effective sector size to its minimum value (512). The purpose of
  43637. ** pPager->sectorSize is to define the "blast radius" of bytes that
  43638. ** might change if a crash occurs while writing to a single byte in
  43639. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  43640. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  43641. ** size. For backwards compatibility of the rollback journal file format,
  43642. ** we cannot reduce the effective sector size below 512.
  43643. */
  43644. static void setSectorSize(Pager *pPager){
  43645. assert( isOpen(pPager->fd) || pPager->tempFile );
  43646. if( pPager->tempFile
  43647. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  43648. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  43649. ){
  43650. /* Sector size doesn't matter for temporary files. Also, the file
  43651. ** may not have been opened yet, in which case the OsSectorSize()
  43652. ** call will segfault. */
  43653. pPager->sectorSize = 512;
  43654. }else{
  43655. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  43656. }
  43657. }
  43658. /*
  43659. ** Playback the journal and thus restore the database file to
  43660. ** the state it was in before we started making changes.
  43661. **
  43662. ** The journal file format is as follows:
  43663. **
  43664. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  43665. ** (2) 4 byte big-endian integer which is the number of valid page records
  43666. ** in the journal. If this value is 0xffffffff, then compute the
  43667. ** number of page records from the journal size.
  43668. ** (3) 4 byte big-endian integer which is the initial value for the
  43669. ** sanity checksum.
  43670. ** (4) 4 byte integer which is the number of pages to truncate the
  43671. ** database to during a rollback.
  43672. ** (5) 4 byte big-endian integer which is the sector size. The header
  43673. ** is this many bytes in size.
  43674. ** (6) 4 byte big-endian integer which is the page size.
  43675. ** (7) zero padding out to the next sector size.
  43676. ** (8) Zero or more pages instances, each as follows:
  43677. ** + 4 byte page number.
  43678. ** + pPager->pageSize bytes of data.
  43679. ** + 4 byte checksum
  43680. **
  43681. ** When we speak of the journal header, we mean the first 7 items above.
  43682. ** Each entry in the journal is an instance of the 8th item.
  43683. **
  43684. ** Call the value from the second bullet "nRec". nRec is the number of
  43685. ** valid page entries in the journal. In most cases, you can compute the
  43686. ** value of nRec from the size of the journal file. But if a power
  43687. ** failure occurred while the journal was being written, it could be the
  43688. ** case that the size of the journal file had already been increased but
  43689. ** the extra entries had not yet made it safely to disk. In such a case,
  43690. ** the value of nRec computed from the file size would be too large. For
  43691. ** that reason, we always use the nRec value in the header.
  43692. **
  43693. ** If the nRec value is 0xffffffff it means that nRec should be computed
  43694. ** from the file size. This value is used when the user selects the
  43695. ** no-sync option for the journal. A power failure could lead to corruption
  43696. ** in this case. But for things like temporary table (which will be
  43697. ** deleted when the power is restored) we don't care.
  43698. **
  43699. ** If the file opened as the journal file is not a well-formed
  43700. ** journal file then all pages up to the first corrupted page are rolled
  43701. ** back (or no pages if the journal header is corrupted). The journal file
  43702. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  43703. ** been encountered.
  43704. **
  43705. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  43706. ** and an error code is returned.
  43707. **
  43708. ** The isHot parameter indicates that we are trying to rollback a journal
  43709. ** that might be a hot journal. Or, it could be that the journal is
  43710. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  43711. ** If the journal really is hot, reset the pager cache prior rolling
  43712. ** back any content. If the journal is merely persistent, no reset is
  43713. ** needed.
  43714. */
  43715. static int pager_playback(Pager *pPager, int isHot){
  43716. sqlite3_vfs *pVfs = pPager->pVfs;
  43717. i64 szJ; /* Size of the journal file in bytes */
  43718. u32 nRec; /* Number of Records in the journal */
  43719. u32 u; /* Unsigned loop counter */
  43720. Pgno mxPg = 0; /* Size of the original file in pages */
  43721. int rc; /* Result code of a subroutine */
  43722. int res = 1; /* Value returned by sqlite3OsAccess() */
  43723. char *zMaster = 0; /* Name of master journal file if any */
  43724. int needPagerReset; /* True to reset page prior to first page rollback */
  43725. int nPlayback = 0; /* Total number of pages restored from journal */
  43726. /* Figure out how many records are in the journal. Abort early if
  43727. ** the journal is empty.
  43728. */
  43729. assert( isOpen(pPager->jfd) );
  43730. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  43731. if( rc!=SQLITE_OK ){
  43732. goto end_playback;
  43733. }
  43734. /* Read the master journal name from the journal, if it is present.
  43735. ** If a master journal file name is specified, but the file is not
  43736. ** present on disk, then the journal is not hot and does not need to be
  43737. ** played back.
  43738. **
  43739. ** TODO: Technically the following is an error because it assumes that
  43740. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  43741. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  43742. ** mxPathname is 512, which is the same as the minimum allowable value
  43743. ** for pageSize.
  43744. */
  43745. zMaster = pPager->pTmpSpace;
  43746. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  43747. if( rc==SQLITE_OK && zMaster[0] ){
  43748. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  43749. }
  43750. zMaster = 0;
  43751. if( rc!=SQLITE_OK || !res ){
  43752. goto end_playback;
  43753. }
  43754. pPager->journalOff = 0;
  43755. needPagerReset = isHot;
  43756. /* This loop terminates either when a readJournalHdr() or
  43757. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  43758. ** occurs.
  43759. */
  43760. while( 1 ){
  43761. /* Read the next journal header from the journal file. If there are
  43762. ** not enough bytes left in the journal file for a complete header, or
  43763. ** it is corrupted, then a process must have failed while writing it.
  43764. ** This indicates nothing more needs to be rolled back.
  43765. */
  43766. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  43767. if( rc!=SQLITE_OK ){
  43768. if( rc==SQLITE_DONE ){
  43769. rc = SQLITE_OK;
  43770. }
  43771. goto end_playback;
  43772. }
  43773. /* If nRec is 0xffffffff, then this journal was created by a process
  43774. ** working in no-sync mode. This means that the rest of the journal
  43775. ** file consists of pages, there are no more journal headers. Compute
  43776. ** the value of nRec based on this assumption.
  43777. */
  43778. if( nRec==0xffffffff ){
  43779. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  43780. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  43781. }
  43782. /* If nRec is 0 and this rollback is of a transaction created by this
  43783. ** process and if this is the final header in the journal, then it means
  43784. ** that this part of the journal was being filled but has not yet been
  43785. ** synced to disk. Compute the number of pages based on the remaining
  43786. ** size of the file.
  43787. **
  43788. ** The third term of the test was added to fix ticket #2565.
  43789. ** When rolling back a hot journal, nRec==0 always means that the next
  43790. ** chunk of the journal contains zero pages to be rolled back. But
  43791. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  43792. ** the journal, it means that the journal might contain additional
  43793. ** pages that need to be rolled back and that the number of pages
  43794. ** should be computed based on the journal file size.
  43795. */
  43796. if( nRec==0 && !isHot &&
  43797. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  43798. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  43799. }
  43800. /* If this is the first header read from the journal, truncate the
  43801. ** database file back to its original size.
  43802. */
  43803. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  43804. rc = pager_truncate(pPager, mxPg);
  43805. if( rc!=SQLITE_OK ){
  43806. goto end_playback;
  43807. }
  43808. pPager->dbSize = mxPg;
  43809. }
  43810. /* Copy original pages out of the journal and back into the
  43811. ** database file and/or page cache.
  43812. */
  43813. for(u=0; u<nRec; u++){
  43814. if( needPagerReset ){
  43815. pager_reset(pPager);
  43816. needPagerReset = 0;
  43817. }
  43818. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  43819. if( rc==SQLITE_OK ){
  43820. nPlayback++;
  43821. }else{
  43822. if( rc==SQLITE_DONE ){
  43823. pPager->journalOff = szJ;
  43824. break;
  43825. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  43826. /* If the journal has been truncated, simply stop reading and
  43827. ** processing the journal. This might happen if the journal was
  43828. ** not completely written and synced prior to a crash. In that
  43829. ** case, the database should have never been written in the
  43830. ** first place so it is OK to simply abandon the rollback. */
  43831. rc = SQLITE_OK;
  43832. goto end_playback;
  43833. }else{
  43834. /* If we are unable to rollback, quit and return the error
  43835. ** code. This will cause the pager to enter the error state
  43836. ** so that no further harm will be done. Perhaps the next
  43837. ** process to come along will be able to rollback the database.
  43838. */
  43839. goto end_playback;
  43840. }
  43841. }
  43842. }
  43843. }
  43844. /*NOTREACHED*/
  43845. assert( 0 );
  43846. end_playback:
  43847. /* Following a rollback, the database file should be back in its original
  43848. ** state prior to the start of the transaction, so invoke the
  43849. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  43850. ** assertion that the transaction counter was modified.
  43851. */
  43852. #ifdef SQLITE_DEBUG
  43853. if( pPager->fd->pMethods ){
  43854. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  43855. }
  43856. #endif
  43857. /* If this playback is happening automatically as a result of an IO or
  43858. ** malloc error that occurred after the change-counter was updated but
  43859. ** before the transaction was committed, then the change-counter
  43860. ** modification may just have been reverted. If this happens in exclusive
  43861. ** mode, then subsequent transactions performed by the connection will not
  43862. ** update the change-counter at all. This may lead to cache inconsistency
  43863. ** problems for other processes at some point in the future. So, just
  43864. ** in case this has happened, clear the changeCountDone flag now.
  43865. */
  43866. pPager->changeCountDone = pPager->tempFile;
  43867. if( rc==SQLITE_OK ){
  43868. zMaster = pPager->pTmpSpace;
  43869. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  43870. testcase( rc!=SQLITE_OK );
  43871. }
  43872. if( rc==SQLITE_OK
  43873. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  43874. ){
  43875. rc = sqlite3PagerSync(pPager, 0);
  43876. }
  43877. if( rc==SQLITE_OK ){
  43878. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  43879. testcase( rc!=SQLITE_OK );
  43880. }
  43881. if( rc==SQLITE_OK && zMaster[0] && res ){
  43882. /* If there was a master journal and this routine will return success,
  43883. ** see if it is possible to delete the master journal.
  43884. */
  43885. rc = pager_delmaster(pPager, zMaster);
  43886. testcase( rc!=SQLITE_OK );
  43887. }
  43888. if( isHot && nPlayback ){
  43889. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  43890. nPlayback, pPager->zJournal);
  43891. }
  43892. /* The Pager.sectorSize variable may have been updated while rolling
  43893. ** back a journal created by a process with a different sector size
  43894. ** value. Reset it to the correct value for this process.
  43895. */
  43896. setSectorSize(pPager);
  43897. return rc;
  43898. }
  43899. /*
  43900. ** Read the content for page pPg out of the database file and into
  43901. ** pPg->pData. A shared lock or greater must be held on the database
  43902. ** file before this function is called.
  43903. **
  43904. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  43905. ** the value read from the database file.
  43906. **
  43907. ** If an IO error occurs, then the IO error is returned to the caller.
  43908. ** Otherwise, SQLITE_OK is returned.
  43909. */
  43910. static int readDbPage(PgHdr *pPg, u32 iFrame){
  43911. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  43912. Pgno pgno = pPg->pgno; /* Page number to read */
  43913. int rc = SQLITE_OK; /* Return code */
  43914. int pgsz = pPager->pageSize; /* Number of bytes to read */
  43915. assert( pPager->eState>=PAGER_READER && !MEMDB );
  43916. assert( isOpen(pPager->fd) );
  43917. #ifndef SQLITE_OMIT_WAL
  43918. if( iFrame ){
  43919. /* Try to pull the page from the write-ahead log. */
  43920. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  43921. }else
  43922. #endif
  43923. {
  43924. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  43925. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  43926. if( rc==SQLITE_IOERR_SHORT_READ ){
  43927. rc = SQLITE_OK;
  43928. }
  43929. }
  43930. if( pgno==1 ){
  43931. if( rc ){
  43932. /* If the read is unsuccessful, set the dbFileVers[] to something
  43933. ** that will never be a valid file version. dbFileVers[] is a copy
  43934. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  43935. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  43936. ** should be page numbers which are never 0xffffffff. So filling
  43937. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  43938. **
  43939. ** For an encrypted database, the situation is more complex: bytes
  43940. ** 24..39 of the database are white noise. But the probability of
  43941. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  43942. ** we should still be ok.
  43943. */
  43944. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  43945. }else{
  43946. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  43947. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  43948. }
  43949. }
  43950. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
  43951. PAGER_INCR(sqlite3_pager_readdb_count);
  43952. PAGER_INCR(pPager->nRead);
  43953. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  43954. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  43955. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  43956. return rc;
  43957. }
  43958. /*
  43959. ** Update the value of the change-counter at offsets 24 and 92 in
  43960. ** the header and the sqlite version number at offset 96.
  43961. **
  43962. ** This is an unconditional update. See also the pager_incr_changecounter()
  43963. ** routine which only updates the change-counter if the update is actually
  43964. ** needed, as determined by the pPager->changeCountDone state variable.
  43965. */
  43966. static void pager_write_changecounter(PgHdr *pPg){
  43967. u32 change_counter;
  43968. /* Increment the value just read and write it back to byte 24. */
  43969. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  43970. put32bits(((char*)pPg->pData)+24, change_counter);
  43971. /* Also store the SQLite version number in bytes 96..99 and in
  43972. ** bytes 92..95 store the change counter for which the version number
  43973. ** is valid. */
  43974. put32bits(((char*)pPg->pData)+92, change_counter);
  43975. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  43976. }
  43977. #ifndef SQLITE_OMIT_WAL
  43978. /*
  43979. ** This function is invoked once for each page that has already been
  43980. ** written into the log file when a WAL transaction is rolled back.
  43981. ** Parameter iPg is the page number of said page. The pCtx argument
  43982. ** is actually a pointer to the Pager structure.
  43983. **
  43984. ** If page iPg is present in the cache, and has no outstanding references,
  43985. ** it is discarded. Otherwise, if there are one or more outstanding
  43986. ** references, the page content is reloaded from the database. If the
  43987. ** attempt to reload content from the database is required and fails,
  43988. ** return an SQLite error code. Otherwise, SQLITE_OK.
  43989. */
  43990. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  43991. int rc = SQLITE_OK;
  43992. Pager *pPager = (Pager *)pCtx;
  43993. PgHdr *pPg;
  43994. assert( pagerUseWal(pPager) );
  43995. pPg = sqlite3PagerLookup(pPager, iPg);
  43996. if( pPg ){
  43997. if( sqlite3PcachePageRefcount(pPg)==1 ){
  43998. sqlite3PcacheDrop(pPg);
  43999. }else{
  44000. u32 iFrame = 0;
  44001. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  44002. if( rc==SQLITE_OK ){
  44003. rc = readDbPage(pPg, iFrame);
  44004. }
  44005. if( rc==SQLITE_OK ){
  44006. pPager->xReiniter(pPg);
  44007. }
  44008. sqlite3PagerUnrefNotNull(pPg);
  44009. }
  44010. }
  44011. /* Normally, if a transaction is rolled back, any backup processes are
  44012. ** updated as data is copied out of the rollback journal and into the
  44013. ** database. This is not generally possible with a WAL database, as
  44014. ** rollback involves simply truncating the log file. Therefore, if one
  44015. ** or more frames have already been written to the log (and therefore
  44016. ** also copied into the backup databases) as part of this transaction,
  44017. ** the backups must be restarted.
  44018. */
  44019. sqlite3BackupRestart(pPager->pBackup);
  44020. return rc;
  44021. }
  44022. /*
  44023. ** This function is called to rollback a transaction on a WAL database.
  44024. */
  44025. static int pagerRollbackWal(Pager *pPager){
  44026. int rc; /* Return Code */
  44027. PgHdr *pList; /* List of dirty pages to revert */
  44028. /* For all pages in the cache that are currently dirty or have already
  44029. ** been written (but not committed) to the log file, do one of the
  44030. ** following:
  44031. **
  44032. ** + Discard the cached page (if refcount==0), or
  44033. ** + Reload page content from the database (if refcount>0).
  44034. */
  44035. pPager->dbSize = pPager->dbOrigSize;
  44036. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  44037. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  44038. while( pList && rc==SQLITE_OK ){
  44039. PgHdr *pNext = pList->pDirty;
  44040. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  44041. pList = pNext;
  44042. }
  44043. return rc;
  44044. }
  44045. /*
  44046. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  44047. ** the contents of the list of pages headed by pList (connected by pDirty),
  44048. ** this function notifies any active backup processes that the pages have
  44049. ** changed.
  44050. **
  44051. ** The list of pages passed into this routine is always sorted by page number.
  44052. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  44053. */
  44054. static int pagerWalFrames(
  44055. Pager *pPager, /* Pager object */
  44056. PgHdr *pList, /* List of frames to log */
  44057. Pgno nTruncate, /* Database size after this commit */
  44058. int isCommit /* True if this is a commit */
  44059. ){
  44060. int rc; /* Return code */
  44061. int nList; /* Number of pages in pList */
  44062. PgHdr *p; /* For looping over pages */
  44063. assert( pPager->pWal );
  44064. assert( pList );
  44065. #ifdef SQLITE_DEBUG
  44066. /* Verify that the page list is in accending order */
  44067. for(p=pList; p && p->pDirty; p=p->pDirty){
  44068. assert( p->pgno < p->pDirty->pgno );
  44069. }
  44070. #endif
  44071. assert( pList->pDirty==0 || isCommit );
  44072. if( isCommit ){
  44073. /* If a WAL transaction is being committed, there is no point in writing
  44074. ** any pages with page numbers greater than nTruncate into the WAL file.
  44075. ** They will never be read by any client. So remove them from the pDirty
  44076. ** list here. */
  44077. PgHdr **ppNext = &pList;
  44078. nList = 0;
  44079. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  44080. if( p->pgno<=nTruncate ){
  44081. ppNext = &p->pDirty;
  44082. nList++;
  44083. }
  44084. }
  44085. assert( pList );
  44086. }else{
  44087. nList = 1;
  44088. }
  44089. pPager->aStat[PAGER_STAT_WRITE] += nList;
  44090. if( pList->pgno==1 ) pager_write_changecounter(pList);
  44091. rc = sqlite3WalFrames(pPager->pWal,
  44092. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  44093. );
  44094. if( rc==SQLITE_OK && pPager->pBackup ){
  44095. for(p=pList; p; p=p->pDirty){
  44096. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  44097. }
  44098. }
  44099. #ifdef SQLITE_CHECK_PAGES
  44100. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  44101. for(p=pList; p; p=p->pDirty){
  44102. pager_set_pagehash(p);
  44103. }
  44104. #endif
  44105. return rc;
  44106. }
  44107. /*
  44108. ** Begin a read transaction on the WAL.
  44109. **
  44110. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  44111. ** makes a snapshot of the database at the current point in time and preserves
  44112. ** that snapshot for use by the reader in spite of concurrently changes by
  44113. ** other writers or checkpointers.
  44114. */
  44115. static int pagerBeginReadTransaction(Pager *pPager){
  44116. int rc; /* Return code */
  44117. int changed = 0; /* True if cache must be reset */
  44118. assert( pagerUseWal(pPager) );
  44119. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  44120. /* sqlite3WalEndReadTransaction() was not called for the previous
  44121. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  44122. ** are in locking_mode=NORMAL and EndRead() was previously called,
  44123. ** the duplicate call is harmless.
  44124. */
  44125. sqlite3WalEndReadTransaction(pPager->pWal);
  44126. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  44127. if( rc!=SQLITE_OK || changed ){
  44128. pager_reset(pPager);
  44129. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  44130. }
  44131. return rc;
  44132. }
  44133. #endif
  44134. /*
  44135. ** This function is called as part of the transition from PAGER_OPEN
  44136. ** to PAGER_READER state to determine the size of the database file
  44137. ** in pages (assuming the page size currently stored in Pager.pageSize).
  44138. **
  44139. ** If no error occurs, SQLITE_OK is returned and the size of the database
  44140. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  44141. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  44142. */
  44143. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  44144. Pgno nPage; /* Value to return via *pnPage */
  44145. /* Query the WAL sub-system for the database size. The WalDbsize()
  44146. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  44147. ** if the database size is not available. The database size is not
  44148. ** available from the WAL sub-system if the log file is empty or
  44149. ** contains no valid committed transactions.
  44150. */
  44151. assert( pPager->eState==PAGER_OPEN );
  44152. assert( pPager->eLock>=SHARED_LOCK );
  44153. nPage = sqlite3WalDbsize(pPager->pWal);
  44154. /* If the number of pages in the database is not available from the
  44155. ** WAL sub-system, determine the page counte based on the size of
  44156. ** the database file. If the size of the database file is not an
  44157. ** integer multiple of the page-size, round up the result.
  44158. */
  44159. if( nPage==0 ){
  44160. i64 n = 0; /* Size of db file in bytes */
  44161. assert( isOpen(pPager->fd) || pPager->tempFile );
  44162. if( isOpen(pPager->fd) ){
  44163. int rc = sqlite3OsFileSize(pPager->fd, &n);
  44164. if( rc!=SQLITE_OK ){
  44165. return rc;
  44166. }
  44167. }
  44168. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  44169. }
  44170. /* If the current number of pages in the file is greater than the
  44171. ** configured maximum pager number, increase the allowed limit so
  44172. ** that the file can be read.
  44173. */
  44174. if( nPage>pPager->mxPgno ){
  44175. pPager->mxPgno = (Pgno)nPage;
  44176. }
  44177. *pnPage = nPage;
  44178. return SQLITE_OK;
  44179. }
  44180. #ifndef SQLITE_OMIT_WAL
  44181. /*
  44182. ** Check if the *-wal file that corresponds to the database opened by pPager
  44183. ** exists if the database is not empy, or verify that the *-wal file does
  44184. ** not exist (by deleting it) if the database file is empty.
  44185. **
  44186. ** If the database is not empty and the *-wal file exists, open the pager
  44187. ** in WAL mode. If the database is empty or if no *-wal file exists and
  44188. ** if no error occurs, make sure Pager.journalMode is not set to
  44189. ** PAGER_JOURNALMODE_WAL.
  44190. **
  44191. ** Return SQLITE_OK or an error code.
  44192. **
  44193. ** The caller must hold a SHARED lock on the database file to call this
  44194. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  44195. ** a WAL on a none-empty database, this ensures there is no race condition
  44196. ** between the xAccess() below and an xDelete() being executed by some
  44197. ** other connection.
  44198. */
  44199. static int pagerOpenWalIfPresent(Pager *pPager){
  44200. int rc = SQLITE_OK;
  44201. assert( pPager->eState==PAGER_OPEN );
  44202. assert( pPager->eLock>=SHARED_LOCK );
  44203. if( !pPager->tempFile ){
  44204. int isWal; /* True if WAL file exists */
  44205. Pgno nPage; /* Size of the database file */
  44206. rc = pagerPagecount(pPager, &nPage);
  44207. if( rc ) return rc;
  44208. if( nPage==0 ){
  44209. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  44210. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  44211. isWal = 0;
  44212. }else{
  44213. rc = sqlite3OsAccess(
  44214. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  44215. );
  44216. }
  44217. if( rc==SQLITE_OK ){
  44218. if( isWal ){
  44219. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  44220. rc = sqlite3PagerOpenWal(pPager, 0);
  44221. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  44222. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  44223. }
  44224. }
  44225. }
  44226. return rc;
  44227. }
  44228. #endif
  44229. /*
  44230. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  44231. ** the entire master journal file. The case pSavepoint==NULL occurs when
  44232. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  44233. ** savepoint.
  44234. **
  44235. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  44236. ** being rolled back), then the rollback consists of up to three stages,
  44237. ** performed in the order specified:
  44238. **
  44239. ** * Pages are played back from the main journal starting at byte
  44240. ** offset PagerSavepoint.iOffset and continuing to
  44241. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  44242. ** file if PagerSavepoint.iHdrOffset is zero.
  44243. **
  44244. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  44245. ** back starting from the journal header immediately following
  44246. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  44247. **
  44248. ** * Pages are then played back from the sub-journal file, starting
  44249. ** with the PagerSavepoint.iSubRec and continuing to the end of
  44250. ** the journal file.
  44251. **
  44252. ** Throughout the rollback process, each time a page is rolled back, the
  44253. ** corresponding bit is set in a bitvec structure (variable pDone in the
  44254. ** implementation below). This is used to ensure that a page is only
  44255. ** rolled back the first time it is encountered in either journal.
  44256. **
  44257. ** If pSavepoint is NULL, then pages are only played back from the main
  44258. ** journal file. There is no need for a bitvec in this case.
  44259. **
  44260. ** In either case, before playback commences the Pager.dbSize variable
  44261. ** is reset to the value that it held at the start of the savepoint
  44262. ** (or transaction). No page with a page-number greater than this value
  44263. ** is played back. If one is encountered it is simply skipped.
  44264. */
  44265. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  44266. i64 szJ; /* Effective size of the main journal */
  44267. i64 iHdrOff; /* End of first segment of main-journal records */
  44268. int rc = SQLITE_OK; /* Return code */
  44269. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  44270. assert( pPager->eState!=PAGER_ERROR );
  44271. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  44272. /* Allocate a bitvec to use to store the set of pages rolled back */
  44273. if( pSavepoint ){
  44274. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  44275. if( !pDone ){
  44276. return SQLITE_NOMEM_BKPT;
  44277. }
  44278. }
  44279. /* Set the database size back to the value it was before the savepoint
  44280. ** being reverted was opened.
  44281. */
  44282. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  44283. pPager->changeCountDone = pPager->tempFile;
  44284. if( !pSavepoint && pagerUseWal(pPager) ){
  44285. return pagerRollbackWal(pPager);
  44286. }
  44287. /* Use pPager->journalOff as the effective size of the main rollback
  44288. ** journal. The actual file might be larger than this in
  44289. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  44290. ** past pPager->journalOff is off-limits to us.
  44291. */
  44292. szJ = pPager->journalOff;
  44293. assert( pagerUseWal(pPager)==0 || szJ==0 );
  44294. /* Begin by rolling back records from the main journal starting at
  44295. ** PagerSavepoint.iOffset and continuing to the next journal header.
  44296. ** There might be records in the main journal that have a page number
  44297. ** greater than the current database size (pPager->dbSize) but those
  44298. ** will be skipped automatically. Pages are added to pDone as they
  44299. ** are played back.
  44300. */
  44301. if( pSavepoint && !pagerUseWal(pPager) ){
  44302. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  44303. pPager->journalOff = pSavepoint->iOffset;
  44304. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  44305. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  44306. }
  44307. assert( rc!=SQLITE_DONE );
  44308. }else{
  44309. pPager->journalOff = 0;
  44310. }
  44311. /* Continue rolling back records out of the main journal starting at
  44312. ** the first journal header seen and continuing until the effective end
  44313. ** of the main journal file. Continue to skip out-of-range pages and
  44314. ** continue adding pages rolled back to pDone.
  44315. */
  44316. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  44317. u32 ii; /* Loop counter */
  44318. u32 nJRec = 0; /* Number of Journal Records */
  44319. u32 dummy;
  44320. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  44321. assert( rc!=SQLITE_DONE );
  44322. /*
  44323. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  44324. ** test is related to ticket #2565. See the discussion in the
  44325. ** pager_playback() function for additional information.
  44326. */
  44327. if( nJRec==0
  44328. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  44329. ){
  44330. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  44331. }
  44332. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  44333. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  44334. }
  44335. assert( rc!=SQLITE_DONE );
  44336. }
  44337. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  44338. /* Finally, rollback pages from the sub-journal. Page that were
  44339. ** previously rolled back out of the main journal (and are hence in pDone)
  44340. ** will be skipped. Out-of-range pages are also skipped.
  44341. */
  44342. if( pSavepoint ){
  44343. u32 ii; /* Loop counter */
  44344. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  44345. if( pagerUseWal(pPager) ){
  44346. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  44347. }
  44348. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  44349. assert( offset==(i64)ii*(4+pPager->pageSize) );
  44350. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  44351. }
  44352. assert( rc!=SQLITE_DONE );
  44353. }
  44354. sqlite3BitvecDestroy(pDone);
  44355. if( rc==SQLITE_OK ){
  44356. pPager->journalOff = szJ;
  44357. }
  44358. return rc;
  44359. }
  44360. /*
  44361. ** Change the maximum number of in-memory pages that are allowed
  44362. ** before attempting to recycle clean and unused pages.
  44363. */
  44364. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  44365. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  44366. }
  44367. /*
  44368. ** Change the maximum number of in-memory pages that are allowed
  44369. ** before attempting to spill pages to journal.
  44370. */
  44371. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  44372. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  44373. }
  44374. /*
  44375. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  44376. */
  44377. static void pagerFixMaplimit(Pager *pPager){
  44378. #if SQLITE_MAX_MMAP_SIZE>0
  44379. sqlite3_file *fd = pPager->fd;
  44380. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  44381. sqlite3_int64 sz;
  44382. sz = pPager->szMmap;
  44383. pPager->bUseFetch = (sz>0);
  44384. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  44385. }
  44386. #endif
  44387. }
  44388. /*
  44389. ** Change the maximum size of any memory mapping made of the database file.
  44390. */
  44391. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  44392. pPager->szMmap = szMmap;
  44393. pagerFixMaplimit(pPager);
  44394. }
  44395. /*
  44396. ** Free as much memory as possible from the pager.
  44397. */
  44398. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  44399. sqlite3PcacheShrink(pPager->pPCache);
  44400. }
  44401. /*
  44402. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  44403. **
  44404. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  44405. ** of the database to damage due to OS crashes or power failures by
  44406. ** changing the number of syncs()s when writing the journals.
  44407. ** There are four levels:
  44408. **
  44409. ** OFF sqlite3OsSync() is never called. This is the default
  44410. ** for temporary and transient files.
  44411. **
  44412. ** NORMAL The journal is synced once before writes begin on the
  44413. ** database. This is normally adequate protection, but
  44414. ** it is theoretically possible, though very unlikely,
  44415. ** that an inopertune power failure could leave the journal
  44416. ** in a state which would cause damage to the database
  44417. ** when it is rolled back.
  44418. **
  44419. ** FULL The journal is synced twice before writes begin on the
  44420. ** database (with some additional information - the nRec field
  44421. ** of the journal header - being written in between the two
  44422. ** syncs). If we assume that writing a
  44423. ** single disk sector is atomic, then this mode provides
  44424. ** assurance that the journal will not be corrupted to the
  44425. ** point of causing damage to the database during rollback.
  44426. **
  44427. ** EXTRA This is like FULL except that is also syncs the directory
  44428. ** that contains the rollback journal after the rollback
  44429. ** journal is unlinked.
  44430. **
  44431. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  44432. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  44433. ** prior to the start of checkpoint and that the database file is synced
  44434. ** at the conclusion of the checkpoint if the entire content of the WAL
  44435. ** was written back into the database. But no sync operations occur for
  44436. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  44437. ** file is synced following each commit operation, in addition to the
  44438. ** syncs associated with NORMAL. There is no difference between FULL
  44439. ** and EXTRA for WAL mode.
  44440. **
  44441. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  44442. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  44443. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  44444. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  44445. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  44446. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  44447. ** the xSync primitive is called and is relevant to all platforms.
  44448. **
  44449. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  44450. ** and FULL=3.
  44451. */
  44452. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  44453. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  44454. Pager *pPager, /* The pager to set safety level for */
  44455. unsigned pgFlags /* Various flags */
  44456. ){
  44457. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  44458. if( pPager->tempFile ){
  44459. pPager->noSync = 1;
  44460. pPager->fullSync = 0;
  44461. pPager->extraSync = 0;
  44462. }else{
  44463. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  44464. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  44465. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  44466. }
  44467. if( pPager->noSync ){
  44468. pPager->syncFlags = 0;
  44469. pPager->ckptSyncFlags = 0;
  44470. }else if( pgFlags & PAGER_FULLFSYNC ){
  44471. pPager->syncFlags = SQLITE_SYNC_FULL;
  44472. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  44473. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  44474. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  44475. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  44476. }else{
  44477. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  44478. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  44479. }
  44480. pPager->walSyncFlags = pPager->syncFlags;
  44481. if( pPager->fullSync ){
  44482. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  44483. }
  44484. if( pgFlags & PAGER_CACHESPILL ){
  44485. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  44486. }else{
  44487. pPager->doNotSpill |= SPILLFLAG_OFF;
  44488. }
  44489. }
  44490. #endif
  44491. /*
  44492. ** The following global variable is incremented whenever the library
  44493. ** attempts to open a temporary file. This information is used for
  44494. ** testing and analysis only.
  44495. */
  44496. #ifdef SQLITE_TEST
  44497. SQLITE_API int sqlite3_opentemp_count = 0;
  44498. #endif
  44499. /*
  44500. ** Open a temporary file.
  44501. **
  44502. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  44503. ** or some other error code if we fail. The OS will automatically
  44504. ** delete the temporary file when it is closed.
  44505. **
  44506. ** The flags passed to the VFS layer xOpen() call are those specified
  44507. ** by parameter vfsFlags ORed with the following:
  44508. **
  44509. ** SQLITE_OPEN_READWRITE
  44510. ** SQLITE_OPEN_CREATE
  44511. ** SQLITE_OPEN_EXCLUSIVE
  44512. ** SQLITE_OPEN_DELETEONCLOSE
  44513. */
  44514. static int pagerOpentemp(
  44515. Pager *pPager, /* The pager object */
  44516. sqlite3_file *pFile, /* Write the file descriptor here */
  44517. int vfsFlags /* Flags passed through to the VFS */
  44518. ){
  44519. int rc; /* Return code */
  44520. #ifdef SQLITE_TEST
  44521. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  44522. #endif
  44523. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  44524. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  44525. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  44526. assert( rc!=SQLITE_OK || isOpen(pFile) );
  44527. return rc;
  44528. }
  44529. /*
  44530. ** Set the busy handler function.
  44531. **
  44532. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  44533. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  44534. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  44535. ** lock. It does *not* invoke the busy handler when upgrading from
  44536. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  44537. ** (which occurs during hot-journal rollback). Summary:
  44538. **
  44539. ** Transition | Invokes xBusyHandler
  44540. ** --------------------------------------------------------
  44541. ** NO_LOCK -> SHARED_LOCK | Yes
  44542. ** SHARED_LOCK -> RESERVED_LOCK | No
  44543. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  44544. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  44545. **
  44546. ** If the busy-handler callback returns non-zero, the lock is
  44547. ** retried. If it returns zero, then the SQLITE_BUSY error is
  44548. ** returned to the caller of the pager API function.
  44549. */
  44550. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  44551. Pager *pPager, /* Pager object */
  44552. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  44553. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  44554. ){
  44555. pPager->xBusyHandler = xBusyHandler;
  44556. pPager->pBusyHandlerArg = pBusyHandlerArg;
  44557. if( isOpen(pPager->fd) ){
  44558. void **ap = (void **)&pPager->xBusyHandler;
  44559. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  44560. assert( ap[1]==pBusyHandlerArg );
  44561. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  44562. }
  44563. }
  44564. /*
  44565. ** Change the page size used by the Pager object. The new page size
  44566. ** is passed in *pPageSize.
  44567. **
  44568. ** If the pager is in the error state when this function is called, it
  44569. ** is a no-op. The value returned is the error state error code (i.e.
  44570. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  44571. **
  44572. ** Otherwise, if all of the following are true:
  44573. **
  44574. ** * the new page size (value of *pPageSize) is valid (a power
  44575. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  44576. **
  44577. ** * there are no outstanding page references, and
  44578. **
  44579. ** * the database is either not an in-memory database or it is
  44580. ** an in-memory database that currently consists of zero pages.
  44581. **
  44582. ** then the pager object page size is set to *pPageSize.
  44583. **
  44584. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  44585. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  44586. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  44587. ** In all other cases, SQLITE_OK is returned.
  44588. **
  44589. ** If the page size is not changed, either because one of the enumerated
  44590. ** conditions above is not true, the pager was in error state when this
  44591. ** function was called, or because the memory allocation attempt failed,
  44592. ** then *pPageSize is set to the old, retained page size before returning.
  44593. */
  44594. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  44595. int rc = SQLITE_OK;
  44596. /* It is not possible to do a full assert_pager_state() here, as this
  44597. ** function may be called from within PagerOpen(), before the state
  44598. ** of the Pager object is internally consistent.
  44599. **
  44600. ** At one point this function returned an error if the pager was in
  44601. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  44602. ** there is at least one outstanding page reference, this function
  44603. ** is a no-op for that case anyhow.
  44604. */
  44605. u32 pageSize = *pPageSize;
  44606. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  44607. if( (pPager->memDb==0 || pPager->dbSize==0)
  44608. && sqlite3PcacheRefCount(pPager->pPCache)==0
  44609. && pageSize && pageSize!=(u32)pPager->pageSize
  44610. ){
  44611. char *pNew = NULL; /* New temp space */
  44612. i64 nByte = 0;
  44613. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  44614. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  44615. }
  44616. if( rc==SQLITE_OK ){
  44617. pNew = (char *)sqlite3PageMalloc(pageSize);
  44618. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  44619. }
  44620. if( rc==SQLITE_OK ){
  44621. pager_reset(pPager);
  44622. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  44623. }
  44624. if( rc==SQLITE_OK ){
  44625. sqlite3PageFree(pPager->pTmpSpace);
  44626. pPager->pTmpSpace = pNew;
  44627. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  44628. pPager->pageSize = pageSize;
  44629. }else{
  44630. sqlite3PageFree(pNew);
  44631. }
  44632. }
  44633. *pPageSize = pPager->pageSize;
  44634. if( rc==SQLITE_OK ){
  44635. if( nReserve<0 ) nReserve = pPager->nReserve;
  44636. assert( nReserve>=0 && nReserve<1000 );
  44637. pPager->nReserve = (i16)nReserve;
  44638. pagerReportSize(pPager);
  44639. pagerFixMaplimit(pPager);
  44640. }
  44641. return rc;
  44642. }
  44643. /*
  44644. ** Return a pointer to the "temporary page" buffer held internally
  44645. ** by the pager. This is a buffer that is big enough to hold the
  44646. ** entire content of a database page. This buffer is used internally
  44647. ** during rollback and will be overwritten whenever a rollback
  44648. ** occurs. But other modules are free to use it too, as long as
  44649. ** no rollbacks are happening.
  44650. */
  44651. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  44652. return pPager->pTmpSpace;
  44653. }
  44654. /*
  44655. ** Attempt to set the maximum database page count if mxPage is positive.
  44656. ** Make no changes if mxPage is zero or negative. And never reduce the
  44657. ** maximum page count below the current size of the database.
  44658. **
  44659. ** Regardless of mxPage, return the current maximum page count.
  44660. */
  44661. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  44662. if( mxPage>0 ){
  44663. pPager->mxPgno = mxPage;
  44664. }
  44665. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  44666. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  44667. return pPager->mxPgno;
  44668. }
  44669. /*
  44670. ** The following set of routines are used to disable the simulated
  44671. ** I/O error mechanism. These routines are used to avoid simulated
  44672. ** errors in places where we do not care about errors.
  44673. **
  44674. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  44675. ** and generate no code.
  44676. */
  44677. #ifdef SQLITE_TEST
  44678. SQLITE_API extern int sqlite3_io_error_pending;
  44679. SQLITE_API extern int sqlite3_io_error_hit;
  44680. static int saved_cnt;
  44681. void disable_simulated_io_errors(void){
  44682. saved_cnt = sqlite3_io_error_pending;
  44683. sqlite3_io_error_pending = -1;
  44684. }
  44685. void enable_simulated_io_errors(void){
  44686. sqlite3_io_error_pending = saved_cnt;
  44687. }
  44688. #else
  44689. # define disable_simulated_io_errors()
  44690. # define enable_simulated_io_errors()
  44691. #endif
  44692. /*
  44693. ** Read the first N bytes from the beginning of the file into memory
  44694. ** that pDest points to.
  44695. **
  44696. ** If the pager was opened on a transient file (zFilename==""), or
  44697. ** opened on a file less than N bytes in size, the output buffer is
  44698. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  44699. ** function is used to read database headers, and a new transient or
  44700. ** zero sized database has a header than consists entirely of zeroes.
  44701. **
  44702. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  44703. ** the error code is returned to the caller and the contents of the
  44704. ** output buffer undefined.
  44705. */
  44706. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  44707. int rc = SQLITE_OK;
  44708. memset(pDest, 0, N);
  44709. assert( isOpen(pPager->fd) || pPager->tempFile );
  44710. /* This routine is only called by btree immediately after creating
  44711. ** the Pager object. There has not been an opportunity to transition
  44712. ** to WAL mode yet.
  44713. */
  44714. assert( !pagerUseWal(pPager) );
  44715. if( isOpen(pPager->fd) ){
  44716. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  44717. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  44718. if( rc==SQLITE_IOERR_SHORT_READ ){
  44719. rc = SQLITE_OK;
  44720. }
  44721. }
  44722. return rc;
  44723. }
  44724. /*
  44725. ** This function may only be called when a read-transaction is open on
  44726. ** the pager. It returns the total number of pages in the database.
  44727. **
  44728. ** However, if the file is between 1 and <page-size> bytes in size, then
  44729. ** this is considered a 1 page file.
  44730. */
  44731. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  44732. assert( pPager->eState>=PAGER_READER );
  44733. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  44734. *pnPage = (int)pPager->dbSize;
  44735. }
  44736. /*
  44737. ** Try to obtain a lock of type locktype on the database file. If
  44738. ** a similar or greater lock is already held, this function is a no-op
  44739. ** (returning SQLITE_OK immediately).
  44740. **
  44741. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  44742. ** the busy callback if the lock is currently not available. Repeat
  44743. ** until the busy callback returns false or until the attempt to
  44744. ** obtain the lock succeeds.
  44745. **
  44746. ** Return SQLITE_OK on success and an error code if we cannot obtain
  44747. ** the lock. If the lock is obtained successfully, set the Pager.state
  44748. ** variable to locktype before returning.
  44749. */
  44750. static int pager_wait_on_lock(Pager *pPager, int locktype){
  44751. int rc; /* Return code */
  44752. /* Check that this is either a no-op (because the requested lock is
  44753. ** already held), or one of the transitions that the busy-handler
  44754. ** may be invoked during, according to the comment above
  44755. ** sqlite3PagerSetBusyhandler().
  44756. */
  44757. assert( (pPager->eLock>=locktype)
  44758. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  44759. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  44760. );
  44761. do {
  44762. rc = pagerLockDb(pPager, locktype);
  44763. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  44764. return rc;
  44765. }
  44766. /*
  44767. ** Function assertTruncateConstraint(pPager) checks that one of the
  44768. ** following is true for all dirty pages currently in the page-cache:
  44769. **
  44770. ** a) The page number is less than or equal to the size of the
  44771. ** current database image, in pages, OR
  44772. **
  44773. ** b) if the page content were written at this time, it would not
  44774. ** be necessary to write the current content out to the sub-journal
  44775. ** (as determined by function subjRequiresPage()).
  44776. **
  44777. ** If the condition asserted by this function were not true, and the
  44778. ** dirty page were to be discarded from the cache via the pagerStress()
  44779. ** routine, pagerStress() would not write the current page content to
  44780. ** the database file. If a savepoint transaction were rolled back after
  44781. ** this happened, the correct behavior would be to restore the current
  44782. ** content of the page. However, since this content is not present in either
  44783. ** the database file or the portion of the rollback journal and
  44784. ** sub-journal rolled back the content could not be restored and the
  44785. ** database image would become corrupt. It is therefore fortunate that
  44786. ** this circumstance cannot arise.
  44787. */
  44788. #if defined(SQLITE_DEBUG)
  44789. static void assertTruncateConstraintCb(PgHdr *pPg){
  44790. assert( pPg->flags&PGHDR_DIRTY );
  44791. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  44792. }
  44793. static void assertTruncateConstraint(Pager *pPager){
  44794. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  44795. }
  44796. #else
  44797. # define assertTruncateConstraint(pPager)
  44798. #endif
  44799. /*
  44800. ** Truncate the in-memory database file image to nPage pages. This
  44801. ** function does not actually modify the database file on disk. It
  44802. ** just sets the internal state of the pager object so that the
  44803. ** truncation will be done when the current transaction is committed.
  44804. **
  44805. ** This function is only called right before committing a transaction.
  44806. ** Once this function has been called, the transaction must either be
  44807. ** rolled back or committed. It is not safe to call this function and
  44808. ** then continue writing to the database.
  44809. */
  44810. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  44811. assert( pPager->dbSize>=nPage );
  44812. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  44813. pPager->dbSize = nPage;
  44814. /* At one point the code here called assertTruncateConstraint() to
  44815. ** ensure that all pages being truncated away by this operation are,
  44816. ** if one or more savepoints are open, present in the savepoint
  44817. ** journal so that they can be restored if the savepoint is rolled
  44818. ** back. This is no longer necessary as this function is now only
  44819. ** called right before committing a transaction. So although the
  44820. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  44821. ** they cannot be rolled back. So the assertTruncateConstraint() call
  44822. ** is no longer correct. */
  44823. }
  44824. /*
  44825. ** This function is called before attempting a hot-journal rollback. It
  44826. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  44827. ** size of the journal file so that the pager_playback() routine knows
  44828. ** that the entire journal file has been synced.
  44829. **
  44830. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  44831. ** that if a power-failure occurs during the rollback, the process that
  44832. ** attempts rollback following system recovery sees the same journal
  44833. ** content as this process.
  44834. **
  44835. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  44836. ** an SQLite error code.
  44837. */
  44838. static int pagerSyncHotJournal(Pager *pPager){
  44839. int rc = SQLITE_OK;
  44840. if( !pPager->noSync ){
  44841. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  44842. }
  44843. if( rc==SQLITE_OK ){
  44844. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  44845. }
  44846. return rc;
  44847. }
  44848. /*
  44849. ** Obtain a reference to a memory mapped page object for page number pgno.
  44850. ** The new object will use the pointer pData, obtained from xFetch().
  44851. ** If successful, set *ppPage to point to the new page reference
  44852. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  44853. ** *ppPage to zero.
  44854. **
  44855. ** Page references obtained by calling this function should be released
  44856. ** by calling pagerReleaseMapPage().
  44857. */
  44858. static int pagerAcquireMapPage(
  44859. Pager *pPager, /* Pager object */
  44860. Pgno pgno, /* Page number */
  44861. void *pData, /* xFetch()'d data for this page */
  44862. PgHdr **ppPage /* OUT: Acquired page object */
  44863. ){
  44864. PgHdr *p; /* Memory mapped page to return */
  44865. if( pPager->pMmapFreelist ){
  44866. *ppPage = p = pPager->pMmapFreelist;
  44867. pPager->pMmapFreelist = p->pDirty;
  44868. p->pDirty = 0;
  44869. memset(p->pExtra, 0, pPager->nExtra);
  44870. }else{
  44871. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  44872. if( p==0 ){
  44873. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  44874. return SQLITE_NOMEM_BKPT;
  44875. }
  44876. p->pExtra = (void *)&p[1];
  44877. p->flags = PGHDR_MMAP;
  44878. p->nRef = 1;
  44879. p->pPager = pPager;
  44880. }
  44881. assert( p->pExtra==(void *)&p[1] );
  44882. assert( p->pPage==0 );
  44883. assert( p->flags==PGHDR_MMAP );
  44884. assert( p->pPager==pPager );
  44885. assert( p->nRef==1 );
  44886. p->pgno = pgno;
  44887. p->pData = pData;
  44888. pPager->nMmapOut++;
  44889. return SQLITE_OK;
  44890. }
  44891. /*
  44892. ** Release a reference to page pPg. pPg must have been returned by an
  44893. ** earlier call to pagerAcquireMapPage().
  44894. */
  44895. static void pagerReleaseMapPage(PgHdr *pPg){
  44896. Pager *pPager = pPg->pPager;
  44897. pPager->nMmapOut--;
  44898. pPg->pDirty = pPager->pMmapFreelist;
  44899. pPager->pMmapFreelist = pPg;
  44900. assert( pPager->fd->pMethods->iVersion>=3 );
  44901. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  44902. }
  44903. /*
  44904. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  44905. */
  44906. static void pagerFreeMapHdrs(Pager *pPager){
  44907. PgHdr *p;
  44908. PgHdr *pNext;
  44909. for(p=pPager->pMmapFreelist; p; p=pNext){
  44910. pNext = p->pDirty;
  44911. sqlite3_free(p);
  44912. }
  44913. }
  44914. /*
  44915. ** Shutdown the page cache. Free all memory and close all files.
  44916. **
  44917. ** If a transaction was in progress when this routine is called, that
  44918. ** transaction is rolled back. All outstanding pages are invalidated
  44919. ** and their memory is freed. Any attempt to use a page associated
  44920. ** with this page cache after this function returns will likely
  44921. ** result in a coredump.
  44922. **
  44923. ** This function always succeeds. If a transaction is active an attempt
  44924. ** is made to roll it back. If an error occurs during the rollback
  44925. ** a hot journal may be left in the filesystem but no error is returned
  44926. ** to the caller.
  44927. */
  44928. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  44929. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  44930. assert( assert_pager_state(pPager) );
  44931. disable_simulated_io_errors();
  44932. sqlite3BeginBenignMalloc();
  44933. pagerFreeMapHdrs(pPager);
  44934. /* pPager->errCode = 0; */
  44935. pPager->exclusiveMode = 0;
  44936. #ifndef SQLITE_OMIT_WAL
  44937. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  44938. pPager->pWal = 0;
  44939. #endif
  44940. pager_reset(pPager);
  44941. if( MEMDB ){
  44942. pager_unlock(pPager);
  44943. }else{
  44944. /* If it is open, sync the journal file before calling UnlockAndRollback.
  44945. ** If this is not done, then an unsynced portion of the open journal
  44946. ** file may be played back into the database. If a power failure occurs
  44947. ** while this is happening, the database could become corrupt.
  44948. **
  44949. ** If an error occurs while trying to sync the journal, shift the pager
  44950. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  44951. ** database and close the journal file without attempting to roll it
  44952. ** back or finalize it. The next database user will have to do hot-journal
  44953. ** rollback before accessing the database file.
  44954. */
  44955. if( isOpen(pPager->jfd) ){
  44956. pager_error(pPager, pagerSyncHotJournal(pPager));
  44957. }
  44958. pagerUnlockAndRollback(pPager);
  44959. }
  44960. sqlite3EndBenignMalloc();
  44961. enable_simulated_io_errors();
  44962. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  44963. IOTRACE(("CLOSE %p\n", pPager))
  44964. sqlite3OsClose(pPager->jfd);
  44965. sqlite3OsClose(pPager->fd);
  44966. sqlite3PageFree(pTmp);
  44967. sqlite3PcacheClose(pPager->pPCache);
  44968. #ifdef SQLITE_HAS_CODEC
  44969. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  44970. #endif
  44971. assert( !pPager->aSavepoint && !pPager->pInJournal );
  44972. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  44973. sqlite3_free(pPager);
  44974. return SQLITE_OK;
  44975. }
  44976. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  44977. /*
  44978. ** Return the page number for page pPg.
  44979. */
  44980. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  44981. return pPg->pgno;
  44982. }
  44983. #endif
  44984. /*
  44985. ** Increment the reference count for page pPg.
  44986. */
  44987. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  44988. sqlite3PcacheRef(pPg);
  44989. }
  44990. /*
  44991. ** Sync the journal. In other words, make sure all the pages that have
  44992. ** been written to the journal have actually reached the surface of the
  44993. ** disk and can be restored in the event of a hot-journal rollback.
  44994. **
  44995. ** If the Pager.noSync flag is set, then this function is a no-op.
  44996. ** Otherwise, the actions required depend on the journal-mode and the
  44997. ** device characteristics of the file-system, as follows:
  44998. **
  44999. ** * If the journal file is an in-memory journal file, no action need
  45000. ** be taken.
  45001. **
  45002. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  45003. ** then the nRec field of the most recently written journal header
  45004. ** is updated to contain the number of journal records that have
  45005. ** been written following it. If the pager is operating in full-sync
  45006. ** mode, then the journal file is synced before this field is updated.
  45007. **
  45008. ** * If the device does not support the SEQUENTIAL property, then
  45009. ** journal file is synced.
  45010. **
  45011. ** Or, in pseudo-code:
  45012. **
  45013. ** if( NOT <in-memory journal> ){
  45014. ** if( NOT SAFE_APPEND ){
  45015. ** if( <full-sync mode> ) xSync(<journal file>);
  45016. ** <update nRec field>
  45017. ** }
  45018. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  45019. ** }
  45020. **
  45021. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  45022. ** page currently held in memory before returning SQLITE_OK. If an IO
  45023. ** error is encountered, then the IO error code is returned to the caller.
  45024. */
  45025. static int syncJournal(Pager *pPager, int newHdr){
  45026. int rc; /* Return code */
  45027. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45028. || pPager->eState==PAGER_WRITER_DBMOD
  45029. );
  45030. assert( assert_pager_state(pPager) );
  45031. assert( !pagerUseWal(pPager) );
  45032. rc = sqlite3PagerExclusiveLock(pPager);
  45033. if( rc!=SQLITE_OK ) return rc;
  45034. if( !pPager->noSync ){
  45035. assert( !pPager->tempFile );
  45036. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  45037. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  45038. assert( isOpen(pPager->jfd) );
  45039. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  45040. /* This block deals with an obscure problem. If the last connection
  45041. ** that wrote to this database was operating in persistent-journal
  45042. ** mode, then the journal file may at this point actually be larger
  45043. ** than Pager.journalOff bytes. If the next thing in the journal
  45044. ** file happens to be a journal-header (written as part of the
  45045. ** previous connection's transaction), and a crash or power-failure
  45046. ** occurs after nRec is updated but before this connection writes
  45047. ** anything else to the journal file (or commits/rolls back its
  45048. ** transaction), then SQLite may become confused when doing the
  45049. ** hot-journal rollback following recovery. It may roll back all
  45050. ** of this connections data, then proceed to rolling back the old,
  45051. ** out-of-date data that follows it. Database corruption.
  45052. **
  45053. ** To work around this, if the journal file does appear to contain
  45054. ** a valid header following Pager.journalOff, then write a 0x00
  45055. ** byte to the start of it to prevent it from being recognized.
  45056. **
  45057. ** Variable iNextHdrOffset is set to the offset at which this
  45058. ** problematic header will occur, if it exists. aMagic is used
  45059. ** as a temporary buffer to inspect the first couple of bytes of
  45060. ** the potential journal header.
  45061. */
  45062. i64 iNextHdrOffset;
  45063. u8 aMagic[8];
  45064. u8 zHeader[sizeof(aJournalMagic)+4];
  45065. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  45066. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  45067. iNextHdrOffset = journalHdrOffset(pPager);
  45068. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  45069. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  45070. static const u8 zerobyte = 0;
  45071. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  45072. }
  45073. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  45074. return rc;
  45075. }
  45076. /* Write the nRec value into the journal file header. If in
  45077. ** full-synchronous mode, sync the journal first. This ensures that
  45078. ** all data has really hit the disk before nRec is updated to mark
  45079. ** it as a candidate for rollback.
  45080. **
  45081. ** This is not required if the persistent media supports the
  45082. ** SAFE_APPEND property. Because in this case it is not possible
  45083. ** for garbage data to be appended to the file, the nRec field
  45084. ** is populated with 0xFFFFFFFF when the journal header is written
  45085. ** and never needs to be updated.
  45086. */
  45087. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  45088. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  45089. IOTRACE(("JSYNC %p\n", pPager))
  45090. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  45091. if( rc!=SQLITE_OK ) return rc;
  45092. }
  45093. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  45094. rc = sqlite3OsWrite(
  45095. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  45096. );
  45097. if( rc!=SQLITE_OK ) return rc;
  45098. }
  45099. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  45100. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  45101. IOTRACE(("JSYNC %p\n", pPager))
  45102. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  45103. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  45104. );
  45105. if( rc!=SQLITE_OK ) return rc;
  45106. }
  45107. pPager->journalHdr = pPager->journalOff;
  45108. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  45109. pPager->nRec = 0;
  45110. rc = writeJournalHdr(pPager);
  45111. if( rc!=SQLITE_OK ) return rc;
  45112. }
  45113. }else{
  45114. pPager->journalHdr = pPager->journalOff;
  45115. }
  45116. }
  45117. /* Unless the pager is in noSync mode, the journal file was just
  45118. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  45119. ** all pages.
  45120. */
  45121. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  45122. pPager->eState = PAGER_WRITER_DBMOD;
  45123. assert( assert_pager_state(pPager) );
  45124. return SQLITE_OK;
  45125. }
  45126. /*
  45127. ** The argument is the first in a linked list of dirty pages connected
  45128. ** by the PgHdr.pDirty pointer. This function writes each one of the
  45129. ** in-memory pages in the list to the database file. The argument may
  45130. ** be NULL, representing an empty list. In this case this function is
  45131. ** a no-op.
  45132. **
  45133. ** The pager must hold at least a RESERVED lock when this function
  45134. ** is called. Before writing anything to the database file, this lock
  45135. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  45136. ** SQLITE_BUSY is returned and no data is written to the database file.
  45137. **
  45138. ** If the pager is a temp-file pager and the actual file-system file
  45139. ** is not yet open, it is created and opened before any data is
  45140. ** written out.
  45141. **
  45142. ** Once the lock has been upgraded and, if necessary, the file opened,
  45143. ** the pages are written out to the database file in list order. Writing
  45144. ** a page is skipped if it meets either of the following criteria:
  45145. **
  45146. ** * The page number is greater than Pager.dbSize, or
  45147. ** * The PGHDR_DONT_WRITE flag is set on the page.
  45148. **
  45149. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  45150. ** is updated accordingly. If page 1 is written out, then the value cached
  45151. ** in Pager.dbFileVers[] is updated to match the new value stored in
  45152. ** the database file.
  45153. **
  45154. ** If everything is successful, SQLITE_OK is returned. If an IO error
  45155. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  45156. ** be obtained, SQLITE_BUSY is returned.
  45157. */
  45158. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  45159. int rc = SQLITE_OK; /* Return code */
  45160. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  45161. assert( !pagerUseWal(pPager) );
  45162. assert( pPager->eState==PAGER_WRITER_DBMOD );
  45163. assert( pPager->eLock==EXCLUSIVE_LOCK );
  45164. /* If the file is a temp-file has not yet been opened, open it now. It
  45165. ** is not possible for rc to be other than SQLITE_OK if this branch
  45166. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  45167. */
  45168. if( !isOpen(pPager->fd) ){
  45169. assert( pPager->tempFile && rc==SQLITE_OK );
  45170. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  45171. }
  45172. /* Before the first write, give the VFS a hint of what the final
  45173. ** file size will be.
  45174. */
  45175. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  45176. if( rc==SQLITE_OK
  45177. && pPager->dbHintSize<pPager->dbSize
  45178. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  45179. ){
  45180. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  45181. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  45182. pPager->dbHintSize = pPager->dbSize;
  45183. }
  45184. while( rc==SQLITE_OK && pList ){
  45185. Pgno pgno = pList->pgno;
  45186. /* If there are dirty pages in the page cache with page numbers greater
  45187. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  45188. ** make the file smaller (presumably by auto-vacuum code). Do not write
  45189. ** any such pages to the file.
  45190. **
  45191. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  45192. ** set (set by sqlite3PagerDontWrite()).
  45193. */
  45194. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  45195. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  45196. char *pData; /* Data to write */
  45197. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  45198. if( pList->pgno==1 ) pager_write_changecounter(pList);
  45199. /* Encode the database */
  45200. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  45201. /* Write out the page data. */
  45202. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  45203. /* If page 1 was just written, update Pager.dbFileVers to match
  45204. ** the value now stored in the database file. If writing this
  45205. ** page caused the database file to grow, update dbFileSize.
  45206. */
  45207. if( pgno==1 ){
  45208. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  45209. }
  45210. if( pgno>pPager->dbFileSize ){
  45211. pPager->dbFileSize = pgno;
  45212. }
  45213. pPager->aStat[PAGER_STAT_WRITE]++;
  45214. /* Update any backup objects copying the contents of this pager. */
  45215. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  45216. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  45217. PAGERID(pPager), pgno, pager_pagehash(pList)));
  45218. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  45219. PAGER_INCR(sqlite3_pager_writedb_count);
  45220. }else{
  45221. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  45222. }
  45223. pager_set_pagehash(pList);
  45224. pList = pList->pDirty;
  45225. }
  45226. return rc;
  45227. }
  45228. /*
  45229. ** Ensure that the sub-journal file is open. If it is already open, this
  45230. ** function is a no-op.
  45231. **
  45232. ** SQLITE_OK is returned if everything goes according to plan. An
  45233. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  45234. ** fails.
  45235. */
  45236. static int openSubJournal(Pager *pPager){
  45237. int rc = SQLITE_OK;
  45238. if( !isOpen(pPager->sjfd) ){
  45239. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  45240. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  45241. | SQLITE_OPEN_DELETEONCLOSE;
  45242. int nStmtSpill = sqlite3Config.nStmtSpill;
  45243. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  45244. nStmtSpill = -1;
  45245. }
  45246. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  45247. }
  45248. return rc;
  45249. }
  45250. /*
  45251. ** Append a record of the current state of page pPg to the sub-journal.
  45252. **
  45253. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  45254. ** for all open savepoints before returning.
  45255. **
  45256. ** This function returns SQLITE_OK if everything is successful, an IO
  45257. ** error code if the attempt to write to the sub-journal fails, or
  45258. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  45259. ** bitvec.
  45260. */
  45261. static int subjournalPage(PgHdr *pPg){
  45262. int rc = SQLITE_OK;
  45263. Pager *pPager = pPg->pPager;
  45264. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  45265. /* Open the sub-journal, if it has not already been opened */
  45266. assert( pPager->useJournal );
  45267. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  45268. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  45269. assert( pagerUseWal(pPager)
  45270. || pageInJournal(pPager, pPg)
  45271. || pPg->pgno>pPager->dbOrigSize
  45272. );
  45273. rc = openSubJournal(pPager);
  45274. /* If the sub-journal was opened successfully (or was already open),
  45275. ** write the journal record into the file. */
  45276. if( rc==SQLITE_OK ){
  45277. void *pData = pPg->pData;
  45278. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  45279. char *pData2;
  45280. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  45281. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  45282. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  45283. if( rc==SQLITE_OK ){
  45284. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  45285. }
  45286. }
  45287. }
  45288. if( rc==SQLITE_OK ){
  45289. pPager->nSubRec++;
  45290. assert( pPager->nSavepoint>0 );
  45291. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  45292. }
  45293. return rc;
  45294. }
  45295. static int subjournalPageIfRequired(PgHdr *pPg){
  45296. if( subjRequiresPage(pPg) ){
  45297. return subjournalPage(pPg);
  45298. }else{
  45299. return SQLITE_OK;
  45300. }
  45301. }
  45302. /*
  45303. ** This function is called by the pcache layer when it has reached some
  45304. ** soft memory limit. The first argument is a pointer to a Pager object
  45305. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  45306. ** database). The second argument is a reference to a page that is
  45307. ** currently dirty but has no outstanding references. The page
  45308. ** is always associated with the Pager object passed as the first
  45309. ** argument.
  45310. **
  45311. ** The job of this function is to make pPg clean by writing its contents
  45312. ** out to the database file, if possible. This may involve syncing the
  45313. ** journal file.
  45314. **
  45315. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  45316. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  45317. ** page clean, the IO error code is returned. If the page cannot be
  45318. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  45319. ** is returned by sqlite3PcacheMakeClean() is not called.
  45320. */
  45321. static int pagerStress(void *p, PgHdr *pPg){
  45322. Pager *pPager = (Pager *)p;
  45323. int rc = SQLITE_OK;
  45324. assert( pPg->pPager==pPager );
  45325. assert( pPg->flags&PGHDR_DIRTY );
  45326. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  45327. ** journal (and adding a new header) is not allowed. This occurs
  45328. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  45329. ** pages belonging to the same sector.
  45330. **
  45331. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  45332. ** regardless of whether or not a sync is required. This is set during
  45333. ** a rollback or by user request, respectively.
  45334. **
  45335. ** Spilling is also prohibited when in an error state since that could
  45336. ** lead to database corruption. In the current implementation it
  45337. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  45338. ** while in the error state, hence it is impossible for this routine to
  45339. ** be called in the error state. Nevertheless, we include a NEVER()
  45340. ** test for the error state as a safeguard against future changes.
  45341. */
  45342. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  45343. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  45344. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  45345. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  45346. if( pPager->doNotSpill
  45347. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  45348. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  45349. ){
  45350. return SQLITE_OK;
  45351. }
  45352. pPg->pDirty = 0;
  45353. if( pagerUseWal(pPager) ){
  45354. /* Write a single frame for this page to the log. */
  45355. rc = subjournalPageIfRequired(pPg);
  45356. if( rc==SQLITE_OK ){
  45357. rc = pagerWalFrames(pPager, pPg, 0, 0);
  45358. }
  45359. }else{
  45360. /* Sync the journal file if required. */
  45361. if( pPg->flags&PGHDR_NEED_SYNC
  45362. || pPager->eState==PAGER_WRITER_CACHEMOD
  45363. ){
  45364. rc = syncJournal(pPager, 1);
  45365. }
  45366. /* Write the contents of the page out to the database file. */
  45367. if( rc==SQLITE_OK ){
  45368. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  45369. rc = pager_write_pagelist(pPager, pPg);
  45370. }
  45371. }
  45372. /* Mark the page as clean. */
  45373. if( rc==SQLITE_OK ){
  45374. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  45375. sqlite3PcacheMakeClean(pPg);
  45376. }
  45377. return pager_error(pPager, rc);
  45378. }
  45379. /*
  45380. ** Flush all unreferenced dirty pages to disk.
  45381. */
  45382. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  45383. int rc = pPager->errCode;
  45384. if( !MEMDB ){
  45385. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  45386. assert( assert_pager_state(pPager) );
  45387. while( rc==SQLITE_OK && pList ){
  45388. PgHdr *pNext = pList->pDirty;
  45389. if( pList->nRef==0 ){
  45390. rc = pagerStress((void*)pPager, pList);
  45391. }
  45392. pList = pNext;
  45393. }
  45394. }
  45395. return rc;
  45396. }
  45397. /*
  45398. ** Allocate and initialize a new Pager object and put a pointer to it
  45399. ** in *ppPager. The pager should eventually be freed by passing it
  45400. ** to sqlite3PagerClose().
  45401. **
  45402. ** The zFilename argument is the path to the database file to open.
  45403. ** If zFilename is NULL then a randomly-named temporary file is created
  45404. ** and used as the file to be cached. Temporary files are be deleted
  45405. ** automatically when they are closed. If zFilename is ":memory:" then
  45406. ** all information is held in cache. It is never written to disk.
  45407. ** This can be used to implement an in-memory database.
  45408. **
  45409. ** The nExtra parameter specifies the number of bytes of space allocated
  45410. ** along with each page reference. This space is available to the user
  45411. ** via the sqlite3PagerGetExtra() API.
  45412. **
  45413. ** The flags argument is used to specify properties that affect the
  45414. ** operation of the pager. It should be passed some bitwise combination
  45415. ** of the PAGER_* flags.
  45416. **
  45417. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  45418. ** of the xOpen() method of the supplied VFS when opening files.
  45419. **
  45420. ** If the pager object is allocated and the specified file opened
  45421. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  45422. ** the new pager object. If an error occurs, *ppPager is set to NULL
  45423. ** and error code returned. This function may return SQLITE_NOMEM
  45424. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  45425. ** various SQLITE_IO_XXX errors.
  45426. */
  45427. SQLITE_PRIVATE int sqlite3PagerOpen(
  45428. sqlite3_vfs *pVfs, /* The virtual file system to use */
  45429. Pager **ppPager, /* OUT: Return the Pager structure here */
  45430. const char *zFilename, /* Name of the database file to open */
  45431. int nExtra, /* Extra bytes append to each in-memory page */
  45432. int flags, /* flags controlling this file */
  45433. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  45434. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  45435. ){
  45436. u8 *pPtr;
  45437. Pager *pPager = 0; /* Pager object to allocate and return */
  45438. int rc = SQLITE_OK; /* Return code */
  45439. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  45440. int memDb = 0; /* True if this is an in-memory file */
  45441. int readOnly = 0; /* True if this is a read-only file */
  45442. int journalFileSize; /* Bytes to allocate for each journal fd */
  45443. char *zPathname = 0; /* Full path to database file */
  45444. int nPathname = 0; /* Number of bytes in zPathname */
  45445. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  45446. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  45447. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  45448. const char *zUri = 0; /* URI args to copy */
  45449. int nUri = 0; /* Number of bytes of URI args at *zUri */
  45450. /* Figure out how much space is required for each journal file-handle
  45451. ** (there are two of them, the main journal and the sub-journal). */
  45452. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  45453. /* Set the output variable to NULL in case an error occurs. */
  45454. *ppPager = 0;
  45455. #ifndef SQLITE_OMIT_MEMORYDB
  45456. if( flags & PAGER_MEMORY ){
  45457. memDb = 1;
  45458. if( zFilename && zFilename[0] ){
  45459. zPathname = sqlite3DbStrDup(0, zFilename);
  45460. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  45461. nPathname = sqlite3Strlen30(zPathname);
  45462. zFilename = 0;
  45463. }
  45464. }
  45465. #endif
  45466. /* Compute and store the full pathname in an allocated buffer pointed
  45467. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  45468. ** leave both nPathname and zPathname set to 0.
  45469. */
  45470. if( zFilename && zFilename[0] ){
  45471. const char *z;
  45472. nPathname = pVfs->mxPathname+1;
  45473. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  45474. if( zPathname==0 ){
  45475. return SQLITE_NOMEM_BKPT;
  45476. }
  45477. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  45478. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  45479. nPathname = sqlite3Strlen30(zPathname);
  45480. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  45481. while( *z ){
  45482. z += sqlite3Strlen30(z)+1;
  45483. z += sqlite3Strlen30(z)+1;
  45484. }
  45485. nUri = (int)(&z[1] - zUri);
  45486. assert( nUri>=0 );
  45487. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  45488. /* This branch is taken when the journal path required by
  45489. ** the database being opened will be more than pVfs->mxPathname
  45490. ** bytes in length. This means the database cannot be opened,
  45491. ** as it will not be possible to open the journal file or even
  45492. ** check for a hot-journal before reading.
  45493. */
  45494. rc = SQLITE_CANTOPEN_BKPT;
  45495. }
  45496. if( rc!=SQLITE_OK ){
  45497. sqlite3DbFree(0, zPathname);
  45498. return rc;
  45499. }
  45500. }
  45501. /* Allocate memory for the Pager structure, PCache object, the
  45502. ** three file descriptors, the database file name and the journal
  45503. ** file name. The layout in memory is as follows:
  45504. **
  45505. ** Pager object (sizeof(Pager) bytes)
  45506. ** PCache object (sqlite3PcacheSize() bytes)
  45507. ** Database file handle (pVfs->szOsFile bytes)
  45508. ** Sub-journal file handle (journalFileSize bytes)
  45509. ** Main journal file handle (journalFileSize bytes)
  45510. ** Database file name (nPathname+1 bytes)
  45511. ** Journal file name (nPathname+8+1 bytes)
  45512. */
  45513. pPtr = (u8 *)sqlite3MallocZero(
  45514. ROUND8(sizeof(*pPager)) + /* Pager structure */
  45515. ROUND8(pcacheSize) + /* PCache object */
  45516. ROUND8(pVfs->szOsFile) + /* The main db file */
  45517. journalFileSize * 2 + /* The two journal files */
  45518. nPathname + 1 + nUri + /* zFilename */
  45519. nPathname + 8 + 2 /* zJournal */
  45520. #ifndef SQLITE_OMIT_WAL
  45521. + nPathname + 4 + 2 /* zWal */
  45522. #endif
  45523. );
  45524. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  45525. if( !pPtr ){
  45526. sqlite3DbFree(0, zPathname);
  45527. return SQLITE_NOMEM_BKPT;
  45528. }
  45529. pPager = (Pager*)(pPtr);
  45530. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  45531. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  45532. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  45533. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  45534. pPager->zFilename = (char*)(pPtr += journalFileSize);
  45535. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  45536. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  45537. if( zPathname ){
  45538. assert( nPathname>0 );
  45539. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  45540. memcpy(pPager->zFilename, zPathname, nPathname);
  45541. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  45542. memcpy(pPager->zJournal, zPathname, nPathname);
  45543. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  45544. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  45545. #ifndef SQLITE_OMIT_WAL
  45546. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  45547. memcpy(pPager->zWal, zPathname, nPathname);
  45548. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  45549. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  45550. #endif
  45551. sqlite3DbFree(0, zPathname);
  45552. }
  45553. pPager->pVfs = pVfs;
  45554. pPager->vfsFlags = vfsFlags;
  45555. /* Open the pager file.
  45556. */
  45557. if( zFilename && zFilename[0] ){
  45558. int fout = 0; /* VFS flags returned by xOpen() */
  45559. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  45560. assert( !memDb );
  45561. readOnly = (fout&SQLITE_OPEN_READONLY);
  45562. /* If the file was successfully opened for read/write access,
  45563. ** choose a default page size in case we have to create the
  45564. ** database file. The default page size is the maximum of:
  45565. **
  45566. ** + SQLITE_DEFAULT_PAGE_SIZE,
  45567. ** + The value returned by sqlite3OsSectorSize()
  45568. ** + The largest page size that can be written atomically.
  45569. */
  45570. if( rc==SQLITE_OK ){
  45571. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  45572. if( !readOnly ){
  45573. setSectorSize(pPager);
  45574. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  45575. if( szPageDflt<pPager->sectorSize ){
  45576. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  45577. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  45578. }else{
  45579. szPageDflt = (u32)pPager->sectorSize;
  45580. }
  45581. }
  45582. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45583. {
  45584. int ii;
  45585. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  45586. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  45587. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  45588. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  45589. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  45590. szPageDflt = ii;
  45591. }
  45592. }
  45593. }
  45594. #endif
  45595. }
  45596. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  45597. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  45598. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  45599. vfsFlags |= SQLITE_OPEN_READONLY;
  45600. goto act_like_temp_file;
  45601. }
  45602. }
  45603. }else{
  45604. /* If a temporary file is requested, it is not opened immediately.
  45605. ** In this case we accept the default page size and delay actually
  45606. ** opening the file until the first call to OsWrite().
  45607. **
  45608. ** This branch is also run for an in-memory database. An in-memory
  45609. ** database is the same as a temp-file that is never written out to
  45610. ** disk and uses an in-memory rollback journal.
  45611. **
  45612. ** This branch also runs for files marked as immutable.
  45613. */
  45614. act_like_temp_file:
  45615. tempFile = 1;
  45616. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  45617. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  45618. pPager->noLock = 1; /* Do no locking */
  45619. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  45620. }
  45621. /* The following call to PagerSetPagesize() serves to set the value of
  45622. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  45623. */
  45624. if( rc==SQLITE_OK ){
  45625. assert( pPager->memDb==0 );
  45626. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  45627. testcase( rc!=SQLITE_OK );
  45628. }
  45629. /* Initialize the PCache object. */
  45630. if( rc==SQLITE_OK ){
  45631. assert( nExtra<1000 );
  45632. nExtra = ROUND8(nExtra);
  45633. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  45634. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  45635. }
  45636. /* If an error occurred above, free the Pager structure and close the file.
  45637. */
  45638. if( rc!=SQLITE_OK ){
  45639. sqlite3OsClose(pPager->fd);
  45640. sqlite3PageFree(pPager->pTmpSpace);
  45641. sqlite3_free(pPager);
  45642. return rc;
  45643. }
  45644. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  45645. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  45646. pPager->useJournal = (u8)useJournal;
  45647. /* pPager->stmtOpen = 0; */
  45648. /* pPager->stmtInUse = 0; */
  45649. /* pPager->nRef = 0; */
  45650. /* pPager->stmtSize = 0; */
  45651. /* pPager->stmtJSize = 0; */
  45652. /* pPager->nPage = 0; */
  45653. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  45654. /* pPager->state = PAGER_UNLOCK; */
  45655. /* pPager->errMask = 0; */
  45656. pPager->tempFile = (u8)tempFile;
  45657. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  45658. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  45659. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  45660. pPager->exclusiveMode = (u8)tempFile;
  45661. pPager->changeCountDone = pPager->tempFile;
  45662. pPager->memDb = (u8)memDb;
  45663. pPager->readOnly = (u8)readOnly;
  45664. assert( useJournal || pPager->tempFile );
  45665. pPager->noSync = pPager->tempFile;
  45666. if( pPager->noSync ){
  45667. assert( pPager->fullSync==0 );
  45668. assert( pPager->extraSync==0 );
  45669. assert( pPager->syncFlags==0 );
  45670. assert( pPager->walSyncFlags==0 );
  45671. assert( pPager->ckptSyncFlags==0 );
  45672. }else{
  45673. pPager->fullSync = 1;
  45674. pPager->extraSync = 0;
  45675. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  45676. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  45677. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  45678. }
  45679. /* pPager->pFirst = 0; */
  45680. /* pPager->pFirstSynced = 0; */
  45681. /* pPager->pLast = 0; */
  45682. pPager->nExtra = (u16)nExtra;
  45683. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  45684. assert( isOpen(pPager->fd) || tempFile );
  45685. setSectorSize(pPager);
  45686. if( !useJournal ){
  45687. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  45688. }else if( memDb ){
  45689. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  45690. }
  45691. /* pPager->xBusyHandler = 0; */
  45692. /* pPager->pBusyHandlerArg = 0; */
  45693. pPager->xReiniter = xReinit;
  45694. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  45695. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  45696. *ppPager = pPager;
  45697. return SQLITE_OK;
  45698. }
  45699. /* Verify that the database file has not be deleted or renamed out from
  45700. ** under the pager. Return SQLITE_OK if the database is still were it ought
  45701. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  45702. ** code from sqlite3OsAccess()) if the database has gone missing.
  45703. */
  45704. static int databaseIsUnmoved(Pager *pPager){
  45705. int bHasMoved = 0;
  45706. int rc;
  45707. if( pPager->tempFile ) return SQLITE_OK;
  45708. if( pPager->dbSize==0 ) return SQLITE_OK;
  45709. assert( pPager->zFilename && pPager->zFilename[0] );
  45710. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  45711. if( rc==SQLITE_NOTFOUND ){
  45712. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  45713. ** has not been moved. That is the historical behavior of SQLite: prior to
  45714. ** version 3.8.3, it never checked */
  45715. rc = SQLITE_OK;
  45716. }else if( rc==SQLITE_OK && bHasMoved ){
  45717. rc = SQLITE_READONLY_DBMOVED;
  45718. }
  45719. return rc;
  45720. }
  45721. /*
  45722. ** This function is called after transitioning from PAGER_UNLOCK to
  45723. ** PAGER_SHARED state. It tests if there is a hot journal present in
  45724. ** the file-system for the given pager. A hot journal is one that
  45725. ** needs to be played back. According to this function, a hot-journal
  45726. ** file exists if the following criteria are met:
  45727. **
  45728. ** * The journal file exists in the file system, and
  45729. ** * No process holds a RESERVED or greater lock on the database file, and
  45730. ** * The database file itself is greater than 0 bytes in size, and
  45731. ** * The first byte of the journal file exists and is not 0x00.
  45732. **
  45733. ** If the current size of the database file is 0 but a journal file
  45734. ** exists, that is probably an old journal left over from a prior
  45735. ** database with the same name. In this case the journal file is
  45736. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  45737. ** is returned.
  45738. **
  45739. ** This routine does not check if there is a master journal filename
  45740. ** at the end of the file. If there is, and that master journal file
  45741. ** does not exist, then the journal file is not really hot. In this
  45742. ** case this routine will return a false-positive. The pager_playback()
  45743. ** routine will discover that the journal file is not really hot and
  45744. ** will not roll it back.
  45745. **
  45746. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  45747. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  45748. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  45749. ** to determine whether or not a hot-journal file exists, the IO error
  45750. ** code is returned and the value of *pExists is undefined.
  45751. */
  45752. static int hasHotJournal(Pager *pPager, int *pExists){
  45753. sqlite3_vfs * const pVfs = pPager->pVfs;
  45754. int rc = SQLITE_OK; /* Return code */
  45755. int exists = 1; /* True if a journal file is present */
  45756. int jrnlOpen = !!isOpen(pPager->jfd);
  45757. assert( pPager->useJournal );
  45758. assert( isOpen(pPager->fd) );
  45759. assert( pPager->eState==PAGER_OPEN );
  45760. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  45761. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  45762. ));
  45763. *pExists = 0;
  45764. if( !jrnlOpen ){
  45765. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  45766. }
  45767. if( rc==SQLITE_OK && exists ){
  45768. int locked = 0; /* True if some process holds a RESERVED lock */
  45769. /* Race condition here: Another process might have been holding the
  45770. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  45771. ** call above, but then delete the journal and drop the lock before
  45772. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  45773. ** is the case, this routine might think there is a hot journal when
  45774. ** in fact there is none. This results in a false-positive which will
  45775. ** be dealt with by the playback routine. Ticket #3883.
  45776. */
  45777. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  45778. if( rc==SQLITE_OK && !locked ){
  45779. Pgno nPage; /* Number of pages in database file */
  45780. rc = pagerPagecount(pPager, &nPage);
  45781. if( rc==SQLITE_OK ){
  45782. /* If the database is zero pages in size, that means that either (1) the
  45783. ** journal is a remnant from a prior database with the same name where
  45784. ** the database file but not the journal was deleted, or (2) the initial
  45785. ** transaction that populates a new database is being rolled back.
  45786. ** In either case, the journal file can be deleted. However, take care
  45787. ** not to delete the journal file if it is already open due to
  45788. ** journal_mode=PERSIST.
  45789. */
  45790. if( nPage==0 && !jrnlOpen ){
  45791. sqlite3BeginBenignMalloc();
  45792. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  45793. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  45794. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  45795. }
  45796. sqlite3EndBenignMalloc();
  45797. }else{
  45798. /* The journal file exists and no other connection has a reserved
  45799. ** or greater lock on the database file. Now check that there is
  45800. ** at least one non-zero bytes at the start of the journal file.
  45801. ** If there is, then we consider this journal to be hot. If not,
  45802. ** it can be ignored.
  45803. */
  45804. if( !jrnlOpen ){
  45805. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  45806. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  45807. }
  45808. if( rc==SQLITE_OK ){
  45809. u8 first = 0;
  45810. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  45811. if( rc==SQLITE_IOERR_SHORT_READ ){
  45812. rc = SQLITE_OK;
  45813. }
  45814. if( !jrnlOpen ){
  45815. sqlite3OsClose(pPager->jfd);
  45816. }
  45817. *pExists = (first!=0);
  45818. }else if( rc==SQLITE_CANTOPEN ){
  45819. /* If we cannot open the rollback journal file in order to see if
  45820. ** it has a zero header, that might be due to an I/O error, or
  45821. ** it might be due to the race condition described above and in
  45822. ** ticket #3883. Either way, assume that the journal is hot.
  45823. ** This might be a false positive. But if it is, then the
  45824. ** automatic journal playback and recovery mechanism will deal
  45825. ** with it under an EXCLUSIVE lock where we do not need to
  45826. ** worry so much with race conditions.
  45827. */
  45828. *pExists = 1;
  45829. rc = SQLITE_OK;
  45830. }
  45831. }
  45832. }
  45833. }
  45834. }
  45835. return rc;
  45836. }
  45837. /*
  45838. ** This function is called to obtain a shared lock on the database file.
  45839. ** It is illegal to call sqlite3PagerGet() until after this function
  45840. ** has been successfully called. If a shared-lock is already held when
  45841. ** this function is called, it is a no-op.
  45842. **
  45843. ** The following operations are also performed by this function.
  45844. **
  45845. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  45846. ** on the database file), then an attempt is made to obtain a
  45847. ** SHARED lock on the database file. Immediately after obtaining
  45848. ** the SHARED lock, the file-system is checked for a hot-journal,
  45849. ** which is played back if present. Following any hot-journal
  45850. ** rollback, the contents of the cache are validated by checking
  45851. ** the 'change-counter' field of the database file header and
  45852. ** discarded if they are found to be invalid.
  45853. **
  45854. ** 2) If the pager is running in exclusive-mode, and there are currently
  45855. ** no outstanding references to any pages, and is in the error state,
  45856. ** then an attempt is made to clear the error state by discarding
  45857. ** the contents of the page cache and rolling back any open journal
  45858. ** file.
  45859. **
  45860. ** If everything is successful, SQLITE_OK is returned. If an IO error
  45861. ** occurs while locking the database, checking for a hot-journal file or
  45862. ** rolling back a journal file, the IO error code is returned.
  45863. */
  45864. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  45865. int rc = SQLITE_OK; /* Return code */
  45866. /* This routine is only called from b-tree and only when there are no
  45867. ** outstanding pages. This implies that the pager state should either
  45868. ** be OPEN or READER. READER is only possible if the pager is or was in
  45869. ** exclusive access mode.
  45870. */
  45871. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  45872. assert( assert_pager_state(pPager) );
  45873. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  45874. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  45875. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  45876. int bHotJournal = 1; /* True if there exists a hot journal-file */
  45877. assert( !MEMDB );
  45878. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  45879. if( rc!=SQLITE_OK ){
  45880. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  45881. goto failed;
  45882. }
  45883. /* If a journal file exists, and there is no RESERVED lock on the
  45884. ** database file, then it either needs to be played back or deleted.
  45885. */
  45886. if( pPager->eLock<=SHARED_LOCK ){
  45887. rc = hasHotJournal(pPager, &bHotJournal);
  45888. }
  45889. if( rc!=SQLITE_OK ){
  45890. goto failed;
  45891. }
  45892. if( bHotJournal ){
  45893. if( pPager->readOnly ){
  45894. rc = SQLITE_READONLY_ROLLBACK;
  45895. goto failed;
  45896. }
  45897. /* Get an EXCLUSIVE lock on the database file. At this point it is
  45898. ** important that a RESERVED lock is not obtained on the way to the
  45899. ** EXCLUSIVE lock. If it were, another process might open the
  45900. ** database file, detect the RESERVED lock, and conclude that the
  45901. ** database is safe to read while this process is still rolling the
  45902. ** hot-journal back.
  45903. **
  45904. ** Because the intermediate RESERVED lock is not requested, any
  45905. ** other process attempting to access the database file will get to
  45906. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  45907. ** on the database file.
  45908. **
  45909. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  45910. ** downgraded to SHARED_LOCK before this function returns.
  45911. */
  45912. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45913. if( rc!=SQLITE_OK ){
  45914. goto failed;
  45915. }
  45916. /* If it is not already open and the file exists on disk, open the
  45917. ** journal for read/write access. Write access is required because
  45918. ** in exclusive-access mode the file descriptor will be kept open
  45919. ** and possibly used for a transaction later on. Also, write-access
  45920. ** is usually required to finalize the journal in journal_mode=persist
  45921. ** mode (and also for journal_mode=truncate on some systems).
  45922. **
  45923. ** If the journal does not exist, it usually means that some
  45924. ** other connection managed to get in and roll it back before
  45925. ** this connection obtained the exclusive lock above. Or, it
  45926. ** may mean that the pager was in the error-state when this
  45927. ** function was called and the journal file does not exist.
  45928. */
  45929. if( !isOpen(pPager->jfd) ){
  45930. sqlite3_vfs * const pVfs = pPager->pVfs;
  45931. int bExists; /* True if journal file exists */
  45932. rc = sqlite3OsAccess(
  45933. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  45934. if( rc==SQLITE_OK && bExists ){
  45935. int fout = 0;
  45936. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  45937. assert( !pPager->tempFile );
  45938. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  45939. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  45940. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  45941. rc = SQLITE_CANTOPEN_BKPT;
  45942. sqlite3OsClose(pPager->jfd);
  45943. }
  45944. }
  45945. }
  45946. /* Playback and delete the journal. Drop the database write
  45947. ** lock and reacquire the read lock. Purge the cache before
  45948. ** playing back the hot-journal so that we don't end up with
  45949. ** an inconsistent cache. Sync the hot journal before playing
  45950. ** it back since the process that crashed and left the hot journal
  45951. ** probably did not sync it and we are required to always sync
  45952. ** the journal before playing it back.
  45953. */
  45954. if( isOpen(pPager->jfd) ){
  45955. assert( rc==SQLITE_OK );
  45956. rc = pagerSyncHotJournal(pPager);
  45957. if( rc==SQLITE_OK ){
  45958. rc = pager_playback(pPager, 1);
  45959. pPager->eState = PAGER_OPEN;
  45960. }
  45961. }else if( !pPager->exclusiveMode ){
  45962. pagerUnlockDb(pPager, SHARED_LOCK);
  45963. }
  45964. if( rc!=SQLITE_OK ){
  45965. /* This branch is taken if an error occurs while trying to open
  45966. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  45967. ** pager_unlock() routine will be called before returning to unlock
  45968. ** the file. If the unlock attempt fails, then Pager.eLock must be
  45969. ** set to UNKNOWN_LOCK (see the comment above the #define for
  45970. ** UNKNOWN_LOCK above for an explanation).
  45971. **
  45972. ** In order to get pager_unlock() to do this, set Pager.eState to
  45973. ** PAGER_ERROR now. This is not actually counted as a transition
  45974. ** to ERROR state in the state diagram at the top of this file,
  45975. ** since we know that the same call to pager_unlock() will very
  45976. ** shortly transition the pager object to the OPEN state. Calling
  45977. ** assert_pager_state() would fail now, as it should not be possible
  45978. ** to be in ERROR state when there are zero outstanding page
  45979. ** references.
  45980. */
  45981. pager_error(pPager, rc);
  45982. goto failed;
  45983. }
  45984. assert( pPager->eState==PAGER_OPEN );
  45985. assert( (pPager->eLock==SHARED_LOCK)
  45986. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  45987. );
  45988. }
  45989. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  45990. /* The shared-lock has just been acquired then check to
  45991. ** see if the database has been modified. If the database has changed,
  45992. ** flush the cache. The hasHeldSharedLock flag prevents this from
  45993. ** occurring on the very first access to a file, in order to save a
  45994. ** single unnecessary sqlite3OsRead() call at the start-up.
  45995. **
  45996. ** Database changes are detected by looking at 15 bytes beginning
  45997. ** at offset 24 into the file. The first 4 of these 16 bytes are
  45998. ** a 32-bit counter that is incremented with each change. The
  45999. ** other bytes change randomly with each file change when
  46000. ** a codec is in use.
  46001. **
  46002. ** There is a vanishingly small chance that a change will not be
  46003. ** detected. The chance of an undetected change is so small that
  46004. ** it can be neglected.
  46005. */
  46006. Pgno nPage = 0;
  46007. char dbFileVers[sizeof(pPager->dbFileVers)];
  46008. rc = pagerPagecount(pPager, &nPage);
  46009. if( rc ) goto failed;
  46010. if( nPage>0 ){
  46011. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  46012. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  46013. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  46014. goto failed;
  46015. }
  46016. }else{
  46017. memset(dbFileVers, 0, sizeof(dbFileVers));
  46018. }
  46019. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  46020. pager_reset(pPager);
  46021. /* Unmap the database file. It is possible that external processes
  46022. ** may have truncated the database file and then extended it back
  46023. ** to its original size while this process was not holding a lock.
  46024. ** In this case there may exist a Pager.pMap mapping that appears
  46025. ** to be the right size but is not actually valid. Avoid this
  46026. ** possibility by unmapping the db here. */
  46027. if( USEFETCH(pPager) ){
  46028. sqlite3OsUnfetch(pPager->fd, 0, 0);
  46029. }
  46030. }
  46031. }
  46032. /* If there is a WAL file in the file-system, open this database in WAL
  46033. ** mode. Otherwise, the following function call is a no-op.
  46034. */
  46035. rc = pagerOpenWalIfPresent(pPager);
  46036. #ifndef SQLITE_OMIT_WAL
  46037. assert( pPager->pWal==0 || rc==SQLITE_OK );
  46038. #endif
  46039. }
  46040. if( pagerUseWal(pPager) ){
  46041. assert( rc==SQLITE_OK );
  46042. rc = pagerBeginReadTransaction(pPager);
  46043. }
  46044. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  46045. rc = pagerPagecount(pPager, &pPager->dbSize);
  46046. }
  46047. failed:
  46048. if( rc!=SQLITE_OK ){
  46049. assert( !MEMDB );
  46050. pager_unlock(pPager);
  46051. assert( pPager->eState==PAGER_OPEN );
  46052. }else{
  46053. pPager->eState = PAGER_READER;
  46054. pPager->hasHeldSharedLock = 1;
  46055. }
  46056. return rc;
  46057. }
  46058. /*
  46059. ** If the reference count has reached zero, rollback any active
  46060. ** transaction and unlock the pager.
  46061. **
  46062. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  46063. ** the rollback journal, the unlock is not performed and there is
  46064. ** nothing to rollback, so this routine is a no-op.
  46065. */
  46066. static void pagerUnlockIfUnused(Pager *pPager){
  46067. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  46068. pagerUnlockAndRollback(pPager);
  46069. }
  46070. }
  46071. /*
  46072. ** Acquire a reference to page number pgno in pager pPager (a page
  46073. ** reference has type DbPage*). If the requested reference is
  46074. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  46075. **
  46076. ** If the requested page is already in the cache, it is returned.
  46077. ** Otherwise, a new page object is allocated and populated with data
  46078. ** read from the database file. In some cases, the pcache module may
  46079. ** choose not to allocate a new page object and may reuse an existing
  46080. ** object with no outstanding references.
  46081. **
  46082. ** The extra data appended to a page is always initialized to zeros the
  46083. ** first time a page is loaded into memory. If the page requested is
  46084. ** already in the cache when this function is called, then the extra
  46085. ** data is left as it was when the page object was last used.
  46086. **
  46087. ** If the database image is smaller than the requested page or if a
  46088. ** non-zero value is passed as the noContent parameter and the
  46089. ** requested page is not already stored in the cache, then no
  46090. ** actual disk read occurs. In this case the memory image of the
  46091. ** page is initialized to all zeros.
  46092. **
  46093. ** If noContent is true, it means that we do not care about the contents
  46094. ** of the page. This occurs in two scenarios:
  46095. **
  46096. ** a) When reading a free-list leaf page from the database, and
  46097. **
  46098. ** b) When a savepoint is being rolled back and we need to load
  46099. ** a new page into the cache to be filled with the data read
  46100. ** from the savepoint journal.
  46101. **
  46102. ** If noContent is true, then the data returned is zeroed instead of
  46103. ** being read from the database. Additionally, the bits corresponding
  46104. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  46105. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  46106. ** savepoints are set. This means if the page is made writable at any
  46107. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  46108. ** will not be journaled. This saves IO.
  46109. **
  46110. ** The acquisition might fail for several reasons. In all cases,
  46111. ** an appropriate error code is returned and *ppPage is set to NULL.
  46112. **
  46113. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  46114. ** to find a page in the in-memory cache first. If the page is not already
  46115. ** in memory, this routine goes to disk to read it in whereas Lookup()
  46116. ** just returns 0. This routine acquires a read-lock the first time it
  46117. ** has to go to disk, and could also playback an old journal if necessary.
  46118. ** Since Lookup() never goes to disk, it never has to deal with locks
  46119. ** or journal files.
  46120. */
  46121. SQLITE_PRIVATE int sqlite3PagerGet(
  46122. Pager *pPager, /* The pager open on the database file */
  46123. Pgno pgno, /* Page number to fetch */
  46124. DbPage **ppPage, /* Write a pointer to the page here */
  46125. int flags /* PAGER_GET_XXX flags */
  46126. ){
  46127. int rc = SQLITE_OK;
  46128. PgHdr *pPg = 0;
  46129. u32 iFrame = 0; /* Frame to read from WAL file */
  46130. const int noContent = (flags & PAGER_GET_NOCONTENT);
  46131. /* It is acceptable to use a read-only (mmap) page for any page except
  46132. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  46133. ** flag was specified by the caller. And so long as the db is not a
  46134. ** temporary or in-memory database. */
  46135. const int bMmapOk = (pgno>1 && USEFETCH(pPager)
  46136. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  46137. #ifdef SQLITE_HAS_CODEC
  46138. && pPager->xCodec==0
  46139. #endif
  46140. );
  46141. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  46142. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  46143. ** test in the previous statement, and avoid testing pgno==0 in the
  46144. ** common case where pgno is large. */
  46145. if( pgno<=1 && pgno==0 ){
  46146. return SQLITE_CORRUPT_BKPT;
  46147. }
  46148. assert( pPager->eState>=PAGER_READER );
  46149. assert( assert_pager_state(pPager) );
  46150. assert( noContent==0 || bMmapOk==0 );
  46151. assert( pPager->hasHeldSharedLock==1 );
  46152. /* If the pager is in the error state, return an error immediately.
  46153. ** Otherwise, request the page from the PCache layer. */
  46154. if( pPager->errCode!=SQLITE_OK ){
  46155. rc = pPager->errCode;
  46156. }else{
  46157. if( bMmapOk && pagerUseWal(pPager) ){
  46158. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  46159. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  46160. }
  46161. if( bMmapOk && iFrame==0 ){
  46162. void *pData = 0;
  46163. rc = sqlite3OsFetch(pPager->fd,
  46164. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  46165. );
  46166. if( rc==SQLITE_OK && pData ){
  46167. if( pPager->eState>PAGER_READER ){
  46168. pPg = sqlite3PagerLookup(pPager, pgno);
  46169. }
  46170. if( pPg==0 ){
  46171. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  46172. }else{
  46173. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  46174. }
  46175. if( pPg ){
  46176. assert( rc==SQLITE_OK );
  46177. *ppPage = pPg;
  46178. return SQLITE_OK;
  46179. }
  46180. }
  46181. if( rc!=SQLITE_OK ){
  46182. goto pager_acquire_err;
  46183. }
  46184. }
  46185. {
  46186. sqlite3_pcache_page *pBase;
  46187. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  46188. if( pBase==0 ){
  46189. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  46190. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  46191. if( pBase==0 ){
  46192. pPg = *ppPage = 0;
  46193. rc = SQLITE_NOMEM_BKPT;
  46194. goto pager_acquire_err;
  46195. }
  46196. }
  46197. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  46198. assert( pPg!=0 );
  46199. }
  46200. }
  46201. if( rc!=SQLITE_OK ){
  46202. /* Either the call to sqlite3PcacheFetch() returned an error or the
  46203. ** pager was already in the error-state when this function was called.
  46204. ** Set pPg to 0 and jump to the exception handler. */
  46205. pPg = 0;
  46206. goto pager_acquire_err;
  46207. }
  46208. assert( pPg==(*ppPage) );
  46209. assert( pPg->pgno==pgno );
  46210. assert( pPg->pPager==pPager || pPg->pPager==0 );
  46211. if( pPg->pPager && !noContent ){
  46212. /* In this case the pcache already contains an initialized copy of
  46213. ** the page. Return without further ado. */
  46214. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  46215. pPager->aStat[PAGER_STAT_HIT]++;
  46216. return SQLITE_OK;
  46217. }else{
  46218. /* The pager cache has created a new page. Its content needs to
  46219. ** be initialized. */
  46220. pPg->pPager = pPager;
  46221. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  46222. ** number greater than this, or the unused locking-page, is requested. */
  46223. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  46224. rc = SQLITE_CORRUPT_BKPT;
  46225. goto pager_acquire_err;
  46226. }
  46227. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  46228. if( pgno>pPager->mxPgno ){
  46229. rc = SQLITE_FULL;
  46230. goto pager_acquire_err;
  46231. }
  46232. if( noContent ){
  46233. /* Failure to set the bits in the InJournal bit-vectors is benign.
  46234. ** It merely means that we might do some extra work to journal a
  46235. ** page that does not need to be journaled. Nevertheless, be sure
  46236. ** to test the case where a malloc error occurs while trying to set
  46237. ** a bit in a bit vector.
  46238. */
  46239. sqlite3BeginBenignMalloc();
  46240. if( pgno<=pPager->dbOrigSize ){
  46241. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  46242. testcase( rc==SQLITE_NOMEM );
  46243. }
  46244. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  46245. testcase( rc==SQLITE_NOMEM );
  46246. sqlite3EndBenignMalloc();
  46247. }
  46248. memset(pPg->pData, 0, pPager->pageSize);
  46249. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  46250. }else{
  46251. if( pagerUseWal(pPager) && bMmapOk==0 ){
  46252. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  46253. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  46254. }
  46255. assert( pPg->pPager==pPager );
  46256. pPager->aStat[PAGER_STAT_MISS]++;
  46257. rc = readDbPage(pPg, iFrame);
  46258. if( rc!=SQLITE_OK ){
  46259. goto pager_acquire_err;
  46260. }
  46261. }
  46262. pager_set_pagehash(pPg);
  46263. }
  46264. return SQLITE_OK;
  46265. pager_acquire_err:
  46266. assert( rc!=SQLITE_OK );
  46267. if( pPg ){
  46268. sqlite3PcacheDrop(pPg);
  46269. }
  46270. pagerUnlockIfUnused(pPager);
  46271. *ppPage = 0;
  46272. return rc;
  46273. }
  46274. /*
  46275. ** Acquire a page if it is already in the in-memory cache. Do
  46276. ** not read the page from disk. Return a pointer to the page,
  46277. ** or 0 if the page is not in cache.
  46278. **
  46279. ** See also sqlite3PagerGet(). The difference between this routine
  46280. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  46281. ** in the page if the page is not already in cache. This routine
  46282. ** returns NULL if the page is not in cache or if a disk I/O error
  46283. ** has ever happened.
  46284. */
  46285. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  46286. sqlite3_pcache_page *pPage;
  46287. assert( pPager!=0 );
  46288. assert( pgno!=0 );
  46289. assert( pPager->pPCache!=0 );
  46290. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  46291. assert( pPage==0 || pPager->hasHeldSharedLock );
  46292. if( pPage==0 ) return 0;
  46293. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  46294. }
  46295. /*
  46296. ** Release a page reference.
  46297. **
  46298. ** If the number of references to the page drop to zero, then the
  46299. ** page is added to the LRU list. When all references to all pages
  46300. ** are released, a rollback occurs and the lock on the database is
  46301. ** removed.
  46302. */
  46303. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  46304. Pager *pPager;
  46305. assert( pPg!=0 );
  46306. pPager = pPg->pPager;
  46307. if( pPg->flags & PGHDR_MMAP ){
  46308. pagerReleaseMapPage(pPg);
  46309. }else{
  46310. sqlite3PcacheRelease(pPg);
  46311. }
  46312. pagerUnlockIfUnused(pPager);
  46313. }
  46314. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  46315. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  46316. }
  46317. /*
  46318. ** This function is called at the start of every write transaction.
  46319. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  46320. ** file when this routine is called.
  46321. **
  46322. ** Open the journal file for pager pPager and write a journal header
  46323. ** to the start of it. If there are active savepoints, open the sub-journal
  46324. ** as well. This function is only used when the journal file is being
  46325. ** opened to write a rollback log for a transaction. It is not used
  46326. ** when opening a hot journal file to roll it back.
  46327. **
  46328. ** If the journal file is already open (as it may be in exclusive mode),
  46329. ** then this function just writes a journal header to the start of the
  46330. ** already open file.
  46331. **
  46332. ** Whether or not the journal file is opened by this function, the
  46333. ** Pager.pInJournal bitvec structure is allocated.
  46334. **
  46335. ** Return SQLITE_OK if everything is successful. Otherwise, return
  46336. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  46337. ** an IO error code if opening or writing the journal file fails.
  46338. */
  46339. static int pager_open_journal(Pager *pPager){
  46340. int rc = SQLITE_OK; /* Return code */
  46341. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  46342. assert( pPager->eState==PAGER_WRITER_LOCKED );
  46343. assert( assert_pager_state(pPager) );
  46344. assert( pPager->pInJournal==0 );
  46345. /* If already in the error state, this function is a no-op. But on
  46346. ** the other hand, this routine is never called if we are already in
  46347. ** an error state. */
  46348. if( NEVER(pPager->errCode) ) return pPager->errCode;
  46349. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  46350. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  46351. if( pPager->pInJournal==0 ){
  46352. return SQLITE_NOMEM_BKPT;
  46353. }
  46354. /* Open the journal file if it is not already open. */
  46355. if( !isOpen(pPager->jfd) ){
  46356. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  46357. sqlite3MemJournalOpen(pPager->jfd);
  46358. }else{
  46359. const int flags = /* VFS flags to open journal file */
  46360. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  46361. (pPager->tempFile ?
  46362. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  46363. (SQLITE_OPEN_MAIN_JOURNAL)
  46364. );
  46365. /* Verify that the database still has the same name as it did when
  46366. ** it was originally opened. */
  46367. rc = databaseIsUnmoved(pPager);
  46368. if( rc==SQLITE_OK ){
  46369. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  46370. rc = sqlite3JournalOpen(
  46371. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  46372. );
  46373. #else
  46374. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  46375. #endif
  46376. }
  46377. }
  46378. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  46379. }
  46380. /* Write the first journal header to the journal file and open
  46381. ** the sub-journal if necessary.
  46382. */
  46383. if( rc==SQLITE_OK ){
  46384. /* TODO: Check if all of these are really required. */
  46385. pPager->nRec = 0;
  46386. pPager->journalOff = 0;
  46387. pPager->setMaster = 0;
  46388. pPager->journalHdr = 0;
  46389. rc = writeJournalHdr(pPager);
  46390. }
  46391. }
  46392. if( rc!=SQLITE_OK ){
  46393. sqlite3BitvecDestroy(pPager->pInJournal);
  46394. pPager->pInJournal = 0;
  46395. }else{
  46396. assert( pPager->eState==PAGER_WRITER_LOCKED );
  46397. pPager->eState = PAGER_WRITER_CACHEMOD;
  46398. }
  46399. return rc;
  46400. }
  46401. /*
  46402. ** Begin a write-transaction on the specified pager object. If a
  46403. ** write-transaction has already been opened, this function is a no-op.
  46404. **
  46405. ** If the exFlag argument is false, then acquire at least a RESERVED
  46406. ** lock on the database file. If exFlag is true, then acquire at least
  46407. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  46408. ** functions need be called.
  46409. **
  46410. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  46411. ** within this transaction will be opened as an in-memory file. This
  46412. ** has no effect if the sub-journal is already opened (as it may be when
  46413. ** running in exclusive mode) or if the transaction does not require a
  46414. ** sub-journal. If the subjInMemory argument is zero, then any required
  46415. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  46416. ** or using a temporary file otherwise.
  46417. */
  46418. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  46419. int rc = SQLITE_OK;
  46420. if( pPager->errCode ) return pPager->errCode;
  46421. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  46422. pPager->subjInMemory = (u8)subjInMemory;
  46423. if( ALWAYS(pPager->eState==PAGER_READER) ){
  46424. assert( pPager->pInJournal==0 );
  46425. if( pagerUseWal(pPager) ){
  46426. /* If the pager is configured to use locking_mode=exclusive, and an
  46427. ** exclusive lock on the database is not already held, obtain it now.
  46428. */
  46429. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  46430. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  46431. if( rc!=SQLITE_OK ){
  46432. return rc;
  46433. }
  46434. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  46435. }
  46436. /* Grab the write lock on the log file. If successful, upgrade to
  46437. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  46438. ** The busy-handler is not invoked if another connection already
  46439. ** holds the write-lock. If possible, the upper layer will call it.
  46440. */
  46441. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  46442. }else{
  46443. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  46444. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  46445. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  46446. ** lock, but not when obtaining the RESERVED lock.
  46447. */
  46448. rc = pagerLockDb(pPager, RESERVED_LOCK);
  46449. if( rc==SQLITE_OK && exFlag ){
  46450. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  46451. }
  46452. }
  46453. if( rc==SQLITE_OK ){
  46454. /* Change to WRITER_LOCKED state.
  46455. **
  46456. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  46457. ** when it has an open transaction, but never to DBMOD or FINISHED.
  46458. ** This is because in those states the code to roll back savepoint
  46459. ** transactions may copy data from the sub-journal into the database
  46460. ** file as well as into the page cache. Which would be incorrect in
  46461. ** WAL mode.
  46462. */
  46463. pPager->eState = PAGER_WRITER_LOCKED;
  46464. pPager->dbHintSize = pPager->dbSize;
  46465. pPager->dbFileSize = pPager->dbSize;
  46466. pPager->dbOrigSize = pPager->dbSize;
  46467. pPager->journalOff = 0;
  46468. }
  46469. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  46470. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  46471. assert( assert_pager_state(pPager) );
  46472. }
  46473. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  46474. return rc;
  46475. }
  46476. /*
  46477. ** Write page pPg onto the end of the rollback journal.
  46478. */
  46479. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  46480. Pager *pPager = pPg->pPager;
  46481. int rc;
  46482. u32 cksum;
  46483. char *pData2;
  46484. i64 iOff = pPager->journalOff;
  46485. /* We should never write to the journal file the page that
  46486. ** contains the database locks. The following assert verifies
  46487. ** that we do not. */
  46488. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  46489. assert( pPager->journalHdr<=pPager->journalOff );
  46490. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  46491. cksum = pager_cksum(pPager, (u8*)pData2);
  46492. /* Even if an IO or diskfull error occurs while journalling the
  46493. ** page in the block above, set the need-sync flag for the page.
  46494. ** Otherwise, when the transaction is rolled back, the logic in
  46495. ** playback_one_page() will think that the page needs to be restored
  46496. ** in the database file. And if an IO error occurs while doing so,
  46497. ** then corruption may follow.
  46498. */
  46499. pPg->flags |= PGHDR_NEED_SYNC;
  46500. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  46501. if( rc!=SQLITE_OK ) return rc;
  46502. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  46503. if( rc!=SQLITE_OK ) return rc;
  46504. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  46505. if( rc!=SQLITE_OK ) return rc;
  46506. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  46507. pPager->journalOff, pPager->pageSize));
  46508. PAGER_INCR(sqlite3_pager_writej_count);
  46509. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  46510. PAGERID(pPager), pPg->pgno,
  46511. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  46512. pPager->journalOff += 8 + pPager->pageSize;
  46513. pPager->nRec++;
  46514. assert( pPager->pInJournal!=0 );
  46515. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  46516. testcase( rc==SQLITE_NOMEM );
  46517. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  46518. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  46519. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  46520. return rc;
  46521. }
  46522. /*
  46523. ** Mark a single data page as writeable. The page is written into the
  46524. ** main journal or sub-journal as required. If the page is written into
  46525. ** one of the journals, the corresponding bit is set in the
  46526. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  46527. ** of any open savepoints as appropriate.
  46528. */
  46529. static int pager_write(PgHdr *pPg){
  46530. Pager *pPager = pPg->pPager;
  46531. int rc = SQLITE_OK;
  46532. /* This routine is not called unless a write-transaction has already
  46533. ** been started. The journal file may or may not be open at this point.
  46534. ** It is never called in the ERROR state.
  46535. */
  46536. assert( pPager->eState==PAGER_WRITER_LOCKED
  46537. || pPager->eState==PAGER_WRITER_CACHEMOD
  46538. || pPager->eState==PAGER_WRITER_DBMOD
  46539. );
  46540. assert( assert_pager_state(pPager) );
  46541. assert( pPager->errCode==0 );
  46542. assert( pPager->readOnly==0 );
  46543. CHECK_PAGE(pPg);
  46544. /* The journal file needs to be opened. Higher level routines have already
  46545. ** obtained the necessary locks to begin the write-transaction, but the
  46546. ** rollback journal might not yet be open. Open it now if this is the case.
  46547. **
  46548. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  46549. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  46550. ** an error might occur and the pager would end up in WRITER_LOCKED state
  46551. ** with pages marked as dirty in the cache.
  46552. */
  46553. if( pPager->eState==PAGER_WRITER_LOCKED ){
  46554. rc = pager_open_journal(pPager);
  46555. if( rc!=SQLITE_OK ) return rc;
  46556. }
  46557. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  46558. assert( assert_pager_state(pPager) );
  46559. /* Mark the page that is about to be modified as dirty. */
  46560. sqlite3PcacheMakeDirty(pPg);
  46561. /* If a rollback journal is in use, them make sure the page that is about
  46562. ** to change is in the rollback journal, or if the page is a new page off
  46563. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  46564. */
  46565. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  46566. if( pPager->pInJournal!=0
  46567. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  46568. ){
  46569. assert( pagerUseWal(pPager)==0 );
  46570. if( pPg->pgno<=pPager->dbOrigSize ){
  46571. rc = pagerAddPageToRollbackJournal(pPg);
  46572. if( rc!=SQLITE_OK ){
  46573. return rc;
  46574. }
  46575. }else{
  46576. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  46577. pPg->flags |= PGHDR_NEED_SYNC;
  46578. }
  46579. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  46580. PAGERID(pPager), pPg->pgno,
  46581. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  46582. }
  46583. }
  46584. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  46585. ** and before writing the page into the rollback journal. Wait until now,
  46586. ** after the page has been successfully journalled, before setting the
  46587. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  46588. */
  46589. pPg->flags |= PGHDR_WRITEABLE;
  46590. /* If the statement journal is open and the page is not in it,
  46591. ** then write the page into the statement journal.
  46592. */
  46593. if( pPager->nSavepoint>0 ){
  46594. rc = subjournalPageIfRequired(pPg);
  46595. }
  46596. /* Update the database size and return. */
  46597. if( pPager->dbSize<pPg->pgno ){
  46598. pPager->dbSize = pPg->pgno;
  46599. }
  46600. return rc;
  46601. }
  46602. /*
  46603. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  46604. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  46605. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  46606. ** a sector need to be journalled in case of a power loss in the middle of
  46607. ** a write.
  46608. **
  46609. ** Usually, the sector size is less than or equal to the page size, in which
  46610. ** case pages can be individually written. This routine only runs in the
  46611. ** exceptional case where the page size is smaller than the sector size.
  46612. */
  46613. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  46614. int rc = SQLITE_OK; /* Return code */
  46615. Pgno nPageCount; /* Total number of pages in database file */
  46616. Pgno pg1; /* First page of the sector pPg is located on. */
  46617. int nPage = 0; /* Number of pages starting at pg1 to journal */
  46618. int ii; /* Loop counter */
  46619. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  46620. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  46621. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  46622. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  46623. ** a journal header to be written between the pages journaled by
  46624. ** this function.
  46625. */
  46626. assert( !MEMDB );
  46627. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  46628. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  46629. /* This trick assumes that both the page-size and sector-size are
  46630. ** an integer power of 2. It sets variable pg1 to the identifier
  46631. ** of the first page of the sector pPg is located on.
  46632. */
  46633. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  46634. nPageCount = pPager->dbSize;
  46635. if( pPg->pgno>nPageCount ){
  46636. nPage = (pPg->pgno - pg1)+1;
  46637. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  46638. nPage = nPageCount+1-pg1;
  46639. }else{
  46640. nPage = nPagePerSector;
  46641. }
  46642. assert(nPage>0);
  46643. assert(pg1<=pPg->pgno);
  46644. assert((pg1+nPage)>pPg->pgno);
  46645. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  46646. Pgno pg = pg1+ii;
  46647. PgHdr *pPage;
  46648. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  46649. if( pg!=PAGER_MJ_PGNO(pPager) ){
  46650. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  46651. if( rc==SQLITE_OK ){
  46652. rc = pager_write(pPage);
  46653. if( pPage->flags&PGHDR_NEED_SYNC ){
  46654. needSync = 1;
  46655. }
  46656. sqlite3PagerUnrefNotNull(pPage);
  46657. }
  46658. }
  46659. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  46660. if( pPage->flags&PGHDR_NEED_SYNC ){
  46661. needSync = 1;
  46662. }
  46663. sqlite3PagerUnrefNotNull(pPage);
  46664. }
  46665. }
  46666. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  46667. ** starting at pg1, then it needs to be set for all of them. Because
  46668. ** writing to any of these nPage pages may damage the others, the
  46669. ** journal file must contain sync()ed copies of all of them
  46670. ** before any of them can be written out to the database file.
  46671. */
  46672. if( rc==SQLITE_OK && needSync ){
  46673. assert( !MEMDB );
  46674. for(ii=0; ii<nPage; ii++){
  46675. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  46676. if( pPage ){
  46677. pPage->flags |= PGHDR_NEED_SYNC;
  46678. sqlite3PagerUnrefNotNull(pPage);
  46679. }
  46680. }
  46681. }
  46682. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  46683. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  46684. return rc;
  46685. }
  46686. /*
  46687. ** Mark a data page as writeable. This routine must be called before
  46688. ** making changes to a page. The caller must check the return value
  46689. ** of this function and be careful not to change any page data unless
  46690. ** this routine returns SQLITE_OK.
  46691. **
  46692. ** The difference between this function and pager_write() is that this
  46693. ** function also deals with the special case where 2 or more pages
  46694. ** fit on a single disk sector. In this case all co-resident pages
  46695. ** must have been written to the journal file before returning.
  46696. **
  46697. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  46698. ** as appropriate. Otherwise, SQLITE_OK.
  46699. */
  46700. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  46701. Pager *pPager = pPg->pPager;
  46702. assert( (pPg->flags & PGHDR_MMAP)==0 );
  46703. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  46704. assert( assert_pager_state(pPager) );
  46705. if( pPager->errCode ){
  46706. return pPager->errCode;
  46707. }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  46708. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  46709. return SQLITE_OK;
  46710. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  46711. return pagerWriteLargeSector(pPg);
  46712. }else{
  46713. return pager_write(pPg);
  46714. }
  46715. }
  46716. /*
  46717. ** Return TRUE if the page given in the argument was previously passed
  46718. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  46719. ** to change the content of the page.
  46720. */
  46721. #ifndef NDEBUG
  46722. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  46723. return pPg->flags & PGHDR_WRITEABLE;
  46724. }
  46725. #endif
  46726. /*
  46727. ** A call to this routine tells the pager that it is not necessary to
  46728. ** write the information on page pPg back to the disk, even though
  46729. ** that page might be marked as dirty. This happens, for example, when
  46730. ** the page has been added as a leaf of the freelist and so its
  46731. ** content no longer matters.
  46732. **
  46733. ** The overlying software layer calls this routine when all of the data
  46734. ** on the given page is unused. The pager marks the page as clean so
  46735. ** that it does not get written to disk.
  46736. **
  46737. ** Tests show that this optimization can quadruple the speed of large
  46738. ** DELETE operations.
  46739. */
  46740. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  46741. Pager *pPager = pPg->pPager;
  46742. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  46743. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  46744. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  46745. pPg->flags |= PGHDR_DONT_WRITE;
  46746. pPg->flags &= ~PGHDR_WRITEABLE;
  46747. pager_set_pagehash(pPg);
  46748. }
  46749. }
  46750. /*
  46751. ** This routine is called to increment the value of the database file
  46752. ** change-counter, stored as a 4-byte big-endian integer starting at
  46753. ** byte offset 24 of the pager file. The secondary change counter at
  46754. ** 92 is also updated, as is the SQLite version number at offset 96.
  46755. **
  46756. ** But this only happens if the pPager->changeCountDone flag is false.
  46757. ** To avoid excess churning of page 1, the update only happens once.
  46758. ** See also the pager_write_changecounter() routine that does an
  46759. ** unconditional update of the change counters.
  46760. **
  46761. ** If the isDirectMode flag is zero, then this is done by calling
  46762. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  46763. ** page data. In this case the file will be updated when the current
  46764. ** transaction is committed.
  46765. **
  46766. ** The isDirectMode flag may only be non-zero if the library was compiled
  46767. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  46768. ** if isDirect is non-zero, then the database file is updated directly
  46769. ** by writing an updated version of page 1 using a call to the
  46770. ** sqlite3OsWrite() function.
  46771. */
  46772. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  46773. int rc = SQLITE_OK;
  46774. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  46775. || pPager->eState==PAGER_WRITER_DBMOD
  46776. );
  46777. assert( assert_pager_state(pPager) );
  46778. /* Declare and initialize constant integer 'isDirect'. If the
  46779. ** atomic-write optimization is enabled in this build, then isDirect
  46780. ** is initialized to the value passed as the isDirectMode parameter
  46781. ** to this function. Otherwise, it is always set to zero.
  46782. **
  46783. ** The idea is that if the atomic-write optimization is not
  46784. ** enabled at compile time, the compiler can omit the tests of
  46785. ** 'isDirect' below, as well as the block enclosed in the
  46786. ** "if( isDirect )" condition.
  46787. */
  46788. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  46789. # define DIRECT_MODE 0
  46790. assert( isDirectMode==0 );
  46791. UNUSED_PARAMETER(isDirectMode);
  46792. #else
  46793. # define DIRECT_MODE isDirectMode
  46794. #endif
  46795. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  46796. PgHdr *pPgHdr; /* Reference to page 1 */
  46797. assert( !pPager->tempFile && isOpen(pPager->fd) );
  46798. /* Open page 1 of the file for writing. */
  46799. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  46800. assert( pPgHdr==0 || rc==SQLITE_OK );
  46801. /* If page one was fetched successfully, and this function is not
  46802. ** operating in direct-mode, make page 1 writable. When not in
  46803. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  46804. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  46805. */
  46806. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  46807. rc = sqlite3PagerWrite(pPgHdr);
  46808. }
  46809. if( rc==SQLITE_OK ){
  46810. /* Actually do the update of the change counter */
  46811. pager_write_changecounter(pPgHdr);
  46812. /* If running in direct mode, write the contents of page 1 to the file. */
  46813. if( DIRECT_MODE ){
  46814. const void *zBuf;
  46815. assert( pPager->dbFileSize>0 );
  46816. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  46817. if( rc==SQLITE_OK ){
  46818. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  46819. pPager->aStat[PAGER_STAT_WRITE]++;
  46820. }
  46821. if( rc==SQLITE_OK ){
  46822. /* Update the pager's copy of the change-counter. Otherwise, the
  46823. ** next time a read transaction is opened the cache will be
  46824. ** flushed (as the change-counter values will not match). */
  46825. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  46826. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  46827. pPager->changeCountDone = 1;
  46828. }
  46829. }else{
  46830. pPager->changeCountDone = 1;
  46831. }
  46832. }
  46833. /* Release the page reference. */
  46834. sqlite3PagerUnref(pPgHdr);
  46835. }
  46836. return rc;
  46837. }
  46838. /*
  46839. ** Sync the database file to disk. This is a no-op for in-memory databases
  46840. ** or pages with the Pager.noSync flag set.
  46841. **
  46842. ** If successful, or if called on a pager for which it is a no-op, this
  46843. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  46844. */
  46845. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  46846. int rc = SQLITE_OK;
  46847. if( isOpen(pPager->fd) ){
  46848. void *pArg = (void*)zMaster;
  46849. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  46850. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  46851. }
  46852. if( rc==SQLITE_OK && !pPager->noSync ){
  46853. assert( !MEMDB );
  46854. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  46855. }
  46856. return rc;
  46857. }
  46858. /*
  46859. ** This function may only be called while a write-transaction is active in
  46860. ** rollback. If the connection is in WAL mode, this call is a no-op.
  46861. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  46862. ** the database file, an attempt is made to obtain one.
  46863. **
  46864. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  46865. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  46866. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  46867. ** returned.
  46868. */
  46869. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  46870. int rc = pPager->errCode;
  46871. assert( assert_pager_state(pPager) );
  46872. if( rc==SQLITE_OK ){
  46873. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  46874. || pPager->eState==PAGER_WRITER_DBMOD
  46875. || pPager->eState==PAGER_WRITER_LOCKED
  46876. );
  46877. assert( assert_pager_state(pPager) );
  46878. if( 0==pagerUseWal(pPager) ){
  46879. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  46880. }
  46881. }
  46882. return rc;
  46883. }
  46884. /*
  46885. ** Sync the database file for the pager pPager. zMaster points to the name
  46886. ** of a master journal file that should be written into the individual
  46887. ** journal file. zMaster may be NULL, which is interpreted as no master
  46888. ** journal (a single database transaction).
  46889. **
  46890. ** This routine ensures that:
  46891. **
  46892. ** * The database file change-counter is updated,
  46893. ** * the journal is synced (unless the atomic-write optimization is used),
  46894. ** * all dirty pages are written to the database file,
  46895. ** * the database file is truncated (if required), and
  46896. ** * the database file synced.
  46897. **
  46898. ** The only thing that remains to commit the transaction is to finalize
  46899. ** (delete, truncate or zero the first part of) the journal file (or
  46900. ** delete the master journal file if specified).
  46901. **
  46902. ** Note that if zMaster==NULL, this does not overwrite a previous value
  46903. ** passed to an sqlite3PagerCommitPhaseOne() call.
  46904. **
  46905. ** If the final parameter - noSync - is true, then the database file itself
  46906. ** is not synced. The caller must call sqlite3PagerSync() directly to
  46907. ** sync the database file before calling CommitPhaseTwo() to delete the
  46908. ** journal file in this case.
  46909. */
  46910. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  46911. Pager *pPager, /* Pager object */
  46912. const char *zMaster, /* If not NULL, the master journal name */
  46913. int noSync /* True to omit the xSync on the db file */
  46914. ){
  46915. int rc = SQLITE_OK; /* Return code */
  46916. assert( pPager->eState==PAGER_WRITER_LOCKED
  46917. || pPager->eState==PAGER_WRITER_CACHEMOD
  46918. || pPager->eState==PAGER_WRITER_DBMOD
  46919. || pPager->eState==PAGER_ERROR
  46920. );
  46921. assert( assert_pager_state(pPager) );
  46922. /* If a prior error occurred, report that error again. */
  46923. if( NEVER(pPager->errCode) ) return pPager->errCode;
  46924. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  46925. pPager->zFilename, zMaster, pPager->dbSize));
  46926. /* If no database changes have been made, return early. */
  46927. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  46928. if( MEMDB ){
  46929. /* If this is an in-memory db, or no pages have been written to, or this
  46930. ** function has already been called, it is mostly a no-op. However, any
  46931. ** backup in progress needs to be restarted.
  46932. */
  46933. sqlite3BackupRestart(pPager->pBackup);
  46934. }else{
  46935. if( pagerUseWal(pPager) ){
  46936. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  46937. PgHdr *pPageOne = 0;
  46938. if( pList==0 ){
  46939. /* Must have at least one page for the WAL commit flag.
  46940. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  46941. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  46942. pList = pPageOne;
  46943. pList->pDirty = 0;
  46944. }
  46945. assert( rc==SQLITE_OK );
  46946. if( ALWAYS(pList) ){
  46947. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  46948. }
  46949. sqlite3PagerUnref(pPageOne);
  46950. if( rc==SQLITE_OK ){
  46951. sqlite3PcacheCleanAll(pPager->pPCache);
  46952. }
  46953. }else{
  46954. /* The following block updates the change-counter. Exactly how it
  46955. ** does this depends on whether or not the atomic-update optimization
  46956. ** was enabled at compile time, and if this transaction meets the
  46957. ** runtime criteria to use the operation:
  46958. **
  46959. ** * The file-system supports the atomic-write property for
  46960. ** blocks of size page-size, and
  46961. ** * This commit is not part of a multi-file transaction, and
  46962. ** * Exactly one page has been modified and store in the journal file.
  46963. **
  46964. ** If the optimization was not enabled at compile time, then the
  46965. ** pager_incr_changecounter() function is called to update the change
  46966. ** counter in 'indirect-mode'. If the optimization is compiled in but
  46967. ** is not applicable to this transaction, call sqlite3JournalCreate()
  46968. ** to make sure the journal file has actually been created, then call
  46969. ** pager_incr_changecounter() to update the change-counter in indirect
  46970. ** mode.
  46971. **
  46972. ** Otherwise, if the optimization is both enabled and applicable,
  46973. ** then call pager_incr_changecounter() to update the change-counter
  46974. ** in 'direct' mode. In this case the journal file will never be
  46975. ** created for this transaction.
  46976. */
  46977. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  46978. PgHdr *pPg;
  46979. assert( isOpen(pPager->jfd)
  46980. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  46981. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  46982. );
  46983. if( !zMaster && isOpen(pPager->jfd)
  46984. && pPager->journalOff==jrnlBufferSize(pPager)
  46985. && pPager->dbSize>=pPager->dbOrigSize
  46986. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  46987. ){
  46988. /* Update the db file change counter via the direct-write method. The
  46989. ** following call will modify the in-memory representation of page 1
  46990. ** to include the updated change counter and then write page 1
  46991. ** directly to the database file. Because of the atomic-write
  46992. ** property of the host file-system, this is safe.
  46993. */
  46994. rc = pager_incr_changecounter(pPager, 1);
  46995. }else{
  46996. rc = sqlite3JournalCreate(pPager->jfd);
  46997. if( rc==SQLITE_OK ){
  46998. rc = pager_incr_changecounter(pPager, 0);
  46999. }
  47000. }
  47001. #else
  47002. rc = pager_incr_changecounter(pPager, 0);
  47003. #endif
  47004. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  47005. /* Write the master journal name into the journal file. If a master
  47006. ** journal file name has already been written to the journal file,
  47007. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  47008. */
  47009. rc = writeMasterJournal(pPager, zMaster);
  47010. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  47011. /* Sync the journal file and write all dirty pages to the database.
  47012. ** If the atomic-update optimization is being used, this sync will not
  47013. ** create the journal file or perform any real IO.
  47014. **
  47015. ** Because the change-counter page was just modified, unless the
  47016. ** atomic-update optimization is used it is almost certain that the
  47017. ** journal requires a sync here. However, in locking_mode=exclusive
  47018. ** on a system under memory pressure it is just possible that this is
  47019. ** not the case. In this case it is likely enough that the redundant
  47020. ** xSync() call will be changed to a no-op by the OS anyhow.
  47021. */
  47022. rc = syncJournal(pPager, 0);
  47023. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  47024. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  47025. if( rc!=SQLITE_OK ){
  47026. assert( rc!=SQLITE_IOERR_BLOCKED );
  47027. goto commit_phase_one_exit;
  47028. }
  47029. sqlite3PcacheCleanAll(pPager->pPCache);
  47030. /* If the file on disk is smaller than the database image, use
  47031. ** pager_truncate to grow the file here. This can happen if the database
  47032. ** image was extended as part of the current transaction and then the
  47033. ** last page in the db image moved to the free-list. In this case the
  47034. ** last page is never written out to disk, leaving the database file
  47035. ** undersized. Fix this now if it is the case. */
  47036. if( pPager->dbSize>pPager->dbFileSize ){
  47037. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  47038. assert( pPager->eState==PAGER_WRITER_DBMOD );
  47039. rc = pager_truncate(pPager, nNew);
  47040. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  47041. }
  47042. /* Finally, sync the database file. */
  47043. if( !noSync ){
  47044. rc = sqlite3PagerSync(pPager, zMaster);
  47045. }
  47046. IOTRACE(("DBSYNC %p\n", pPager))
  47047. }
  47048. }
  47049. commit_phase_one_exit:
  47050. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  47051. pPager->eState = PAGER_WRITER_FINISHED;
  47052. }
  47053. return rc;
  47054. }
  47055. /*
  47056. ** When this function is called, the database file has been completely
  47057. ** updated to reflect the changes made by the current transaction and
  47058. ** synced to disk. The journal file still exists in the file-system
  47059. ** though, and if a failure occurs at this point it will eventually
  47060. ** be used as a hot-journal and the current transaction rolled back.
  47061. **
  47062. ** This function finalizes the journal file, either by deleting,
  47063. ** truncating or partially zeroing it, so that it cannot be used
  47064. ** for hot-journal rollback. Once this is done the transaction is
  47065. ** irrevocably committed.
  47066. **
  47067. ** If an error occurs, an IO error code is returned and the pager
  47068. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  47069. */
  47070. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  47071. int rc = SQLITE_OK; /* Return code */
  47072. /* This routine should not be called if a prior error has occurred.
  47073. ** But if (due to a coding error elsewhere in the system) it does get
  47074. ** called, just return the same error code without doing anything. */
  47075. if( NEVER(pPager->errCode) ) return pPager->errCode;
  47076. assert( pPager->eState==PAGER_WRITER_LOCKED
  47077. || pPager->eState==PAGER_WRITER_FINISHED
  47078. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  47079. );
  47080. assert( assert_pager_state(pPager) );
  47081. /* An optimization. If the database was not actually modified during
  47082. ** this transaction, the pager is running in exclusive-mode and is
  47083. ** using persistent journals, then this function is a no-op.
  47084. **
  47085. ** The start of the journal file currently contains a single journal
  47086. ** header with the nRec field set to 0. If such a journal is used as
  47087. ** a hot-journal during hot-journal rollback, 0 changes will be made
  47088. ** to the database file. So there is no need to zero the journal
  47089. ** header. Since the pager is in exclusive mode, there is no need
  47090. ** to drop any locks either.
  47091. */
  47092. if( pPager->eState==PAGER_WRITER_LOCKED
  47093. && pPager->exclusiveMode
  47094. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  47095. ){
  47096. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  47097. pPager->eState = PAGER_READER;
  47098. return SQLITE_OK;
  47099. }
  47100. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  47101. pPager->iDataVersion++;
  47102. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  47103. return pager_error(pPager, rc);
  47104. }
  47105. /*
  47106. ** If a write transaction is open, then all changes made within the
  47107. ** transaction are reverted and the current write-transaction is closed.
  47108. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  47109. ** state if an error occurs.
  47110. **
  47111. ** If the pager is already in PAGER_ERROR state when this function is called,
  47112. ** it returns Pager.errCode immediately. No work is performed in this case.
  47113. **
  47114. ** Otherwise, in rollback mode, this function performs two functions:
  47115. **
  47116. ** 1) It rolls back the journal file, restoring all database file and
  47117. ** in-memory cache pages to the state they were in when the transaction
  47118. ** was opened, and
  47119. **
  47120. ** 2) It finalizes the journal file, so that it is not used for hot
  47121. ** rollback at any point in the future.
  47122. **
  47123. ** Finalization of the journal file (task 2) is only performed if the
  47124. ** rollback is successful.
  47125. **
  47126. ** In WAL mode, all cache-entries containing data modified within the
  47127. ** current transaction are either expelled from the cache or reverted to
  47128. ** their pre-transaction state by re-reading data from the database or
  47129. ** WAL files. The WAL transaction is then closed.
  47130. */
  47131. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  47132. int rc = SQLITE_OK; /* Return code */
  47133. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  47134. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  47135. ** the pager is already in the ERROR state, the rollback is not
  47136. ** attempted here. Instead, the error code is returned to the caller.
  47137. */
  47138. assert( assert_pager_state(pPager) );
  47139. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  47140. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  47141. if( pagerUseWal(pPager) ){
  47142. int rc2;
  47143. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  47144. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  47145. if( rc==SQLITE_OK ) rc = rc2;
  47146. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  47147. int eState = pPager->eState;
  47148. rc = pager_end_transaction(pPager, 0, 0);
  47149. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  47150. /* This can happen using journal_mode=off. Move the pager to the error
  47151. ** state to indicate that the contents of the cache may not be trusted.
  47152. ** Any active readers will get SQLITE_ABORT.
  47153. */
  47154. pPager->errCode = SQLITE_ABORT;
  47155. pPager->eState = PAGER_ERROR;
  47156. return rc;
  47157. }
  47158. }else{
  47159. rc = pager_playback(pPager, 0);
  47160. }
  47161. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  47162. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  47163. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  47164. || rc==SQLITE_CANTOPEN
  47165. );
  47166. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  47167. ** cache. So call pager_error() on the way out to make any error persistent.
  47168. */
  47169. return pager_error(pPager, rc);
  47170. }
  47171. /*
  47172. ** Return TRUE if the database file is opened read-only. Return FALSE
  47173. ** if the database is (in theory) writable.
  47174. */
  47175. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  47176. return pPager->readOnly;
  47177. }
  47178. #ifdef SQLITE_DEBUG
  47179. /*
  47180. ** Return the sum of the reference counts for all pages held by pPager.
  47181. */
  47182. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  47183. return sqlite3PcacheRefCount(pPager->pPCache);
  47184. }
  47185. #endif
  47186. /*
  47187. ** Return the approximate number of bytes of memory currently
  47188. ** used by the pager and its associated cache.
  47189. */
  47190. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  47191. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  47192. + 5*sizeof(void*);
  47193. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  47194. + sqlite3MallocSize(pPager)
  47195. + pPager->pageSize;
  47196. }
  47197. /*
  47198. ** Return the number of references to the specified page.
  47199. */
  47200. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  47201. return sqlite3PcachePageRefcount(pPage);
  47202. }
  47203. #ifdef SQLITE_TEST
  47204. /*
  47205. ** This routine is used for testing and analysis only.
  47206. */
  47207. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  47208. static int a[11];
  47209. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  47210. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  47211. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  47212. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  47213. a[4] = pPager->eState;
  47214. a[5] = pPager->errCode;
  47215. a[6] = pPager->aStat[PAGER_STAT_HIT];
  47216. a[7] = pPager->aStat[PAGER_STAT_MISS];
  47217. a[8] = 0; /* Used to be pPager->nOvfl */
  47218. a[9] = pPager->nRead;
  47219. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  47220. return a;
  47221. }
  47222. #endif
  47223. /*
  47224. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  47225. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  47226. ** current cache hit or miss count, according to the value of eStat. If the
  47227. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  47228. ** returning.
  47229. */
  47230. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  47231. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  47232. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  47233. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  47234. );
  47235. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  47236. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  47237. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  47238. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  47239. if( reset ){
  47240. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  47241. }
  47242. }
  47243. /*
  47244. ** Return true if this is an in-memory pager.
  47245. */
  47246. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  47247. return MEMDB;
  47248. }
  47249. /*
  47250. ** Check that there are at least nSavepoint savepoints open. If there are
  47251. ** currently less than nSavepoints open, then open one or more savepoints
  47252. ** to make up the difference. If the number of savepoints is already
  47253. ** equal to nSavepoint, then this function is a no-op.
  47254. **
  47255. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  47256. ** occurs while opening the sub-journal file, then an IO error code is
  47257. ** returned. Otherwise, SQLITE_OK.
  47258. */
  47259. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  47260. int rc = SQLITE_OK; /* Return code */
  47261. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  47262. int ii; /* Iterator variable */
  47263. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  47264. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  47265. assert( assert_pager_state(pPager) );
  47266. assert( nSavepoint>nCurrent && pPager->useJournal );
  47267. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  47268. ** if the allocation fails. Otherwise, zero the new portion in case a
  47269. ** malloc failure occurs while populating it in the for(...) loop below.
  47270. */
  47271. aNew = (PagerSavepoint *)sqlite3Realloc(
  47272. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  47273. );
  47274. if( !aNew ){
  47275. return SQLITE_NOMEM_BKPT;
  47276. }
  47277. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  47278. pPager->aSavepoint = aNew;
  47279. /* Populate the PagerSavepoint structures just allocated. */
  47280. for(ii=nCurrent; ii<nSavepoint; ii++){
  47281. aNew[ii].nOrig = pPager->dbSize;
  47282. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  47283. aNew[ii].iOffset = pPager->journalOff;
  47284. }else{
  47285. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  47286. }
  47287. aNew[ii].iSubRec = pPager->nSubRec;
  47288. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  47289. if( !aNew[ii].pInSavepoint ){
  47290. return SQLITE_NOMEM_BKPT;
  47291. }
  47292. if( pagerUseWal(pPager) ){
  47293. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  47294. }
  47295. pPager->nSavepoint = ii+1;
  47296. }
  47297. assert( pPager->nSavepoint==nSavepoint );
  47298. assertTruncateConstraint(pPager);
  47299. return rc;
  47300. }
  47301. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  47302. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  47303. assert( assert_pager_state(pPager) );
  47304. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  47305. return pagerOpenSavepoint(pPager, nSavepoint);
  47306. }else{
  47307. return SQLITE_OK;
  47308. }
  47309. }
  47310. /*
  47311. ** This function is called to rollback or release (commit) a savepoint.
  47312. ** The savepoint to release or rollback need not be the most recently
  47313. ** created savepoint.
  47314. **
  47315. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  47316. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  47317. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  47318. ** that have occurred since the specified savepoint was created.
  47319. **
  47320. ** The savepoint to rollback or release is identified by parameter
  47321. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  47322. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  47323. ** on the most recently created savepoint. If iSavepoint is greater than
  47324. ** (Pager.nSavepoint-1), then this function is a no-op.
  47325. **
  47326. ** If a negative value is passed to this function, then the current
  47327. ** transaction is rolled back. This is different to calling
  47328. ** sqlite3PagerRollback() because this function does not terminate
  47329. ** the transaction or unlock the database, it just restores the
  47330. ** contents of the database to its original state.
  47331. **
  47332. ** In any case, all savepoints with an index greater than iSavepoint
  47333. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  47334. ** then savepoint iSavepoint is also destroyed.
  47335. **
  47336. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  47337. ** or an IO error code if an IO error occurs while rolling back a
  47338. ** savepoint. If no errors occur, SQLITE_OK is returned.
  47339. */
  47340. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  47341. int rc = pPager->errCode; /* Return code */
  47342. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  47343. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  47344. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  47345. int ii; /* Iterator variable */
  47346. int nNew; /* Number of remaining savepoints after this op. */
  47347. /* Figure out how many savepoints will still be active after this
  47348. ** operation. Store this value in nNew. Then free resources associated
  47349. ** with any savepoints that are destroyed by this operation.
  47350. */
  47351. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  47352. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  47353. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  47354. }
  47355. pPager->nSavepoint = nNew;
  47356. /* If this is a release of the outermost savepoint, truncate
  47357. ** the sub-journal to zero bytes in size. */
  47358. if( op==SAVEPOINT_RELEASE ){
  47359. if( nNew==0 && isOpen(pPager->sjfd) ){
  47360. /* Only truncate if it is an in-memory sub-journal. */
  47361. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  47362. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  47363. assert( rc==SQLITE_OK );
  47364. }
  47365. pPager->nSubRec = 0;
  47366. }
  47367. }
  47368. /* Else this is a rollback operation, playback the specified savepoint.
  47369. ** If this is a temp-file, it is possible that the journal file has
  47370. ** not yet been opened. In this case there have been no changes to
  47371. ** the database file, so the playback operation can be skipped.
  47372. */
  47373. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  47374. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  47375. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  47376. assert(rc!=SQLITE_DONE);
  47377. }
  47378. }
  47379. return rc;
  47380. }
  47381. /*
  47382. ** Return the full pathname of the database file.
  47383. **
  47384. ** Except, if the pager is in-memory only, then return an empty string if
  47385. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  47386. ** used to report the filename to the user, for compatibility with legacy
  47387. ** behavior. But when the Btree needs to know the filename for matching to
  47388. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  47389. ** participate in shared-cache.
  47390. */
  47391. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  47392. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  47393. }
  47394. /*
  47395. ** Return the VFS structure for the pager.
  47396. */
  47397. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  47398. return pPager->pVfs;
  47399. }
  47400. /*
  47401. ** Return the file handle for the database file associated
  47402. ** with the pager. This might return NULL if the file has
  47403. ** not yet been opened.
  47404. */
  47405. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  47406. return pPager->fd;
  47407. }
  47408. /*
  47409. ** Return the file handle for the journal file (if it exists).
  47410. ** This will be either the rollback journal or the WAL file.
  47411. */
  47412. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  47413. #if SQLITE_OMIT_WAL
  47414. return pPager->jfd;
  47415. #else
  47416. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  47417. #endif
  47418. }
  47419. /*
  47420. ** Return the full pathname of the journal file.
  47421. */
  47422. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  47423. return pPager->zJournal;
  47424. }
  47425. #ifdef SQLITE_HAS_CODEC
  47426. /*
  47427. ** Set or retrieve the codec for this pager
  47428. */
  47429. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  47430. Pager *pPager,
  47431. void *(*xCodec)(void*,void*,Pgno,int),
  47432. void (*xCodecSizeChng)(void*,int,int),
  47433. void (*xCodecFree)(void*),
  47434. void *pCodec
  47435. ){
  47436. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  47437. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  47438. pPager->xCodecSizeChng = xCodecSizeChng;
  47439. pPager->xCodecFree = xCodecFree;
  47440. pPager->pCodec = pCodec;
  47441. pagerReportSize(pPager);
  47442. }
  47443. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  47444. return pPager->pCodec;
  47445. }
  47446. /*
  47447. ** This function is called by the wal module when writing page content
  47448. ** into the log file.
  47449. **
  47450. ** This function returns a pointer to a buffer containing the encrypted
  47451. ** page content. If a malloc fails, this function may return NULL.
  47452. */
  47453. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  47454. void *aData = 0;
  47455. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  47456. return aData;
  47457. }
  47458. /*
  47459. ** Return the current pager state
  47460. */
  47461. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  47462. return pPager->eState;
  47463. }
  47464. #endif /* SQLITE_HAS_CODEC */
  47465. #ifndef SQLITE_OMIT_AUTOVACUUM
  47466. /*
  47467. ** Move the page pPg to location pgno in the file.
  47468. **
  47469. ** There must be no references to the page previously located at
  47470. ** pgno (which we call pPgOld) though that page is allowed to be
  47471. ** in cache. If the page previously located at pgno is not already
  47472. ** in the rollback journal, it is not put there by by this routine.
  47473. **
  47474. ** References to the page pPg remain valid. Updating any
  47475. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  47476. ** allocated along with the page) is the responsibility of the caller.
  47477. **
  47478. ** A transaction must be active when this routine is called. It used to be
  47479. ** required that a statement transaction was not active, but this restriction
  47480. ** has been removed (CREATE INDEX needs to move a page when a statement
  47481. ** transaction is active).
  47482. **
  47483. ** If the fourth argument, isCommit, is non-zero, then this page is being
  47484. ** moved as part of a database reorganization just before the transaction
  47485. ** is being committed. In this case, it is guaranteed that the database page
  47486. ** pPg refers to will not be written to again within this transaction.
  47487. **
  47488. ** This function may return SQLITE_NOMEM or an IO error code if an error
  47489. ** occurs. Otherwise, it returns SQLITE_OK.
  47490. */
  47491. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  47492. PgHdr *pPgOld; /* The page being overwritten. */
  47493. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  47494. int rc; /* Return code */
  47495. Pgno origPgno; /* The original page number */
  47496. assert( pPg->nRef>0 );
  47497. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  47498. || pPager->eState==PAGER_WRITER_DBMOD
  47499. );
  47500. assert( assert_pager_state(pPager) );
  47501. /* In order to be able to rollback, an in-memory database must journal
  47502. ** the page we are moving from.
  47503. */
  47504. if( MEMDB ){
  47505. rc = sqlite3PagerWrite(pPg);
  47506. if( rc ) return rc;
  47507. }
  47508. /* If the page being moved is dirty and has not been saved by the latest
  47509. ** savepoint, then save the current contents of the page into the
  47510. ** sub-journal now. This is required to handle the following scenario:
  47511. **
  47512. ** BEGIN;
  47513. ** <journal page X, then modify it in memory>
  47514. ** SAVEPOINT one;
  47515. ** <Move page X to location Y>
  47516. ** ROLLBACK TO one;
  47517. **
  47518. ** If page X were not written to the sub-journal here, it would not
  47519. ** be possible to restore its contents when the "ROLLBACK TO one"
  47520. ** statement were is processed.
  47521. **
  47522. ** subjournalPage() may need to allocate space to store pPg->pgno into
  47523. ** one or more savepoint bitvecs. This is the reason this function
  47524. ** may return SQLITE_NOMEM.
  47525. */
  47526. if( (pPg->flags & PGHDR_DIRTY)!=0
  47527. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  47528. ){
  47529. return rc;
  47530. }
  47531. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  47532. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  47533. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  47534. /* If the journal needs to be sync()ed before page pPg->pgno can
  47535. ** be written to, store pPg->pgno in local variable needSyncPgno.
  47536. **
  47537. ** If the isCommit flag is set, there is no need to remember that
  47538. ** the journal needs to be sync()ed before database page pPg->pgno
  47539. ** can be written to. The caller has already promised not to write to it.
  47540. */
  47541. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  47542. needSyncPgno = pPg->pgno;
  47543. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  47544. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  47545. assert( pPg->flags&PGHDR_DIRTY );
  47546. }
  47547. /* If the cache contains a page with page-number pgno, remove it
  47548. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  47549. ** page pgno before the 'move' operation, it needs to be retained
  47550. ** for the page moved there.
  47551. */
  47552. pPg->flags &= ~PGHDR_NEED_SYNC;
  47553. pPgOld = sqlite3PagerLookup(pPager, pgno);
  47554. assert( !pPgOld || pPgOld->nRef==1 );
  47555. if( pPgOld ){
  47556. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  47557. if( MEMDB ){
  47558. /* Do not discard pages from an in-memory database since we might
  47559. ** need to rollback later. Just move the page out of the way. */
  47560. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  47561. }else{
  47562. sqlite3PcacheDrop(pPgOld);
  47563. }
  47564. }
  47565. origPgno = pPg->pgno;
  47566. sqlite3PcacheMove(pPg, pgno);
  47567. sqlite3PcacheMakeDirty(pPg);
  47568. /* For an in-memory database, make sure the original page continues
  47569. ** to exist, in case the transaction needs to roll back. Use pPgOld
  47570. ** as the original page since it has already been allocated.
  47571. */
  47572. if( MEMDB ){
  47573. assert( pPgOld );
  47574. sqlite3PcacheMove(pPgOld, origPgno);
  47575. sqlite3PagerUnrefNotNull(pPgOld);
  47576. }
  47577. if( needSyncPgno ){
  47578. /* If needSyncPgno is non-zero, then the journal file needs to be
  47579. ** sync()ed before any data is written to database file page needSyncPgno.
  47580. ** Currently, no such page exists in the page-cache and the
  47581. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  47582. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  47583. ** flag.
  47584. **
  47585. ** If the attempt to load the page into the page-cache fails, (due
  47586. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  47587. ** array. Otherwise, if the page is loaded and written again in
  47588. ** this transaction, it may be written to the database file before
  47589. ** it is synced into the journal file. This way, it may end up in
  47590. ** the journal file twice, but that is not a problem.
  47591. */
  47592. PgHdr *pPgHdr;
  47593. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  47594. if( rc!=SQLITE_OK ){
  47595. if( needSyncPgno<=pPager->dbOrigSize ){
  47596. assert( pPager->pTmpSpace!=0 );
  47597. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  47598. }
  47599. return rc;
  47600. }
  47601. pPgHdr->flags |= PGHDR_NEED_SYNC;
  47602. sqlite3PcacheMakeDirty(pPgHdr);
  47603. sqlite3PagerUnrefNotNull(pPgHdr);
  47604. }
  47605. return SQLITE_OK;
  47606. }
  47607. #endif
  47608. /*
  47609. ** The page handle passed as the first argument refers to a dirty page
  47610. ** with a page number other than iNew. This function changes the page's
  47611. ** page number to iNew and sets the value of the PgHdr.flags field to
  47612. ** the value passed as the third parameter.
  47613. */
  47614. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  47615. assert( pPg->pgno!=iNew );
  47616. pPg->flags = flags;
  47617. sqlite3PcacheMove(pPg, iNew);
  47618. }
  47619. /*
  47620. ** Return a pointer to the data for the specified page.
  47621. */
  47622. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  47623. assert( pPg->nRef>0 || pPg->pPager->memDb );
  47624. return pPg->pData;
  47625. }
  47626. /*
  47627. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  47628. ** allocated along with the specified page.
  47629. */
  47630. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  47631. return pPg->pExtra;
  47632. }
  47633. /*
  47634. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  47635. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  47636. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  47637. ** the locking-mode is set to the value specified.
  47638. **
  47639. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  47640. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  47641. ** locking-mode.
  47642. */
  47643. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  47644. assert( eMode==PAGER_LOCKINGMODE_QUERY
  47645. || eMode==PAGER_LOCKINGMODE_NORMAL
  47646. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  47647. assert( PAGER_LOCKINGMODE_QUERY<0 );
  47648. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  47649. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  47650. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  47651. pPager->exclusiveMode = (u8)eMode;
  47652. }
  47653. return (int)pPager->exclusiveMode;
  47654. }
  47655. /*
  47656. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  47657. **
  47658. ** PAGER_JOURNALMODE_DELETE
  47659. ** PAGER_JOURNALMODE_TRUNCATE
  47660. ** PAGER_JOURNALMODE_PERSIST
  47661. ** PAGER_JOURNALMODE_OFF
  47662. ** PAGER_JOURNALMODE_MEMORY
  47663. ** PAGER_JOURNALMODE_WAL
  47664. **
  47665. ** The journalmode is set to the value specified if the change is allowed.
  47666. ** The change may be disallowed for the following reasons:
  47667. **
  47668. ** * An in-memory database can only have its journal_mode set to _OFF
  47669. ** or _MEMORY.
  47670. **
  47671. ** * Temporary databases cannot have _WAL journalmode.
  47672. **
  47673. ** The returned indicate the current (possibly updated) journal-mode.
  47674. */
  47675. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  47676. u8 eOld = pPager->journalMode; /* Prior journalmode */
  47677. #ifdef SQLITE_DEBUG
  47678. /* The print_pager_state() routine is intended to be used by the debugger
  47679. ** only. We invoke it once here to suppress a compiler warning. */
  47680. print_pager_state(pPager);
  47681. #endif
  47682. /* The eMode parameter is always valid */
  47683. assert( eMode==PAGER_JOURNALMODE_DELETE
  47684. || eMode==PAGER_JOURNALMODE_TRUNCATE
  47685. || eMode==PAGER_JOURNALMODE_PERSIST
  47686. || eMode==PAGER_JOURNALMODE_OFF
  47687. || eMode==PAGER_JOURNALMODE_WAL
  47688. || eMode==PAGER_JOURNALMODE_MEMORY );
  47689. /* This routine is only called from the OP_JournalMode opcode, and
  47690. ** the logic there will never allow a temporary file to be changed
  47691. ** to WAL mode.
  47692. */
  47693. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  47694. /* Do allow the journalmode of an in-memory database to be set to
  47695. ** anything other than MEMORY or OFF
  47696. */
  47697. if( MEMDB ){
  47698. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  47699. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  47700. eMode = eOld;
  47701. }
  47702. }
  47703. if( eMode!=eOld ){
  47704. /* Change the journal mode. */
  47705. assert( pPager->eState!=PAGER_ERROR );
  47706. pPager->journalMode = (u8)eMode;
  47707. /* When transistioning from TRUNCATE or PERSIST to any other journal
  47708. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  47709. ** delete the journal file.
  47710. */
  47711. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  47712. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  47713. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  47714. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  47715. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  47716. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  47717. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  47718. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  47719. /* In this case we would like to delete the journal file. If it is
  47720. ** not possible, then that is not a problem. Deleting the journal file
  47721. ** here is an optimization only.
  47722. **
  47723. ** Before deleting the journal file, obtain a RESERVED lock on the
  47724. ** database file. This ensures that the journal file is not deleted
  47725. ** while it is in use by some other client.
  47726. */
  47727. sqlite3OsClose(pPager->jfd);
  47728. if( pPager->eLock>=RESERVED_LOCK ){
  47729. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  47730. }else{
  47731. int rc = SQLITE_OK;
  47732. int state = pPager->eState;
  47733. assert( state==PAGER_OPEN || state==PAGER_READER );
  47734. if( state==PAGER_OPEN ){
  47735. rc = sqlite3PagerSharedLock(pPager);
  47736. }
  47737. if( pPager->eState==PAGER_READER ){
  47738. assert( rc==SQLITE_OK );
  47739. rc = pagerLockDb(pPager, RESERVED_LOCK);
  47740. }
  47741. if( rc==SQLITE_OK ){
  47742. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  47743. }
  47744. if( rc==SQLITE_OK && state==PAGER_READER ){
  47745. pagerUnlockDb(pPager, SHARED_LOCK);
  47746. }else if( state==PAGER_OPEN ){
  47747. pager_unlock(pPager);
  47748. }
  47749. assert( state==pPager->eState );
  47750. }
  47751. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  47752. sqlite3OsClose(pPager->jfd);
  47753. }
  47754. }
  47755. /* Return the new journal mode */
  47756. return (int)pPager->journalMode;
  47757. }
  47758. /*
  47759. ** Return the current journal mode.
  47760. */
  47761. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  47762. return (int)pPager->journalMode;
  47763. }
  47764. /*
  47765. ** Return TRUE if the pager is in a state where it is OK to change the
  47766. ** journalmode. Journalmode changes can only happen when the database
  47767. ** is unmodified.
  47768. */
  47769. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  47770. assert( assert_pager_state(pPager) );
  47771. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  47772. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  47773. return 1;
  47774. }
  47775. /*
  47776. ** Get/set the size-limit used for persistent journal files.
  47777. **
  47778. ** Setting the size limit to -1 means no limit is enforced.
  47779. ** An attempt to set a limit smaller than -1 is a no-op.
  47780. */
  47781. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  47782. if( iLimit>=-1 ){
  47783. pPager->journalSizeLimit = iLimit;
  47784. sqlite3WalLimit(pPager->pWal, iLimit);
  47785. }
  47786. return pPager->journalSizeLimit;
  47787. }
  47788. /*
  47789. ** Return a pointer to the pPager->pBackup variable. The backup module
  47790. ** in backup.c maintains the content of this variable. This module
  47791. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  47792. ** sqlite3BackupUpdate() only.
  47793. */
  47794. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  47795. return &pPager->pBackup;
  47796. }
  47797. #ifndef SQLITE_OMIT_VACUUM
  47798. /*
  47799. ** Unless this is an in-memory or temporary database, clear the pager cache.
  47800. */
  47801. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  47802. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  47803. }
  47804. #endif
  47805. #ifndef SQLITE_OMIT_WAL
  47806. /*
  47807. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  47808. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  47809. ** or wal_blocking_checkpoint() API functions.
  47810. **
  47811. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  47812. */
  47813. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  47814. int rc = SQLITE_OK;
  47815. if( pPager->pWal ){
  47816. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  47817. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  47818. pPager->pBusyHandlerArg,
  47819. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  47820. pnLog, pnCkpt
  47821. );
  47822. }
  47823. return rc;
  47824. }
  47825. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  47826. return sqlite3WalCallback(pPager->pWal);
  47827. }
  47828. /*
  47829. ** Return true if the underlying VFS for the given pager supports the
  47830. ** primitives necessary for write-ahead logging.
  47831. */
  47832. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  47833. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  47834. if( pPager->noLock ) return 0;
  47835. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  47836. }
  47837. /*
  47838. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  47839. ** is obtained instead, immediately release it.
  47840. */
  47841. static int pagerExclusiveLock(Pager *pPager){
  47842. int rc; /* Return code */
  47843. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  47844. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  47845. if( rc!=SQLITE_OK ){
  47846. /* If the attempt to grab the exclusive lock failed, release the
  47847. ** pending lock that may have been obtained instead. */
  47848. pagerUnlockDb(pPager, SHARED_LOCK);
  47849. }
  47850. return rc;
  47851. }
  47852. /*
  47853. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  47854. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  47855. ** lock on the database file and use heap-memory to store the wal-index
  47856. ** in. Otherwise, use the normal shared-memory.
  47857. */
  47858. static int pagerOpenWal(Pager *pPager){
  47859. int rc = SQLITE_OK;
  47860. assert( pPager->pWal==0 && pPager->tempFile==0 );
  47861. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  47862. /* If the pager is already in exclusive-mode, the WAL module will use
  47863. ** heap-memory for the wal-index instead of the VFS shared-memory
  47864. ** implementation. Take the exclusive lock now, before opening the WAL
  47865. ** file, to make sure this is safe.
  47866. */
  47867. if( pPager->exclusiveMode ){
  47868. rc = pagerExclusiveLock(pPager);
  47869. }
  47870. /* Open the connection to the log file. If this operation fails,
  47871. ** (e.g. due to malloc() failure), return an error code.
  47872. */
  47873. if( rc==SQLITE_OK ){
  47874. rc = sqlite3WalOpen(pPager->pVfs,
  47875. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  47876. pPager->journalSizeLimit, &pPager->pWal
  47877. );
  47878. }
  47879. pagerFixMaplimit(pPager);
  47880. return rc;
  47881. }
  47882. /*
  47883. ** The caller must be holding a SHARED lock on the database file to call
  47884. ** this function.
  47885. **
  47886. ** If the pager passed as the first argument is open on a real database
  47887. ** file (not a temp file or an in-memory database), and the WAL file
  47888. ** is not already open, make an attempt to open it now. If successful,
  47889. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  47890. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  47891. ** not modified in either case.
  47892. **
  47893. ** If the pager is open on a temp-file (or in-memory database), or if
  47894. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  47895. ** without doing anything.
  47896. */
  47897. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  47898. Pager *pPager, /* Pager object */
  47899. int *pbOpen /* OUT: Set to true if call is a no-op */
  47900. ){
  47901. int rc = SQLITE_OK; /* Return code */
  47902. assert( assert_pager_state(pPager) );
  47903. assert( pPager->eState==PAGER_OPEN || pbOpen );
  47904. assert( pPager->eState==PAGER_READER || !pbOpen );
  47905. assert( pbOpen==0 || *pbOpen==0 );
  47906. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  47907. if( !pPager->tempFile && !pPager->pWal ){
  47908. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  47909. /* Close any rollback journal previously open */
  47910. sqlite3OsClose(pPager->jfd);
  47911. rc = pagerOpenWal(pPager);
  47912. if( rc==SQLITE_OK ){
  47913. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  47914. pPager->eState = PAGER_OPEN;
  47915. }
  47916. }else{
  47917. *pbOpen = 1;
  47918. }
  47919. return rc;
  47920. }
  47921. /*
  47922. ** This function is called to close the connection to the log file prior
  47923. ** to switching from WAL to rollback mode.
  47924. **
  47925. ** Before closing the log file, this function attempts to take an
  47926. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  47927. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  47928. ** If successful, the EXCLUSIVE lock is not released before returning.
  47929. */
  47930. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  47931. int rc = SQLITE_OK;
  47932. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  47933. /* If the log file is not already open, but does exist in the file-system,
  47934. ** it may need to be checkpointed before the connection can switch to
  47935. ** rollback mode. Open it now so this can happen.
  47936. */
  47937. if( !pPager->pWal ){
  47938. int logexists = 0;
  47939. rc = pagerLockDb(pPager, SHARED_LOCK);
  47940. if( rc==SQLITE_OK ){
  47941. rc = sqlite3OsAccess(
  47942. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  47943. );
  47944. }
  47945. if( rc==SQLITE_OK && logexists ){
  47946. rc = pagerOpenWal(pPager);
  47947. }
  47948. }
  47949. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  47950. ** the database file, the log and log-summary files will be deleted.
  47951. */
  47952. if( rc==SQLITE_OK && pPager->pWal ){
  47953. rc = pagerExclusiveLock(pPager);
  47954. if( rc==SQLITE_OK ){
  47955. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  47956. pPager->pageSize, (u8*)pPager->pTmpSpace);
  47957. pPager->pWal = 0;
  47958. pagerFixMaplimit(pPager);
  47959. }
  47960. }
  47961. return rc;
  47962. }
  47963. #ifdef SQLITE_ENABLE_SNAPSHOT
  47964. /*
  47965. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  47966. ** currently open. Otherwise, return an error.
  47967. */
  47968. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  47969. int rc = SQLITE_ERROR;
  47970. if( pPager->pWal ){
  47971. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  47972. }
  47973. return rc;
  47974. }
  47975. /*
  47976. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  47977. ** read transaction is opened, attempt to read from the snapshot it
  47978. ** identifies. If this is not a WAL database, return an error.
  47979. */
  47980. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  47981. int rc = SQLITE_OK;
  47982. if( pPager->pWal ){
  47983. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  47984. }else{
  47985. rc = SQLITE_ERROR;
  47986. }
  47987. return rc;
  47988. }
  47989. #endif /* SQLITE_ENABLE_SNAPSHOT */
  47990. #endif /* !SQLITE_OMIT_WAL */
  47991. #ifdef SQLITE_ENABLE_ZIPVFS
  47992. /*
  47993. ** A read-lock must be held on the pager when this function is called. If
  47994. ** the pager is in WAL mode and the WAL file currently contains one or more
  47995. ** frames, return the size in bytes of the page images stored within the
  47996. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  47997. ** is empty, return 0.
  47998. */
  47999. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  48000. assert( pPager->eState>=PAGER_READER );
  48001. return sqlite3WalFramesize(pPager->pWal);
  48002. }
  48003. #endif
  48004. #endif /* SQLITE_OMIT_DISKIO */
  48005. /************** End of pager.c ***********************************************/
  48006. /************** Begin file wal.c *********************************************/
  48007. /*
  48008. ** 2010 February 1
  48009. **
  48010. ** The author disclaims copyright to this source code. In place of
  48011. ** a legal notice, here is a blessing:
  48012. **
  48013. ** May you do good and not evil.
  48014. ** May you find forgiveness for yourself and forgive others.
  48015. ** May you share freely, never taking more than you give.
  48016. **
  48017. *************************************************************************
  48018. **
  48019. ** This file contains the implementation of a write-ahead log (WAL) used in
  48020. ** "journal_mode=WAL" mode.
  48021. **
  48022. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  48023. **
  48024. ** A WAL file consists of a header followed by zero or more "frames".
  48025. ** Each frame records the revised content of a single page from the
  48026. ** database file. All changes to the database are recorded by writing
  48027. ** frames into the WAL. Transactions commit when a frame is written that
  48028. ** contains a commit marker. A single WAL can and usually does record
  48029. ** multiple transactions. Periodically, the content of the WAL is
  48030. ** transferred back into the database file in an operation called a
  48031. ** "checkpoint".
  48032. **
  48033. ** A single WAL file can be used multiple times. In other words, the
  48034. ** WAL can fill up with frames and then be checkpointed and then new
  48035. ** frames can overwrite the old ones. A WAL always grows from beginning
  48036. ** toward the end. Checksums and counters attached to each frame are
  48037. ** used to determine which frames within the WAL are valid and which
  48038. ** are leftovers from prior checkpoints.
  48039. **
  48040. ** The WAL header is 32 bytes in size and consists of the following eight
  48041. ** big-endian 32-bit unsigned integer values:
  48042. **
  48043. ** 0: Magic number. 0x377f0682 or 0x377f0683
  48044. ** 4: File format version. Currently 3007000
  48045. ** 8: Database page size. Example: 1024
  48046. ** 12: Checkpoint sequence number
  48047. ** 16: Salt-1, random integer incremented with each checkpoint
  48048. ** 20: Salt-2, a different random integer changing with each ckpt
  48049. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  48050. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  48051. **
  48052. ** Immediately following the wal-header are zero or more frames. Each
  48053. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  48054. ** of page data. The frame-header is six big-endian 32-bit unsigned
  48055. ** integer values, as follows:
  48056. **
  48057. ** 0: Page number.
  48058. ** 4: For commit records, the size of the database image in pages
  48059. ** after the commit. For all other records, zero.
  48060. ** 8: Salt-1 (copied from the header)
  48061. ** 12: Salt-2 (copied from the header)
  48062. ** 16: Checksum-1.
  48063. ** 20: Checksum-2.
  48064. **
  48065. ** A frame is considered valid if and only if the following conditions are
  48066. ** true:
  48067. **
  48068. ** (1) The salt-1 and salt-2 values in the frame-header match
  48069. ** salt values in the wal-header
  48070. **
  48071. ** (2) The checksum values in the final 8 bytes of the frame-header
  48072. ** exactly match the checksum computed consecutively on the
  48073. ** WAL header and the first 8 bytes and the content of all frames
  48074. ** up to and including the current frame.
  48075. **
  48076. ** The checksum is computed using 32-bit big-endian integers if the
  48077. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  48078. ** is computed using little-endian if the magic number is 0x377f0682.
  48079. ** The checksum values are always stored in the frame header in a
  48080. ** big-endian format regardless of which byte order is used to compute
  48081. ** the checksum. The checksum is computed by interpreting the input as
  48082. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  48083. ** algorithm used for the checksum is as follows:
  48084. **
  48085. ** for i from 0 to n-1 step 2:
  48086. ** s0 += x[i] + s1;
  48087. ** s1 += x[i+1] + s0;
  48088. ** endfor
  48089. **
  48090. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  48091. ** in reverse order (the largest fibonacci weight occurs on the first element
  48092. ** of the sequence being summed.) The s1 value spans all 32-bit
  48093. ** terms of the sequence whereas s0 omits the final term.
  48094. **
  48095. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  48096. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  48097. ** The VFS.xSync operations serve as write barriers - all writes launched
  48098. ** before the xSync must complete before any write that launches after the
  48099. ** xSync begins.
  48100. **
  48101. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  48102. ** value is randomized. This prevents old and new frames in the WAL from
  48103. ** being considered valid at the same time and being checkpointing together
  48104. ** following a crash.
  48105. **
  48106. ** READER ALGORITHM
  48107. **
  48108. ** To read a page from the database (call it page number P), a reader
  48109. ** first checks the WAL to see if it contains page P. If so, then the
  48110. ** last valid instance of page P that is a followed by a commit frame
  48111. ** or is a commit frame itself becomes the value read. If the WAL
  48112. ** contains no copies of page P that are valid and which are a commit
  48113. ** frame or are followed by a commit frame, then page P is read from
  48114. ** the database file.
  48115. **
  48116. ** To start a read transaction, the reader records the index of the last
  48117. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  48118. ** for all subsequent read operations. New transactions can be appended
  48119. ** to the WAL, but as long as the reader uses its original mxFrame value
  48120. ** and ignores the newly appended content, it will see a consistent snapshot
  48121. ** of the database from a single point in time. This technique allows
  48122. ** multiple concurrent readers to view different versions of the database
  48123. ** content simultaneously.
  48124. **
  48125. ** The reader algorithm in the previous paragraphs works correctly, but
  48126. ** because frames for page P can appear anywhere within the WAL, the
  48127. ** reader has to scan the entire WAL looking for page P frames. If the
  48128. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  48129. ** and read performance suffers. To overcome this problem, a separate
  48130. ** data structure called the wal-index is maintained to expedite the
  48131. ** search for frames of a particular page.
  48132. **
  48133. ** WAL-INDEX FORMAT
  48134. **
  48135. ** Conceptually, the wal-index is shared memory, though VFS implementations
  48136. ** might choose to implement the wal-index using a mmapped file. Because
  48137. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  48138. ** on a network filesystem. All users of the database must be able to
  48139. ** share memory.
  48140. **
  48141. ** The wal-index is transient. After a crash, the wal-index can (and should
  48142. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  48143. ** to either truncate or zero the header of the wal-index when the last
  48144. ** connection to it closes. Because the wal-index is transient, it can
  48145. ** use an architecture-specific format; it does not have to be cross-platform.
  48146. ** Hence, unlike the database and WAL file formats which store all values
  48147. ** as big endian, the wal-index can store multi-byte values in the native
  48148. ** byte order of the host computer.
  48149. **
  48150. ** The purpose of the wal-index is to answer this question quickly: Given
  48151. ** a page number P and a maximum frame index M, return the index of the
  48152. ** last frame in the wal before frame M for page P in the WAL, or return
  48153. ** NULL if there are no frames for page P in the WAL prior to M.
  48154. **
  48155. ** The wal-index consists of a header region, followed by an one or
  48156. ** more index blocks.
  48157. **
  48158. ** The wal-index header contains the total number of frames within the WAL
  48159. ** in the mxFrame field.
  48160. **
  48161. ** Each index block except for the first contains information on
  48162. ** HASHTABLE_NPAGE frames. The first index block contains information on
  48163. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  48164. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  48165. ** first index block are the same size as all other index blocks in the
  48166. ** wal-index.
  48167. **
  48168. ** Each index block contains two sections, a page-mapping that contains the
  48169. ** database page number associated with each wal frame, and a hash-table
  48170. ** that allows readers to query an index block for a specific page number.
  48171. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  48172. ** for the first index block) 32-bit page numbers. The first entry in the
  48173. ** first index-block contains the database page number corresponding to the
  48174. ** first frame in the WAL file. The first entry in the second index block
  48175. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  48176. ** the log, and so on.
  48177. **
  48178. ** The last index block in a wal-index usually contains less than the full
  48179. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  48180. ** depending on the contents of the WAL file. This does not change the
  48181. ** allocated size of the page-mapping array - the page-mapping array merely
  48182. ** contains unused entries.
  48183. **
  48184. ** Even without using the hash table, the last frame for page P
  48185. ** can be found by scanning the page-mapping sections of each index block
  48186. ** starting with the last index block and moving toward the first, and
  48187. ** within each index block, starting at the end and moving toward the
  48188. ** beginning. The first entry that equals P corresponds to the frame
  48189. ** holding the content for that page.
  48190. **
  48191. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  48192. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  48193. ** hash table for each page number in the mapping section, so the hash
  48194. ** table is never more than half full. The expected number of collisions
  48195. ** prior to finding a match is 1. Each entry of the hash table is an
  48196. ** 1-based index of an entry in the mapping section of the same
  48197. ** index block. Let K be the 1-based index of the largest entry in
  48198. ** the mapping section. (For index blocks other than the last, K will
  48199. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  48200. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  48201. ** contain a value of 0.
  48202. **
  48203. ** To look for page P in the hash table, first compute a hash iKey on
  48204. ** P as follows:
  48205. **
  48206. ** iKey = (P * 383) % HASHTABLE_NSLOT
  48207. **
  48208. ** Then start scanning entries of the hash table, starting with iKey
  48209. ** (wrapping around to the beginning when the end of the hash table is
  48210. ** reached) until an unused hash slot is found. Let the first unused slot
  48211. ** be at index iUnused. (iUnused might be less than iKey if there was
  48212. ** wrap-around.) Because the hash table is never more than half full,
  48213. ** the search is guaranteed to eventually hit an unused entry. Let
  48214. ** iMax be the value between iKey and iUnused, closest to iUnused,
  48215. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  48216. ** no hash slot such that aHash[i]==p) then page P is not in the
  48217. ** current index block. Otherwise the iMax-th mapping entry of the
  48218. ** current index block corresponds to the last entry that references
  48219. ** page P.
  48220. **
  48221. ** A hash search begins with the last index block and moves toward the
  48222. ** first index block, looking for entries corresponding to page P. On
  48223. ** average, only two or three slots in each index block need to be
  48224. ** examined in order to either find the last entry for page P, or to
  48225. ** establish that no such entry exists in the block. Each index block
  48226. ** holds over 4000 entries. So two or three index blocks are sufficient
  48227. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  48228. ** comparisons (on average) suffice to either locate a frame in the
  48229. ** WAL or to establish that the frame does not exist in the WAL. This
  48230. ** is much faster than scanning the entire 10MB WAL.
  48231. **
  48232. ** Note that entries are added in order of increasing K. Hence, one
  48233. ** reader might be using some value K0 and a second reader that started
  48234. ** at a later time (after additional transactions were added to the WAL
  48235. ** and to the wal-index) might be using a different value K1, where K1>K0.
  48236. ** Both readers can use the same hash table and mapping section to get
  48237. ** the correct result. There may be entries in the hash table with
  48238. ** K>K0 but to the first reader, those entries will appear to be unused
  48239. ** slots in the hash table and so the first reader will get an answer as
  48240. ** if no values greater than K0 had ever been inserted into the hash table
  48241. ** in the first place - which is what reader one wants. Meanwhile, the
  48242. ** second reader using K1 will see additional values that were inserted
  48243. ** later, which is exactly what reader two wants.
  48244. **
  48245. ** When a rollback occurs, the value of K is decreased. Hash table entries
  48246. ** that correspond to frames greater than the new K value are removed
  48247. ** from the hash table at this point.
  48248. */
  48249. #ifndef SQLITE_OMIT_WAL
  48250. /* #include "wal.h" */
  48251. /*
  48252. ** Trace output macros
  48253. */
  48254. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48255. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  48256. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  48257. #else
  48258. # define WALTRACE(X)
  48259. #endif
  48260. /*
  48261. ** The maximum (and only) versions of the wal and wal-index formats
  48262. ** that may be interpreted by this version of SQLite.
  48263. **
  48264. ** If a client begins recovering a WAL file and finds that (a) the checksum
  48265. ** values in the wal-header are correct and (b) the version field is not
  48266. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  48267. **
  48268. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  48269. ** checksum test is successful) and finds that the version field is not
  48270. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  48271. ** returns SQLITE_CANTOPEN.
  48272. */
  48273. #define WAL_MAX_VERSION 3007000
  48274. #define WALINDEX_MAX_VERSION 3007000
  48275. /*
  48276. ** Indices of various locking bytes. WAL_NREADER is the number
  48277. ** of available reader locks and should be at least 3. The default
  48278. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  48279. */
  48280. #define WAL_WRITE_LOCK 0
  48281. #define WAL_ALL_BUT_WRITE 1
  48282. #define WAL_CKPT_LOCK 1
  48283. #define WAL_RECOVER_LOCK 2
  48284. #define WAL_READ_LOCK(I) (3+(I))
  48285. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  48286. /* Object declarations */
  48287. typedef struct WalIndexHdr WalIndexHdr;
  48288. typedef struct WalIterator WalIterator;
  48289. typedef struct WalCkptInfo WalCkptInfo;
  48290. /*
  48291. ** The following object holds a copy of the wal-index header content.
  48292. **
  48293. ** The actual header in the wal-index consists of two copies of this
  48294. ** object followed by one instance of the WalCkptInfo object.
  48295. ** For all versions of SQLite through 3.10.0 and probably beyond,
  48296. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  48297. ** the total header size is 136 bytes.
  48298. **
  48299. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  48300. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  48301. ** added in 3.7.1 when support for 64K pages was added.
  48302. */
  48303. struct WalIndexHdr {
  48304. u32 iVersion; /* Wal-index version */
  48305. u32 unused; /* Unused (padding) field */
  48306. u32 iChange; /* Counter incremented each transaction */
  48307. u8 isInit; /* 1 when initialized */
  48308. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  48309. u16 szPage; /* Database page size in bytes. 1==64K */
  48310. u32 mxFrame; /* Index of last valid frame in the WAL */
  48311. u32 nPage; /* Size of database in pages */
  48312. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  48313. u32 aSalt[2]; /* Two salt values copied from WAL header */
  48314. u32 aCksum[2]; /* Checksum over all prior fields */
  48315. };
  48316. /*
  48317. ** A copy of the following object occurs in the wal-index immediately
  48318. ** following the second copy of the WalIndexHdr. This object stores
  48319. ** information used by checkpoint.
  48320. **
  48321. ** nBackfill is the number of frames in the WAL that have been written
  48322. ** back into the database. (We call the act of moving content from WAL to
  48323. ** database "backfilling".) The nBackfill number is never greater than
  48324. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  48325. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  48326. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  48327. ** mxFrame back to zero when the WAL is reset.
  48328. **
  48329. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  48330. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  48331. ** the nBackfillAttempted is set before any backfilling is done and the
  48332. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  48333. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  48334. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  48335. **
  48336. ** The aLock[] field is a set of bytes used for locking. These bytes should
  48337. ** never be read or written.
  48338. **
  48339. ** There is one entry in aReadMark[] for each reader lock. If a reader
  48340. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  48341. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  48342. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  48343. ** a special case; its value is never used and it exists as a place-holder
  48344. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  48345. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  48346. ** directly from the database.
  48347. **
  48348. ** The value of aReadMark[K] may only be changed by a thread that
  48349. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  48350. ** aReadMark[K] cannot changed while there is a reader is using that mark
  48351. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  48352. **
  48353. ** The checkpointer may only transfer frames from WAL to database where
  48354. ** the frame numbers are less than or equal to every aReadMark[] that is
  48355. ** in use (that is, every aReadMark[j] for which there is a corresponding
  48356. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  48357. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  48358. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  48359. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  48360. ** in the WAL has been backfilled into the database) then new readers
  48361. ** will choose aReadMark[0] which has value 0 and hence such reader will
  48362. ** get all their all content directly from the database file and ignore
  48363. ** the WAL.
  48364. **
  48365. ** Writers normally append new frames to the end of the WAL. However,
  48366. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  48367. ** written back into the database) and if no readers are using the WAL
  48368. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  48369. ** the writer will first "reset" the WAL back to the beginning and start
  48370. ** writing new content beginning at frame 1.
  48371. **
  48372. ** We assume that 32-bit loads are atomic and so no locks are needed in
  48373. ** order to read from any aReadMark[] entries.
  48374. */
  48375. struct WalCkptInfo {
  48376. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  48377. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  48378. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  48379. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  48380. u32 notUsed0; /* Available for future enhancements */
  48381. };
  48382. #define READMARK_NOT_USED 0xffffffff
  48383. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  48384. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  48385. ** only support mandatory file-locks, we do not read or write data
  48386. ** from the region of the file on which locks are applied.
  48387. */
  48388. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  48389. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  48390. /* Size of header before each frame in wal */
  48391. #define WAL_FRAME_HDRSIZE 24
  48392. /* Size of write ahead log header, including checksum. */
  48393. /* #define WAL_HDRSIZE 24 */
  48394. #define WAL_HDRSIZE 32
  48395. /* WAL magic value. Either this value, or the same value with the least
  48396. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  48397. ** big-endian format in the first 4 bytes of a WAL file.
  48398. **
  48399. ** If the LSB is set, then the checksums for each frame within the WAL
  48400. ** file are calculated by treating all data as an array of 32-bit
  48401. ** big-endian words. Otherwise, they are calculated by interpreting
  48402. ** all data as 32-bit little-endian words.
  48403. */
  48404. #define WAL_MAGIC 0x377f0682
  48405. /*
  48406. ** Return the offset of frame iFrame in the write-ahead log file,
  48407. ** assuming a database page size of szPage bytes. The offset returned
  48408. ** is to the start of the write-ahead log frame-header.
  48409. */
  48410. #define walFrameOffset(iFrame, szPage) ( \
  48411. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  48412. )
  48413. /*
  48414. ** An open write-ahead log file is represented by an instance of the
  48415. ** following object.
  48416. */
  48417. struct Wal {
  48418. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  48419. sqlite3_file *pDbFd; /* File handle for the database file */
  48420. sqlite3_file *pWalFd; /* File handle for WAL file */
  48421. u32 iCallback; /* Value to pass to log callback (or 0) */
  48422. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  48423. int nWiData; /* Size of array apWiData */
  48424. int szFirstBlock; /* Size of first block written to WAL file */
  48425. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  48426. u32 szPage; /* Database page size */
  48427. i16 readLock; /* Which read lock is being held. -1 for none */
  48428. u8 syncFlags; /* Flags to use to sync header writes */
  48429. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  48430. u8 writeLock; /* True if in a write transaction */
  48431. u8 ckptLock; /* True if holding a checkpoint lock */
  48432. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  48433. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  48434. u8 syncHeader; /* Fsync the WAL header if true */
  48435. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  48436. WalIndexHdr hdr; /* Wal-index header for current transaction */
  48437. u32 minFrame; /* Ignore wal frames before this one */
  48438. u32 iReCksum; /* On commit, recalculate checksums from here */
  48439. const char *zWalName; /* Name of WAL file */
  48440. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  48441. #ifdef SQLITE_DEBUG
  48442. u8 lockError; /* True if a locking error has occurred */
  48443. #endif
  48444. #ifdef SQLITE_ENABLE_SNAPSHOT
  48445. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  48446. #endif
  48447. };
  48448. /*
  48449. ** Candidate values for Wal.exclusiveMode.
  48450. */
  48451. #define WAL_NORMAL_MODE 0
  48452. #define WAL_EXCLUSIVE_MODE 1
  48453. #define WAL_HEAPMEMORY_MODE 2
  48454. /*
  48455. ** Possible values for WAL.readOnly
  48456. */
  48457. #define WAL_RDWR 0 /* Normal read/write connection */
  48458. #define WAL_RDONLY 1 /* The WAL file is readonly */
  48459. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  48460. /*
  48461. ** Each page of the wal-index mapping contains a hash-table made up of
  48462. ** an array of HASHTABLE_NSLOT elements of the following type.
  48463. */
  48464. typedef u16 ht_slot;
  48465. /*
  48466. ** This structure is used to implement an iterator that loops through
  48467. ** all frames in the WAL in database page order. Where two or more frames
  48468. ** correspond to the same database page, the iterator visits only the
  48469. ** frame most recently written to the WAL (in other words, the frame with
  48470. ** the largest index).
  48471. **
  48472. ** The internals of this structure are only accessed by:
  48473. **
  48474. ** walIteratorInit() - Create a new iterator,
  48475. ** walIteratorNext() - Step an iterator,
  48476. ** walIteratorFree() - Free an iterator.
  48477. **
  48478. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  48479. */
  48480. struct WalIterator {
  48481. int iPrior; /* Last result returned from the iterator */
  48482. int nSegment; /* Number of entries in aSegment[] */
  48483. struct WalSegment {
  48484. int iNext; /* Next slot in aIndex[] not yet returned */
  48485. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  48486. u32 *aPgno; /* Array of page numbers. */
  48487. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  48488. int iZero; /* Frame number associated with aPgno[0] */
  48489. } aSegment[1]; /* One for every 32KB page in the wal-index */
  48490. };
  48491. /*
  48492. ** Define the parameters of the hash tables in the wal-index file. There
  48493. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  48494. ** wal-index.
  48495. **
  48496. ** Changing any of these constants will alter the wal-index format and
  48497. ** create incompatibilities.
  48498. */
  48499. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  48500. #define HASHTABLE_HASH_1 383 /* Should be prime */
  48501. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  48502. /*
  48503. ** The block of page numbers associated with the first hash-table in a
  48504. ** wal-index is smaller than usual. This is so that there is a complete
  48505. ** hash-table on each aligned 32KB page of the wal-index.
  48506. */
  48507. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  48508. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  48509. #define WALINDEX_PGSZ ( \
  48510. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  48511. )
  48512. /*
  48513. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  48514. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  48515. ** numbered from zero.
  48516. **
  48517. ** If this call is successful, *ppPage is set to point to the wal-index
  48518. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  48519. ** then an SQLite error code is returned and *ppPage is set to 0.
  48520. */
  48521. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  48522. int rc = SQLITE_OK;
  48523. /* Enlarge the pWal->apWiData[] array if required */
  48524. if( pWal->nWiData<=iPage ){
  48525. int nByte = sizeof(u32*)*(iPage+1);
  48526. volatile u32 **apNew;
  48527. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  48528. if( !apNew ){
  48529. *ppPage = 0;
  48530. return SQLITE_NOMEM_BKPT;
  48531. }
  48532. memset((void*)&apNew[pWal->nWiData], 0,
  48533. sizeof(u32*)*(iPage+1-pWal->nWiData));
  48534. pWal->apWiData = apNew;
  48535. pWal->nWiData = iPage+1;
  48536. }
  48537. /* Request a pointer to the required page from the VFS */
  48538. if( pWal->apWiData[iPage]==0 ){
  48539. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  48540. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  48541. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  48542. }else{
  48543. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  48544. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  48545. );
  48546. if( rc==SQLITE_READONLY ){
  48547. pWal->readOnly |= WAL_SHM_RDONLY;
  48548. rc = SQLITE_OK;
  48549. }
  48550. }
  48551. }
  48552. *ppPage = pWal->apWiData[iPage];
  48553. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  48554. return rc;
  48555. }
  48556. /*
  48557. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  48558. */
  48559. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  48560. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  48561. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  48562. }
  48563. /*
  48564. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  48565. */
  48566. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  48567. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  48568. return (volatile WalIndexHdr*)pWal->apWiData[0];
  48569. }
  48570. /*
  48571. ** The argument to this macro must be of type u32. On a little-endian
  48572. ** architecture, it returns the u32 value that results from interpreting
  48573. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  48574. ** returns the value that would be produced by interpreting the 4 bytes
  48575. ** of the input value as a little-endian integer.
  48576. */
  48577. #define BYTESWAP32(x) ( \
  48578. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  48579. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  48580. )
  48581. /*
  48582. ** Generate or extend an 8 byte checksum based on the data in
  48583. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  48584. ** initial values of 0 and 0 if aIn==NULL).
  48585. **
  48586. ** The checksum is written back into aOut[] before returning.
  48587. **
  48588. ** nByte must be a positive multiple of 8.
  48589. */
  48590. static void walChecksumBytes(
  48591. int nativeCksum, /* True for native byte-order, false for non-native */
  48592. u8 *a, /* Content to be checksummed */
  48593. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  48594. const u32 *aIn, /* Initial checksum value input */
  48595. u32 *aOut /* OUT: Final checksum value output */
  48596. ){
  48597. u32 s1, s2;
  48598. u32 *aData = (u32 *)a;
  48599. u32 *aEnd = (u32 *)&a[nByte];
  48600. if( aIn ){
  48601. s1 = aIn[0];
  48602. s2 = aIn[1];
  48603. }else{
  48604. s1 = s2 = 0;
  48605. }
  48606. assert( nByte>=8 );
  48607. assert( (nByte&0x00000007)==0 );
  48608. if( nativeCksum ){
  48609. do {
  48610. s1 += *aData++ + s2;
  48611. s2 += *aData++ + s1;
  48612. }while( aData<aEnd );
  48613. }else{
  48614. do {
  48615. s1 += BYTESWAP32(aData[0]) + s2;
  48616. s2 += BYTESWAP32(aData[1]) + s1;
  48617. aData += 2;
  48618. }while( aData<aEnd );
  48619. }
  48620. aOut[0] = s1;
  48621. aOut[1] = s2;
  48622. }
  48623. static void walShmBarrier(Wal *pWal){
  48624. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  48625. sqlite3OsShmBarrier(pWal->pDbFd);
  48626. }
  48627. }
  48628. /*
  48629. ** Write the header information in pWal->hdr into the wal-index.
  48630. **
  48631. ** The checksum on pWal->hdr is updated before it is written.
  48632. */
  48633. static void walIndexWriteHdr(Wal *pWal){
  48634. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  48635. const int nCksum = offsetof(WalIndexHdr, aCksum);
  48636. assert( pWal->writeLock );
  48637. pWal->hdr.isInit = 1;
  48638. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  48639. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  48640. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  48641. walShmBarrier(pWal);
  48642. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  48643. }
  48644. /*
  48645. ** This function encodes a single frame header and writes it to a buffer
  48646. ** supplied by the caller. A frame-header is made up of a series of
  48647. ** 4-byte big-endian integers, as follows:
  48648. **
  48649. ** 0: Page number.
  48650. ** 4: For commit records, the size of the database image in pages
  48651. ** after the commit. For all other records, zero.
  48652. ** 8: Salt-1 (copied from the wal-header)
  48653. ** 12: Salt-2 (copied from the wal-header)
  48654. ** 16: Checksum-1.
  48655. ** 20: Checksum-2.
  48656. */
  48657. static void walEncodeFrame(
  48658. Wal *pWal, /* The write-ahead log */
  48659. u32 iPage, /* Database page number for frame */
  48660. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  48661. u8 *aData, /* Pointer to page data */
  48662. u8 *aFrame /* OUT: Write encoded frame here */
  48663. ){
  48664. int nativeCksum; /* True for native byte-order checksums */
  48665. u32 *aCksum = pWal->hdr.aFrameCksum;
  48666. assert( WAL_FRAME_HDRSIZE==24 );
  48667. sqlite3Put4byte(&aFrame[0], iPage);
  48668. sqlite3Put4byte(&aFrame[4], nTruncate);
  48669. if( pWal->iReCksum==0 ){
  48670. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  48671. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  48672. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  48673. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  48674. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  48675. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  48676. }else{
  48677. memset(&aFrame[8], 0, 16);
  48678. }
  48679. }
  48680. /*
  48681. ** Check to see if the frame with header in aFrame[] and content
  48682. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  48683. ** *pnTruncate and return true. Return if the frame is not valid.
  48684. */
  48685. static int walDecodeFrame(
  48686. Wal *pWal, /* The write-ahead log */
  48687. u32 *piPage, /* OUT: Database page number for frame */
  48688. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  48689. u8 *aData, /* Pointer to page data (for checksum) */
  48690. u8 *aFrame /* Frame data */
  48691. ){
  48692. int nativeCksum; /* True for native byte-order checksums */
  48693. u32 *aCksum = pWal->hdr.aFrameCksum;
  48694. u32 pgno; /* Page number of the frame */
  48695. assert( WAL_FRAME_HDRSIZE==24 );
  48696. /* A frame is only valid if the salt values in the frame-header
  48697. ** match the salt values in the wal-header.
  48698. */
  48699. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  48700. return 0;
  48701. }
  48702. /* A frame is only valid if the page number is creater than zero.
  48703. */
  48704. pgno = sqlite3Get4byte(&aFrame[0]);
  48705. if( pgno==0 ){
  48706. return 0;
  48707. }
  48708. /* A frame is only valid if a checksum of the WAL header,
  48709. ** all prior frams, the first 16 bytes of this frame-header,
  48710. ** and the frame-data matches the checksum in the last 8
  48711. ** bytes of this frame-header.
  48712. */
  48713. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  48714. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  48715. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  48716. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  48717. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  48718. ){
  48719. /* Checksum failed. */
  48720. return 0;
  48721. }
  48722. /* If we reach this point, the frame is valid. Return the page number
  48723. ** and the new database size.
  48724. */
  48725. *piPage = pgno;
  48726. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  48727. return 1;
  48728. }
  48729. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48730. /*
  48731. ** Names of locks. This routine is used to provide debugging output and is not
  48732. ** a part of an ordinary build.
  48733. */
  48734. static const char *walLockName(int lockIdx){
  48735. if( lockIdx==WAL_WRITE_LOCK ){
  48736. return "WRITE-LOCK";
  48737. }else if( lockIdx==WAL_CKPT_LOCK ){
  48738. return "CKPT-LOCK";
  48739. }else if( lockIdx==WAL_RECOVER_LOCK ){
  48740. return "RECOVER-LOCK";
  48741. }else{
  48742. static char zName[15];
  48743. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  48744. lockIdx-WAL_READ_LOCK(0));
  48745. return zName;
  48746. }
  48747. }
  48748. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  48749. /*
  48750. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  48751. ** A lock cannot be moved directly between shared and exclusive - it must go
  48752. ** through the unlocked state first.
  48753. **
  48754. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  48755. */
  48756. static int walLockShared(Wal *pWal, int lockIdx){
  48757. int rc;
  48758. if( pWal->exclusiveMode ) return SQLITE_OK;
  48759. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  48760. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  48761. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  48762. walLockName(lockIdx), rc ? "failed" : "ok"));
  48763. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  48764. return rc;
  48765. }
  48766. static void walUnlockShared(Wal *pWal, int lockIdx){
  48767. if( pWal->exclusiveMode ) return;
  48768. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  48769. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  48770. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  48771. }
  48772. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  48773. int rc;
  48774. if( pWal->exclusiveMode ) return SQLITE_OK;
  48775. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  48776. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  48777. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  48778. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  48779. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  48780. return rc;
  48781. }
  48782. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  48783. if( pWal->exclusiveMode ) return;
  48784. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  48785. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  48786. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  48787. walLockName(lockIdx), n));
  48788. }
  48789. /*
  48790. ** Compute a hash on a page number. The resulting hash value must land
  48791. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  48792. ** the hash to the next value in the event of a collision.
  48793. */
  48794. static int walHash(u32 iPage){
  48795. assert( iPage>0 );
  48796. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  48797. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  48798. }
  48799. static int walNextHash(int iPriorHash){
  48800. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  48801. }
  48802. /*
  48803. ** Return pointers to the hash table and page number array stored on
  48804. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  48805. ** numbered starting from 0.
  48806. **
  48807. ** Set output variable *paHash to point to the start of the hash table
  48808. ** in the wal-index file. Set *piZero to one less than the frame
  48809. ** number of the first frame indexed by this hash table. If a
  48810. ** slot in the hash table is set to N, it refers to frame number
  48811. ** (*piZero+N) in the log.
  48812. **
  48813. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  48814. ** first frame indexed by the hash table, frame (*piZero+1).
  48815. */
  48816. static int walHashGet(
  48817. Wal *pWal, /* WAL handle */
  48818. int iHash, /* Find the iHash'th table */
  48819. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  48820. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  48821. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  48822. ){
  48823. int rc; /* Return code */
  48824. volatile u32 *aPgno;
  48825. rc = walIndexPage(pWal, iHash, &aPgno);
  48826. assert( rc==SQLITE_OK || iHash>0 );
  48827. if( rc==SQLITE_OK ){
  48828. u32 iZero;
  48829. volatile ht_slot *aHash;
  48830. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  48831. if( iHash==0 ){
  48832. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  48833. iZero = 0;
  48834. }else{
  48835. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  48836. }
  48837. *paPgno = &aPgno[-1];
  48838. *paHash = aHash;
  48839. *piZero = iZero;
  48840. }
  48841. return rc;
  48842. }
  48843. /*
  48844. ** Return the number of the wal-index page that contains the hash-table
  48845. ** and page-number array that contain entries corresponding to WAL frame
  48846. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  48847. ** are numbered starting from 0.
  48848. */
  48849. static int walFramePage(u32 iFrame){
  48850. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  48851. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  48852. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  48853. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  48854. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  48855. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  48856. );
  48857. return iHash;
  48858. }
  48859. /*
  48860. ** Return the page number associated with frame iFrame in this WAL.
  48861. */
  48862. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  48863. int iHash = walFramePage(iFrame);
  48864. if( iHash==0 ){
  48865. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  48866. }
  48867. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  48868. }
  48869. /*
  48870. ** Remove entries from the hash table that point to WAL slots greater
  48871. ** than pWal->hdr.mxFrame.
  48872. **
  48873. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  48874. ** to a rollback or savepoint.
  48875. **
  48876. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  48877. ** updated. Any later hash tables will be automatically cleared when
  48878. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  48879. ** actually needed.
  48880. */
  48881. static void walCleanupHash(Wal *pWal){
  48882. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  48883. volatile u32 *aPgno = 0; /* Page number array for hash table */
  48884. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  48885. int iLimit = 0; /* Zero values greater than this */
  48886. int nByte; /* Number of bytes to zero in aPgno[] */
  48887. int i; /* Used to iterate through aHash[] */
  48888. assert( pWal->writeLock );
  48889. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  48890. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  48891. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  48892. if( pWal->hdr.mxFrame==0 ) return;
  48893. /* Obtain pointers to the hash-table and page-number array containing
  48894. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  48895. ** that the page said hash-table and array reside on is already mapped.
  48896. */
  48897. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  48898. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  48899. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  48900. /* Zero all hash-table entries that correspond to frame numbers greater
  48901. ** than pWal->hdr.mxFrame.
  48902. */
  48903. iLimit = pWal->hdr.mxFrame - iZero;
  48904. assert( iLimit>0 );
  48905. for(i=0; i<HASHTABLE_NSLOT; i++){
  48906. if( aHash[i]>iLimit ){
  48907. aHash[i] = 0;
  48908. }
  48909. }
  48910. /* Zero the entries in the aPgno array that correspond to frames with
  48911. ** frame numbers greater than pWal->hdr.mxFrame.
  48912. */
  48913. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  48914. memset((void *)&aPgno[iLimit+1], 0, nByte);
  48915. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  48916. /* Verify that the every entry in the mapping region is still reachable
  48917. ** via the hash table even after the cleanup.
  48918. */
  48919. if( iLimit ){
  48920. int j; /* Loop counter */
  48921. int iKey; /* Hash key */
  48922. for(j=1; j<=iLimit; j++){
  48923. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  48924. if( aHash[iKey]==j ) break;
  48925. }
  48926. assert( aHash[iKey]==j );
  48927. }
  48928. }
  48929. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  48930. }
  48931. /*
  48932. ** Set an entry in the wal-index that will map database page number
  48933. ** pPage into WAL frame iFrame.
  48934. */
  48935. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  48936. int rc; /* Return code */
  48937. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  48938. volatile u32 *aPgno = 0; /* Page number array */
  48939. volatile ht_slot *aHash = 0; /* Hash table */
  48940. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  48941. /* Assuming the wal-index file was successfully mapped, populate the
  48942. ** page number array and hash table entry.
  48943. */
  48944. if( rc==SQLITE_OK ){
  48945. int iKey; /* Hash table key */
  48946. int idx; /* Value to write to hash-table slot */
  48947. int nCollide; /* Number of hash collisions */
  48948. idx = iFrame - iZero;
  48949. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  48950. /* If this is the first entry to be added to this hash-table, zero the
  48951. ** entire hash table and aPgno[] array before proceeding.
  48952. */
  48953. if( idx==1 ){
  48954. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  48955. memset((void*)&aPgno[1], 0, nByte);
  48956. }
  48957. /* If the entry in aPgno[] is already set, then the previous writer
  48958. ** must have exited unexpectedly in the middle of a transaction (after
  48959. ** writing one or more dirty pages to the WAL to free up memory).
  48960. ** Remove the remnants of that writers uncommitted transaction from
  48961. ** the hash-table before writing any new entries.
  48962. */
  48963. if( aPgno[idx] ){
  48964. walCleanupHash(pWal);
  48965. assert( !aPgno[idx] );
  48966. }
  48967. /* Write the aPgno[] array entry and the hash-table slot. */
  48968. nCollide = idx;
  48969. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  48970. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  48971. }
  48972. aPgno[idx] = iPage;
  48973. aHash[iKey] = (ht_slot)idx;
  48974. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  48975. /* Verify that the number of entries in the hash table exactly equals
  48976. ** the number of entries in the mapping region.
  48977. */
  48978. {
  48979. int i; /* Loop counter */
  48980. int nEntry = 0; /* Number of entries in the hash table */
  48981. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  48982. assert( nEntry==idx );
  48983. }
  48984. /* Verify that the every entry in the mapping region is reachable
  48985. ** via the hash table. This turns out to be a really, really expensive
  48986. ** thing to check, so only do this occasionally - not on every
  48987. ** iteration.
  48988. */
  48989. if( (idx&0x3ff)==0 ){
  48990. int i; /* Loop counter */
  48991. for(i=1; i<=idx; i++){
  48992. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  48993. if( aHash[iKey]==i ) break;
  48994. }
  48995. assert( aHash[iKey]==i );
  48996. }
  48997. }
  48998. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  48999. }
  49000. return rc;
  49001. }
  49002. /*
  49003. ** Recover the wal-index by reading the write-ahead log file.
  49004. **
  49005. ** This routine first tries to establish an exclusive lock on the
  49006. ** wal-index to prevent other threads/processes from doing anything
  49007. ** with the WAL or wal-index while recovery is running. The
  49008. ** WAL_RECOVER_LOCK is also held so that other threads will know
  49009. ** that this thread is running recovery. If unable to establish
  49010. ** the necessary locks, this routine returns SQLITE_BUSY.
  49011. */
  49012. static int walIndexRecover(Wal *pWal){
  49013. int rc; /* Return Code */
  49014. i64 nSize; /* Size of log file */
  49015. u32 aFrameCksum[2] = {0, 0};
  49016. int iLock; /* Lock offset to lock for checkpoint */
  49017. int nLock; /* Number of locks to hold */
  49018. /* Obtain an exclusive lock on all byte in the locking range not already
  49019. ** locked by the caller. The caller is guaranteed to have locked the
  49020. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  49021. ** If successful, the same bytes that are locked here are unlocked before
  49022. ** this function returns.
  49023. */
  49024. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  49025. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  49026. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  49027. assert( pWal->writeLock );
  49028. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  49029. nLock = SQLITE_SHM_NLOCK - iLock;
  49030. rc = walLockExclusive(pWal, iLock, nLock);
  49031. if( rc ){
  49032. return rc;
  49033. }
  49034. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  49035. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  49036. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  49037. if( rc!=SQLITE_OK ){
  49038. goto recovery_error;
  49039. }
  49040. if( nSize>WAL_HDRSIZE ){
  49041. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  49042. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  49043. int szFrame; /* Number of bytes in buffer aFrame[] */
  49044. u8 *aData; /* Pointer to data part of aFrame buffer */
  49045. int iFrame; /* Index of last frame read */
  49046. i64 iOffset; /* Next offset to read from log file */
  49047. int szPage; /* Page size according to the log */
  49048. u32 magic; /* Magic value read from WAL header */
  49049. u32 version; /* Magic value read from WAL header */
  49050. int isValid; /* True if this frame is valid */
  49051. /* Read in the WAL header. */
  49052. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  49053. if( rc!=SQLITE_OK ){
  49054. goto recovery_error;
  49055. }
  49056. /* If the database page size is not a power of two, or is greater than
  49057. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  49058. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  49059. ** WAL file.
  49060. */
  49061. magic = sqlite3Get4byte(&aBuf[0]);
  49062. szPage = sqlite3Get4byte(&aBuf[8]);
  49063. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  49064. || szPage&(szPage-1)
  49065. || szPage>SQLITE_MAX_PAGE_SIZE
  49066. || szPage<512
  49067. ){
  49068. goto finished;
  49069. }
  49070. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  49071. pWal->szPage = szPage;
  49072. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  49073. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  49074. /* Verify that the WAL header checksum is correct */
  49075. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  49076. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  49077. );
  49078. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  49079. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  49080. ){
  49081. goto finished;
  49082. }
  49083. /* Verify that the version number on the WAL format is one that
  49084. ** are able to understand */
  49085. version = sqlite3Get4byte(&aBuf[4]);
  49086. if( version!=WAL_MAX_VERSION ){
  49087. rc = SQLITE_CANTOPEN_BKPT;
  49088. goto finished;
  49089. }
  49090. /* Malloc a buffer to read frames into. */
  49091. szFrame = szPage + WAL_FRAME_HDRSIZE;
  49092. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  49093. if( !aFrame ){
  49094. rc = SQLITE_NOMEM_BKPT;
  49095. goto recovery_error;
  49096. }
  49097. aData = &aFrame[WAL_FRAME_HDRSIZE];
  49098. /* Read all frames from the log file. */
  49099. iFrame = 0;
  49100. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  49101. u32 pgno; /* Database page number for frame */
  49102. u32 nTruncate; /* dbsize field from frame header */
  49103. /* Read and decode the next log frame. */
  49104. iFrame++;
  49105. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  49106. if( rc!=SQLITE_OK ) break;
  49107. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  49108. if( !isValid ) break;
  49109. rc = walIndexAppend(pWal, iFrame, pgno);
  49110. if( rc!=SQLITE_OK ) break;
  49111. /* If nTruncate is non-zero, this is a commit record. */
  49112. if( nTruncate ){
  49113. pWal->hdr.mxFrame = iFrame;
  49114. pWal->hdr.nPage = nTruncate;
  49115. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  49116. testcase( szPage<=32768 );
  49117. testcase( szPage>=65536 );
  49118. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  49119. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  49120. }
  49121. }
  49122. sqlite3_free(aFrame);
  49123. }
  49124. finished:
  49125. if( rc==SQLITE_OK ){
  49126. volatile WalCkptInfo *pInfo;
  49127. int i;
  49128. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  49129. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  49130. walIndexWriteHdr(pWal);
  49131. /* Reset the checkpoint-header. This is safe because this thread is
  49132. ** currently holding locks that exclude all other readers, writers and
  49133. ** checkpointers.
  49134. */
  49135. pInfo = walCkptInfo(pWal);
  49136. pInfo->nBackfill = 0;
  49137. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  49138. pInfo->aReadMark[0] = 0;
  49139. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  49140. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  49141. /* If more than one frame was recovered from the log file, report an
  49142. ** event via sqlite3_log(). This is to help with identifying performance
  49143. ** problems caused by applications routinely shutting down without
  49144. ** checkpointing the log file.
  49145. */
  49146. if( pWal->hdr.nPage ){
  49147. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  49148. "recovered %d frames from WAL file %s",
  49149. pWal->hdr.mxFrame, pWal->zWalName
  49150. );
  49151. }
  49152. }
  49153. recovery_error:
  49154. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  49155. walUnlockExclusive(pWal, iLock, nLock);
  49156. return rc;
  49157. }
  49158. /*
  49159. ** Close an open wal-index.
  49160. */
  49161. static void walIndexClose(Wal *pWal, int isDelete){
  49162. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  49163. int i;
  49164. for(i=0; i<pWal->nWiData; i++){
  49165. sqlite3_free((void *)pWal->apWiData[i]);
  49166. pWal->apWiData[i] = 0;
  49167. }
  49168. }else{
  49169. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  49170. }
  49171. }
  49172. /*
  49173. ** Open a connection to the WAL file zWalName. The database file must
  49174. ** already be opened on connection pDbFd. The buffer that zWalName points
  49175. ** to must remain valid for the lifetime of the returned Wal* handle.
  49176. **
  49177. ** A SHARED lock should be held on the database file when this function
  49178. ** is called. The purpose of this SHARED lock is to prevent any other
  49179. ** client from unlinking the WAL or wal-index file. If another process
  49180. ** were to do this just after this client opened one of these files, the
  49181. ** system would be badly broken.
  49182. **
  49183. ** If the log file is successfully opened, SQLITE_OK is returned and
  49184. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  49185. ** an SQLite error code is returned and *ppWal is left unmodified.
  49186. */
  49187. SQLITE_PRIVATE int sqlite3WalOpen(
  49188. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  49189. sqlite3_file *pDbFd, /* The open database file */
  49190. const char *zWalName, /* Name of the WAL file */
  49191. int bNoShm, /* True to run in heap-memory mode */
  49192. i64 mxWalSize, /* Truncate WAL to this size on reset */
  49193. Wal **ppWal /* OUT: Allocated Wal handle */
  49194. ){
  49195. int rc; /* Return Code */
  49196. Wal *pRet; /* Object to allocate and return */
  49197. int flags; /* Flags passed to OsOpen() */
  49198. assert( zWalName && zWalName[0] );
  49199. assert( pDbFd );
  49200. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  49201. ** this source file. Verify that the #defines of the locking byte offsets
  49202. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  49203. ** For that matter, if the lock offset ever changes from its initial design
  49204. ** value of 120, we need to know that so there is an assert() to check it.
  49205. */
  49206. assert( 120==WALINDEX_LOCK_OFFSET );
  49207. assert( 136==WALINDEX_HDR_SIZE );
  49208. #ifdef WIN_SHM_BASE
  49209. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  49210. #endif
  49211. #ifdef UNIX_SHM_BASE
  49212. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  49213. #endif
  49214. /* Allocate an instance of struct Wal to return. */
  49215. *ppWal = 0;
  49216. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  49217. if( !pRet ){
  49218. return SQLITE_NOMEM_BKPT;
  49219. }
  49220. pRet->pVfs = pVfs;
  49221. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  49222. pRet->pDbFd = pDbFd;
  49223. pRet->readLock = -1;
  49224. pRet->mxWalSize = mxWalSize;
  49225. pRet->zWalName = zWalName;
  49226. pRet->syncHeader = 1;
  49227. pRet->padToSectorBoundary = 1;
  49228. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  49229. /* Open file handle on the write-ahead log file. */
  49230. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  49231. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  49232. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  49233. pRet->readOnly = WAL_RDONLY;
  49234. }
  49235. if( rc!=SQLITE_OK ){
  49236. walIndexClose(pRet, 0);
  49237. sqlite3OsClose(pRet->pWalFd);
  49238. sqlite3_free(pRet);
  49239. }else{
  49240. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  49241. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  49242. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  49243. pRet->padToSectorBoundary = 0;
  49244. }
  49245. *ppWal = pRet;
  49246. WALTRACE(("WAL%d: opened\n", pRet));
  49247. }
  49248. return rc;
  49249. }
  49250. /*
  49251. ** Change the size to which the WAL file is trucated on each reset.
  49252. */
  49253. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  49254. if( pWal ) pWal->mxWalSize = iLimit;
  49255. }
  49256. /*
  49257. ** Find the smallest page number out of all pages held in the WAL that
  49258. ** has not been returned by any prior invocation of this method on the
  49259. ** same WalIterator object. Write into *piFrame the frame index where
  49260. ** that page was last written into the WAL. Write into *piPage the page
  49261. ** number.
  49262. **
  49263. ** Return 0 on success. If there are no pages in the WAL with a page
  49264. ** number larger than *piPage, then return 1.
  49265. */
  49266. static int walIteratorNext(
  49267. WalIterator *p, /* Iterator */
  49268. u32 *piPage, /* OUT: The page number of the next page */
  49269. u32 *piFrame /* OUT: Wal frame index of next page */
  49270. ){
  49271. u32 iMin; /* Result pgno must be greater than iMin */
  49272. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  49273. int i; /* For looping through segments */
  49274. iMin = p->iPrior;
  49275. assert( iMin<0xffffffff );
  49276. for(i=p->nSegment-1; i>=0; i--){
  49277. struct WalSegment *pSegment = &p->aSegment[i];
  49278. while( pSegment->iNext<pSegment->nEntry ){
  49279. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  49280. if( iPg>iMin ){
  49281. if( iPg<iRet ){
  49282. iRet = iPg;
  49283. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  49284. }
  49285. break;
  49286. }
  49287. pSegment->iNext++;
  49288. }
  49289. }
  49290. *piPage = p->iPrior = iRet;
  49291. return (iRet==0xFFFFFFFF);
  49292. }
  49293. /*
  49294. ** This function merges two sorted lists into a single sorted list.
  49295. **
  49296. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  49297. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  49298. ** is guaranteed for all J<K:
  49299. **
  49300. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  49301. ** aContent[aRight[J]] < aContent[aRight[K]]
  49302. **
  49303. ** This routine overwrites aRight[] with a new (probably longer) sequence
  49304. ** of indices such that the aRight[] contains every index that appears in
  49305. ** either aLeft[] or the old aRight[] and such that the second condition
  49306. ** above is still met.
  49307. **
  49308. ** The aContent[aLeft[X]] values will be unique for all X. And the
  49309. ** aContent[aRight[X]] values will be unique too. But there might be
  49310. ** one or more combinations of X and Y such that
  49311. **
  49312. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  49313. **
  49314. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  49315. */
  49316. static void walMerge(
  49317. const u32 *aContent, /* Pages in wal - keys for the sort */
  49318. ht_slot *aLeft, /* IN: Left hand input list */
  49319. int nLeft, /* IN: Elements in array *paLeft */
  49320. ht_slot **paRight, /* IN/OUT: Right hand input list */
  49321. int *pnRight, /* IN/OUT: Elements in *paRight */
  49322. ht_slot *aTmp /* Temporary buffer */
  49323. ){
  49324. int iLeft = 0; /* Current index in aLeft */
  49325. int iRight = 0; /* Current index in aRight */
  49326. int iOut = 0; /* Current index in output buffer */
  49327. int nRight = *pnRight;
  49328. ht_slot *aRight = *paRight;
  49329. assert( nLeft>0 && nRight>0 );
  49330. while( iRight<nRight || iLeft<nLeft ){
  49331. ht_slot logpage;
  49332. Pgno dbpage;
  49333. if( (iLeft<nLeft)
  49334. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  49335. ){
  49336. logpage = aLeft[iLeft++];
  49337. }else{
  49338. logpage = aRight[iRight++];
  49339. }
  49340. dbpage = aContent[logpage];
  49341. aTmp[iOut++] = logpage;
  49342. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  49343. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  49344. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  49345. }
  49346. *paRight = aLeft;
  49347. *pnRight = iOut;
  49348. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  49349. }
  49350. /*
  49351. ** Sort the elements in list aList using aContent[] as the sort key.
  49352. ** Remove elements with duplicate keys, preferring to keep the
  49353. ** larger aList[] values.
  49354. **
  49355. ** The aList[] entries are indices into aContent[]. The values in
  49356. ** aList[] are to be sorted so that for all J<K:
  49357. **
  49358. ** aContent[aList[J]] < aContent[aList[K]]
  49359. **
  49360. ** For any X and Y such that
  49361. **
  49362. ** aContent[aList[X]] == aContent[aList[Y]]
  49363. **
  49364. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  49365. ** the smaller.
  49366. */
  49367. static void walMergesort(
  49368. const u32 *aContent, /* Pages in wal */
  49369. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  49370. ht_slot *aList, /* IN/OUT: List to sort */
  49371. int *pnList /* IN/OUT: Number of elements in aList[] */
  49372. ){
  49373. struct Sublist {
  49374. int nList; /* Number of elements in aList */
  49375. ht_slot *aList; /* Pointer to sub-list content */
  49376. };
  49377. const int nList = *pnList; /* Size of input list */
  49378. int nMerge = 0; /* Number of elements in list aMerge */
  49379. ht_slot *aMerge = 0; /* List to be merged */
  49380. int iList; /* Index into input list */
  49381. u32 iSub = 0; /* Index into aSub array */
  49382. struct Sublist aSub[13]; /* Array of sub-lists */
  49383. memset(aSub, 0, sizeof(aSub));
  49384. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  49385. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  49386. for(iList=0; iList<nList; iList++){
  49387. nMerge = 1;
  49388. aMerge = &aList[iList];
  49389. for(iSub=0; iList & (1<<iSub); iSub++){
  49390. struct Sublist *p;
  49391. assert( iSub<ArraySize(aSub) );
  49392. p = &aSub[iSub];
  49393. assert( p->aList && p->nList<=(1<<iSub) );
  49394. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  49395. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  49396. }
  49397. aSub[iSub].aList = aMerge;
  49398. aSub[iSub].nList = nMerge;
  49399. }
  49400. for(iSub++; iSub<ArraySize(aSub); iSub++){
  49401. if( nList & (1<<iSub) ){
  49402. struct Sublist *p;
  49403. assert( iSub<ArraySize(aSub) );
  49404. p = &aSub[iSub];
  49405. assert( p->nList<=(1<<iSub) );
  49406. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  49407. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  49408. }
  49409. }
  49410. assert( aMerge==aList );
  49411. *pnList = nMerge;
  49412. #ifdef SQLITE_DEBUG
  49413. {
  49414. int i;
  49415. for(i=1; i<*pnList; i++){
  49416. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  49417. }
  49418. }
  49419. #endif
  49420. }
  49421. /*
  49422. ** Free an iterator allocated by walIteratorInit().
  49423. */
  49424. static void walIteratorFree(WalIterator *p){
  49425. sqlite3_free(p);
  49426. }
  49427. /*
  49428. ** Construct a WalInterator object that can be used to loop over all
  49429. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  49430. ** lock.
  49431. **
  49432. ** On success, make *pp point to the newly allocated WalInterator object
  49433. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  49434. ** returns an error, the value of *pp is undefined.
  49435. **
  49436. ** The calling routine should invoke walIteratorFree() to destroy the
  49437. ** WalIterator object when it has finished with it.
  49438. */
  49439. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  49440. WalIterator *p; /* Return value */
  49441. int nSegment; /* Number of segments to merge */
  49442. u32 iLast; /* Last frame in log */
  49443. int nByte; /* Number of bytes to allocate */
  49444. int i; /* Iterator variable */
  49445. ht_slot *aTmp; /* Temp space used by merge-sort */
  49446. int rc = SQLITE_OK; /* Return Code */
  49447. /* This routine only runs while holding the checkpoint lock. And
  49448. ** it only runs if there is actually content in the log (mxFrame>0).
  49449. */
  49450. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  49451. iLast = pWal->hdr.mxFrame;
  49452. /* Allocate space for the WalIterator object. */
  49453. nSegment = walFramePage(iLast) + 1;
  49454. nByte = sizeof(WalIterator)
  49455. + (nSegment-1)*sizeof(struct WalSegment)
  49456. + iLast*sizeof(ht_slot);
  49457. p = (WalIterator *)sqlite3_malloc64(nByte);
  49458. if( !p ){
  49459. return SQLITE_NOMEM_BKPT;
  49460. }
  49461. memset(p, 0, nByte);
  49462. p->nSegment = nSegment;
  49463. /* Allocate temporary space used by the merge-sort routine. This block
  49464. ** of memory will be freed before this function returns.
  49465. */
  49466. aTmp = (ht_slot *)sqlite3_malloc64(
  49467. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  49468. );
  49469. if( !aTmp ){
  49470. rc = SQLITE_NOMEM_BKPT;
  49471. }
  49472. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  49473. volatile ht_slot *aHash;
  49474. u32 iZero;
  49475. volatile u32 *aPgno;
  49476. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  49477. if( rc==SQLITE_OK ){
  49478. int j; /* Counter variable */
  49479. int nEntry; /* Number of entries in this segment */
  49480. ht_slot *aIndex; /* Sorted index for this segment */
  49481. aPgno++;
  49482. if( (i+1)==nSegment ){
  49483. nEntry = (int)(iLast - iZero);
  49484. }else{
  49485. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  49486. }
  49487. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  49488. iZero++;
  49489. for(j=0; j<nEntry; j++){
  49490. aIndex[j] = (ht_slot)j;
  49491. }
  49492. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  49493. p->aSegment[i].iZero = iZero;
  49494. p->aSegment[i].nEntry = nEntry;
  49495. p->aSegment[i].aIndex = aIndex;
  49496. p->aSegment[i].aPgno = (u32 *)aPgno;
  49497. }
  49498. }
  49499. sqlite3_free(aTmp);
  49500. if( rc!=SQLITE_OK ){
  49501. walIteratorFree(p);
  49502. }
  49503. *pp = p;
  49504. return rc;
  49505. }
  49506. /*
  49507. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  49508. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  49509. ** busy-handler function. Invoke it and retry the lock until either the
  49510. ** lock is successfully obtained or the busy-handler returns 0.
  49511. */
  49512. static int walBusyLock(
  49513. Wal *pWal, /* WAL connection */
  49514. int (*xBusy)(void*), /* Function to call when busy */
  49515. void *pBusyArg, /* Context argument for xBusyHandler */
  49516. int lockIdx, /* Offset of first byte to lock */
  49517. int n /* Number of bytes to lock */
  49518. ){
  49519. int rc;
  49520. do {
  49521. rc = walLockExclusive(pWal, lockIdx, n);
  49522. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  49523. return rc;
  49524. }
  49525. /*
  49526. ** The cache of the wal-index header must be valid to call this function.
  49527. ** Return the page-size in bytes used by the database.
  49528. */
  49529. static int walPagesize(Wal *pWal){
  49530. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  49531. }
  49532. /*
  49533. ** The following is guaranteed when this function is called:
  49534. **
  49535. ** a) the WRITER lock is held,
  49536. ** b) the entire log file has been checkpointed, and
  49537. ** c) any existing readers are reading exclusively from the database
  49538. ** file - there are no readers that may attempt to read a frame from
  49539. ** the log file.
  49540. **
  49541. ** This function updates the shared-memory structures so that the next
  49542. ** client to write to the database (which may be this one) does so by
  49543. ** writing frames into the start of the log file.
  49544. **
  49545. ** The value of parameter salt1 is used as the aSalt[1] value in the
  49546. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  49547. ** one obtained from sqlite3_randomness()).
  49548. */
  49549. static void walRestartHdr(Wal *pWal, u32 salt1){
  49550. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  49551. int i; /* Loop counter */
  49552. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  49553. pWal->nCkpt++;
  49554. pWal->hdr.mxFrame = 0;
  49555. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  49556. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  49557. walIndexWriteHdr(pWal);
  49558. pInfo->nBackfill = 0;
  49559. pInfo->nBackfillAttempted = 0;
  49560. pInfo->aReadMark[1] = 0;
  49561. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  49562. assert( pInfo->aReadMark[0]==0 );
  49563. }
  49564. /*
  49565. ** Copy as much content as we can from the WAL back into the database file
  49566. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  49567. **
  49568. ** The amount of information copies from WAL to database might be limited
  49569. ** by active readers. This routine will never overwrite a database page
  49570. ** that a concurrent reader might be using.
  49571. **
  49572. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  49573. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  49574. ** checkpoints are always run by a background thread or background
  49575. ** process, foreground threads will never block on a lengthy fsync call.
  49576. **
  49577. ** Fsync is called on the WAL before writing content out of the WAL and
  49578. ** into the database. This ensures that if the new content is persistent
  49579. ** in the WAL and can be recovered following a power-loss or hard reset.
  49580. **
  49581. ** Fsync is also called on the database file if (and only if) the entire
  49582. ** WAL content is copied into the database file. This second fsync makes
  49583. ** it safe to delete the WAL since the new content will persist in the
  49584. ** database file.
  49585. **
  49586. ** This routine uses and updates the nBackfill field of the wal-index header.
  49587. ** This is the only routine that will increase the value of nBackfill.
  49588. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  49589. ** its value.)
  49590. **
  49591. ** The caller must be holding sufficient locks to ensure that no other
  49592. ** checkpoint is running (in any other thread or process) at the same
  49593. ** time.
  49594. */
  49595. static int walCheckpoint(
  49596. Wal *pWal, /* Wal connection */
  49597. int eMode, /* One of PASSIVE, FULL or RESTART */
  49598. int (*xBusy)(void*), /* Function to call when busy */
  49599. void *pBusyArg, /* Context argument for xBusyHandler */
  49600. int sync_flags, /* Flags for OsSync() (or 0) */
  49601. u8 *zBuf /* Temporary buffer to use */
  49602. ){
  49603. int rc = SQLITE_OK; /* Return code */
  49604. int szPage; /* Database page-size */
  49605. WalIterator *pIter = 0; /* Wal iterator context */
  49606. u32 iDbpage = 0; /* Next database page to write */
  49607. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  49608. u32 mxSafeFrame; /* Max frame that can be backfilled */
  49609. u32 mxPage; /* Max database page to write */
  49610. int i; /* Loop counter */
  49611. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  49612. szPage = walPagesize(pWal);
  49613. testcase( szPage<=32768 );
  49614. testcase( szPage>=65536 );
  49615. pInfo = walCkptInfo(pWal);
  49616. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  49617. /* Allocate the iterator */
  49618. rc = walIteratorInit(pWal, &pIter);
  49619. if( rc!=SQLITE_OK ){
  49620. return rc;
  49621. }
  49622. assert( pIter );
  49623. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  49624. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  49625. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  49626. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  49627. ** safe to write into the database. Frames beyond mxSafeFrame might
  49628. ** overwrite database pages that are in use by active readers and thus
  49629. ** cannot be backfilled from the WAL.
  49630. */
  49631. mxSafeFrame = pWal->hdr.mxFrame;
  49632. mxPage = pWal->hdr.nPage;
  49633. for(i=1; i<WAL_NREADER; i++){
  49634. /* Thread-sanitizer reports that the following is an unsafe read,
  49635. ** as some other thread may be in the process of updating the value
  49636. ** of the aReadMark[] slot. The assumption here is that if that is
  49637. ** happening, the other client may only be increasing the value,
  49638. ** not decreasing it. So assuming either that either the "old" or
  49639. ** "new" version of the value is read, and not some arbitrary value
  49640. ** that would never be written by a real client, things are still
  49641. ** safe. */
  49642. u32 y = pInfo->aReadMark[i];
  49643. if( mxSafeFrame>y ){
  49644. assert( y<=pWal->hdr.mxFrame );
  49645. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  49646. if( rc==SQLITE_OK ){
  49647. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  49648. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  49649. }else if( rc==SQLITE_BUSY ){
  49650. mxSafeFrame = y;
  49651. xBusy = 0;
  49652. }else{
  49653. goto walcheckpoint_out;
  49654. }
  49655. }
  49656. }
  49657. if( pInfo->nBackfill<mxSafeFrame
  49658. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  49659. ){
  49660. i64 nSize; /* Current size of database file */
  49661. u32 nBackfill = pInfo->nBackfill;
  49662. pInfo->nBackfillAttempted = mxSafeFrame;
  49663. /* Sync the WAL to disk */
  49664. if( sync_flags ){
  49665. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  49666. }
  49667. /* If the database may grow as a result of this checkpoint, hint
  49668. ** about the eventual size of the db file to the VFS layer.
  49669. */
  49670. if( rc==SQLITE_OK ){
  49671. i64 nReq = ((i64)mxPage * szPage);
  49672. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  49673. if( rc==SQLITE_OK && nSize<nReq ){
  49674. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  49675. }
  49676. }
  49677. /* Iterate through the contents of the WAL, copying data to the db file */
  49678. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  49679. i64 iOffset;
  49680. assert( walFramePgno(pWal, iFrame)==iDbpage );
  49681. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  49682. continue;
  49683. }
  49684. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  49685. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  49686. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  49687. if( rc!=SQLITE_OK ) break;
  49688. iOffset = (iDbpage-1)*(i64)szPage;
  49689. testcase( IS_BIG_INT(iOffset) );
  49690. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  49691. if( rc!=SQLITE_OK ) break;
  49692. }
  49693. /* If work was actually accomplished... */
  49694. if( rc==SQLITE_OK ){
  49695. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  49696. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  49697. testcase( IS_BIG_INT(szDb) );
  49698. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  49699. if( rc==SQLITE_OK && sync_flags ){
  49700. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  49701. }
  49702. }
  49703. if( rc==SQLITE_OK ){
  49704. pInfo->nBackfill = mxSafeFrame;
  49705. }
  49706. }
  49707. /* Release the reader lock held while backfilling */
  49708. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  49709. }
  49710. if( rc==SQLITE_BUSY ){
  49711. /* Reset the return code so as not to report a checkpoint failure
  49712. ** just because there are active readers. */
  49713. rc = SQLITE_OK;
  49714. }
  49715. }
  49716. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  49717. ** entire wal file has been copied into the database file, then block
  49718. ** until all readers have finished using the wal file. This ensures that
  49719. ** the next process to write to the database restarts the wal file.
  49720. */
  49721. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  49722. assert( pWal->writeLock );
  49723. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  49724. rc = SQLITE_BUSY;
  49725. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  49726. u32 salt1;
  49727. sqlite3_randomness(4, &salt1);
  49728. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  49729. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  49730. if( rc==SQLITE_OK ){
  49731. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  49732. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  49733. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  49734. ** truncates the log file to zero bytes just prior to a
  49735. ** successful return.
  49736. **
  49737. ** In theory, it might be safe to do this without updating the
  49738. ** wal-index header in shared memory, as all subsequent reader or
  49739. ** writer clients should see that the entire log file has been
  49740. ** checkpointed and behave accordingly. This seems unsafe though,
  49741. ** as it would leave the system in a state where the contents of
  49742. ** the wal-index header do not match the contents of the
  49743. ** file-system. To avoid this, update the wal-index header to
  49744. ** indicate that the log file contains zero valid frames. */
  49745. walRestartHdr(pWal, salt1);
  49746. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  49747. }
  49748. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  49749. }
  49750. }
  49751. }
  49752. walcheckpoint_out:
  49753. walIteratorFree(pIter);
  49754. return rc;
  49755. }
  49756. /*
  49757. ** If the WAL file is currently larger than nMax bytes in size, truncate
  49758. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  49759. */
  49760. static void walLimitSize(Wal *pWal, i64 nMax){
  49761. i64 sz;
  49762. int rx;
  49763. sqlite3BeginBenignMalloc();
  49764. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  49765. if( rx==SQLITE_OK && (sz > nMax ) ){
  49766. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  49767. }
  49768. sqlite3EndBenignMalloc();
  49769. if( rx ){
  49770. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  49771. }
  49772. }
  49773. /*
  49774. ** Close a connection to a log file.
  49775. */
  49776. SQLITE_PRIVATE int sqlite3WalClose(
  49777. Wal *pWal, /* Wal to close */
  49778. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  49779. int nBuf,
  49780. u8 *zBuf /* Buffer of at least nBuf bytes */
  49781. ){
  49782. int rc = SQLITE_OK;
  49783. if( pWal ){
  49784. int isDelete = 0; /* True to unlink wal and wal-index files */
  49785. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  49786. ** ordinary, rollback-mode locking methods, this guarantees that the
  49787. ** connection associated with this log file is the only connection to
  49788. ** the database. In this case checkpoint the database and unlink both
  49789. ** the wal and wal-index files.
  49790. **
  49791. ** The EXCLUSIVE lock is not released before returning.
  49792. */
  49793. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  49794. if( rc==SQLITE_OK ){
  49795. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  49796. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  49797. }
  49798. rc = sqlite3WalCheckpoint(
  49799. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  49800. );
  49801. if( rc==SQLITE_OK ){
  49802. int bPersist = -1;
  49803. sqlite3OsFileControlHint(
  49804. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  49805. );
  49806. if( bPersist!=1 ){
  49807. /* Try to delete the WAL file if the checkpoint completed and
  49808. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  49809. ** mode (!bPersist) */
  49810. isDelete = 1;
  49811. }else if( pWal->mxWalSize>=0 ){
  49812. /* Try to truncate the WAL file to zero bytes if the checkpoint
  49813. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  49814. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  49815. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  49816. ** to zero bytes as truncating to the journal_size_limit might
  49817. ** leave a corrupt WAL file on disk. */
  49818. walLimitSize(pWal, 0);
  49819. }
  49820. }
  49821. }
  49822. walIndexClose(pWal, isDelete);
  49823. sqlite3OsClose(pWal->pWalFd);
  49824. if( isDelete ){
  49825. sqlite3BeginBenignMalloc();
  49826. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  49827. sqlite3EndBenignMalloc();
  49828. }
  49829. WALTRACE(("WAL%p: closed\n", pWal));
  49830. sqlite3_free((void *)pWal->apWiData);
  49831. sqlite3_free(pWal);
  49832. }
  49833. return rc;
  49834. }
  49835. /*
  49836. ** Try to read the wal-index header. Return 0 on success and 1 if
  49837. ** there is a problem.
  49838. **
  49839. ** The wal-index is in shared memory. Another thread or process might
  49840. ** be writing the header at the same time this procedure is trying to
  49841. ** read it, which might result in inconsistency. A dirty read is detected
  49842. ** by verifying that both copies of the header are the same and also by
  49843. ** a checksum on the header.
  49844. **
  49845. ** If and only if the read is consistent and the header is different from
  49846. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  49847. ** and *pChanged is set to 1.
  49848. **
  49849. ** If the checksum cannot be verified return non-zero. If the header
  49850. ** is read successfully and the checksum verified, return zero.
  49851. */
  49852. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  49853. u32 aCksum[2]; /* Checksum on the header content */
  49854. WalIndexHdr h1, h2; /* Two copies of the header content */
  49855. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  49856. /* The first page of the wal-index must be mapped at this point. */
  49857. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  49858. /* Read the header. This might happen concurrently with a write to the
  49859. ** same area of shared memory on a different CPU in a SMP,
  49860. ** meaning it is possible that an inconsistent snapshot is read
  49861. ** from the file. If this happens, return non-zero.
  49862. **
  49863. ** There are two copies of the header at the beginning of the wal-index.
  49864. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  49865. ** Memory barriers are used to prevent the compiler or the hardware from
  49866. ** reordering the reads and writes.
  49867. */
  49868. aHdr = walIndexHdr(pWal);
  49869. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  49870. walShmBarrier(pWal);
  49871. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  49872. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  49873. return 1; /* Dirty read */
  49874. }
  49875. if( h1.isInit==0 ){
  49876. return 1; /* Malformed header - probably all zeros */
  49877. }
  49878. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  49879. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  49880. return 1; /* Checksum does not match */
  49881. }
  49882. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  49883. *pChanged = 1;
  49884. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  49885. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  49886. testcase( pWal->szPage<=32768 );
  49887. testcase( pWal->szPage>=65536 );
  49888. }
  49889. /* The header was successfully read. Return zero. */
  49890. return 0;
  49891. }
  49892. /*
  49893. ** Read the wal-index header from the wal-index and into pWal->hdr.
  49894. ** If the wal-header appears to be corrupt, try to reconstruct the
  49895. ** wal-index from the WAL before returning.
  49896. **
  49897. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  49898. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  49899. ** to 0.
  49900. **
  49901. ** If the wal-index header is successfully read, return SQLITE_OK.
  49902. ** Otherwise an SQLite error code.
  49903. */
  49904. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  49905. int rc; /* Return code */
  49906. int badHdr; /* True if a header read failed */
  49907. volatile u32 *page0; /* Chunk of wal-index containing header */
  49908. /* Ensure that page 0 of the wal-index (the page that contains the
  49909. ** wal-index header) is mapped. Return early if an error occurs here.
  49910. */
  49911. assert( pChanged );
  49912. rc = walIndexPage(pWal, 0, &page0);
  49913. if( rc!=SQLITE_OK ){
  49914. return rc;
  49915. };
  49916. assert( page0 || pWal->writeLock==0 );
  49917. /* If the first page of the wal-index has been mapped, try to read the
  49918. ** wal-index header immediately, without holding any lock. This usually
  49919. ** works, but may fail if the wal-index header is corrupt or currently
  49920. ** being modified by another thread or process.
  49921. */
  49922. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  49923. /* If the first attempt failed, it might have been due to a race
  49924. ** with a writer. So get a WRITE lock and try again.
  49925. */
  49926. assert( badHdr==0 || pWal->writeLock==0 );
  49927. if( badHdr ){
  49928. if( pWal->readOnly & WAL_SHM_RDONLY ){
  49929. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  49930. walUnlockShared(pWal, WAL_WRITE_LOCK);
  49931. rc = SQLITE_READONLY_RECOVERY;
  49932. }
  49933. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  49934. pWal->writeLock = 1;
  49935. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  49936. badHdr = walIndexTryHdr(pWal, pChanged);
  49937. if( badHdr ){
  49938. /* If the wal-index header is still malformed even while holding
  49939. ** a WRITE lock, it can only mean that the header is corrupted and
  49940. ** needs to be reconstructed. So run recovery to do exactly that.
  49941. */
  49942. rc = walIndexRecover(pWal);
  49943. *pChanged = 1;
  49944. }
  49945. }
  49946. pWal->writeLock = 0;
  49947. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49948. }
  49949. }
  49950. /* If the header is read successfully, check the version number to make
  49951. ** sure the wal-index was not constructed with some future format that
  49952. ** this version of SQLite cannot understand.
  49953. */
  49954. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  49955. rc = SQLITE_CANTOPEN_BKPT;
  49956. }
  49957. return rc;
  49958. }
  49959. /*
  49960. ** This is the value that walTryBeginRead returns when it needs to
  49961. ** be retried.
  49962. */
  49963. #define WAL_RETRY (-1)
  49964. /*
  49965. ** Attempt to start a read transaction. This might fail due to a race or
  49966. ** other transient condition. When that happens, it returns WAL_RETRY to
  49967. ** indicate to the caller that it is safe to retry immediately.
  49968. **
  49969. ** On success return SQLITE_OK. On a permanent failure (such an
  49970. ** I/O error or an SQLITE_BUSY because another process is running
  49971. ** recovery) return a positive error code.
  49972. **
  49973. ** The useWal parameter is true to force the use of the WAL and disable
  49974. ** the case where the WAL is bypassed because it has been completely
  49975. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  49976. ** to make a copy of the wal-index header into pWal->hdr. If the
  49977. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  49978. ** to the caller that the local paget cache is obsolete and needs to be
  49979. ** flushed.) When useWal==1, the wal-index header is assumed to already
  49980. ** be loaded and the pChanged parameter is unused.
  49981. **
  49982. ** The caller must set the cnt parameter to the number of prior calls to
  49983. ** this routine during the current read attempt that returned WAL_RETRY.
  49984. ** This routine will start taking more aggressive measures to clear the
  49985. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  49986. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  49987. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  49988. ** and is not honoring the locking protocol. There is a vanishingly small
  49989. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  49990. ** bad luck when there is lots of contention for the wal-index, but that
  49991. ** possibility is so small that it can be safely neglected, we believe.
  49992. **
  49993. ** On success, this routine obtains a read lock on
  49994. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  49995. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  49996. ** that means the Wal does not hold any read lock. The reader must not
  49997. ** access any database page that is modified by a WAL frame up to and
  49998. ** including frame number aReadMark[pWal->readLock]. The reader will
  49999. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  50000. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  50001. ** completely and get all content directly from the database file.
  50002. ** If the useWal parameter is 1 then the WAL will never be ignored and
  50003. ** this routine will always set pWal->readLock>0 on success.
  50004. ** When the read transaction is completed, the caller must release the
  50005. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  50006. **
  50007. ** This routine uses the nBackfill and aReadMark[] fields of the header
  50008. ** to select a particular WAL_READ_LOCK() that strives to let the
  50009. ** checkpoint process do as much work as possible. This routine might
  50010. ** update values of the aReadMark[] array in the header, but if it does
  50011. ** so it takes care to hold an exclusive lock on the corresponding
  50012. ** WAL_READ_LOCK() while changing values.
  50013. */
  50014. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  50015. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  50016. u32 mxReadMark; /* Largest aReadMark[] value */
  50017. int mxI; /* Index of largest aReadMark[] value */
  50018. int i; /* Loop counter */
  50019. int rc = SQLITE_OK; /* Return code */
  50020. u32 mxFrame; /* Wal frame to lock to */
  50021. assert( pWal->readLock<0 ); /* Not currently locked */
  50022. /* Take steps to avoid spinning forever if there is a protocol error.
  50023. **
  50024. ** Circumstances that cause a RETRY should only last for the briefest
  50025. ** instances of time. No I/O or other system calls are done while the
  50026. ** locks are held, so the locks should not be held for very long. But
  50027. ** if we are unlucky, another process that is holding a lock might get
  50028. ** paged out or take a page-fault that is time-consuming to resolve,
  50029. ** during the few nanoseconds that it is holding the lock. In that case,
  50030. ** it might take longer than normal for the lock to free.
  50031. **
  50032. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  50033. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  50034. ** is more of a scheduler yield than an actual delay. But on the 10th
  50035. ** an subsequent retries, the delays start becoming longer and longer,
  50036. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  50037. ** The total delay time before giving up is less than 10 seconds.
  50038. */
  50039. if( cnt>5 ){
  50040. int nDelay = 1; /* Pause time in microseconds */
  50041. if( cnt>100 ){
  50042. VVA_ONLY( pWal->lockError = 1; )
  50043. return SQLITE_PROTOCOL;
  50044. }
  50045. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  50046. sqlite3OsSleep(pWal->pVfs, nDelay);
  50047. }
  50048. if( !useWal ){
  50049. rc = walIndexReadHdr(pWal, pChanged);
  50050. if( rc==SQLITE_BUSY ){
  50051. /* If there is not a recovery running in another thread or process
  50052. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  50053. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  50054. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  50055. ** would be technically correct. But the race is benign since with
  50056. ** WAL_RETRY this routine will be called again and will probably be
  50057. ** right on the second iteration.
  50058. */
  50059. if( pWal->apWiData[0]==0 ){
  50060. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  50061. ** We assume this is a transient condition, so return WAL_RETRY. The
  50062. ** xShmMap() implementation used by the default unix and win32 VFS
  50063. ** modules may return SQLITE_BUSY due to a race condition in the
  50064. ** code that determines whether or not the shared-memory region
  50065. ** must be zeroed before the requested page is returned.
  50066. */
  50067. rc = WAL_RETRY;
  50068. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  50069. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  50070. rc = WAL_RETRY;
  50071. }else if( rc==SQLITE_BUSY ){
  50072. rc = SQLITE_BUSY_RECOVERY;
  50073. }
  50074. }
  50075. if( rc!=SQLITE_OK ){
  50076. return rc;
  50077. }
  50078. }
  50079. pInfo = walCkptInfo(pWal);
  50080. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  50081. #ifdef SQLITE_ENABLE_SNAPSHOT
  50082. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
  50083. || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
  50084. #endif
  50085. ){
  50086. /* The WAL has been completely backfilled (or it is empty).
  50087. ** and can be safely ignored.
  50088. */
  50089. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  50090. walShmBarrier(pWal);
  50091. if( rc==SQLITE_OK ){
  50092. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  50093. /* It is not safe to allow the reader to continue here if frames
  50094. ** may have been appended to the log before READ_LOCK(0) was obtained.
  50095. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  50096. ** which implies that the database file contains a trustworthy
  50097. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  50098. ** happening, this is usually correct.
  50099. **
  50100. ** However, if frames have been appended to the log (or if the log
  50101. ** is wrapped and written for that matter) before the READ_LOCK(0)
  50102. ** is obtained, that is not necessarily true. A checkpointer may
  50103. ** have started to backfill the appended frames but crashed before
  50104. ** it finished. Leaving a corrupt image in the database file.
  50105. */
  50106. walUnlockShared(pWal, WAL_READ_LOCK(0));
  50107. return WAL_RETRY;
  50108. }
  50109. pWal->readLock = 0;
  50110. return SQLITE_OK;
  50111. }else if( rc!=SQLITE_BUSY ){
  50112. return rc;
  50113. }
  50114. }
  50115. /* If we get this far, it means that the reader will want to use
  50116. ** the WAL to get at content from recent commits. The job now is
  50117. ** to select one of the aReadMark[] entries that is closest to
  50118. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  50119. */
  50120. mxReadMark = 0;
  50121. mxI = 0;
  50122. mxFrame = pWal->hdr.mxFrame;
  50123. #ifdef SQLITE_ENABLE_SNAPSHOT
  50124. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  50125. mxFrame = pWal->pSnapshot->mxFrame;
  50126. }
  50127. #endif
  50128. for(i=1; i<WAL_NREADER; i++){
  50129. u32 thisMark = pInfo->aReadMark[i];
  50130. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  50131. assert( thisMark!=READMARK_NOT_USED );
  50132. mxReadMark = thisMark;
  50133. mxI = i;
  50134. }
  50135. }
  50136. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  50137. && (mxReadMark<mxFrame || mxI==0)
  50138. ){
  50139. for(i=1; i<WAL_NREADER; i++){
  50140. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  50141. if( rc==SQLITE_OK ){
  50142. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  50143. mxI = i;
  50144. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  50145. break;
  50146. }else if( rc!=SQLITE_BUSY ){
  50147. return rc;
  50148. }
  50149. }
  50150. }
  50151. if( mxI==0 ){
  50152. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  50153. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  50154. }
  50155. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  50156. if( rc ){
  50157. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  50158. }
  50159. /* Now that the read-lock has been obtained, check that neither the
  50160. ** value in the aReadMark[] array or the contents of the wal-index
  50161. ** header have changed.
  50162. **
  50163. ** It is necessary to check that the wal-index header did not change
  50164. ** between the time it was read and when the shared-lock was obtained
  50165. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  50166. ** that the log file may have been wrapped by a writer, or that frames
  50167. ** that occur later in the log than pWal->hdr.mxFrame may have been
  50168. ** copied into the database by a checkpointer. If either of these things
  50169. ** happened, then reading the database with the current value of
  50170. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  50171. ** instead.
  50172. **
  50173. ** Before checking that the live wal-index header has not changed
  50174. ** since it was read, set Wal.minFrame to the first frame in the wal
  50175. ** file that has not yet been checkpointed. This client will not need
  50176. ** to read any frames earlier than minFrame from the wal file - they
  50177. ** can be safely read directly from the database file.
  50178. **
  50179. ** Because a ShmBarrier() call is made between taking the copy of
  50180. ** nBackfill and checking that the wal-header in shared-memory still
  50181. ** matches the one cached in pWal->hdr, it is guaranteed that the
  50182. ** checkpointer that set nBackfill was not working with a wal-index
  50183. ** header newer than that cached in pWal->hdr. If it were, that could
  50184. ** cause a problem. The checkpointer could omit to checkpoint
  50185. ** a version of page X that lies before pWal->minFrame (call that version
  50186. ** A) on the basis that there is a newer version (version B) of the same
  50187. ** page later in the wal file. But if version B happens to like past
  50188. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  50189. ** that it can read version A from the database file. However, since
  50190. ** we can guarantee that the checkpointer that set nBackfill could not
  50191. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  50192. */
  50193. pWal->minFrame = pInfo->nBackfill+1;
  50194. walShmBarrier(pWal);
  50195. if( pInfo->aReadMark[mxI]!=mxReadMark
  50196. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  50197. ){
  50198. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  50199. return WAL_RETRY;
  50200. }else{
  50201. assert( mxReadMark<=pWal->hdr.mxFrame );
  50202. pWal->readLock = (i16)mxI;
  50203. }
  50204. return rc;
  50205. }
  50206. /*
  50207. ** Begin a read transaction on the database.
  50208. **
  50209. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  50210. ** it takes a snapshot of the state of the WAL and wal-index for the current
  50211. ** instant in time. The current thread will continue to use this snapshot.
  50212. ** Other threads might append new content to the WAL and wal-index but
  50213. ** that extra content is ignored by the current thread.
  50214. **
  50215. ** If the database contents have changes since the previous read
  50216. ** transaction, then *pChanged is set to 1 before returning. The
  50217. ** Pager layer will use this to know that is cache is stale and
  50218. ** needs to be flushed.
  50219. */
  50220. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  50221. int rc; /* Return code */
  50222. int cnt = 0; /* Number of TryBeginRead attempts */
  50223. #ifdef SQLITE_ENABLE_SNAPSHOT
  50224. int bChanged = 0;
  50225. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  50226. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  50227. bChanged = 1;
  50228. }
  50229. #endif
  50230. do{
  50231. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  50232. }while( rc==WAL_RETRY );
  50233. testcase( (rc&0xff)==SQLITE_BUSY );
  50234. testcase( (rc&0xff)==SQLITE_IOERR );
  50235. testcase( rc==SQLITE_PROTOCOL );
  50236. testcase( rc==SQLITE_OK );
  50237. #ifdef SQLITE_ENABLE_SNAPSHOT
  50238. if( rc==SQLITE_OK ){
  50239. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  50240. /* At this point the client has a lock on an aReadMark[] slot holding
  50241. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  50242. ** is populated with the wal-index header corresponding to the head
  50243. ** of the wal file. Verify that pSnapshot is still valid before
  50244. ** continuing. Reasons why pSnapshot might no longer be valid:
  50245. **
  50246. ** (1) The WAL file has been reset since the snapshot was taken.
  50247. ** In this case, the salt will have changed.
  50248. **
  50249. ** (2) A checkpoint as been attempted that wrote frames past
  50250. ** pSnapshot->mxFrame into the database file. Note that the
  50251. ** checkpoint need not have completed for this to cause problems.
  50252. */
  50253. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  50254. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  50255. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  50256. /* It is possible that there is a checkpointer thread running
  50257. ** concurrent with this code. If this is the case, it may be that the
  50258. ** checkpointer has already determined that it will checkpoint
  50259. ** snapshot X, where X is later in the wal file than pSnapshot, but
  50260. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  50261. ** its intent. To avoid the race condition this leads to, ensure that
  50262. ** there is no checkpointer process by taking a shared CKPT lock
  50263. ** before checking pInfo->nBackfillAttempted. */
  50264. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  50265. if( rc==SQLITE_OK ){
  50266. /* Check that the wal file has not been wrapped. Assuming that it has
  50267. ** not, also check that no checkpointer has attempted to checkpoint any
  50268. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  50269. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  50270. ** with *pSnapshot and set *pChanged as appropriate for opening the
  50271. ** snapshot. */
  50272. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  50273. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  50274. ){
  50275. assert( pWal->readLock>0 );
  50276. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  50277. *pChanged = bChanged;
  50278. }else{
  50279. rc = SQLITE_BUSY_SNAPSHOT;
  50280. }
  50281. /* Release the shared CKPT lock obtained above. */
  50282. walUnlockShared(pWal, WAL_CKPT_LOCK);
  50283. }
  50284. if( rc!=SQLITE_OK ){
  50285. sqlite3WalEndReadTransaction(pWal);
  50286. }
  50287. }
  50288. }
  50289. #endif
  50290. return rc;
  50291. }
  50292. /*
  50293. ** Finish with a read transaction. All this does is release the
  50294. ** read-lock.
  50295. */
  50296. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  50297. sqlite3WalEndWriteTransaction(pWal);
  50298. if( pWal->readLock>=0 ){
  50299. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  50300. pWal->readLock = -1;
  50301. }
  50302. }
  50303. /*
  50304. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  50305. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  50306. ** to zero.
  50307. **
  50308. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  50309. ** error does occur, the final value of *piRead is undefined.
  50310. */
  50311. SQLITE_PRIVATE int sqlite3WalFindFrame(
  50312. Wal *pWal, /* WAL handle */
  50313. Pgno pgno, /* Database page number to read data for */
  50314. u32 *piRead /* OUT: Frame number (or zero) */
  50315. ){
  50316. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  50317. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  50318. int iHash; /* Used to loop through N hash tables */
  50319. int iMinHash;
  50320. /* This routine is only be called from within a read transaction. */
  50321. assert( pWal->readLock>=0 || pWal->lockError );
  50322. /* If the "last page" field of the wal-index header snapshot is 0, then
  50323. ** no data will be read from the wal under any circumstances. Return early
  50324. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  50325. ** then the WAL is ignored by the reader so return early, as if the
  50326. ** WAL were empty.
  50327. */
  50328. if( iLast==0 || pWal->readLock==0 ){
  50329. *piRead = 0;
  50330. return SQLITE_OK;
  50331. }
  50332. /* Search the hash table or tables for an entry matching page number
  50333. ** pgno. Each iteration of the following for() loop searches one
  50334. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  50335. **
  50336. ** This code might run concurrently to the code in walIndexAppend()
  50337. ** that adds entries to the wal-index (and possibly to this hash
  50338. ** table). This means the value just read from the hash
  50339. ** slot (aHash[iKey]) may have been added before or after the
  50340. ** current read transaction was opened. Values added after the
  50341. ** read transaction was opened may have been written incorrectly -
  50342. ** i.e. these slots may contain garbage data. However, we assume
  50343. ** that any slots written before the current read transaction was
  50344. ** opened remain unmodified.
  50345. **
  50346. ** For the reasons above, the if(...) condition featured in the inner
  50347. ** loop of the following block is more stringent that would be required
  50348. ** if we had exclusive access to the hash-table:
  50349. **
  50350. ** (aPgno[iFrame]==pgno):
  50351. ** This condition filters out normal hash-table collisions.
  50352. **
  50353. ** (iFrame<=iLast):
  50354. ** This condition filters out entries that were added to the hash
  50355. ** table after the current read-transaction had started.
  50356. */
  50357. iMinHash = walFramePage(pWal->minFrame);
  50358. for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
  50359. volatile ht_slot *aHash; /* Pointer to hash table */
  50360. volatile u32 *aPgno; /* Pointer to array of page numbers */
  50361. u32 iZero; /* Frame number corresponding to aPgno[0] */
  50362. int iKey; /* Hash slot index */
  50363. int nCollide; /* Number of hash collisions remaining */
  50364. int rc; /* Error code */
  50365. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  50366. if( rc!=SQLITE_OK ){
  50367. return rc;
  50368. }
  50369. nCollide = HASHTABLE_NSLOT;
  50370. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  50371. u32 iFrame = aHash[iKey] + iZero;
  50372. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  50373. assert( iFrame>iRead || CORRUPT_DB );
  50374. iRead = iFrame;
  50375. }
  50376. if( (nCollide--)==0 ){
  50377. return SQLITE_CORRUPT_BKPT;
  50378. }
  50379. }
  50380. }
  50381. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  50382. /* If expensive assert() statements are available, do a linear search
  50383. ** of the wal-index file content. Make sure the results agree with the
  50384. ** result obtained using the hash indexes above. */
  50385. {
  50386. u32 iRead2 = 0;
  50387. u32 iTest;
  50388. assert( pWal->minFrame>0 );
  50389. for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
  50390. if( walFramePgno(pWal, iTest)==pgno ){
  50391. iRead2 = iTest;
  50392. break;
  50393. }
  50394. }
  50395. assert( iRead==iRead2 );
  50396. }
  50397. #endif
  50398. *piRead = iRead;
  50399. return SQLITE_OK;
  50400. }
  50401. /*
  50402. ** Read the contents of frame iRead from the wal file into buffer pOut
  50403. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  50404. ** error code otherwise.
  50405. */
  50406. SQLITE_PRIVATE int sqlite3WalReadFrame(
  50407. Wal *pWal, /* WAL handle */
  50408. u32 iRead, /* Frame to read */
  50409. int nOut, /* Size of buffer pOut in bytes */
  50410. u8 *pOut /* Buffer to write page data to */
  50411. ){
  50412. int sz;
  50413. i64 iOffset;
  50414. sz = pWal->hdr.szPage;
  50415. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  50416. testcase( sz<=32768 );
  50417. testcase( sz>=65536 );
  50418. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  50419. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  50420. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  50421. }
  50422. /*
  50423. ** Return the size of the database in pages (or zero, if unknown).
  50424. */
  50425. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  50426. if( pWal && ALWAYS(pWal->readLock>=0) ){
  50427. return pWal->hdr.nPage;
  50428. }
  50429. return 0;
  50430. }
  50431. /*
  50432. ** This function starts a write transaction on the WAL.
  50433. **
  50434. ** A read transaction must have already been started by a prior call
  50435. ** to sqlite3WalBeginReadTransaction().
  50436. **
  50437. ** If another thread or process has written into the database since
  50438. ** the read transaction was started, then it is not possible for this
  50439. ** thread to write as doing so would cause a fork. So this routine
  50440. ** returns SQLITE_BUSY in that case and no write transaction is started.
  50441. **
  50442. ** There can only be a single writer active at a time.
  50443. */
  50444. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  50445. int rc;
  50446. /* Cannot start a write transaction without first holding a read
  50447. ** transaction. */
  50448. assert( pWal->readLock>=0 );
  50449. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  50450. if( pWal->readOnly ){
  50451. return SQLITE_READONLY;
  50452. }
  50453. /* Only one writer allowed at a time. Get the write lock. Return
  50454. ** SQLITE_BUSY if unable.
  50455. */
  50456. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  50457. if( rc ){
  50458. return rc;
  50459. }
  50460. pWal->writeLock = 1;
  50461. /* If another connection has written to the database file since the
  50462. ** time the read transaction on this connection was started, then
  50463. ** the write is disallowed.
  50464. */
  50465. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  50466. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  50467. pWal->writeLock = 0;
  50468. rc = SQLITE_BUSY_SNAPSHOT;
  50469. }
  50470. return rc;
  50471. }
  50472. /*
  50473. ** End a write transaction. The commit has already been done. This
  50474. ** routine merely releases the lock.
  50475. */
  50476. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  50477. if( pWal->writeLock ){
  50478. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  50479. pWal->writeLock = 0;
  50480. pWal->iReCksum = 0;
  50481. pWal->truncateOnCommit = 0;
  50482. }
  50483. return SQLITE_OK;
  50484. }
  50485. /*
  50486. ** If any data has been written (but not committed) to the log file, this
  50487. ** function moves the write-pointer back to the start of the transaction.
  50488. **
  50489. ** Additionally, the callback function is invoked for each frame written
  50490. ** to the WAL since the start of the transaction. If the callback returns
  50491. ** other than SQLITE_OK, it is not invoked again and the error code is
  50492. ** returned to the caller.
  50493. **
  50494. ** Otherwise, if the callback function does not return an error, this
  50495. ** function returns SQLITE_OK.
  50496. */
  50497. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  50498. int rc = SQLITE_OK;
  50499. if( ALWAYS(pWal->writeLock) ){
  50500. Pgno iMax = pWal->hdr.mxFrame;
  50501. Pgno iFrame;
  50502. /* Restore the clients cache of the wal-index header to the state it
  50503. ** was in before the client began writing to the database.
  50504. */
  50505. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  50506. for(iFrame=pWal->hdr.mxFrame+1;
  50507. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  50508. iFrame++
  50509. ){
  50510. /* This call cannot fail. Unless the page for which the page number
  50511. ** is passed as the second argument is (a) in the cache and
  50512. ** (b) has an outstanding reference, then xUndo is either a no-op
  50513. ** (if (a) is false) or simply expels the page from the cache (if (b)
  50514. ** is false).
  50515. **
  50516. ** If the upper layer is doing a rollback, it is guaranteed that there
  50517. ** are no outstanding references to any page other than page 1. And
  50518. ** page 1 is never written to the log until the transaction is
  50519. ** committed. As a result, the call to xUndo may not fail.
  50520. */
  50521. assert( walFramePgno(pWal, iFrame)!=1 );
  50522. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  50523. }
  50524. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  50525. }
  50526. return rc;
  50527. }
  50528. /*
  50529. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  50530. ** values. This function populates the array with values required to
  50531. ** "rollback" the write position of the WAL handle back to the current
  50532. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  50533. */
  50534. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  50535. assert( pWal->writeLock );
  50536. aWalData[0] = pWal->hdr.mxFrame;
  50537. aWalData[1] = pWal->hdr.aFrameCksum[0];
  50538. aWalData[2] = pWal->hdr.aFrameCksum[1];
  50539. aWalData[3] = pWal->nCkpt;
  50540. }
  50541. /*
  50542. ** Move the write position of the WAL back to the point identified by
  50543. ** the values in the aWalData[] array. aWalData must point to an array
  50544. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  50545. ** by a call to WalSavepoint().
  50546. */
  50547. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  50548. int rc = SQLITE_OK;
  50549. assert( pWal->writeLock );
  50550. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  50551. if( aWalData[3]!=pWal->nCkpt ){
  50552. /* This savepoint was opened immediately after the write-transaction
  50553. ** was started. Right after that, the writer decided to wrap around
  50554. ** to the start of the log. Update the savepoint values to match.
  50555. */
  50556. aWalData[0] = 0;
  50557. aWalData[3] = pWal->nCkpt;
  50558. }
  50559. if( aWalData[0]<pWal->hdr.mxFrame ){
  50560. pWal->hdr.mxFrame = aWalData[0];
  50561. pWal->hdr.aFrameCksum[0] = aWalData[1];
  50562. pWal->hdr.aFrameCksum[1] = aWalData[2];
  50563. walCleanupHash(pWal);
  50564. }
  50565. return rc;
  50566. }
  50567. /*
  50568. ** This function is called just before writing a set of frames to the log
  50569. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  50570. ** to the current log file, it is possible to overwrite the start of the
  50571. ** existing log file with the new frames (i.e. "reset" the log). If so,
  50572. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  50573. ** unchanged.
  50574. **
  50575. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  50576. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  50577. ** if an error occurs.
  50578. */
  50579. static int walRestartLog(Wal *pWal){
  50580. int rc = SQLITE_OK;
  50581. int cnt;
  50582. if( pWal->readLock==0 ){
  50583. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  50584. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  50585. if( pInfo->nBackfill>0 ){
  50586. u32 salt1;
  50587. sqlite3_randomness(4, &salt1);
  50588. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  50589. if( rc==SQLITE_OK ){
  50590. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  50591. ** readers are currently using the WAL), then the transactions
  50592. ** frames will overwrite the start of the existing log. Update the
  50593. ** wal-index header to reflect this.
  50594. **
  50595. ** In theory it would be Ok to update the cache of the header only
  50596. ** at this point. But updating the actual wal-index header is also
  50597. ** safe and means there is no special case for sqlite3WalUndo()
  50598. ** to handle if this transaction is rolled back. */
  50599. walRestartHdr(pWal, salt1);
  50600. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  50601. }else if( rc!=SQLITE_BUSY ){
  50602. return rc;
  50603. }
  50604. }
  50605. walUnlockShared(pWal, WAL_READ_LOCK(0));
  50606. pWal->readLock = -1;
  50607. cnt = 0;
  50608. do{
  50609. int notUsed;
  50610. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  50611. }while( rc==WAL_RETRY );
  50612. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  50613. testcase( (rc&0xff)==SQLITE_IOERR );
  50614. testcase( rc==SQLITE_PROTOCOL );
  50615. testcase( rc==SQLITE_OK );
  50616. }
  50617. return rc;
  50618. }
  50619. /*
  50620. ** Information about the current state of the WAL file and where
  50621. ** the next fsync should occur - passed from sqlite3WalFrames() into
  50622. ** walWriteToLog().
  50623. */
  50624. typedef struct WalWriter {
  50625. Wal *pWal; /* The complete WAL information */
  50626. sqlite3_file *pFd; /* The WAL file to which we write */
  50627. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  50628. int syncFlags; /* Flags for the fsync */
  50629. int szPage; /* Size of one page */
  50630. } WalWriter;
  50631. /*
  50632. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  50633. ** Do a sync when crossing the p->iSyncPoint boundary.
  50634. **
  50635. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  50636. ** first write the part before iSyncPoint, then sync, then write the
  50637. ** rest.
  50638. */
  50639. static int walWriteToLog(
  50640. WalWriter *p, /* WAL to write to */
  50641. void *pContent, /* Content to be written */
  50642. int iAmt, /* Number of bytes to write */
  50643. sqlite3_int64 iOffset /* Start writing at this offset */
  50644. ){
  50645. int rc;
  50646. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  50647. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  50648. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  50649. if( rc ) return rc;
  50650. iOffset += iFirstAmt;
  50651. iAmt -= iFirstAmt;
  50652. pContent = (void*)(iFirstAmt + (char*)pContent);
  50653. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  50654. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  50655. if( iAmt==0 || rc ) return rc;
  50656. }
  50657. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  50658. return rc;
  50659. }
  50660. /*
  50661. ** Write out a single frame of the WAL
  50662. */
  50663. static int walWriteOneFrame(
  50664. WalWriter *p, /* Where to write the frame */
  50665. PgHdr *pPage, /* The page of the frame to be written */
  50666. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  50667. sqlite3_int64 iOffset /* Byte offset at which to write */
  50668. ){
  50669. int rc; /* Result code from subfunctions */
  50670. void *pData; /* Data actually written */
  50671. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  50672. #if defined(SQLITE_HAS_CODEC)
  50673. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  50674. #else
  50675. pData = pPage->pData;
  50676. #endif
  50677. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  50678. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  50679. if( rc ) return rc;
  50680. /* Write the page data */
  50681. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  50682. return rc;
  50683. }
  50684. /*
  50685. ** This function is called as part of committing a transaction within which
  50686. ** one or more frames have been overwritten. It updates the checksums for
  50687. ** all frames written to the wal file by the current transaction starting
  50688. ** with the earliest to have been overwritten.
  50689. **
  50690. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  50691. */
  50692. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  50693. const int szPage = pWal->szPage;/* Database page size */
  50694. int rc = SQLITE_OK; /* Return code */
  50695. u8 *aBuf; /* Buffer to load data from wal file into */
  50696. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  50697. u32 iRead; /* Next frame to read from wal file */
  50698. i64 iCksumOff;
  50699. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  50700. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  50701. /* Find the checksum values to use as input for the recalculating the
  50702. ** first checksum. If the first frame is frame 1 (implying that the current
  50703. ** transaction restarted the wal file), these values must be read from the
  50704. ** wal-file header. Otherwise, read them from the frame header of the
  50705. ** previous frame. */
  50706. assert( pWal->iReCksum>0 );
  50707. if( pWal->iReCksum==1 ){
  50708. iCksumOff = 24;
  50709. }else{
  50710. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  50711. }
  50712. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  50713. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  50714. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  50715. iRead = pWal->iReCksum;
  50716. pWal->iReCksum = 0;
  50717. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  50718. i64 iOff = walFrameOffset(iRead, szPage);
  50719. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  50720. if( rc==SQLITE_OK ){
  50721. u32 iPgno, nDbSize;
  50722. iPgno = sqlite3Get4byte(aBuf);
  50723. nDbSize = sqlite3Get4byte(&aBuf[4]);
  50724. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  50725. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  50726. }
  50727. }
  50728. sqlite3_free(aBuf);
  50729. return rc;
  50730. }
  50731. /*
  50732. ** Write a set of frames to the log. The caller must hold the write-lock
  50733. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  50734. */
  50735. SQLITE_PRIVATE int sqlite3WalFrames(
  50736. Wal *pWal, /* Wal handle to write to */
  50737. int szPage, /* Database page-size in bytes */
  50738. PgHdr *pList, /* List of dirty pages to write */
  50739. Pgno nTruncate, /* Database size after this commit */
  50740. int isCommit, /* True if this is a commit */
  50741. int sync_flags /* Flags to pass to OsSync() (or 0) */
  50742. ){
  50743. int rc; /* Used to catch return codes */
  50744. u32 iFrame; /* Next frame address */
  50745. PgHdr *p; /* Iterator to run through pList with. */
  50746. PgHdr *pLast = 0; /* Last frame in list */
  50747. int nExtra = 0; /* Number of extra copies of last page */
  50748. int szFrame; /* The size of a single frame */
  50749. i64 iOffset; /* Next byte to write in WAL file */
  50750. WalWriter w; /* The writer */
  50751. u32 iFirst = 0; /* First frame that may be overwritten */
  50752. WalIndexHdr *pLive; /* Pointer to shared header */
  50753. assert( pList );
  50754. assert( pWal->writeLock );
  50755. /* If this frame set completes a transaction, then nTruncate>0. If
  50756. ** nTruncate==0 then this frame set does not complete the transaction. */
  50757. assert( (isCommit!=0)==(nTruncate!=0) );
  50758. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  50759. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  50760. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  50761. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  50762. }
  50763. #endif
  50764. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  50765. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  50766. iFirst = pLive->mxFrame+1;
  50767. }
  50768. /* See if it is possible to write these frames into the start of the
  50769. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  50770. */
  50771. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  50772. return rc;
  50773. }
  50774. /* If this is the first frame written into the log, write the WAL
  50775. ** header to the start of the WAL file. See comments at the top of
  50776. ** this source file for a description of the WAL header format.
  50777. */
  50778. iFrame = pWal->hdr.mxFrame;
  50779. if( iFrame==0 ){
  50780. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  50781. u32 aCksum[2]; /* Checksum for wal-header */
  50782. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  50783. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  50784. sqlite3Put4byte(&aWalHdr[8], szPage);
  50785. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  50786. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  50787. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  50788. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  50789. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  50790. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  50791. pWal->szPage = szPage;
  50792. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  50793. pWal->hdr.aFrameCksum[0] = aCksum[0];
  50794. pWal->hdr.aFrameCksum[1] = aCksum[1];
  50795. pWal->truncateOnCommit = 1;
  50796. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  50797. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  50798. if( rc!=SQLITE_OK ){
  50799. return rc;
  50800. }
  50801. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  50802. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  50803. ** an out-of-order write following a WAL restart could result in
  50804. ** database corruption. See the ticket:
  50805. **
  50806. ** http://localhost:591/sqlite/info/ff5be73dee
  50807. */
  50808. if( pWal->syncHeader && sync_flags ){
  50809. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  50810. if( rc ) return rc;
  50811. }
  50812. }
  50813. assert( (int)pWal->szPage==szPage );
  50814. /* Setup information needed to write frames into the WAL */
  50815. w.pWal = pWal;
  50816. w.pFd = pWal->pWalFd;
  50817. w.iSyncPoint = 0;
  50818. w.syncFlags = sync_flags;
  50819. w.szPage = szPage;
  50820. iOffset = walFrameOffset(iFrame+1, szPage);
  50821. szFrame = szPage + WAL_FRAME_HDRSIZE;
  50822. /* Write all frames into the log file exactly once */
  50823. for(p=pList; p; p=p->pDirty){
  50824. int nDbSize; /* 0 normally. Positive == commit flag */
  50825. /* Check if this page has already been written into the wal file by
  50826. ** the current transaction. If so, overwrite the existing frame and
  50827. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  50828. ** checksums must be recomputed when the transaction is committed. */
  50829. if( iFirst && (p->pDirty || isCommit==0) ){
  50830. u32 iWrite = 0;
  50831. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  50832. assert( rc==SQLITE_OK || iWrite==0 );
  50833. if( iWrite>=iFirst ){
  50834. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  50835. void *pData;
  50836. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  50837. pWal->iReCksum = iWrite;
  50838. }
  50839. #if defined(SQLITE_HAS_CODEC)
  50840. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  50841. #else
  50842. pData = p->pData;
  50843. #endif
  50844. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  50845. if( rc ) return rc;
  50846. p->flags &= ~PGHDR_WAL_APPEND;
  50847. continue;
  50848. }
  50849. }
  50850. iFrame++;
  50851. assert( iOffset==walFrameOffset(iFrame, szPage) );
  50852. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  50853. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  50854. if( rc ) return rc;
  50855. pLast = p;
  50856. iOffset += szFrame;
  50857. p->flags |= PGHDR_WAL_APPEND;
  50858. }
  50859. /* Recalculate checksums within the wal file if required. */
  50860. if( isCommit && pWal->iReCksum ){
  50861. rc = walRewriteChecksums(pWal, iFrame);
  50862. if( rc ) return rc;
  50863. }
  50864. /* If this is the end of a transaction, then we might need to pad
  50865. ** the transaction and/or sync the WAL file.
  50866. **
  50867. ** Padding and syncing only occur if this set of frames complete a
  50868. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  50869. ** or synchronous==OFF, then no padding or syncing are needed.
  50870. **
  50871. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  50872. ** needed and only the sync is done. If padding is needed, then the
  50873. ** final frame is repeated (with its commit mark) until the next sector
  50874. ** boundary is crossed. Only the part of the WAL prior to the last
  50875. ** sector boundary is synced; the part of the last frame that extends
  50876. ** past the sector boundary is written after the sync.
  50877. */
  50878. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  50879. if( pWal->padToSectorBoundary ){
  50880. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  50881. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  50882. while( iOffset<w.iSyncPoint ){
  50883. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  50884. if( rc ) return rc;
  50885. iOffset += szFrame;
  50886. nExtra++;
  50887. }
  50888. }else{
  50889. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  50890. }
  50891. }
  50892. /* If this frame set completes the first transaction in the WAL and
  50893. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  50894. ** journal size limit, if possible.
  50895. */
  50896. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  50897. i64 sz = pWal->mxWalSize;
  50898. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  50899. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  50900. }
  50901. walLimitSize(pWal, sz);
  50902. pWal->truncateOnCommit = 0;
  50903. }
  50904. /* Append data to the wal-index. It is not necessary to lock the
  50905. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  50906. ** guarantees that there are no other writers, and no data that may
  50907. ** be in use by existing readers is being overwritten.
  50908. */
  50909. iFrame = pWal->hdr.mxFrame;
  50910. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  50911. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  50912. iFrame++;
  50913. rc = walIndexAppend(pWal, iFrame, p->pgno);
  50914. }
  50915. while( rc==SQLITE_OK && nExtra>0 ){
  50916. iFrame++;
  50917. nExtra--;
  50918. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  50919. }
  50920. if( rc==SQLITE_OK ){
  50921. /* Update the private copy of the header. */
  50922. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  50923. testcase( szPage<=32768 );
  50924. testcase( szPage>=65536 );
  50925. pWal->hdr.mxFrame = iFrame;
  50926. if( isCommit ){
  50927. pWal->hdr.iChange++;
  50928. pWal->hdr.nPage = nTruncate;
  50929. }
  50930. /* If this is a commit, update the wal-index header too. */
  50931. if( isCommit ){
  50932. walIndexWriteHdr(pWal);
  50933. pWal->iCallback = iFrame;
  50934. }
  50935. }
  50936. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  50937. return rc;
  50938. }
  50939. /*
  50940. ** This routine is called to implement sqlite3_wal_checkpoint() and
  50941. ** related interfaces.
  50942. **
  50943. ** Obtain a CHECKPOINT lock and then backfill as much information as
  50944. ** we can from WAL into the database.
  50945. **
  50946. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  50947. ** callback. In this case this function runs a blocking checkpoint.
  50948. */
  50949. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  50950. Wal *pWal, /* Wal connection */
  50951. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  50952. int (*xBusy)(void*), /* Function to call when busy */
  50953. void *pBusyArg, /* Context argument for xBusyHandler */
  50954. int sync_flags, /* Flags to sync db file with (or 0) */
  50955. int nBuf, /* Size of temporary buffer */
  50956. u8 *zBuf, /* Temporary buffer to use */
  50957. int *pnLog, /* OUT: Number of frames in WAL */
  50958. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  50959. ){
  50960. int rc; /* Return code */
  50961. int isChanged = 0; /* True if a new wal-index header is loaded */
  50962. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  50963. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  50964. assert( pWal->ckptLock==0 );
  50965. assert( pWal->writeLock==0 );
  50966. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  50967. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  50968. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  50969. if( pWal->readOnly ) return SQLITE_READONLY;
  50970. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  50971. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  50972. ** "checkpoint" lock on the database file. */
  50973. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  50974. if( rc ){
  50975. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  50976. ** checkpoint operation at the same time, the lock cannot be obtained and
  50977. ** SQLITE_BUSY is returned.
  50978. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  50979. ** it will not be invoked in this case.
  50980. */
  50981. testcase( rc==SQLITE_BUSY );
  50982. testcase( xBusy!=0 );
  50983. return rc;
  50984. }
  50985. pWal->ckptLock = 1;
  50986. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  50987. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  50988. ** file.
  50989. **
  50990. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  50991. ** immediately, and a busy-handler is configured, it is invoked and the
  50992. ** writer lock retried until either the busy-handler returns 0 or the
  50993. ** lock is successfully obtained.
  50994. */
  50995. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  50996. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  50997. if( rc==SQLITE_OK ){
  50998. pWal->writeLock = 1;
  50999. }else if( rc==SQLITE_BUSY ){
  51000. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  51001. xBusy2 = 0;
  51002. rc = SQLITE_OK;
  51003. }
  51004. }
  51005. /* Read the wal-index header. */
  51006. if( rc==SQLITE_OK ){
  51007. rc = walIndexReadHdr(pWal, &isChanged);
  51008. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  51009. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  51010. }
  51011. }
  51012. /* Copy data from the log to the database file. */
  51013. if( rc==SQLITE_OK ){
  51014. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  51015. rc = SQLITE_CORRUPT_BKPT;
  51016. }else{
  51017. rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  51018. }
  51019. /* If no error occurred, set the output variables. */
  51020. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  51021. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  51022. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  51023. }
  51024. }
  51025. if( isChanged ){
  51026. /* If a new wal-index header was loaded before the checkpoint was
  51027. ** performed, then the pager-cache associated with pWal is now
  51028. ** out of date. So zero the cached wal-index header to ensure that
  51029. ** next time the pager opens a snapshot on this database it knows that
  51030. ** the cache needs to be reset.
  51031. */
  51032. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  51033. }
  51034. /* Release the locks. */
  51035. sqlite3WalEndWriteTransaction(pWal);
  51036. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  51037. pWal->ckptLock = 0;
  51038. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  51039. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  51040. }
  51041. /* Return the value to pass to a sqlite3_wal_hook callback, the
  51042. ** number of frames in the WAL at the point of the last commit since
  51043. ** sqlite3WalCallback() was called. If no commits have occurred since
  51044. ** the last call, then return 0.
  51045. */
  51046. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  51047. u32 ret = 0;
  51048. if( pWal ){
  51049. ret = pWal->iCallback;
  51050. pWal->iCallback = 0;
  51051. }
  51052. return (int)ret;
  51053. }
  51054. /*
  51055. ** This function is called to change the WAL subsystem into or out
  51056. ** of locking_mode=EXCLUSIVE.
  51057. **
  51058. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  51059. ** into locking_mode=NORMAL. This means that we must acquire a lock
  51060. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  51061. ** or if the acquisition of the lock fails, then return 0. If the
  51062. ** transition out of exclusive-mode is successful, return 1. This
  51063. ** operation must occur while the pager is still holding the exclusive
  51064. ** lock on the main database file.
  51065. **
  51066. ** If op is one, then change from locking_mode=NORMAL into
  51067. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  51068. ** be released. Return 1 if the transition is made and 0 if the
  51069. ** WAL is already in exclusive-locking mode - meaning that this
  51070. ** routine is a no-op. The pager must already hold the exclusive lock
  51071. ** on the main database file before invoking this operation.
  51072. **
  51073. ** If op is negative, then do a dry-run of the op==1 case but do
  51074. ** not actually change anything. The pager uses this to see if it
  51075. ** should acquire the database exclusive lock prior to invoking
  51076. ** the op==1 case.
  51077. */
  51078. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  51079. int rc;
  51080. assert( pWal->writeLock==0 );
  51081. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  51082. /* pWal->readLock is usually set, but might be -1 if there was a
  51083. ** prior error while attempting to acquire are read-lock. This cannot
  51084. ** happen if the connection is actually in exclusive mode (as no xShmLock
  51085. ** locks are taken in this case). Nor should the pager attempt to
  51086. ** upgrade to exclusive-mode following such an error.
  51087. */
  51088. assert( pWal->readLock>=0 || pWal->lockError );
  51089. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  51090. if( op==0 ){
  51091. if( pWal->exclusiveMode ){
  51092. pWal->exclusiveMode = 0;
  51093. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  51094. pWal->exclusiveMode = 1;
  51095. }
  51096. rc = pWal->exclusiveMode==0;
  51097. }else{
  51098. /* Already in locking_mode=NORMAL */
  51099. rc = 0;
  51100. }
  51101. }else if( op>0 ){
  51102. assert( pWal->exclusiveMode==0 );
  51103. assert( pWal->readLock>=0 );
  51104. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  51105. pWal->exclusiveMode = 1;
  51106. rc = 1;
  51107. }else{
  51108. rc = pWal->exclusiveMode==0;
  51109. }
  51110. return rc;
  51111. }
  51112. /*
  51113. ** Return true if the argument is non-NULL and the WAL module is using
  51114. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  51115. ** WAL module is using shared-memory, return false.
  51116. */
  51117. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  51118. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  51119. }
  51120. #ifdef SQLITE_ENABLE_SNAPSHOT
  51121. /* Create a snapshot object. The content of a snapshot is opaque to
  51122. ** every other subsystem, so the WAL module can put whatever it needs
  51123. ** in the object.
  51124. */
  51125. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  51126. int rc = SQLITE_OK;
  51127. WalIndexHdr *pRet;
  51128. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  51129. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  51130. if( pRet==0 ){
  51131. rc = SQLITE_NOMEM_BKPT;
  51132. }else{
  51133. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  51134. *ppSnapshot = (sqlite3_snapshot*)pRet;
  51135. }
  51136. return rc;
  51137. }
  51138. /* Try to open on pSnapshot when the next read-transaction starts
  51139. */
  51140. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  51141. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  51142. }
  51143. #endif /* SQLITE_ENABLE_SNAPSHOT */
  51144. #ifdef SQLITE_ENABLE_ZIPVFS
  51145. /*
  51146. ** If the argument is not NULL, it points to a Wal object that holds a
  51147. ** read-lock. This function returns the database page-size if it is known,
  51148. ** or zero if it is not (or if pWal is NULL).
  51149. */
  51150. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  51151. assert( pWal==0 || pWal->readLock>=0 );
  51152. return (pWal ? pWal->szPage : 0);
  51153. }
  51154. #endif
  51155. /* Return the sqlite3_file object for the WAL file
  51156. */
  51157. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  51158. return pWal->pWalFd;
  51159. }
  51160. #endif /* #ifndef SQLITE_OMIT_WAL */
  51161. /************** End of wal.c *************************************************/
  51162. /************** Begin file btmutex.c *****************************************/
  51163. /*
  51164. ** 2007 August 27
  51165. **
  51166. ** The author disclaims copyright to this source code. In place of
  51167. ** a legal notice, here is a blessing:
  51168. **
  51169. ** May you do good and not evil.
  51170. ** May you find forgiveness for yourself and forgive others.
  51171. ** May you share freely, never taking more than you give.
  51172. **
  51173. *************************************************************************
  51174. **
  51175. ** This file contains code used to implement mutexes on Btree objects.
  51176. ** This code really belongs in btree.c. But btree.c is getting too
  51177. ** big and we want to break it down some. This packaged seemed like
  51178. ** a good breakout.
  51179. */
  51180. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  51181. /************** Begin file btreeInt.h ****************************************/
  51182. /*
  51183. ** 2004 April 6
  51184. **
  51185. ** The author disclaims copyright to this source code. In place of
  51186. ** a legal notice, here is a blessing:
  51187. **
  51188. ** May you do good and not evil.
  51189. ** May you find forgiveness for yourself and forgive others.
  51190. ** May you share freely, never taking more than you give.
  51191. **
  51192. *************************************************************************
  51193. ** This file implements an external (disk-based) database using BTrees.
  51194. ** For a detailed discussion of BTrees, refer to
  51195. **
  51196. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  51197. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  51198. ** Publishing Company, Reading, Massachusetts.
  51199. **
  51200. ** The basic idea is that each page of the file contains N database
  51201. ** entries and N+1 pointers to subpages.
  51202. **
  51203. ** ----------------------------------------------------------------
  51204. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  51205. ** ----------------------------------------------------------------
  51206. **
  51207. ** All of the keys on the page that Ptr(0) points to have values less
  51208. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  51209. ** values greater than Key(0) and less than Key(1). All of the keys
  51210. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  51211. ** so forth.
  51212. **
  51213. ** Finding a particular key requires reading O(log(M)) pages from the
  51214. ** disk where M is the number of entries in the tree.
  51215. **
  51216. ** In this implementation, a single file can hold one or more separate
  51217. ** BTrees. Each BTree is identified by the index of its root page. The
  51218. ** key and data for any entry are combined to form the "payload". A
  51219. ** fixed amount of payload can be carried directly on the database
  51220. ** page. If the payload is larger than the preset amount then surplus
  51221. ** bytes are stored on overflow pages. The payload for an entry
  51222. ** and the preceding pointer are combined to form a "Cell". Each
  51223. ** page has a small header which contains the Ptr(N) pointer and other
  51224. ** information such as the size of key and data.
  51225. **
  51226. ** FORMAT DETAILS
  51227. **
  51228. ** The file is divided into pages. The first page is called page 1,
  51229. ** the second is page 2, and so forth. A page number of zero indicates
  51230. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  51231. ** Each page can be either a btree page, a freelist page, an overflow
  51232. ** page, or a pointer-map page.
  51233. **
  51234. ** The first page is always a btree page. The first 100 bytes of the first
  51235. ** page contain a special header (the "file header") that describes the file.
  51236. ** The format of the file header is as follows:
  51237. **
  51238. ** OFFSET SIZE DESCRIPTION
  51239. ** 0 16 Header string: "SQLite format 3\000"
  51240. ** 16 2 Page size in bytes. (1 means 65536)
  51241. ** 18 1 File format write version
  51242. ** 19 1 File format read version
  51243. ** 20 1 Bytes of unused space at the end of each page
  51244. ** 21 1 Max embedded payload fraction (must be 64)
  51245. ** 22 1 Min embedded payload fraction (must be 32)
  51246. ** 23 1 Min leaf payload fraction (must be 32)
  51247. ** 24 4 File change counter
  51248. ** 28 4 Reserved for future use
  51249. ** 32 4 First freelist page
  51250. ** 36 4 Number of freelist pages in the file
  51251. ** 40 60 15 4-byte meta values passed to higher layers
  51252. **
  51253. ** 40 4 Schema cookie
  51254. ** 44 4 File format of schema layer
  51255. ** 48 4 Size of page cache
  51256. ** 52 4 Largest root-page (auto/incr_vacuum)
  51257. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  51258. ** 60 4 User version
  51259. ** 64 4 Incremental vacuum mode
  51260. ** 68 4 Application-ID
  51261. ** 72 20 unused
  51262. ** 92 4 The version-valid-for number
  51263. ** 96 4 SQLITE_VERSION_NUMBER
  51264. **
  51265. ** All of the integer values are big-endian (most significant byte first).
  51266. **
  51267. ** The file change counter is incremented when the database is changed
  51268. ** This counter allows other processes to know when the file has changed
  51269. ** and thus when they need to flush their cache.
  51270. **
  51271. ** The max embedded payload fraction is the amount of the total usable
  51272. ** space in a page that can be consumed by a single cell for standard
  51273. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  51274. ** is to limit the maximum cell size so that at least 4 cells will fit
  51275. ** on one page. Thus the default max embedded payload fraction is 64.
  51276. **
  51277. ** If the payload for a cell is larger than the max payload, then extra
  51278. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  51279. ** as many bytes as possible are moved into the overflow pages without letting
  51280. ** the cell size drop below the min embedded payload fraction.
  51281. **
  51282. ** The min leaf payload fraction is like the min embedded payload fraction
  51283. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  51284. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  51285. ** not specified in the header.
  51286. **
  51287. ** Each btree pages is divided into three sections: The header, the
  51288. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  51289. ** file header that occurs before the page header.
  51290. **
  51291. ** |----------------|
  51292. ** | file header | 100 bytes. Page 1 only.
  51293. ** |----------------|
  51294. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  51295. ** |----------------|
  51296. ** | cell pointer | | 2 bytes per cell. Sorted order.
  51297. ** | array | | Grows downward
  51298. ** | | v
  51299. ** |----------------|
  51300. ** | unallocated |
  51301. ** | space |
  51302. ** |----------------| ^ Grows upwards
  51303. ** | cell content | | Arbitrary order interspersed with freeblocks.
  51304. ** | area | | and free space fragments.
  51305. ** |----------------|
  51306. **
  51307. ** The page headers looks like this:
  51308. **
  51309. ** OFFSET SIZE DESCRIPTION
  51310. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  51311. ** 1 2 byte offset to the first freeblock
  51312. ** 3 2 number of cells on this page
  51313. ** 5 2 first byte of the cell content area
  51314. ** 7 1 number of fragmented free bytes
  51315. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  51316. **
  51317. ** The flags define the format of this btree page. The leaf flag means that
  51318. ** this page has no children. The zerodata flag means that this page carries
  51319. ** only keys and no data. The intkey flag means that the key is an integer
  51320. ** which is stored in the key size entry of the cell header rather than in
  51321. ** the payload area.
  51322. **
  51323. ** The cell pointer array begins on the first byte after the page header.
  51324. ** The cell pointer array contains zero or more 2-byte numbers which are
  51325. ** offsets from the beginning of the page to the cell content in the cell
  51326. ** content area. The cell pointers occur in sorted order. The system strives
  51327. ** to keep free space after the last cell pointer so that new cells can
  51328. ** be easily added without having to defragment the page.
  51329. **
  51330. ** Cell content is stored at the very end of the page and grows toward the
  51331. ** beginning of the page.
  51332. **
  51333. ** Unused space within the cell content area is collected into a linked list of
  51334. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  51335. ** to the first freeblock is given in the header. Freeblocks occur in
  51336. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  51337. ** any group of 3 or fewer unused bytes in the cell content area cannot
  51338. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  51339. ** a fragment. The total number of bytes in all fragments is recorded.
  51340. ** in the page header at offset 7.
  51341. **
  51342. ** SIZE DESCRIPTION
  51343. ** 2 Byte offset of the next freeblock
  51344. ** 2 Bytes in this freeblock
  51345. **
  51346. ** Cells are of variable length. Cells are stored in the cell content area at
  51347. ** the end of the page. Pointers to the cells are in the cell pointer array
  51348. ** that immediately follows the page header. Cells is not necessarily
  51349. ** contiguous or in order, but cell pointers are contiguous and in order.
  51350. **
  51351. ** Cell content makes use of variable length integers. A variable
  51352. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  51353. ** byte are used. The integer consists of all bytes that have bit 8 set and
  51354. ** the first byte with bit 8 clear. The most significant byte of the integer
  51355. ** appears first. A variable-length integer may not be more than 9 bytes long.
  51356. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  51357. ** allows a 64-bit integer to be encoded in 9 bytes.
  51358. **
  51359. ** 0x00 becomes 0x00000000
  51360. ** 0x7f becomes 0x0000007f
  51361. ** 0x81 0x00 becomes 0x00000080
  51362. ** 0x82 0x00 becomes 0x00000100
  51363. ** 0x80 0x7f becomes 0x0000007f
  51364. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  51365. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  51366. **
  51367. ** Variable length integers are used for rowids and to hold the number of
  51368. ** bytes of key and data in a btree cell.
  51369. **
  51370. ** The content of a cell looks like this:
  51371. **
  51372. ** SIZE DESCRIPTION
  51373. ** 4 Page number of the left child. Omitted if leaf flag is set.
  51374. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  51375. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  51376. ** * Payload
  51377. ** 4 First page of the overflow chain. Omitted if no overflow
  51378. **
  51379. ** Overflow pages form a linked list. Each page except the last is completely
  51380. ** filled with data (pagesize - 4 bytes). The last page can have as little
  51381. ** as 1 byte of data.
  51382. **
  51383. ** SIZE DESCRIPTION
  51384. ** 4 Page number of next overflow page
  51385. ** * Data
  51386. **
  51387. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  51388. ** file header points to the first in a linked list of trunk page. Each trunk
  51389. ** page points to multiple leaf pages. The content of a leaf page is
  51390. ** unspecified. A trunk page looks like this:
  51391. **
  51392. ** SIZE DESCRIPTION
  51393. ** 4 Page number of next trunk page
  51394. ** 4 Number of leaf pointers on this page
  51395. ** * zero or more pages numbers of leaves
  51396. */
  51397. /* #include "sqliteInt.h" */
  51398. /* The following value is the maximum cell size assuming a maximum page
  51399. ** size give above.
  51400. */
  51401. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  51402. /* The maximum number of cells on a single page of the database. This
  51403. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  51404. ** plus 2 bytes for the index to the cell in the page header). Such
  51405. ** small cells will be rare, but they are possible.
  51406. */
  51407. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  51408. /* Forward declarations */
  51409. typedef struct MemPage MemPage;
  51410. typedef struct BtLock BtLock;
  51411. typedef struct CellInfo CellInfo;
  51412. /*
  51413. ** This is a magic string that appears at the beginning of every
  51414. ** SQLite database in order to identify the file as a real database.
  51415. **
  51416. ** You can change this value at compile-time by specifying a
  51417. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  51418. ** header must be exactly 16 bytes including the zero-terminator so
  51419. ** the string itself should be 15 characters long. If you change
  51420. ** the header, then your custom library will not be able to read
  51421. ** databases generated by the standard tools and the standard tools
  51422. ** will not be able to read databases created by your custom library.
  51423. */
  51424. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  51425. # define SQLITE_FILE_HEADER "SQLite format 3"
  51426. #endif
  51427. /*
  51428. ** Page type flags. An ORed combination of these flags appear as the
  51429. ** first byte of on-disk image of every BTree page.
  51430. */
  51431. #define PTF_INTKEY 0x01
  51432. #define PTF_ZERODATA 0x02
  51433. #define PTF_LEAFDATA 0x04
  51434. #define PTF_LEAF 0x08
  51435. /*
  51436. ** As each page of the file is loaded into memory, an instance of the following
  51437. ** structure is appended and initialized to zero. This structure stores
  51438. ** information about the page that is decoded from the raw file page.
  51439. **
  51440. ** The pParent field points back to the parent page. This allows us to
  51441. ** walk up the BTree from any leaf to the root. Care must be taken to
  51442. ** unref() the parent page pointer when this page is no longer referenced.
  51443. ** The pageDestructor() routine handles that chore.
  51444. **
  51445. ** Access to all fields of this structure is controlled by the mutex
  51446. ** stored in MemPage.pBt->mutex.
  51447. */
  51448. struct MemPage {
  51449. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  51450. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  51451. u8 intKey; /* True if table b-trees. False for index b-trees */
  51452. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  51453. u8 leaf; /* True if a leaf page */
  51454. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  51455. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  51456. u8 max1bytePayload; /* min(maxLocal,127) */
  51457. u8 bBusy; /* Prevent endless loops on corrupt database files */
  51458. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  51459. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  51460. u16 cellOffset; /* Index in aData of first cell pointer */
  51461. u16 nFree; /* Number of free bytes on the page */
  51462. u16 nCell; /* Number of cells on this page, local and ovfl */
  51463. u16 maskPage; /* Mask for page offset */
  51464. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  51465. ** non-overflow cell */
  51466. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  51467. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  51468. u8 *aData; /* Pointer to disk image of the page data */
  51469. u8 *aDataEnd; /* One byte past the end of usable data */
  51470. u8 *aCellIdx; /* The cell index area */
  51471. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  51472. DbPage *pDbPage; /* Pager page handle */
  51473. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  51474. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  51475. Pgno pgno; /* Page number for this page */
  51476. };
  51477. /*
  51478. ** The in-memory image of a disk page has the auxiliary information appended
  51479. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  51480. ** that extra information.
  51481. */
  51482. #define EXTRA_SIZE sizeof(MemPage)
  51483. /*
  51484. ** A linked list of the following structures is stored at BtShared.pLock.
  51485. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  51486. ** is opened on the table with root page BtShared.iTable. Locks are removed
  51487. ** from this list when a transaction is committed or rolled back, or when
  51488. ** a btree handle is closed.
  51489. */
  51490. struct BtLock {
  51491. Btree *pBtree; /* Btree handle holding this lock */
  51492. Pgno iTable; /* Root page of table */
  51493. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  51494. BtLock *pNext; /* Next in BtShared.pLock list */
  51495. };
  51496. /* Candidate values for BtLock.eLock */
  51497. #define READ_LOCK 1
  51498. #define WRITE_LOCK 2
  51499. /* A Btree handle
  51500. **
  51501. ** A database connection contains a pointer to an instance of
  51502. ** this object for every database file that it has open. This structure
  51503. ** is opaque to the database connection. The database connection cannot
  51504. ** see the internals of this structure and only deals with pointers to
  51505. ** this structure.
  51506. **
  51507. ** For some database files, the same underlying database cache might be
  51508. ** shared between multiple connections. In that case, each connection
  51509. ** has it own instance of this object. But each instance of this object
  51510. ** points to the same BtShared object. The database cache and the
  51511. ** schema associated with the database file are all contained within
  51512. ** the BtShared object.
  51513. **
  51514. ** All fields in this structure are accessed under sqlite3.mutex.
  51515. ** The pBt pointer itself may not be changed while there exists cursors
  51516. ** in the referenced BtShared that point back to this Btree since those
  51517. ** cursors have to go through this Btree to find their BtShared and
  51518. ** they often do so without holding sqlite3.mutex.
  51519. */
  51520. struct Btree {
  51521. sqlite3 *db; /* The database connection holding this btree */
  51522. BtShared *pBt; /* Sharable content of this btree */
  51523. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  51524. u8 sharable; /* True if we can share pBt with another db */
  51525. u8 locked; /* True if db currently has pBt locked */
  51526. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  51527. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  51528. int nBackup; /* Number of backup operations reading this btree */
  51529. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  51530. Btree *pNext; /* List of other sharable Btrees from the same db */
  51531. Btree *pPrev; /* Back pointer of the same list */
  51532. #ifndef SQLITE_OMIT_SHARED_CACHE
  51533. BtLock lock; /* Object used to lock page 1 */
  51534. #endif
  51535. };
  51536. /*
  51537. ** Btree.inTrans may take one of the following values.
  51538. **
  51539. ** If the shared-data extension is enabled, there may be multiple users
  51540. ** of the Btree structure. At most one of these may open a write transaction,
  51541. ** but any number may have active read transactions.
  51542. */
  51543. #define TRANS_NONE 0
  51544. #define TRANS_READ 1
  51545. #define TRANS_WRITE 2
  51546. /*
  51547. ** An instance of this object represents a single database file.
  51548. **
  51549. ** A single database file can be in use at the same time by two
  51550. ** or more database connections. When two or more connections are
  51551. ** sharing the same database file, each connection has it own
  51552. ** private Btree object for the file and each of those Btrees points
  51553. ** to this one BtShared object. BtShared.nRef is the number of
  51554. ** connections currently sharing this database file.
  51555. **
  51556. ** Fields in this structure are accessed under the BtShared.mutex
  51557. ** mutex, except for nRef and pNext which are accessed under the
  51558. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  51559. ** may not be modified once it is initially set as long as nRef>0.
  51560. ** The pSchema field may be set once under BtShared.mutex and
  51561. ** thereafter is unchanged as long as nRef>0.
  51562. **
  51563. ** isPending:
  51564. **
  51565. ** If a BtShared client fails to obtain a write-lock on a database
  51566. ** table (because there exists one or more read-locks on the table),
  51567. ** the shared-cache enters 'pending-lock' state and isPending is
  51568. ** set to true.
  51569. **
  51570. ** The shared-cache leaves the 'pending lock' state when either of
  51571. ** the following occur:
  51572. **
  51573. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  51574. ** 2) The number of locks held by other connections drops to zero.
  51575. **
  51576. ** while in the 'pending-lock' state, no connection may start a new
  51577. ** transaction.
  51578. **
  51579. ** This feature is included to help prevent writer-starvation.
  51580. */
  51581. struct BtShared {
  51582. Pager *pPager; /* The page cache */
  51583. sqlite3 *db; /* Database connection currently using this Btree */
  51584. BtCursor *pCursor; /* A list of all open cursors */
  51585. MemPage *pPage1; /* First page of the database */
  51586. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  51587. #ifndef SQLITE_OMIT_AUTOVACUUM
  51588. u8 autoVacuum; /* True if auto-vacuum is enabled */
  51589. u8 incrVacuum; /* True if incr-vacuum is enabled */
  51590. u8 bDoTruncate; /* True to truncate db on commit */
  51591. #endif
  51592. u8 inTransaction; /* Transaction state */
  51593. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  51594. #ifdef SQLITE_HAS_CODEC
  51595. u8 optimalReserve; /* Desired amount of reserved space per page */
  51596. #endif
  51597. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  51598. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  51599. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  51600. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  51601. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  51602. u32 pageSize; /* Total number of bytes on a page */
  51603. u32 usableSize; /* Number of usable bytes on each page */
  51604. int nTransaction; /* Number of open transactions (read + write) */
  51605. u32 nPage; /* Number of pages in the database */
  51606. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  51607. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  51608. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  51609. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  51610. #ifndef SQLITE_OMIT_SHARED_CACHE
  51611. int nRef; /* Number of references to this structure */
  51612. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  51613. BtLock *pLock; /* List of locks held on this shared-btree struct */
  51614. Btree *pWriter; /* Btree with currently open write transaction */
  51615. #endif
  51616. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  51617. };
  51618. /*
  51619. ** Allowed values for BtShared.btsFlags
  51620. */
  51621. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  51622. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  51623. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  51624. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  51625. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  51626. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  51627. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  51628. /*
  51629. ** An instance of the following structure is used to hold information
  51630. ** about a cell. The parseCellPtr() function fills in this structure
  51631. ** based on information extract from the raw disk page.
  51632. */
  51633. struct CellInfo {
  51634. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  51635. u8 *pPayload; /* Pointer to the start of payload */
  51636. u32 nPayload; /* Bytes of payload */
  51637. u16 nLocal; /* Amount of payload held locally, not on overflow */
  51638. u16 nSize; /* Size of the cell content on the main b-tree page */
  51639. };
  51640. /*
  51641. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  51642. ** this will be declared corrupt. This value is calculated based on a
  51643. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  51644. ** root-node and 3 for all other internal nodes.
  51645. **
  51646. ** If a tree that appears to be taller than this is encountered, it is
  51647. ** assumed that the database is corrupt.
  51648. */
  51649. #define BTCURSOR_MAX_DEPTH 20
  51650. /*
  51651. ** A cursor is a pointer to a particular entry within a particular
  51652. ** b-tree within a database file.
  51653. **
  51654. ** The entry is identified by its MemPage and the index in
  51655. ** MemPage.aCell[] of the entry.
  51656. **
  51657. ** A single database file can be shared by two more database connections,
  51658. ** but cursors cannot be shared. Each cursor is associated with a
  51659. ** particular database connection identified BtCursor.pBtree.db.
  51660. **
  51661. ** Fields in this structure are accessed under the BtShared.mutex
  51662. ** found at self->pBt->mutex.
  51663. **
  51664. ** skipNext meaning:
  51665. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  51666. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  51667. ** eState==FAULT: Cursor fault with skipNext as error code.
  51668. */
  51669. struct BtCursor {
  51670. Btree *pBtree; /* The Btree to which this cursor belongs */
  51671. BtShared *pBt; /* The BtShared this cursor points to */
  51672. BtCursor *pNext; /* Forms a linked list of all cursors */
  51673. Pgno *aOverflow; /* Cache of overflow page locations */
  51674. CellInfo info; /* A parse of the cell we are pointing at */
  51675. i64 nKey; /* Size of pKey, or last integer key */
  51676. void *pKey; /* Saved key that was cursor last known position */
  51677. Pgno pgnoRoot; /* The root page of this tree */
  51678. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  51679. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  51680. ** Error code if eState==CURSOR_FAULT */
  51681. u8 curFlags; /* zero or more BTCF_* flags defined below */
  51682. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  51683. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  51684. u8 hints; /* As configured by CursorSetHints() */
  51685. /* All fields above are zeroed when the cursor is allocated. See
  51686. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  51687. ** initialized. */
  51688. i8 iPage; /* Index of current page in apPage */
  51689. u8 curIntKey; /* Value of apPage[0]->intKey */
  51690. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  51691. void *padding1; /* Make object size a multiple of 16 */
  51692. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  51693. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  51694. };
  51695. /*
  51696. ** Legal values for BtCursor.curFlags
  51697. */
  51698. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  51699. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  51700. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  51701. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  51702. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  51703. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  51704. /*
  51705. ** Potential values for BtCursor.eState.
  51706. **
  51707. ** CURSOR_INVALID:
  51708. ** Cursor does not point to a valid entry. This can happen (for example)
  51709. ** because the table is empty or because BtreeCursorFirst() has not been
  51710. ** called.
  51711. **
  51712. ** CURSOR_VALID:
  51713. ** Cursor points to a valid entry. getPayload() etc. may be called.
  51714. **
  51715. ** CURSOR_SKIPNEXT:
  51716. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  51717. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  51718. ** operation should be a no-op.
  51719. **
  51720. ** CURSOR_REQUIRESEEK:
  51721. ** The table that this cursor was opened on still exists, but has been
  51722. ** modified since the cursor was last used. The cursor position is saved
  51723. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  51724. ** this state, restoreCursorPosition() can be called to attempt to
  51725. ** seek the cursor to the saved position.
  51726. **
  51727. ** CURSOR_FAULT:
  51728. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  51729. ** on a different connection that shares the BtShared cache with this
  51730. ** cursor. The error has left the cache in an inconsistent state.
  51731. ** Do nothing else with this cursor. Any attempt to use the cursor
  51732. ** should return the error code stored in BtCursor.skipNext
  51733. */
  51734. #define CURSOR_INVALID 0
  51735. #define CURSOR_VALID 1
  51736. #define CURSOR_SKIPNEXT 2
  51737. #define CURSOR_REQUIRESEEK 3
  51738. #define CURSOR_FAULT 4
  51739. /*
  51740. ** The database page the PENDING_BYTE occupies. This page is never used.
  51741. */
  51742. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  51743. /*
  51744. ** These macros define the location of the pointer-map entry for a
  51745. ** database page. The first argument to each is the number of usable
  51746. ** bytes on each page of the database (often 1024). The second is the
  51747. ** page number to look up in the pointer map.
  51748. **
  51749. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  51750. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  51751. ** the offset of the requested map entry.
  51752. **
  51753. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  51754. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  51755. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  51756. ** this test.
  51757. */
  51758. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  51759. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  51760. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  51761. /*
  51762. ** The pointer map is a lookup table that identifies the parent page for
  51763. ** each child page in the database file. The parent page is the page that
  51764. ** contains a pointer to the child. Every page in the database contains
  51765. ** 0 or 1 parent pages. (In this context 'database page' refers
  51766. ** to any page that is not part of the pointer map itself.) Each pointer map
  51767. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  51768. ** The PTRMAP_XXX identifiers below are the valid types.
  51769. **
  51770. ** The purpose of the pointer map is to facility moving pages from one
  51771. ** position in the file to another as part of autovacuum. When a page
  51772. ** is moved, the pointer in its parent must be updated to point to the
  51773. ** new location. The pointer map is used to locate the parent page quickly.
  51774. **
  51775. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  51776. ** used in this case.
  51777. **
  51778. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  51779. ** is not used in this case.
  51780. **
  51781. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  51782. ** overflow pages. The page number identifies the page that
  51783. ** contains the cell with a pointer to this overflow page.
  51784. **
  51785. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  51786. ** overflow pages. The page-number identifies the previous
  51787. ** page in the overflow page list.
  51788. **
  51789. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  51790. ** identifies the parent page in the btree.
  51791. */
  51792. #define PTRMAP_ROOTPAGE 1
  51793. #define PTRMAP_FREEPAGE 2
  51794. #define PTRMAP_OVERFLOW1 3
  51795. #define PTRMAP_OVERFLOW2 4
  51796. #define PTRMAP_BTREE 5
  51797. /* A bunch of assert() statements to check the transaction state variables
  51798. ** of handle p (type Btree*) are internally consistent.
  51799. */
  51800. #define btreeIntegrity(p) \
  51801. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  51802. assert( p->pBt->inTransaction>=p->inTrans );
  51803. /*
  51804. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  51805. ** if the database supports auto-vacuum or not. Because it is used
  51806. ** within an expression that is an argument to another macro
  51807. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  51808. ** So, this macro is defined instead.
  51809. */
  51810. #ifndef SQLITE_OMIT_AUTOVACUUM
  51811. #define ISAUTOVACUUM (pBt->autoVacuum)
  51812. #else
  51813. #define ISAUTOVACUUM 0
  51814. #endif
  51815. /*
  51816. ** This structure is passed around through all the sanity checking routines
  51817. ** in order to keep track of some global state information.
  51818. **
  51819. ** The aRef[] array is allocated so that there is 1 bit for each page in
  51820. ** the database. As the integrity-check proceeds, for each page used in
  51821. ** the database the corresponding bit is set. This allows integrity-check to
  51822. ** detect pages that are used twice and orphaned pages (both of which
  51823. ** indicate corruption).
  51824. */
  51825. typedef struct IntegrityCk IntegrityCk;
  51826. struct IntegrityCk {
  51827. BtShared *pBt; /* The tree being checked out */
  51828. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  51829. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  51830. Pgno nPage; /* Number of pages in the database */
  51831. int mxErr; /* Stop accumulating errors when this reaches zero */
  51832. int nErr; /* Number of messages written to zErrMsg so far */
  51833. int mallocFailed; /* A memory allocation error has occurred */
  51834. const char *zPfx; /* Error message prefix */
  51835. int v1, v2; /* Values for up to two %d fields in zPfx */
  51836. StrAccum errMsg; /* Accumulate the error message text here */
  51837. u32 *heap; /* Min-heap used for analyzing cell coverage */
  51838. };
  51839. /*
  51840. ** Routines to read or write a two- and four-byte big-endian integer values.
  51841. */
  51842. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  51843. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  51844. #define get4byte sqlite3Get4byte
  51845. #define put4byte sqlite3Put4byte
  51846. /*
  51847. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  51848. ** two-byte aligned address. get2bytea() is only used for accessing the
  51849. ** cell addresses in a btree header.
  51850. */
  51851. #if SQLITE_BYTEORDER==4321
  51852. # define get2byteAligned(x) (*(u16*)(x))
  51853. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  51854. && GCC_VERSION>=4008000
  51855. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  51856. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  51857. && defined(_MSC_VER) && _MSC_VER>=1300
  51858. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  51859. #else
  51860. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  51861. #endif
  51862. /************** End of btreeInt.h ********************************************/
  51863. /************** Continuing where we left off in btmutex.c ********************/
  51864. #ifndef SQLITE_OMIT_SHARED_CACHE
  51865. #if SQLITE_THREADSAFE
  51866. /*
  51867. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  51868. ** set BtShared.db to the database handle associated with p and the
  51869. ** p->locked boolean to true.
  51870. */
  51871. static void lockBtreeMutex(Btree *p){
  51872. assert( p->locked==0 );
  51873. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  51874. assert( sqlite3_mutex_held(p->db->mutex) );
  51875. sqlite3_mutex_enter(p->pBt->mutex);
  51876. p->pBt->db = p->db;
  51877. p->locked = 1;
  51878. }
  51879. /*
  51880. ** Release the BtShared mutex associated with B-Tree handle p and
  51881. ** clear the p->locked boolean.
  51882. */
  51883. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  51884. BtShared *pBt = p->pBt;
  51885. assert( p->locked==1 );
  51886. assert( sqlite3_mutex_held(pBt->mutex) );
  51887. assert( sqlite3_mutex_held(p->db->mutex) );
  51888. assert( p->db==pBt->db );
  51889. sqlite3_mutex_leave(pBt->mutex);
  51890. p->locked = 0;
  51891. }
  51892. /* Forward reference */
  51893. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  51894. /*
  51895. ** Enter a mutex on the given BTree object.
  51896. **
  51897. ** If the object is not sharable, then no mutex is ever required
  51898. ** and this routine is a no-op. The underlying mutex is non-recursive.
  51899. ** But we keep a reference count in Btree.wantToLock so the behavior
  51900. ** of this interface is recursive.
  51901. **
  51902. ** To avoid deadlocks, multiple Btrees are locked in the same order
  51903. ** by all database connections. The p->pNext is a list of other
  51904. ** Btrees belonging to the same database connection as the p Btree
  51905. ** which need to be locked after p. If we cannot get a lock on
  51906. ** p, then first unlock all of the others on p->pNext, then wait
  51907. ** for the lock to become available on p, then relock all of the
  51908. ** subsequent Btrees that desire a lock.
  51909. */
  51910. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  51911. /* Some basic sanity checking on the Btree. The list of Btrees
  51912. ** connected by pNext and pPrev should be in sorted order by
  51913. ** Btree.pBt value. All elements of the list should belong to
  51914. ** the same connection. Only shared Btrees are on the list. */
  51915. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  51916. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  51917. assert( p->pNext==0 || p->pNext->db==p->db );
  51918. assert( p->pPrev==0 || p->pPrev->db==p->db );
  51919. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  51920. /* Check for locking consistency */
  51921. assert( !p->locked || p->wantToLock>0 );
  51922. assert( p->sharable || p->wantToLock==0 );
  51923. /* We should already hold a lock on the database connection */
  51924. assert( sqlite3_mutex_held(p->db->mutex) );
  51925. /* Unless the database is sharable and unlocked, then BtShared.db
  51926. ** should already be set correctly. */
  51927. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  51928. if( !p->sharable ) return;
  51929. p->wantToLock++;
  51930. if( p->locked ) return;
  51931. btreeLockCarefully(p);
  51932. }
  51933. /* This is a helper function for sqlite3BtreeLock(). By moving
  51934. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  51935. ** into this routine, we avoid unnecessary stack pointer changes
  51936. ** and thus help the sqlite3BtreeLock() routine to run much faster
  51937. ** in the common case.
  51938. */
  51939. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  51940. Btree *pLater;
  51941. /* In most cases, we should be able to acquire the lock we
  51942. ** want without having to go through the ascending lock
  51943. ** procedure that follows. Just be sure not to block.
  51944. */
  51945. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  51946. p->pBt->db = p->db;
  51947. p->locked = 1;
  51948. return;
  51949. }
  51950. /* To avoid deadlock, first release all locks with a larger
  51951. ** BtShared address. Then acquire our lock. Then reacquire
  51952. ** the other BtShared locks that we used to hold in ascending
  51953. ** order.
  51954. */
  51955. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  51956. assert( pLater->sharable );
  51957. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  51958. assert( !pLater->locked || pLater->wantToLock>0 );
  51959. if( pLater->locked ){
  51960. unlockBtreeMutex(pLater);
  51961. }
  51962. }
  51963. lockBtreeMutex(p);
  51964. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  51965. if( pLater->wantToLock ){
  51966. lockBtreeMutex(pLater);
  51967. }
  51968. }
  51969. }
  51970. /*
  51971. ** Exit the recursive mutex on a Btree.
  51972. */
  51973. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  51974. assert( sqlite3_mutex_held(p->db->mutex) );
  51975. if( p->sharable ){
  51976. assert( p->wantToLock>0 );
  51977. p->wantToLock--;
  51978. if( p->wantToLock==0 ){
  51979. unlockBtreeMutex(p);
  51980. }
  51981. }
  51982. }
  51983. #ifndef NDEBUG
  51984. /*
  51985. ** Return true if the BtShared mutex is held on the btree, or if the
  51986. ** B-Tree is not marked as sharable.
  51987. **
  51988. ** This routine is used only from within assert() statements.
  51989. */
  51990. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  51991. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  51992. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  51993. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  51994. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  51995. return (p->sharable==0 || p->locked);
  51996. }
  51997. #endif
  51998. /*
  51999. ** Enter the mutex on every Btree associated with a database
  52000. ** connection. This is needed (for example) prior to parsing
  52001. ** a statement since we will be comparing table and column names
  52002. ** against all schemas and we do not want those schemas being
  52003. ** reset out from under us.
  52004. **
  52005. ** There is a corresponding leave-all procedures.
  52006. **
  52007. ** Enter the mutexes in accending order by BtShared pointer address
  52008. ** to avoid the possibility of deadlock when two threads with
  52009. ** two or more btrees in common both try to lock all their btrees
  52010. ** at the same instant.
  52011. */
  52012. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  52013. int i;
  52014. Btree *p;
  52015. assert( sqlite3_mutex_held(db->mutex) );
  52016. for(i=0; i<db->nDb; i++){
  52017. p = db->aDb[i].pBt;
  52018. if( p ) sqlite3BtreeEnter(p);
  52019. }
  52020. }
  52021. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  52022. int i;
  52023. Btree *p;
  52024. assert( sqlite3_mutex_held(db->mutex) );
  52025. for(i=0; i<db->nDb; i++){
  52026. p = db->aDb[i].pBt;
  52027. if( p ) sqlite3BtreeLeave(p);
  52028. }
  52029. }
  52030. #ifndef NDEBUG
  52031. /*
  52032. ** Return true if the current thread holds the database connection
  52033. ** mutex and all required BtShared mutexes.
  52034. **
  52035. ** This routine is used inside assert() statements only.
  52036. */
  52037. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  52038. int i;
  52039. if( !sqlite3_mutex_held(db->mutex) ){
  52040. return 0;
  52041. }
  52042. for(i=0; i<db->nDb; i++){
  52043. Btree *p;
  52044. p = db->aDb[i].pBt;
  52045. if( p && p->sharable &&
  52046. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  52047. return 0;
  52048. }
  52049. }
  52050. return 1;
  52051. }
  52052. #endif /* NDEBUG */
  52053. #ifndef NDEBUG
  52054. /*
  52055. ** Return true if the correct mutexes are held for accessing the
  52056. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  52057. ** access are:
  52058. **
  52059. ** (1) The mutex on db
  52060. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  52061. **
  52062. ** If pSchema is not NULL, then iDb is computed from pSchema and
  52063. ** db using sqlite3SchemaToIndex().
  52064. */
  52065. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  52066. Btree *p;
  52067. assert( db!=0 );
  52068. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  52069. assert( iDb>=0 && iDb<db->nDb );
  52070. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  52071. if( iDb==1 ) return 1;
  52072. p = db->aDb[iDb].pBt;
  52073. assert( p!=0 );
  52074. return p->sharable==0 || p->locked==1;
  52075. }
  52076. #endif /* NDEBUG */
  52077. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  52078. /*
  52079. ** The following are special cases for mutex enter routines for use
  52080. ** in single threaded applications that use shared cache. Except for
  52081. ** these two routines, all mutex operations are no-ops in that case and
  52082. ** are null #defines in btree.h.
  52083. **
  52084. ** If shared cache is disabled, then all btree mutex routines, including
  52085. ** the ones below, are no-ops and are null #defines in btree.h.
  52086. */
  52087. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  52088. p->pBt->db = p->db;
  52089. }
  52090. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  52091. int i;
  52092. for(i=0; i<db->nDb; i++){
  52093. Btree *p = db->aDb[i].pBt;
  52094. if( p ){
  52095. p->pBt->db = p->db;
  52096. }
  52097. }
  52098. }
  52099. #endif /* if SQLITE_THREADSAFE */
  52100. #ifndef SQLITE_OMIT_INCRBLOB
  52101. /*
  52102. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  52103. **
  52104. ** These entry points are used by incremental I/O only. Enter() is required
  52105. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  52106. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  52107. */
  52108. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  52109. sqlite3BtreeEnter(pCur->pBtree);
  52110. }
  52111. # if SQLITE_THREADSAFE
  52112. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  52113. sqlite3BtreeLeave(pCur->pBtree);
  52114. }
  52115. # endif
  52116. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  52117. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  52118. /************** End of btmutex.c *********************************************/
  52119. /************** Begin file btree.c *******************************************/
  52120. /*
  52121. ** 2004 April 6
  52122. **
  52123. ** The author disclaims copyright to this source code. In place of
  52124. ** a legal notice, here is a blessing:
  52125. **
  52126. ** May you do good and not evil.
  52127. ** May you find forgiveness for yourself and forgive others.
  52128. ** May you share freely, never taking more than you give.
  52129. **
  52130. *************************************************************************
  52131. ** This file implements an external (disk-based) database using BTrees.
  52132. ** See the header comment on "btreeInt.h" for additional information.
  52133. ** Including a description of file format and an overview of operation.
  52134. */
  52135. /* #include "btreeInt.h" */
  52136. /*
  52137. ** The header string that appears at the beginning of every
  52138. ** SQLite database.
  52139. */
  52140. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  52141. /*
  52142. ** Set this global variable to 1 to enable tracing using the TRACE
  52143. ** macro.
  52144. */
  52145. #if 0
  52146. int sqlite3BtreeTrace=1; /* True to enable tracing */
  52147. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  52148. #else
  52149. # define TRACE(X)
  52150. #endif
  52151. /*
  52152. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  52153. ** But if the value is zero, make it 65536.
  52154. **
  52155. ** This routine is used to extract the "offset to cell content area" value
  52156. ** from the header of a btree page. If the page size is 65536 and the page
  52157. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  52158. ** This routine makes the necessary adjustment to 65536.
  52159. */
  52160. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  52161. /*
  52162. ** Values passed as the 5th argument to allocateBtreePage()
  52163. */
  52164. #define BTALLOC_ANY 0 /* Allocate any page */
  52165. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  52166. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  52167. /*
  52168. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  52169. ** defined, or 0 if it is. For example:
  52170. **
  52171. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  52172. */
  52173. #ifndef SQLITE_OMIT_AUTOVACUUM
  52174. #define IfNotOmitAV(expr) (expr)
  52175. #else
  52176. #define IfNotOmitAV(expr) 0
  52177. #endif
  52178. #ifndef SQLITE_OMIT_SHARED_CACHE
  52179. /*
  52180. ** A list of BtShared objects that are eligible for participation
  52181. ** in shared cache. This variable has file scope during normal builds,
  52182. ** but the test harness needs to access it so we make it global for
  52183. ** test builds.
  52184. **
  52185. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  52186. */
  52187. #ifdef SQLITE_TEST
  52188. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  52189. #else
  52190. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  52191. #endif
  52192. #endif /* SQLITE_OMIT_SHARED_CACHE */
  52193. #ifndef SQLITE_OMIT_SHARED_CACHE
  52194. /*
  52195. ** Enable or disable the shared pager and schema features.
  52196. **
  52197. ** This routine has no effect on existing database connections.
  52198. ** The shared cache setting effects only future calls to
  52199. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  52200. */
  52201. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
  52202. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  52203. return SQLITE_OK;
  52204. }
  52205. #endif
  52206. #ifdef SQLITE_OMIT_SHARED_CACHE
  52207. /*
  52208. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  52209. ** and clearAllSharedCacheTableLocks()
  52210. ** manipulate entries in the BtShared.pLock linked list used to store
  52211. ** shared-cache table level locks. If the library is compiled with the
  52212. ** shared-cache feature disabled, then there is only ever one user
  52213. ** of each BtShared structure and so this locking is not necessary.
  52214. ** So define the lock related functions as no-ops.
  52215. */
  52216. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  52217. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  52218. #define clearAllSharedCacheTableLocks(a)
  52219. #define downgradeAllSharedCacheTableLocks(a)
  52220. #define hasSharedCacheTableLock(a,b,c,d) 1
  52221. #define hasReadConflicts(a, b) 0
  52222. #endif
  52223. #ifndef SQLITE_OMIT_SHARED_CACHE
  52224. #ifdef SQLITE_DEBUG
  52225. /*
  52226. **** This function is only used as part of an assert() statement. ***
  52227. **
  52228. ** Check to see if pBtree holds the required locks to read or write to the
  52229. ** table with root page iRoot. Return 1 if it does and 0 if not.
  52230. **
  52231. ** For example, when writing to a table with root-page iRoot via
  52232. ** Btree connection pBtree:
  52233. **
  52234. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  52235. **
  52236. ** When writing to an index that resides in a sharable database, the
  52237. ** caller should have first obtained a lock specifying the root page of
  52238. ** the corresponding table. This makes things a bit more complicated,
  52239. ** as this module treats each table as a separate structure. To determine
  52240. ** the table corresponding to the index being written, this
  52241. ** function has to search through the database schema.
  52242. **
  52243. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  52244. ** hold a write-lock on the schema table (root page 1). This is also
  52245. ** acceptable.
  52246. */
  52247. static int hasSharedCacheTableLock(
  52248. Btree *pBtree, /* Handle that must hold lock */
  52249. Pgno iRoot, /* Root page of b-tree */
  52250. int isIndex, /* True if iRoot is the root of an index b-tree */
  52251. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  52252. ){
  52253. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  52254. Pgno iTab = 0;
  52255. BtLock *pLock;
  52256. /* If this database is not shareable, or if the client is reading
  52257. ** and has the read-uncommitted flag set, then no lock is required.
  52258. ** Return true immediately.
  52259. */
  52260. if( (pBtree->sharable==0)
  52261. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  52262. ){
  52263. return 1;
  52264. }
  52265. /* If the client is reading or writing an index and the schema is
  52266. ** not loaded, then it is too difficult to actually check to see if
  52267. ** the correct locks are held. So do not bother - just return true.
  52268. ** This case does not come up very often anyhow.
  52269. */
  52270. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  52271. return 1;
  52272. }
  52273. /* Figure out the root-page that the lock should be held on. For table
  52274. ** b-trees, this is just the root page of the b-tree being read or
  52275. ** written. For index b-trees, it is the root page of the associated
  52276. ** table. */
  52277. if( isIndex ){
  52278. HashElem *p;
  52279. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  52280. Index *pIdx = (Index *)sqliteHashData(p);
  52281. if( pIdx->tnum==(int)iRoot ){
  52282. if( iTab ){
  52283. /* Two or more indexes share the same root page. There must
  52284. ** be imposter tables. So just return true. The assert is not
  52285. ** useful in that case. */
  52286. return 1;
  52287. }
  52288. iTab = pIdx->pTable->tnum;
  52289. }
  52290. }
  52291. }else{
  52292. iTab = iRoot;
  52293. }
  52294. /* Search for the required lock. Either a write-lock on root-page iTab, a
  52295. ** write-lock on the schema table, or (if the client is reading) a
  52296. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  52297. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  52298. if( pLock->pBtree==pBtree
  52299. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  52300. && pLock->eLock>=eLockType
  52301. ){
  52302. return 1;
  52303. }
  52304. }
  52305. /* Failed to find the required lock. */
  52306. return 0;
  52307. }
  52308. #endif /* SQLITE_DEBUG */
  52309. #ifdef SQLITE_DEBUG
  52310. /*
  52311. **** This function may be used as part of assert() statements only. ****
  52312. **
  52313. ** Return true if it would be illegal for pBtree to write into the
  52314. ** table or index rooted at iRoot because other shared connections are
  52315. ** simultaneously reading that same table or index.
  52316. **
  52317. ** It is illegal for pBtree to write if some other Btree object that
  52318. ** shares the same BtShared object is currently reading or writing
  52319. ** the iRoot table. Except, if the other Btree object has the
  52320. ** read-uncommitted flag set, then it is OK for the other object to
  52321. ** have a read cursor.
  52322. **
  52323. ** For example, before writing to any part of the table or index
  52324. ** rooted at page iRoot, one should call:
  52325. **
  52326. ** assert( !hasReadConflicts(pBtree, iRoot) );
  52327. */
  52328. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  52329. BtCursor *p;
  52330. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  52331. if( p->pgnoRoot==iRoot
  52332. && p->pBtree!=pBtree
  52333. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  52334. ){
  52335. return 1;
  52336. }
  52337. }
  52338. return 0;
  52339. }
  52340. #endif /* #ifdef SQLITE_DEBUG */
  52341. /*
  52342. ** Query to see if Btree handle p may obtain a lock of type eLock
  52343. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  52344. ** SQLITE_OK if the lock may be obtained (by calling
  52345. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  52346. */
  52347. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  52348. BtShared *pBt = p->pBt;
  52349. BtLock *pIter;
  52350. assert( sqlite3BtreeHoldsMutex(p) );
  52351. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  52352. assert( p->db!=0 );
  52353. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  52354. /* If requesting a write-lock, then the Btree must have an open write
  52355. ** transaction on this file. And, obviously, for this to be so there
  52356. ** must be an open write transaction on the file itself.
  52357. */
  52358. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  52359. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  52360. /* This routine is a no-op if the shared-cache is not enabled */
  52361. if( !p->sharable ){
  52362. return SQLITE_OK;
  52363. }
  52364. /* If some other connection is holding an exclusive lock, the
  52365. ** requested lock may not be obtained.
  52366. */
  52367. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  52368. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  52369. return SQLITE_LOCKED_SHAREDCACHE;
  52370. }
  52371. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  52372. /* The condition (pIter->eLock!=eLock) in the following if(...)
  52373. ** statement is a simplification of:
  52374. **
  52375. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  52376. **
  52377. ** since we know that if eLock==WRITE_LOCK, then no other connection
  52378. ** may hold a WRITE_LOCK on any table in this file (since there can
  52379. ** only be a single writer).
  52380. */
  52381. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  52382. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  52383. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  52384. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  52385. if( eLock==WRITE_LOCK ){
  52386. assert( p==pBt->pWriter );
  52387. pBt->btsFlags |= BTS_PENDING;
  52388. }
  52389. return SQLITE_LOCKED_SHAREDCACHE;
  52390. }
  52391. }
  52392. return SQLITE_OK;
  52393. }
  52394. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  52395. #ifndef SQLITE_OMIT_SHARED_CACHE
  52396. /*
  52397. ** Add a lock on the table with root-page iTable to the shared-btree used
  52398. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  52399. ** WRITE_LOCK.
  52400. **
  52401. ** This function assumes the following:
  52402. **
  52403. ** (a) The specified Btree object p is connected to a sharable
  52404. ** database (one with the BtShared.sharable flag set), and
  52405. **
  52406. ** (b) No other Btree objects hold a lock that conflicts
  52407. ** with the requested lock (i.e. querySharedCacheTableLock() has
  52408. ** already been called and returned SQLITE_OK).
  52409. **
  52410. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  52411. ** is returned if a malloc attempt fails.
  52412. */
  52413. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  52414. BtShared *pBt = p->pBt;
  52415. BtLock *pLock = 0;
  52416. BtLock *pIter;
  52417. assert( sqlite3BtreeHoldsMutex(p) );
  52418. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  52419. assert( p->db!=0 );
  52420. /* A connection with the read-uncommitted flag set will never try to
  52421. ** obtain a read-lock using this function. The only read-lock obtained
  52422. ** by a connection in read-uncommitted mode is on the sqlite_master
  52423. ** table, and that lock is obtained in BtreeBeginTrans(). */
  52424. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  52425. /* This function should only be called on a sharable b-tree after it
  52426. ** has been determined that no other b-tree holds a conflicting lock. */
  52427. assert( p->sharable );
  52428. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  52429. /* First search the list for an existing lock on this table. */
  52430. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  52431. if( pIter->iTable==iTable && pIter->pBtree==p ){
  52432. pLock = pIter;
  52433. break;
  52434. }
  52435. }
  52436. /* If the above search did not find a BtLock struct associating Btree p
  52437. ** with table iTable, allocate one and link it into the list.
  52438. */
  52439. if( !pLock ){
  52440. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  52441. if( !pLock ){
  52442. return SQLITE_NOMEM_BKPT;
  52443. }
  52444. pLock->iTable = iTable;
  52445. pLock->pBtree = p;
  52446. pLock->pNext = pBt->pLock;
  52447. pBt->pLock = pLock;
  52448. }
  52449. /* Set the BtLock.eLock variable to the maximum of the current lock
  52450. ** and the requested lock. This means if a write-lock was already held
  52451. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  52452. */
  52453. assert( WRITE_LOCK>READ_LOCK );
  52454. if( eLock>pLock->eLock ){
  52455. pLock->eLock = eLock;
  52456. }
  52457. return SQLITE_OK;
  52458. }
  52459. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  52460. #ifndef SQLITE_OMIT_SHARED_CACHE
  52461. /*
  52462. ** Release all the table locks (locks obtained via calls to
  52463. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  52464. **
  52465. ** This function assumes that Btree p has an open read or write
  52466. ** transaction. If it does not, then the BTS_PENDING flag
  52467. ** may be incorrectly cleared.
  52468. */
  52469. static void clearAllSharedCacheTableLocks(Btree *p){
  52470. BtShared *pBt = p->pBt;
  52471. BtLock **ppIter = &pBt->pLock;
  52472. assert( sqlite3BtreeHoldsMutex(p) );
  52473. assert( p->sharable || 0==*ppIter );
  52474. assert( p->inTrans>0 );
  52475. while( *ppIter ){
  52476. BtLock *pLock = *ppIter;
  52477. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  52478. assert( pLock->pBtree->inTrans>=pLock->eLock );
  52479. if( pLock->pBtree==p ){
  52480. *ppIter = pLock->pNext;
  52481. assert( pLock->iTable!=1 || pLock==&p->lock );
  52482. if( pLock->iTable!=1 ){
  52483. sqlite3_free(pLock);
  52484. }
  52485. }else{
  52486. ppIter = &pLock->pNext;
  52487. }
  52488. }
  52489. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  52490. if( pBt->pWriter==p ){
  52491. pBt->pWriter = 0;
  52492. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  52493. }else if( pBt->nTransaction==2 ){
  52494. /* This function is called when Btree p is concluding its
  52495. ** transaction. If there currently exists a writer, and p is not
  52496. ** that writer, then the number of locks held by connections other
  52497. ** than the writer must be about to drop to zero. In this case
  52498. ** set the BTS_PENDING flag to 0.
  52499. **
  52500. ** If there is not currently a writer, then BTS_PENDING must
  52501. ** be zero already. So this next line is harmless in that case.
  52502. */
  52503. pBt->btsFlags &= ~BTS_PENDING;
  52504. }
  52505. }
  52506. /*
  52507. ** This function changes all write-locks held by Btree p into read-locks.
  52508. */
  52509. static void downgradeAllSharedCacheTableLocks(Btree *p){
  52510. BtShared *pBt = p->pBt;
  52511. if( pBt->pWriter==p ){
  52512. BtLock *pLock;
  52513. pBt->pWriter = 0;
  52514. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  52515. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  52516. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  52517. pLock->eLock = READ_LOCK;
  52518. }
  52519. }
  52520. }
  52521. #endif /* SQLITE_OMIT_SHARED_CACHE */
  52522. static void releasePage(MemPage *pPage); /* Forward reference */
  52523. /*
  52524. ***** This routine is used inside of assert() only ****
  52525. **
  52526. ** Verify that the cursor holds the mutex on its BtShared
  52527. */
  52528. #ifdef SQLITE_DEBUG
  52529. static int cursorHoldsMutex(BtCursor *p){
  52530. return sqlite3_mutex_held(p->pBt->mutex);
  52531. }
  52532. static int cursorOwnsBtShared(BtCursor *p){
  52533. assert( cursorHoldsMutex(p) );
  52534. return (p->pBtree->db==p->pBt->db);
  52535. }
  52536. #endif
  52537. /*
  52538. ** Invalidate the overflow cache of the cursor passed as the first argument.
  52539. ** on the shared btree structure pBt.
  52540. */
  52541. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  52542. /*
  52543. ** Invalidate the overflow page-list cache for all cursors opened
  52544. ** on the shared btree structure pBt.
  52545. */
  52546. static void invalidateAllOverflowCache(BtShared *pBt){
  52547. BtCursor *p;
  52548. assert( sqlite3_mutex_held(pBt->mutex) );
  52549. for(p=pBt->pCursor; p; p=p->pNext){
  52550. invalidateOverflowCache(p);
  52551. }
  52552. }
  52553. #ifndef SQLITE_OMIT_INCRBLOB
  52554. /*
  52555. ** This function is called before modifying the contents of a table
  52556. ** to invalidate any incrblob cursors that are open on the
  52557. ** row or one of the rows being modified.
  52558. **
  52559. ** If argument isClearTable is true, then the entire contents of the
  52560. ** table is about to be deleted. In this case invalidate all incrblob
  52561. ** cursors open on any row within the table with root-page pgnoRoot.
  52562. **
  52563. ** Otherwise, if argument isClearTable is false, then the row with
  52564. ** rowid iRow is being replaced or deleted. In this case invalidate
  52565. ** only those incrblob cursors open on that specific row.
  52566. */
  52567. static void invalidateIncrblobCursors(
  52568. Btree *pBtree, /* The database file to check */
  52569. i64 iRow, /* The rowid that might be changing */
  52570. int isClearTable /* True if all rows are being deleted */
  52571. ){
  52572. BtCursor *p;
  52573. if( pBtree->hasIncrblobCur==0 ) return;
  52574. assert( sqlite3BtreeHoldsMutex(pBtree) );
  52575. pBtree->hasIncrblobCur = 0;
  52576. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  52577. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  52578. pBtree->hasIncrblobCur = 1;
  52579. if( isClearTable || p->info.nKey==iRow ){
  52580. p->eState = CURSOR_INVALID;
  52581. }
  52582. }
  52583. }
  52584. }
  52585. #else
  52586. /* Stub function when INCRBLOB is omitted */
  52587. #define invalidateIncrblobCursors(x,y,z)
  52588. #endif /* SQLITE_OMIT_INCRBLOB */
  52589. /*
  52590. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  52591. ** when a page that previously contained data becomes a free-list leaf
  52592. ** page.
  52593. **
  52594. ** The BtShared.pHasContent bitvec exists to work around an obscure
  52595. ** bug caused by the interaction of two useful IO optimizations surrounding
  52596. ** free-list leaf pages:
  52597. **
  52598. ** 1) When all data is deleted from a page and the page becomes
  52599. ** a free-list leaf page, the page is not written to the database
  52600. ** (as free-list leaf pages contain no meaningful data). Sometimes
  52601. ** such a page is not even journalled (as it will not be modified,
  52602. ** why bother journalling it?).
  52603. **
  52604. ** 2) When a free-list leaf page is reused, its content is not read
  52605. ** from the database or written to the journal file (why should it
  52606. ** be, if it is not at all meaningful?).
  52607. **
  52608. ** By themselves, these optimizations work fine and provide a handy
  52609. ** performance boost to bulk delete or insert operations. However, if
  52610. ** a page is moved to the free-list and then reused within the same
  52611. ** transaction, a problem comes up. If the page is not journalled when
  52612. ** it is moved to the free-list and it is also not journalled when it
  52613. ** is extracted from the free-list and reused, then the original data
  52614. ** may be lost. In the event of a rollback, it may not be possible
  52615. ** to restore the database to its original configuration.
  52616. **
  52617. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  52618. ** moved to become a free-list leaf page, the corresponding bit is
  52619. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  52620. ** optimization 2 above is omitted if the corresponding bit is already
  52621. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  52622. ** at the end of every transaction.
  52623. */
  52624. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  52625. int rc = SQLITE_OK;
  52626. if( !pBt->pHasContent ){
  52627. assert( pgno<=pBt->nPage );
  52628. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  52629. if( !pBt->pHasContent ){
  52630. rc = SQLITE_NOMEM_BKPT;
  52631. }
  52632. }
  52633. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  52634. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  52635. }
  52636. return rc;
  52637. }
  52638. /*
  52639. ** Query the BtShared.pHasContent vector.
  52640. **
  52641. ** This function is called when a free-list leaf page is removed from the
  52642. ** free-list for reuse. It returns false if it is safe to retrieve the
  52643. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  52644. */
  52645. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  52646. Bitvec *p = pBt->pHasContent;
  52647. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  52648. }
  52649. /*
  52650. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  52651. ** invoked at the conclusion of each write-transaction.
  52652. */
  52653. static void btreeClearHasContent(BtShared *pBt){
  52654. sqlite3BitvecDestroy(pBt->pHasContent);
  52655. pBt->pHasContent = 0;
  52656. }
  52657. /*
  52658. ** Release all of the apPage[] pages for a cursor.
  52659. */
  52660. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  52661. int i;
  52662. for(i=0; i<=pCur->iPage; i++){
  52663. releasePage(pCur->apPage[i]);
  52664. pCur->apPage[i] = 0;
  52665. }
  52666. pCur->iPage = -1;
  52667. }
  52668. /*
  52669. ** The cursor passed as the only argument must point to a valid entry
  52670. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  52671. ** function saves the current cursor key in variables pCur->nKey and
  52672. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  52673. ** code otherwise.
  52674. **
  52675. ** If the cursor is open on an intkey table, then the integer key
  52676. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  52677. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  52678. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  52679. ** the key.
  52680. */
  52681. static int saveCursorKey(BtCursor *pCur){
  52682. int rc;
  52683. assert( CURSOR_VALID==pCur->eState );
  52684. assert( 0==pCur->pKey );
  52685. assert( cursorHoldsMutex(pCur) );
  52686. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  52687. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  52688. /* If this is an intKey table, then the above call to BtreeKeySize()
  52689. ** stores the integer key in pCur->nKey. In this case this value is
  52690. ** all that is required. Otherwise, if pCur is not open on an intKey
  52691. ** table, then malloc space for and store the pCur->nKey bytes of key
  52692. ** data. */
  52693. if( 0==pCur->curIntKey ){
  52694. void *pKey = sqlite3Malloc( pCur->nKey );
  52695. if( pKey ){
  52696. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  52697. if( rc==SQLITE_OK ){
  52698. pCur->pKey = pKey;
  52699. }else{
  52700. sqlite3_free(pKey);
  52701. }
  52702. }else{
  52703. rc = SQLITE_NOMEM_BKPT;
  52704. }
  52705. }
  52706. assert( !pCur->curIntKey || !pCur->pKey );
  52707. return rc;
  52708. }
  52709. /*
  52710. ** Save the current cursor position in the variables BtCursor.nKey
  52711. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  52712. **
  52713. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  52714. ** prior to calling this routine.
  52715. */
  52716. static int saveCursorPosition(BtCursor *pCur){
  52717. int rc;
  52718. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  52719. assert( 0==pCur->pKey );
  52720. assert( cursorHoldsMutex(pCur) );
  52721. if( pCur->eState==CURSOR_SKIPNEXT ){
  52722. pCur->eState = CURSOR_VALID;
  52723. }else{
  52724. pCur->skipNext = 0;
  52725. }
  52726. rc = saveCursorKey(pCur);
  52727. if( rc==SQLITE_OK ){
  52728. btreeReleaseAllCursorPages(pCur);
  52729. pCur->eState = CURSOR_REQUIRESEEK;
  52730. }
  52731. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  52732. return rc;
  52733. }
  52734. /* Forward reference */
  52735. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  52736. /*
  52737. ** Save the positions of all cursors (except pExcept) that are open on
  52738. ** the table with root-page iRoot. "Saving the cursor position" means that
  52739. ** the location in the btree is remembered in such a way that it can be
  52740. ** moved back to the same spot after the btree has been modified. This
  52741. ** routine is called just before cursor pExcept is used to modify the
  52742. ** table, for example in BtreeDelete() or BtreeInsert().
  52743. **
  52744. ** If there are two or more cursors on the same btree, then all such
  52745. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  52746. ** routine enforces that rule. This routine only needs to be called in
  52747. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  52748. **
  52749. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  52750. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  52751. ** pointless call to this routine.
  52752. **
  52753. ** Implementation note: This routine merely checks to see if any cursors
  52754. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  52755. ** event that cursors are in need to being saved.
  52756. */
  52757. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  52758. BtCursor *p;
  52759. assert( sqlite3_mutex_held(pBt->mutex) );
  52760. assert( pExcept==0 || pExcept->pBt==pBt );
  52761. for(p=pBt->pCursor; p; p=p->pNext){
  52762. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  52763. }
  52764. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  52765. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  52766. return SQLITE_OK;
  52767. }
  52768. /* This helper routine to saveAllCursors does the actual work of saving
  52769. ** the cursors if and when a cursor is found that actually requires saving.
  52770. ** The common case is that no cursors need to be saved, so this routine is
  52771. ** broken out from its caller to avoid unnecessary stack pointer movement.
  52772. */
  52773. static int SQLITE_NOINLINE saveCursorsOnList(
  52774. BtCursor *p, /* The first cursor that needs saving */
  52775. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  52776. BtCursor *pExcept /* Do not save this cursor */
  52777. ){
  52778. do{
  52779. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  52780. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  52781. int rc = saveCursorPosition(p);
  52782. if( SQLITE_OK!=rc ){
  52783. return rc;
  52784. }
  52785. }else{
  52786. testcase( p->iPage>0 );
  52787. btreeReleaseAllCursorPages(p);
  52788. }
  52789. }
  52790. p = p->pNext;
  52791. }while( p );
  52792. return SQLITE_OK;
  52793. }
  52794. /*
  52795. ** Clear the current cursor position.
  52796. */
  52797. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  52798. assert( cursorHoldsMutex(pCur) );
  52799. sqlite3_free(pCur->pKey);
  52800. pCur->pKey = 0;
  52801. pCur->eState = CURSOR_INVALID;
  52802. }
  52803. /*
  52804. ** In this version of BtreeMoveto, pKey is a packed index record
  52805. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  52806. ** record and then call BtreeMovetoUnpacked() to do the work.
  52807. */
  52808. static int btreeMoveto(
  52809. BtCursor *pCur, /* Cursor open on the btree to be searched */
  52810. const void *pKey, /* Packed key if the btree is an index */
  52811. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  52812. int bias, /* Bias search to the high end */
  52813. int *pRes /* Write search results here */
  52814. ){
  52815. int rc; /* Status code */
  52816. UnpackedRecord *pIdxKey; /* Unpacked index key */
  52817. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  52818. char *pFree = 0;
  52819. if( pKey ){
  52820. assert( nKey==(i64)(int)nKey );
  52821. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  52822. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  52823. );
  52824. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  52825. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  52826. if( pIdxKey->nField==0 ){
  52827. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  52828. return SQLITE_CORRUPT_BKPT;
  52829. }
  52830. }else{
  52831. pIdxKey = 0;
  52832. }
  52833. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  52834. if( pFree ){
  52835. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  52836. }
  52837. return rc;
  52838. }
  52839. /*
  52840. ** Restore the cursor to the position it was in (or as close to as possible)
  52841. ** when saveCursorPosition() was called. Note that this call deletes the
  52842. ** saved position info stored by saveCursorPosition(), so there can be
  52843. ** at most one effective restoreCursorPosition() call after each
  52844. ** saveCursorPosition().
  52845. */
  52846. static int btreeRestoreCursorPosition(BtCursor *pCur){
  52847. int rc;
  52848. int skipNext;
  52849. assert( cursorOwnsBtShared(pCur) );
  52850. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  52851. if( pCur->eState==CURSOR_FAULT ){
  52852. return pCur->skipNext;
  52853. }
  52854. pCur->eState = CURSOR_INVALID;
  52855. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  52856. if( rc==SQLITE_OK ){
  52857. sqlite3_free(pCur->pKey);
  52858. pCur->pKey = 0;
  52859. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  52860. pCur->skipNext |= skipNext;
  52861. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  52862. pCur->eState = CURSOR_SKIPNEXT;
  52863. }
  52864. }
  52865. return rc;
  52866. }
  52867. #define restoreCursorPosition(p) \
  52868. (p->eState>=CURSOR_REQUIRESEEK ? \
  52869. btreeRestoreCursorPosition(p) : \
  52870. SQLITE_OK)
  52871. /*
  52872. ** Determine whether or not a cursor has moved from the position where
  52873. ** it was last placed, or has been invalidated for any other reason.
  52874. ** Cursors can move when the row they are pointing at is deleted out
  52875. ** from under them, for example. Cursor might also move if a btree
  52876. ** is rebalanced.
  52877. **
  52878. ** Calling this routine with a NULL cursor pointer returns false.
  52879. **
  52880. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  52881. ** back to where it ought to be if this routine returns true.
  52882. */
  52883. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  52884. return pCur->eState!=CURSOR_VALID;
  52885. }
  52886. /*
  52887. ** This routine restores a cursor back to its original position after it
  52888. ** has been moved by some outside activity (such as a btree rebalance or
  52889. ** a row having been deleted out from under the cursor).
  52890. **
  52891. ** On success, the *pDifferentRow parameter is false if the cursor is left
  52892. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  52893. ** was pointing to has been deleted, forcing the cursor to point to some
  52894. ** nearby row.
  52895. **
  52896. ** This routine should only be called for a cursor that just returned
  52897. ** TRUE from sqlite3BtreeCursorHasMoved().
  52898. */
  52899. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  52900. int rc;
  52901. assert( pCur!=0 );
  52902. assert( pCur->eState!=CURSOR_VALID );
  52903. rc = restoreCursorPosition(pCur);
  52904. if( rc ){
  52905. *pDifferentRow = 1;
  52906. return rc;
  52907. }
  52908. if( pCur->eState!=CURSOR_VALID ){
  52909. *pDifferentRow = 1;
  52910. }else{
  52911. assert( pCur->skipNext==0 );
  52912. *pDifferentRow = 0;
  52913. }
  52914. return SQLITE_OK;
  52915. }
  52916. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  52917. /*
  52918. ** Provide hints to the cursor. The particular hint given (and the type
  52919. ** and number of the varargs parameters) is determined by the eHintType
  52920. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  52921. */
  52922. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  52923. /* Used only by system that substitute their own storage engine */
  52924. }
  52925. #endif
  52926. /*
  52927. ** Provide flag hints to the cursor.
  52928. */
  52929. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  52930. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  52931. pCur->hints = x;
  52932. }
  52933. #ifndef SQLITE_OMIT_AUTOVACUUM
  52934. /*
  52935. ** Given a page number of a regular database page, return the page
  52936. ** number for the pointer-map page that contains the entry for the
  52937. ** input page number.
  52938. **
  52939. ** Return 0 (not a valid page) for pgno==1 since there is
  52940. ** no pointer map associated with page 1. The integrity_check logic
  52941. ** requires that ptrmapPageno(*,1)!=1.
  52942. */
  52943. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  52944. int nPagesPerMapPage;
  52945. Pgno iPtrMap, ret;
  52946. assert( sqlite3_mutex_held(pBt->mutex) );
  52947. if( pgno<2 ) return 0;
  52948. nPagesPerMapPage = (pBt->usableSize/5)+1;
  52949. iPtrMap = (pgno-2)/nPagesPerMapPage;
  52950. ret = (iPtrMap*nPagesPerMapPage) + 2;
  52951. if( ret==PENDING_BYTE_PAGE(pBt) ){
  52952. ret++;
  52953. }
  52954. return ret;
  52955. }
  52956. /*
  52957. ** Write an entry into the pointer map.
  52958. **
  52959. ** This routine updates the pointer map entry for page number 'key'
  52960. ** so that it maps to type 'eType' and parent page number 'pgno'.
  52961. **
  52962. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  52963. ** a no-op. If an error occurs, the appropriate error code is written
  52964. ** into *pRC.
  52965. */
  52966. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  52967. DbPage *pDbPage; /* The pointer map page */
  52968. u8 *pPtrmap; /* The pointer map data */
  52969. Pgno iPtrmap; /* The pointer map page number */
  52970. int offset; /* Offset in pointer map page */
  52971. int rc; /* Return code from subfunctions */
  52972. if( *pRC ) return;
  52973. assert( sqlite3_mutex_held(pBt->mutex) );
  52974. /* The master-journal page number must never be used as a pointer map page */
  52975. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  52976. assert( pBt->autoVacuum );
  52977. if( key==0 ){
  52978. *pRC = SQLITE_CORRUPT_BKPT;
  52979. return;
  52980. }
  52981. iPtrmap = PTRMAP_PAGENO(pBt, key);
  52982. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  52983. if( rc!=SQLITE_OK ){
  52984. *pRC = rc;
  52985. return;
  52986. }
  52987. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  52988. if( offset<0 ){
  52989. *pRC = SQLITE_CORRUPT_BKPT;
  52990. goto ptrmap_exit;
  52991. }
  52992. assert( offset <= (int)pBt->usableSize-5 );
  52993. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  52994. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  52995. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  52996. *pRC= rc = sqlite3PagerWrite(pDbPage);
  52997. if( rc==SQLITE_OK ){
  52998. pPtrmap[offset] = eType;
  52999. put4byte(&pPtrmap[offset+1], parent);
  53000. }
  53001. }
  53002. ptrmap_exit:
  53003. sqlite3PagerUnref(pDbPage);
  53004. }
  53005. /*
  53006. ** Read an entry from the pointer map.
  53007. **
  53008. ** This routine retrieves the pointer map entry for page 'key', writing
  53009. ** the type and parent page number to *pEType and *pPgno respectively.
  53010. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  53011. */
  53012. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  53013. DbPage *pDbPage; /* The pointer map page */
  53014. int iPtrmap; /* Pointer map page index */
  53015. u8 *pPtrmap; /* Pointer map page data */
  53016. int offset; /* Offset of entry in pointer map */
  53017. int rc;
  53018. assert( sqlite3_mutex_held(pBt->mutex) );
  53019. iPtrmap = PTRMAP_PAGENO(pBt, key);
  53020. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  53021. if( rc!=0 ){
  53022. return rc;
  53023. }
  53024. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  53025. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  53026. if( offset<0 ){
  53027. sqlite3PagerUnref(pDbPage);
  53028. return SQLITE_CORRUPT_BKPT;
  53029. }
  53030. assert( offset <= (int)pBt->usableSize-5 );
  53031. assert( pEType!=0 );
  53032. *pEType = pPtrmap[offset];
  53033. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  53034. sqlite3PagerUnref(pDbPage);
  53035. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  53036. return SQLITE_OK;
  53037. }
  53038. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  53039. #define ptrmapPut(w,x,y,z,rc)
  53040. #define ptrmapGet(w,x,y,z) SQLITE_OK
  53041. #define ptrmapPutOvflPtr(x, y, rc)
  53042. #endif
  53043. /*
  53044. ** Given a btree page and a cell index (0 means the first cell on
  53045. ** the page, 1 means the second cell, and so forth) return a pointer
  53046. ** to the cell content.
  53047. **
  53048. ** findCellPastPtr() does the same except it skips past the initial
  53049. ** 4-byte child pointer found on interior pages, if there is one.
  53050. **
  53051. ** This routine works only for pages that do not contain overflow cells.
  53052. */
  53053. #define findCell(P,I) \
  53054. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  53055. #define findCellPastPtr(P,I) \
  53056. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  53057. /*
  53058. ** This is common tail processing for btreeParseCellPtr() and
  53059. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  53060. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  53061. ** structure.
  53062. */
  53063. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  53064. MemPage *pPage, /* Page containing the cell */
  53065. u8 *pCell, /* Pointer to the cell text. */
  53066. CellInfo *pInfo /* Fill in this structure */
  53067. ){
  53068. /* If the payload will not fit completely on the local page, we have
  53069. ** to decide how much to store locally and how much to spill onto
  53070. ** overflow pages. The strategy is to minimize the amount of unused
  53071. ** space on overflow pages while keeping the amount of local storage
  53072. ** in between minLocal and maxLocal.
  53073. **
  53074. ** Warning: changing the way overflow payload is distributed in any
  53075. ** way will result in an incompatible file format.
  53076. */
  53077. int minLocal; /* Minimum amount of payload held locally */
  53078. int maxLocal; /* Maximum amount of payload held locally */
  53079. int surplus; /* Overflow payload available for local storage */
  53080. minLocal = pPage->minLocal;
  53081. maxLocal = pPage->maxLocal;
  53082. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  53083. testcase( surplus==maxLocal );
  53084. testcase( surplus==maxLocal+1 );
  53085. if( surplus <= maxLocal ){
  53086. pInfo->nLocal = (u16)surplus;
  53087. }else{
  53088. pInfo->nLocal = (u16)minLocal;
  53089. }
  53090. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  53091. }
  53092. /*
  53093. ** The following routines are implementations of the MemPage.xParseCell()
  53094. ** method.
  53095. **
  53096. ** Parse a cell content block and fill in the CellInfo structure.
  53097. **
  53098. ** btreeParseCellPtr() => table btree leaf nodes
  53099. ** btreeParseCellNoPayload() => table btree internal nodes
  53100. ** btreeParseCellPtrIndex() => index btree nodes
  53101. **
  53102. ** There is also a wrapper function btreeParseCell() that works for
  53103. ** all MemPage types and that references the cell by index rather than
  53104. ** by pointer.
  53105. */
  53106. static void btreeParseCellPtrNoPayload(
  53107. MemPage *pPage, /* Page containing the cell */
  53108. u8 *pCell, /* Pointer to the cell text. */
  53109. CellInfo *pInfo /* Fill in this structure */
  53110. ){
  53111. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53112. assert( pPage->leaf==0 );
  53113. assert( pPage->childPtrSize==4 );
  53114. #ifndef SQLITE_DEBUG
  53115. UNUSED_PARAMETER(pPage);
  53116. #endif
  53117. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  53118. pInfo->nPayload = 0;
  53119. pInfo->nLocal = 0;
  53120. pInfo->pPayload = 0;
  53121. return;
  53122. }
  53123. static void btreeParseCellPtr(
  53124. MemPage *pPage, /* Page containing the cell */
  53125. u8 *pCell, /* Pointer to the cell text. */
  53126. CellInfo *pInfo /* Fill in this structure */
  53127. ){
  53128. u8 *pIter; /* For scanning through pCell */
  53129. u32 nPayload; /* Number of bytes of cell payload */
  53130. u64 iKey; /* Extracted Key value */
  53131. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53132. assert( pPage->leaf==0 || pPage->leaf==1 );
  53133. assert( pPage->intKeyLeaf );
  53134. assert( pPage->childPtrSize==0 );
  53135. pIter = pCell;
  53136. /* The next block of code is equivalent to:
  53137. **
  53138. ** pIter += getVarint32(pIter, nPayload);
  53139. **
  53140. ** The code is inlined to avoid a function call.
  53141. */
  53142. nPayload = *pIter;
  53143. if( nPayload>=0x80 ){
  53144. u8 *pEnd = &pIter[8];
  53145. nPayload &= 0x7f;
  53146. do{
  53147. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  53148. }while( (*pIter)>=0x80 && pIter<pEnd );
  53149. }
  53150. pIter++;
  53151. /* The next block of code is equivalent to:
  53152. **
  53153. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  53154. **
  53155. ** The code is inlined to avoid a function call.
  53156. */
  53157. iKey = *pIter;
  53158. if( iKey>=0x80 ){
  53159. u8 *pEnd = &pIter[7];
  53160. iKey &= 0x7f;
  53161. while(1){
  53162. iKey = (iKey<<7) | (*++pIter & 0x7f);
  53163. if( (*pIter)<0x80 ) break;
  53164. if( pIter>=pEnd ){
  53165. iKey = (iKey<<8) | *++pIter;
  53166. break;
  53167. }
  53168. }
  53169. }
  53170. pIter++;
  53171. pInfo->nKey = *(i64*)&iKey;
  53172. pInfo->nPayload = nPayload;
  53173. pInfo->pPayload = pIter;
  53174. testcase( nPayload==pPage->maxLocal );
  53175. testcase( nPayload==pPage->maxLocal+1 );
  53176. if( nPayload<=pPage->maxLocal ){
  53177. /* This is the (easy) common case where the entire payload fits
  53178. ** on the local page. No overflow is required.
  53179. */
  53180. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  53181. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  53182. pInfo->nLocal = (u16)nPayload;
  53183. }else{
  53184. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  53185. }
  53186. }
  53187. static void btreeParseCellPtrIndex(
  53188. MemPage *pPage, /* Page containing the cell */
  53189. u8 *pCell, /* Pointer to the cell text. */
  53190. CellInfo *pInfo /* Fill in this structure */
  53191. ){
  53192. u8 *pIter; /* For scanning through pCell */
  53193. u32 nPayload; /* Number of bytes of cell payload */
  53194. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53195. assert( pPage->leaf==0 || pPage->leaf==1 );
  53196. assert( pPage->intKeyLeaf==0 );
  53197. pIter = pCell + pPage->childPtrSize;
  53198. nPayload = *pIter;
  53199. if( nPayload>=0x80 ){
  53200. u8 *pEnd = &pIter[8];
  53201. nPayload &= 0x7f;
  53202. do{
  53203. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  53204. }while( *(pIter)>=0x80 && pIter<pEnd );
  53205. }
  53206. pIter++;
  53207. pInfo->nKey = nPayload;
  53208. pInfo->nPayload = nPayload;
  53209. pInfo->pPayload = pIter;
  53210. testcase( nPayload==pPage->maxLocal );
  53211. testcase( nPayload==pPage->maxLocal+1 );
  53212. if( nPayload<=pPage->maxLocal ){
  53213. /* This is the (easy) common case where the entire payload fits
  53214. ** on the local page. No overflow is required.
  53215. */
  53216. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  53217. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  53218. pInfo->nLocal = (u16)nPayload;
  53219. }else{
  53220. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  53221. }
  53222. }
  53223. static void btreeParseCell(
  53224. MemPage *pPage, /* Page containing the cell */
  53225. int iCell, /* The cell index. First cell is 0 */
  53226. CellInfo *pInfo /* Fill in this structure */
  53227. ){
  53228. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  53229. }
  53230. /*
  53231. ** The following routines are implementations of the MemPage.xCellSize
  53232. ** method.
  53233. **
  53234. ** Compute the total number of bytes that a Cell needs in the cell
  53235. ** data area of the btree-page. The return number includes the cell
  53236. ** data header and the local payload, but not any overflow page or
  53237. ** the space used by the cell pointer.
  53238. **
  53239. ** cellSizePtrNoPayload() => table internal nodes
  53240. ** cellSizePtr() => all index nodes & table leaf nodes
  53241. */
  53242. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  53243. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  53244. u8 *pEnd; /* End mark for a varint */
  53245. u32 nSize; /* Size value to return */
  53246. #ifdef SQLITE_DEBUG
  53247. /* The value returned by this function should always be the same as
  53248. ** the (CellInfo.nSize) value found by doing a full parse of the
  53249. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  53250. ** this function verifies that this invariant is not violated. */
  53251. CellInfo debuginfo;
  53252. pPage->xParseCell(pPage, pCell, &debuginfo);
  53253. #endif
  53254. nSize = *pIter;
  53255. if( nSize>=0x80 ){
  53256. pEnd = &pIter[8];
  53257. nSize &= 0x7f;
  53258. do{
  53259. nSize = (nSize<<7) | (*++pIter & 0x7f);
  53260. }while( *(pIter)>=0x80 && pIter<pEnd );
  53261. }
  53262. pIter++;
  53263. if( pPage->intKey ){
  53264. /* pIter now points at the 64-bit integer key value, a variable length
  53265. ** integer. The following block moves pIter to point at the first byte
  53266. ** past the end of the key value. */
  53267. pEnd = &pIter[9];
  53268. while( (*pIter++)&0x80 && pIter<pEnd );
  53269. }
  53270. testcase( nSize==pPage->maxLocal );
  53271. testcase( nSize==pPage->maxLocal+1 );
  53272. if( nSize<=pPage->maxLocal ){
  53273. nSize += (u32)(pIter - pCell);
  53274. if( nSize<4 ) nSize = 4;
  53275. }else{
  53276. int minLocal = pPage->minLocal;
  53277. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  53278. testcase( nSize==pPage->maxLocal );
  53279. testcase( nSize==pPage->maxLocal+1 );
  53280. if( nSize>pPage->maxLocal ){
  53281. nSize = minLocal;
  53282. }
  53283. nSize += 4 + (u16)(pIter - pCell);
  53284. }
  53285. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  53286. return (u16)nSize;
  53287. }
  53288. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  53289. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  53290. u8 *pEnd; /* End mark for a varint */
  53291. #ifdef SQLITE_DEBUG
  53292. /* The value returned by this function should always be the same as
  53293. ** the (CellInfo.nSize) value found by doing a full parse of the
  53294. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  53295. ** this function verifies that this invariant is not violated. */
  53296. CellInfo debuginfo;
  53297. pPage->xParseCell(pPage, pCell, &debuginfo);
  53298. #else
  53299. UNUSED_PARAMETER(pPage);
  53300. #endif
  53301. assert( pPage->childPtrSize==4 );
  53302. pEnd = pIter + 9;
  53303. while( (*pIter++)&0x80 && pIter<pEnd );
  53304. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  53305. return (u16)(pIter - pCell);
  53306. }
  53307. #ifdef SQLITE_DEBUG
  53308. /* This variation on cellSizePtr() is used inside of assert() statements
  53309. ** only. */
  53310. static u16 cellSize(MemPage *pPage, int iCell){
  53311. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  53312. }
  53313. #endif
  53314. #ifndef SQLITE_OMIT_AUTOVACUUM
  53315. /*
  53316. ** If the cell pCell, part of page pPage contains a pointer
  53317. ** to an overflow page, insert an entry into the pointer-map
  53318. ** for the overflow page.
  53319. */
  53320. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  53321. CellInfo info;
  53322. if( *pRC ) return;
  53323. assert( pCell!=0 );
  53324. pPage->xParseCell(pPage, pCell, &info);
  53325. if( info.nLocal<info.nPayload ){
  53326. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  53327. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  53328. }
  53329. }
  53330. #endif
  53331. /*
  53332. ** Defragment the page given. All Cells are moved to the
  53333. ** end of the page and all free space is collected into one
  53334. ** big FreeBlk that occurs in between the header and cell
  53335. ** pointer array and the cell content area.
  53336. **
  53337. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  53338. ** b-tree page so that there are no freeblocks or fragment bytes, all
  53339. ** unused bytes are contained in the unallocated space region, and all
  53340. ** cells are packed tightly at the end of the page.
  53341. */
  53342. static int defragmentPage(MemPage *pPage){
  53343. int i; /* Loop counter */
  53344. int pc; /* Address of the i-th cell */
  53345. int hdr; /* Offset to the page header */
  53346. int size; /* Size of a cell */
  53347. int usableSize; /* Number of usable bytes on a page */
  53348. int cellOffset; /* Offset to the cell pointer array */
  53349. int cbrk; /* Offset to the cell content area */
  53350. int nCell; /* Number of cells on the page */
  53351. unsigned char *data; /* The page data */
  53352. unsigned char *temp; /* Temp area for cell content */
  53353. unsigned char *src; /* Source of content */
  53354. int iCellFirst; /* First allowable cell index */
  53355. int iCellLast; /* Last possible cell index */
  53356. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53357. assert( pPage->pBt!=0 );
  53358. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  53359. assert( pPage->nOverflow==0 );
  53360. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53361. temp = 0;
  53362. src = data = pPage->aData;
  53363. hdr = pPage->hdrOffset;
  53364. cellOffset = pPage->cellOffset;
  53365. nCell = pPage->nCell;
  53366. assert( nCell==get2byte(&data[hdr+3]) );
  53367. usableSize = pPage->pBt->usableSize;
  53368. cbrk = usableSize;
  53369. iCellFirst = cellOffset + 2*nCell;
  53370. iCellLast = usableSize - 4;
  53371. for(i=0; i<nCell; i++){
  53372. u8 *pAddr; /* The i-th cell pointer */
  53373. pAddr = &data[cellOffset + i*2];
  53374. pc = get2byte(pAddr);
  53375. testcase( pc==iCellFirst );
  53376. testcase( pc==iCellLast );
  53377. /* These conditions have already been verified in btreeInitPage()
  53378. ** if PRAGMA cell_size_check=ON.
  53379. */
  53380. if( pc<iCellFirst || pc>iCellLast ){
  53381. return SQLITE_CORRUPT_BKPT;
  53382. }
  53383. assert( pc>=iCellFirst && pc<=iCellLast );
  53384. size = pPage->xCellSize(pPage, &src[pc]);
  53385. cbrk -= size;
  53386. if( cbrk<iCellFirst || pc+size>usableSize ){
  53387. return SQLITE_CORRUPT_BKPT;
  53388. }
  53389. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  53390. testcase( cbrk+size==usableSize );
  53391. testcase( pc+size==usableSize );
  53392. put2byte(pAddr, cbrk);
  53393. if( temp==0 ){
  53394. int x;
  53395. if( cbrk==pc ) continue;
  53396. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  53397. x = get2byte(&data[hdr+5]);
  53398. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  53399. src = temp;
  53400. }
  53401. memcpy(&data[cbrk], &src[pc], size);
  53402. }
  53403. assert( cbrk>=iCellFirst );
  53404. put2byte(&data[hdr+5], cbrk);
  53405. data[hdr+1] = 0;
  53406. data[hdr+2] = 0;
  53407. data[hdr+7] = 0;
  53408. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  53409. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53410. if( cbrk-iCellFirst!=pPage->nFree ){
  53411. return SQLITE_CORRUPT_BKPT;
  53412. }
  53413. return SQLITE_OK;
  53414. }
  53415. /*
  53416. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  53417. ** size. If one can be found, return a pointer to the space and remove it
  53418. ** from the free-list.
  53419. **
  53420. ** If no suitable space can be found on the free-list, return NULL.
  53421. **
  53422. ** This function may detect corruption within pPg. If corruption is
  53423. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  53424. **
  53425. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  53426. ** will be ignored if adding the extra space to the fragmentation count
  53427. ** causes the fragmentation count to exceed 60.
  53428. */
  53429. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  53430. const int hdr = pPg->hdrOffset;
  53431. u8 * const aData = pPg->aData;
  53432. int iAddr = hdr + 1;
  53433. int pc = get2byte(&aData[iAddr]);
  53434. int x;
  53435. int usableSize = pPg->pBt->usableSize;
  53436. assert( pc>0 );
  53437. do{
  53438. int size; /* Size of the free slot */
  53439. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  53440. ** increasing offset. */
  53441. if( pc>usableSize-4 || pc<iAddr+4 ){
  53442. *pRc = SQLITE_CORRUPT_BKPT;
  53443. return 0;
  53444. }
  53445. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  53446. ** freeblock form a big-endian integer which is the size of the freeblock
  53447. ** in bytes, including the 4-byte header. */
  53448. size = get2byte(&aData[pc+2]);
  53449. if( (x = size - nByte)>=0 ){
  53450. testcase( x==4 );
  53451. testcase( x==3 );
  53452. if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
  53453. *pRc = SQLITE_CORRUPT_BKPT;
  53454. return 0;
  53455. }else if( x<4 ){
  53456. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  53457. ** number of bytes in fragments may not exceed 60. */
  53458. if( aData[hdr+7]>57 ) return 0;
  53459. /* Remove the slot from the free-list. Update the number of
  53460. ** fragmented bytes within the page. */
  53461. memcpy(&aData[iAddr], &aData[pc], 2);
  53462. aData[hdr+7] += (u8)x;
  53463. }else{
  53464. /* The slot remains on the free-list. Reduce its size to account
  53465. ** for the portion used by the new allocation. */
  53466. put2byte(&aData[pc+2], x);
  53467. }
  53468. return &aData[pc + x];
  53469. }
  53470. iAddr = pc;
  53471. pc = get2byte(&aData[pc]);
  53472. }while( pc );
  53473. return 0;
  53474. }
  53475. /*
  53476. ** Allocate nByte bytes of space from within the B-Tree page passed
  53477. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  53478. ** of the first byte of allocated space. Return either SQLITE_OK or
  53479. ** an error code (usually SQLITE_CORRUPT).
  53480. **
  53481. ** The caller guarantees that there is sufficient space to make the
  53482. ** allocation. This routine might need to defragment in order to bring
  53483. ** all the space together, however. This routine will avoid using
  53484. ** the first two bytes past the cell pointer area since presumably this
  53485. ** allocation is being made in order to insert a new cell, so we will
  53486. ** also end up needing a new cell pointer.
  53487. */
  53488. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  53489. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  53490. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  53491. int top; /* First byte of cell content area */
  53492. int rc = SQLITE_OK; /* Integer return code */
  53493. int gap; /* First byte of gap between cell pointers and cell content */
  53494. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53495. assert( pPage->pBt );
  53496. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53497. assert( nByte>=0 ); /* Minimum cell size is 4 */
  53498. assert( pPage->nFree>=nByte );
  53499. assert( pPage->nOverflow==0 );
  53500. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  53501. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  53502. gap = pPage->cellOffset + 2*pPage->nCell;
  53503. assert( gap<=65536 );
  53504. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  53505. ** and the reserved space is zero (the usual value for reserved space)
  53506. ** then the cell content offset of an empty page wants to be 65536.
  53507. ** However, that integer is too large to be stored in a 2-byte unsigned
  53508. ** integer, so a value of 0 is used in its place. */
  53509. top = get2byte(&data[hdr+5]);
  53510. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  53511. if( gap>top ){
  53512. if( top==0 && pPage->pBt->usableSize==65536 ){
  53513. top = 65536;
  53514. }else{
  53515. return SQLITE_CORRUPT_BKPT;
  53516. }
  53517. }
  53518. /* If there is enough space between gap and top for one more cell pointer
  53519. ** array entry offset, and if the freelist is not empty, then search the
  53520. ** freelist looking for a free slot big enough to satisfy the request.
  53521. */
  53522. testcase( gap+2==top );
  53523. testcase( gap+1==top );
  53524. testcase( gap==top );
  53525. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  53526. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  53527. if( pSpace ){
  53528. assert( pSpace>=data && (pSpace - data)<65536 );
  53529. *pIdx = (int)(pSpace - data);
  53530. return SQLITE_OK;
  53531. }else if( rc ){
  53532. return rc;
  53533. }
  53534. }
  53535. /* The request could not be fulfilled using a freelist slot. Check
  53536. ** to see if defragmentation is necessary.
  53537. */
  53538. testcase( gap+2+nByte==top );
  53539. if( gap+2+nByte>top ){
  53540. assert( pPage->nCell>0 || CORRUPT_DB );
  53541. rc = defragmentPage(pPage);
  53542. if( rc ) return rc;
  53543. top = get2byteNotZero(&data[hdr+5]);
  53544. assert( gap+nByte<=top );
  53545. }
  53546. /* Allocate memory from the gap in between the cell pointer array
  53547. ** and the cell content area. The btreeInitPage() call has already
  53548. ** validated the freelist. Given that the freelist is valid, there
  53549. ** is no way that the allocation can extend off the end of the page.
  53550. ** The assert() below verifies the previous sentence.
  53551. */
  53552. top -= nByte;
  53553. put2byte(&data[hdr+5], top);
  53554. assert( top+nByte <= (int)pPage->pBt->usableSize );
  53555. *pIdx = top;
  53556. return SQLITE_OK;
  53557. }
  53558. /*
  53559. ** Return a section of the pPage->aData to the freelist.
  53560. ** The first byte of the new free block is pPage->aData[iStart]
  53561. ** and the size of the block is iSize bytes.
  53562. **
  53563. ** Adjacent freeblocks are coalesced.
  53564. **
  53565. ** Note that even though the freeblock list was checked by btreeInitPage(),
  53566. ** that routine will not detect overlap between cells or freeblocks. Nor
  53567. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  53568. ** at the end of the page. So do additional corruption checks inside this
  53569. ** routine and return SQLITE_CORRUPT if any problems are found.
  53570. */
  53571. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  53572. u16 iPtr; /* Address of ptr to next freeblock */
  53573. u16 iFreeBlk; /* Address of the next freeblock */
  53574. u8 hdr; /* Page header size. 0 or 100 */
  53575. u8 nFrag = 0; /* Reduction in fragmentation */
  53576. u16 iOrigSize = iSize; /* Original value of iSize */
  53577. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  53578. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  53579. unsigned char *data = pPage->aData; /* Page content */
  53580. assert( pPage->pBt!=0 );
  53581. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53582. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  53583. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  53584. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53585. assert( iSize>=4 ); /* Minimum cell size is 4 */
  53586. assert( iStart<=iLast );
  53587. /* Overwrite deleted information with zeros when the secure_delete
  53588. ** option is enabled */
  53589. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  53590. memset(&data[iStart], 0, iSize);
  53591. }
  53592. /* The list of freeblocks must be in ascending order. Find the
  53593. ** spot on the list where iStart should be inserted.
  53594. */
  53595. hdr = pPage->hdrOffset;
  53596. iPtr = hdr + 1;
  53597. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  53598. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  53599. }else{
  53600. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  53601. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  53602. iPtr = iFreeBlk;
  53603. }
  53604. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  53605. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  53606. /* At this point:
  53607. ** iFreeBlk: First freeblock after iStart, or zero if none
  53608. ** iPtr: The address of a pointer to iFreeBlk
  53609. **
  53610. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  53611. */
  53612. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  53613. nFrag = iFreeBlk - iEnd;
  53614. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  53615. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  53616. if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
  53617. iSize = iEnd - iStart;
  53618. iFreeBlk = get2byte(&data[iFreeBlk]);
  53619. }
  53620. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  53621. ** pointer in the page header) then check to see if iStart should be
  53622. ** coalesced onto the end of iPtr.
  53623. */
  53624. if( iPtr>hdr+1 ){
  53625. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  53626. if( iPtrEnd+3>=iStart ){
  53627. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  53628. nFrag += iStart - iPtrEnd;
  53629. iSize = iEnd - iPtr;
  53630. iStart = iPtr;
  53631. }
  53632. }
  53633. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  53634. data[hdr+7] -= nFrag;
  53635. }
  53636. if( iStart==get2byte(&data[hdr+5]) ){
  53637. /* The new freeblock is at the beginning of the cell content area,
  53638. ** so just extend the cell content area rather than create another
  53639. ** freelist entry */
  53640. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  53641. put2byte(&data[hdr+1], iFreeBlk);
  53642. put2byte(&data[hdr+5], iEnd);
  53643. }else{
  53644. /* Insert the new freeblock into the freelist */
  53645. put2byte(&data[iPtr], iStart);
  53646. put2byte(&data[iStart], iFreeBlk);
  53647. put2byte(&data[iStart+2], iSize);
  53648. }
  53649. pPage->nFree += iOrigSize;
  53650. return SQLITE_OK;
  53651. }
  53652. /*
  53653. ** Decode the flags byte (the first byte of the header) for a page
  53654. ** and initialize fields of the MemPage structure accordingly.
  53655. **
  53656. ** Only the following combinations are supported. Anything different
  53657. ** indicates a corrupt database files:
  53658. **
  53659. ** PTF_ZERODATA
  53660. ** PTF_ZERODATA | PTF_LEAF
  53661. ** PTF_LEAFDATA | PTF_INTKEY
  53662. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  53663. */
  53664. static int decodeFlags(MemPage *pPage, int flagByte){
  53665. BtShared *pBt; /* A copy of pPage->pBt */
  53666. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  53667. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53668. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  53669. flagByte &= ~PTF_LEAF;
  53670. pPage->childPtrSize = 4-4*pPage->leaf;
  53671. pPage->xCellSize = cellSizePtr;
  53672. pBt = pPage->pBt;
  53673. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  53674. /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
  53675. ** table b-tree page. */
  53676. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  53677. /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
  53678. ** table b-tree page. */
  53679. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  53680. pPage->intKey = 1;
  53681. if( pPage->leaf ){
  53682. pPage->intKeyLeaf = 1;
  53683. pPage->xParseCell = btreeParseCellPtr;
  53684. }else{
  53685. pPage->intKeyLeaf = 0;
  53686. pPage->xCellSize = cellSizePtrNoPayload;
  53687. pPage->xParseCell = btreeParseCellPtrNoPayload;
  53688. }
  53689. pPage->maxLocal = pBt->maxLeaf;
  53690. pPage->minLocal = pBt->minLeaf;
  53691. }else if( flagByte==PTF_ZERODATA ){
  53692. /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
  53693. ** index b-tree page. */
  53694. assert( (PTF_ZERODATA)==2 );
  53695. /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
  53696. ** index b-tree page. */
  53697. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  53698. pPage->intKey = 0;
  53699. pPage->intKeyLeaf = 0;
  53700. pPage->xParseCell = btreeParseCellPtrIndex;
  53701. pPage->maxLocal = pBt->maxLocal;
  53702. pPage->minLocal = pBt->minLocal;
  53703. }else{
  53704. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  53705. ** an error. */
  53706. return SQLITE_CORRUPT_BKPT;
  53707. }
  53708. pPage->max1bytePayload = pBt->max1bytePayload;
  53709. return SQLITE_OK;
  53710. }
  53711. /*
  53712. ** Initialize the auxiliary information for a disk block.
  53713. **
  53714. ** Return SQLITE_OK on success. If we see that the page does
  53715. ** not contain a well-formed database page, then return
  53716. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  53717. ** guarantee that the page is well-formed. It only shows that
  53718. ** we failed to detect any corruption.
  53719. */
  53720. static int btreeInitPage(MemPage *pPage){
  53721. assert( pPage->pBt!=0 );
  53722. assert( pPage->pBt->db!=0 );
  53723. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53724. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  53725. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  53726. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  53727. if( !pPage->isInit ){
  53728. u16 pc; /* Address of a freeblock within pPage->aData[] */
  53729. u8 hdr; /* Offset to beginning of page header */
  53730. u8 *data; /* Equal to pPage->aData */
  53731. BtShared *pBt; /* The main btree structure */
  53732. int usableSize; /* Amount of usable space on each page */
  53733. u16 cellOffset; /* Offset from start of page to first cell pointer */
  53734. int nFree; /* Number of unused bytes on the page */
  53735. int top; /* First byte of the cell content area */
  53736. int iCellFirst; /* First allowable cell or freeblock offset */
  53737. int iCellLast; /* Last possible cell or freeblock offset */
  53738. pBt = pPage->pBt;
  53739. hdr = pPage->hdrOffset;
  53740. data = pPage->aData;
  53741. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  53742. ** the b-tree page type. */
  53743. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  53744. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  53745. pPage->maskPage = (u16)(pBt->pageSize - 1);
  53746. pPage->nOverflow = 0;
  53747. usableSize = pBt->usableSize;
  53748. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  53749. pPage->aDataEnd = &data[usableSize];
  53750. pPage->aCellIdx = &data[cellOffset];
  53751. pPage->aDataOfst = &data[pPage->childPtrSize];
  53752. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  53753. ** the start of the cell content area. A zero value for this integer is
  53754. ** interpreted as 65536. */
  53755. top = get2byteNotZero(&data[hdr+5]);
  53756. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  53757. ** number of cells on the page. */
  53758. pPage->nCell = get2byte(&data[hdr+3]);
  53759. if( pPage->nCell>MX_CELL(pBt) ){
  53760. /* To many cells for a single page. The page must be corrupt */
  53761. return SQLITE_CORRUPT_BKPT;
  53762. }
  53763. testcase( pPage->nCell==MX_CELL(pBt) );
  53764. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  53765. ** possible for a root page of a table that contains no rows) then the
  53766. ** offset to the cell content area will equal the page size minus the
  53767. ** bytes of reserved space. */
  53768. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  53769. /* A malformed database page might cause us to read past the end
  53770. ** of page when parsing a cell.
  53771. **
  53772. ** The following block of code checks early to see if a cell extends
  53773. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  53774. ** returned if it does.
  53775. */
  53776. iCellFirst = cellOffset + 2*pPage->nCell;
  53777. iCellLast = usableSize - 4;
  53778. if( pBt->db->flags & SQLITE_CellSizeCk ){
  53779. int i; /* Index into the cell pointer array */
  53780. int sz; /* Size of a cell */
  53781. if( !pPage->leaf ) iCellLast--;
  53782. for(i=0; i<pPage->nCell; i++){
  53783. pc = get2byteAligned(&data[cellOffset+i*2]);
  53784. testcase( pc==iCellFirst );
  53785. testcase( pc==iCellLast );
  53786. if( pc<iCellFirst || pc>iCellLast ){
  53787. return SQLITE_CORRUPT_BKPT;
  53788. }
  53789. sz = pPage->xCellSize(pPage, &data[pc]);
  53790. testcase( pc+sz==usableSize );
  53791. if( pc+sz>usableSize ){
  53792. return SQLITE_CORRUPT_BKPT;
  53793. }
  53794. }
  53795. if( !pPage->leaf ) iCellLast++;
  53796. }
  53797. /* Compute the total free space on the page
  53798. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  53799. ** start of the first freeblock on the page, or is zero if there are no
  53800. ** freeblocks. */
  53801. pc = get2byte(&data[hdr+1]);
  53802. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  53803. while( pc>0 ){
  53804. u16 next, size;
  53805. if( pc<iCellFirst || pc>iCellLast ){
  53806. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  53807. ** always be at least one cell before the first freeblock.
  53808. **
  53809. ** Or, the freeblock is off the end of the page
  53810. */
  53811. return SQLITE_CORRUPT_BKPT;
  53812. }
  53813. next = get2byte(&data[pc]);
  53814. size = get2byte(&data[pc+2]);
  53815. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  53816. /* Free blocks must be in ascending order. And the last byte of
  53817. ** the free-block must lie on the database page. */
  53818. return SQLITE_CORRUPT_BKPT;
  53819. }
  53820. nFree = nFree + size;
  53821. pc = next;
  53822. }
  53823. /* At this point, nFree contains the sum of the offset to the start
  53824. ** of the cell-content area plus the number of free bytes within
  53825. ** the cell-content area. If this is greater than the usable-size
  53826. ** of the page, then the page must be corrupted. This check also
  53827. ** serves to verify that the offset to the start of the cell-content
  53828. ** area, according to the page header, lies within the page.
  53829. */
  53830. if( nFree>usableSize ){
  53831. return SQLITE_CORRUPT_BKPT;
  53832. }
  53833. pPage->nFree = (u16)(nFree - iCellFirst);
  53834. pPage->isInit = 1;
  53835. }
  53836. return SQLITE_OK;
  53837. }
  53838. /*
  53839. ** Set up a raw page so that it looks like a database page holding
  53840. ** no entries.
  53841. */
  53842. static void zeroPage(MemPage *pPage, int flags){
  53843. unsigned char *data = pPage->aData;
  53844. BtShared *pBt = pPage->pBt;
  53845. u8 hdr = pPage->hdrOffset;
  53846. u16 first;
  53847. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  53848. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  53849. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  53850. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53851. assert( sqlite3_mutex_held(pBt->mutex) );
  53852. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  53853. memset(&data[hdr], 0, pBt->usableSize - hdr);
  53854. }
  53855. data[hdr] = (char)flags;
  53856. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  53857. memset(&data[hdr+1], 0, 4);
  53858. data[hdr+7] = 0;
  53859. put2byte(&data[hdr+5], pBt->usableSize);
  53860. pPage->nFree = (u16)(pBt->usableSize - first);
  53861. decodeFlags(pPage, flags);
  53862. pPage->cellOffset = first;
  53863. pPage->aDataEnd = &data[pBt->usableSize];
  53864. pPage->aCellIdx = &data[first];
  53865. pPage->aDataOfst = &data[pPage->childPtrSize];
  53866. pPage->nOverflow = 0;
  53867. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  53868. pPage->maskPage = (u16)(pBt->pageSize - 1);
  53869. pPage->nCell = 0;
  53870. pPage->isInit = 1;
  53871. }
  53872. /*
  53873. ** Convert a DbPage obtained from the pager into a MemPage used by
  53874. ** the btree layer.
  53875. */
  53876. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  53877. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  53878. if( pgno!=pPage->pgno ){
  53879. pPage->aData = sqlite3PagerGetData(pDbPage);
  53880. pPage->pDbPage = pDbPage;
  53881. pPage->pBt = pBt;
  53882. pPage->pgno = pgno;
  53883. pPage->hdrOffset = pgno==1 ? 100 : 0;
  53884. }
  53885. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  53886. return pPage;
  53887. }
  53888. /*
  53889. ** Get a page from the pager. Initialize the MemPage.pBt and
  53890. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  53891. **
  53892. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  53893. ** about the content of the page at this time. So do not go to the disk
  53894. ** to fetch the content. Just fill in the content with zeros for now.
  53895. ** If in the future we call sqlite3PagerWrite() on this page, that
  53896. ** means we have started to be concerned about content and the disk
  53897. ** read should occur at that point.
  53898. */
  53899. static int btreeGetPage(
  53900. BtShared *pBt, /* The btree */
  53901. Pgno pgno, /* Number of the page to fetch */
  53902. MemPage **ppPage, /* Return the page in this parameter */
  53903. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  53904. ){
  53905. int rc;
  53906. DbPage *pDbPage;
  53907. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  53908. assert( sqlite3_mutex_held(pBt->mutex) );
  53909. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  53910. if( rc ) return rc;
  53911. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  53912. return SQLITE_OK;
  53913. }
  53914. /*
  53915. ** Retrieve a page from the pager cache. If the requested page is not
  53916. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  53917. ** MemPage.aData elements if needed.
  53918. */
  53919. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  53920. DbPage *pDbPage;
  53921. assert( sqlite3_mutex_held(pBt->mutex) );
  53922. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  53923. if( pDbPage ){
  53924. return btreePageFromDbPage(pDbPage, pgno, pBt);
  53925. }
  53926. return 0;
  53927. }
  53928. /*
  53929. ** Return the size of the database file in pages. If there is any kind of
  53930. ** error, return ((unsigned int)-1).
  53931. */
  53932. static Pgno btreePagecount(BtShared *pBt){
  53933. return pBt->nPage;
  53934. }
  53935. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  53936. assert( sqlite3BtreeHoldsMutex(p) );
  53937. assert( ((p->pBt->nPage)&0x8000000)==0 );
  53938. return btreePagecount(p->pBt);
  53939. }
  53940. /*
  53941. ** Get a page from the pager and initialize it.
  53942. **
  53943. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  53944. ** call. Do additional sanity checking on the page in this case.
  53945. ** And if the fetch fails, this routine must decrement pCur->iPage.
  53946. **
  53947. ** The page is fetched as read-write unless pCur is not NULL and is
  53948. ** a read-only cursor.
  53949. **
  53950. ** If an error occurs, then *ppPage is undefined. It
  53951. ** may remain unchanged, or it may be set to an invalid value.
  53952. */
  53953. static int getAndInitPage(
  53954. BtShared *pBt, /* The database file */
  53955. Pgno pgno, /* Number of the page to get */
  53956. MemPage **ppPage, /* Write the page pointer here */
  53957. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  53958. int bReadOnly /* True for a read-only page */
  53959. ){
  53960. int rc;
  53961. DbPage *pDbPage;
  53962. assert( sqlite3_mutex_held(pBt->mutex) );
  53963. assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
  53964. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  53965. assert( pCur==0 || pCur->iPage>0 );
  53966. if( pgno>btreePagecount(pBt) ){
  53967. rc = SQLITE_CORRUPT_BKPT;
  53968. goto getAndInitPage_error;
  53969. }
  53970. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  53971. if( rc ){
  53972. goto getAndInitPage_error;
  53973. }
  53974. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  53975. if( (*ppPage)->isInit==0 ){
  53976. btreePageFromDbPage(pDbPage, pgno, pBt);
  53977. rc = btreeInitPage(*ppPage);
  53978. if( rc!=SQLITE_OK ){
  53979. releasePage(*ppPage);
  53980. goto getAndInitPage_error;
  53981. }
  53982. }
  53983. assert( (*ppPage)->pgno==pgno );
  53984. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  53985. /* If obtaining a child page for a cursor, we must verify that the page is
  53986. ** compatible with the root page. */
  53987. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  53988. rc = SQLITE_CORRUPT_BKPT;
  53989. releasePage(*ppPage);
  53990. goto getAndInitPage_error;
  53991. }
  53992. return SQLITE_OK;
  53993. getAndInitPage_error:
  53994. if( pCur ) pCur->iPage--;
  53995. testcase( pgno==0 );
  53996. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  53997. return rc;
  53998. }
  53999. /*
  54000. ** Release a MemPage. This should be called once for each prior
  54001. ** call to btreeGetPage.
  54002. */
  54003. static void releasePageNotNull(MemPage *pPage){
  54004. assert( pPage->aData );
  54005. assert( pPage->pBt );
  54006. assert( pPage->pDbPage!=0 );
  54007. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  54008. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  54009. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54010. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  54011. }
  54012. static void releasePage(MemPage *pPage){
  54013. if( pPage ) releasePageNotNull(pPage);
  54014. }
  54015. /*
  54016. ** Get an unused page.
  54017. **
  54018. ** This works just like btreeGetPage() with the addition:
  54019. **
  54020. ** * If the page is already in use for some other purpose, immediately
  54021. ** release it and return an SQLITE_CURRUPT error.
  54022. ** * Make sure the isInit flag is clear
  54023. */
  54024. static int btreeGetUnusedPage(
  54025. BtShared *pBt, /* The btree */
  54026. Pgno pgno, /* Number of the page to fetch */
  54027. MemPage **ppPage, /* Return the page in this parameter */
  54028. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  54029. ){
  54030. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  54031. if( rc==SQLITE_OK ){
  54032. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  54033. releasePage(*ppPage);
  54034. *ppPage = 0;
  54035. return SQLITE_CORRUPT_BKPT;
  54036. }
  54037. (*ppPage)->isInit = 0;
  54038. }else{
  54039. *ppPage = 0;
  54040. }
  54041. return rc;
  54042. }
  54043. /*
  54044. ** During a rollback, when the pager reloads information into the cache
  54045. ** so that the cache is restored to its original state at the start of
  54046. ** the transaction, for each page restored this routine is called.
  54047. **
  54048. ** This routine needs to reset the extra data section at the end of the
  54049. ** page to agree with the restored data.
  54050. */
  54051. static void pageReinit(DbPage *pData){
  54052. MemPage *pPage;
  54053. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  54054. assert( sqlite3PagerPageRefcount(pData)>0 );
  54055. if( pPage->isInit ){
  54056. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54057. pPage->isInit = 0;
  54058. if( sqlite3PagerPageRefcount(pData)>1 ){
  54059. /* pPage might not be a btree page; it might be an overflow page
  54060. ** or ptrmap page or a free page. In those cases, the following
  54061. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  54062. ** But no harm is done by this. And it is very important that
  54063. ** btreeInitPage() be called on every btree page so we make
  54064. ** the call for every page that comes in for re-initing. */
  54065. btreeInitPage(pPage);
  54066. }
  54067. }
  54068. }
  54069. /*
  54070. ** Invoke the busy handler for a btree.
  54071. */
  54072. static int btreeInvokeBusyHandler(void *pArg){
  54073. BtShared *pBt = (BtShared*)pArg;
  54074. assert( pBt->db );
  54075. assert( sqlite3_mutex_held(pBt->db->mutex) );
  54076. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  54077. }
  54078. /*
  54079. ** Open a database file.
  54080. **
  54081. ** zFilename is the name of the database file. If zFilename is NULL
  54082. ** then an ephemeral database is created. The ephemeral database might
  54083. ** be exclusively in memory, or it might use a disk-based memory cache.
  54084. ** Either way, the ephemeral database will be automatically deleted
  54085. ** when sqlite3BtreeClose() is called.
  54086. **
  54087. ** If zFilename is ":memory:" then an in-memory database is created
  54088. ** that is automatically destroyed when it is closed.
  54089. **
  54090. ** The "flags" parameter is a bitmask that might contain bits like
  54091. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  54092. **
  54093. ** If the database is already opened in the same database connection
  54094. ** and we are in shared cache mode, then the open will fail with an
  54095. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  54096. ** objects in the same database connection since doing so will lead
  54097. ** to problems with locking.
  54098. */
  54099. SQLITE_PRIVATE int sqlite3BtreeOpen(
  54100. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  54101. const char *zFilename, /* Name of the file containing the BTree database */
  54102. sqlite3 *db, /* Associated database handle */
  54103. Btree **ppBtree, /* Pointer to new Btree object written here */
  54104. int flags, /* Options */
  54105. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  54106. ){
  54107. BtShared *pBt = 0; /* Shared part of btree structure */
  54108. Btree *p; /* Handle to return */
  54109. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  54110. int rc = SQLITE_OK; /* Result code from this function */
  54111. u8 nReserve; /* Byte of unused space on each page */
  54112. unsigned char zDbHeader[100]; /* Database header content */
  54113. /* True if opening an ephemeral, temporary database */
  54114. const int isTempDb = zFilename==0 || zFilename[0]==0;
  54115. /* Set the variable isMemdb to true for an in-memory database, or
  54116. ** false for a file-based database.
  54117. */
  54118. #ifdef SQLITE_OMIT_MEMORYDB
  54119. const int isMemdb = 0;
  54120. #else
  54121. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  54122. || (isTempDb && sqlite3TempInMemory(db))
  54123. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  54124. #endif
  54125. assert( db!=0 );
  54126. assert( pVfs!=0 );
  54127. assert( sqlite3_mutex_held(db->mutex) );
  54128. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  54129. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  54130. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  54131. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  54132. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  54133. if( isMemdb ){
  54134. flags |= BTREE_MEMORY;
  54135. }
  54136. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  54137. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  54138. }
  54139. p = sqlite3MallocZero(sizeof(Btree));
  54140. if( !p ){
  54141. return SQLITE_NOMEM_BKPT;
  54142. }
  54143. p->inTrans = TRANS_NONE;
  54144. p->db = db;
  54145. #ifndef SQLITE_OMIT_SHARED_CACHE
  54146. p->lock.pBtree = p;
  54147. p->lock.iTable = 1;
  54148. #endif
  54149. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  54150. /*
  54151. ** If this Btree is a candidate for shared cache, try to find an
  54152. ** existing BtShared object that we can share with
  54153. */
  54154. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  54155. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  54156. int nFilename = sqlite3Strlen30(zFilename)+1;
  54157. int nFullPathname = pVfs->mxPathname+1;
  54158. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  54159. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  54160. p->sharable = 1;
  54161. if( !zFullPathname ){
  54162. sqlite3_free(p);
  54163. return SQLITE_NOMEM_BKPT;
  54164. }
  54165. if( isMemdb ){
  54166. memcpy(zFullPathname, zFilename, nFilename);
  54167. }else{
  54168. rc = sqlite3OsFullPathname(pVfs, zFilename,
  54169. nFullPathname, zFullPathname);
  54170. if( rc ){
  54171. sqlite3_free(zFullPathname);
  54172. sqlite3_free(p);
  54173. return rc;
  54174. }
  54175. }
  54176. #if SQLITE_THREADSAFE
  54177. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  54178. sqlite3_mutex_enter(mutexOpen);
  54179. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  54180. sqlite3_mutex_enter(mutexShared);
  54181. #endif
  54182. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  54183. assert( pBt->nRef>0 );
  54184. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  54185. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  54186. int iDb;
  54187. for(iDb=db->nDb-1; iDb>=0; iDb--){
  54188. Btree *pExisting = db->aDb[iDb].pBt;
  54189. if( pExisting && pExisting->pBt==pBt ){
  54190. sqlite3_mutex_leave(mutexShared);
  54191. sqlite3_mutex_leave(mutexOpen);
  54192. sqlite3_free(zFullPathname);
  54193. sqlite3_free(p);
  54194. return SQLITE_CONSTRAINT;
  54195. }
  54196. }
  54197. p->pBt = pBt;
  54198. pBt->nRef++;
  54199. break;
  54200. }
  54201. }
  54202. sqlite3_mutex_leave(mutexShared);
  54203. sqlite3_free(zFullPathname);
  54204. }
  54205. #ifdef SQLITE_DEBUG
  54206. else{
  54207. /* In debug mode, we mark all persistent databases as sharable
  54208. ** even when they are not. This exercises the locking code and
  54209. ** gives more opportunity for asserts(sqlite3_mutex_held())
  54210. ** statements to find locking problems.
  54211. */
  54212. p->sharable = 1;
  54213. }
  54214. #endif
  54215. }
  54216. #endif
  54217. if( pBt==0 ){
  54218. /*
  54219. ** The following asserts make sure that structures used by the btree are
  54220. ** the right size. This is to guard against size changes that result
  54221. ** when compiling on a different architecture.
  54222. */
  54223. assert( sizeof(i64)==8 );
  54224. assert( sizeof(u64)==8 );
  54225. assert( sizeof(u32)==4 );
  54226. assert( sizeof(u16)==2 );
  54227. assert( sizeof(Pgno)==4 );
  54228. pBt = sqlite3MallocZero( sizeof(*pBt) );
  54229. if( pBt==0 ){
  54230. rc = SQLITE_NOMEM_BKPT;
  54231. goto btree_open_out;
  54232. }
  54233. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  54234. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  54235. if( rc==SQLITE_OK ){
  54236. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  54237. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  54238. }
  54239. if( rc!=SQLITE_OK ){
  54240. goto btree_open_out;
  54241. }
  54242. pBt->openFlags = (u8)flags;
  54243. pBt->db = db;
  54244. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  54245. p->pBt = pBt;
  54246. pBt->pCursor = 0;
  54247. pBt->pPage1 = 0;
  54248. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  54249. #ifdef SQLITE_SECURE_DELETE
  54250. pBt->btsFlags |= BTS_SECURE_DELETE;
  54251. #endif
  54252. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  54253. ** determined by the 2-byte integer located at an offset of 16 bytes from
  54254. ** the beginning of the database file. */
  54255. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  54256. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  54257. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  54258. pBt->pageSize = 0;
  54259. #ifndef SQLITE_OMIT_AUTOVACUUM
  54260. /* If the magic name ":memory:" will create an in-memory database, then
  54261. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  54262. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  54263. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  54264. ** regular file-name. In this case the auto-vacuum applies as per normal.
  54265. */
  54266. if( zFilename && !isMemdb ){
  54267. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  54268. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  54269. }
  54270. #endif
  54271. nReserve = 0;
  54272. }else{
  54273. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  54274. ** determined by the one-byte unsigned integer found at an offset of 20
  54275. ** into the database file header. */
  54276. nReserve = zDbHeader[20];
  54277. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  54278. #ifndef SQLITE_OMIT_AUTOVACUUM
  54279. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  54280. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  54281. #endif
  54282. }
  54283. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  54284. if( rc ) goto btree_open_out;
  54285. pBt->usableSize = pBt->pageSize - nReserve;
  54286. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  54287. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  54288. /* Add the new BtShared object to the linked list sharable BtShareds.
  54289. */
  54290. if( p->sharable ){
  54291. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  54292. pBt->nRef = 1;
  54293. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  54294. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  54295. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  54296. if( pBt->mutex==0 ){
  54297. rc = SQLITE_NOMEM_BKPT;
  54298. goto btree_open_out;
  54299. }
  54300. }
  54301. sqlite3_mutex_enter(mutexShared);
  54302. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  54303. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  54304. sqlite3_mutex_leave(mutexShared);
  54305. }
  54306. #endif
  54307. }
  54308. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  54309. /* If the new Btree uses a sharable pBtShared, then link the new
  54310. ** Btree into the list of all sharable Btrees for the same connection.
  54311. ** The list is kept in ascending order by pBt address.
  54312. */
  54313. if( p->sharable ){
  54314. int i;
  54315. Btree *pSib;
  54316. for(i=0; i<db->nDb; i++){
  54317. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  54318. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  54319. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  54320. p->pNext = pSib;
  54321. p->pPrev = 0;
  54322. pSib->pPrev = p;
  54323. }else{
  54324. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  54325. pSib = pSib->pNext;
  54326. }
  54327. p->pNext = pSib->pNext;
  54328. p->pPrev = pSib;
  54329. if( p->pNext ){
  54330. p->pNext->pPrev = p;
  54331. }
  54332. pSib->pNext = p;
  54333. }
  54334. break;
  54335. }
  54336. }
  54337. }
  54338. #endif
  54339. *ppBtree = p;
  54340. btree_open_out:
  54341. if( rc!=SQLITE_OK ){
  54342. if( pBt && pBt->pPager ){
  54343. sqlite3PagerClose(pBt->pPager);
  54344. }
  54345. sqlite3_free(pBt);
  54346. sqlite3_free(p);
  54347. *ppBtree = 0;
  54348. }else{
  54349. /* If the B-Tree was successfully opened, set the pager-cache size to the
  54350. ** default value. Except, when opening on an existing shared pager-cache,
  54351. ** do not change the pager-cache size.
  54352. */
  54353. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  54354. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  54355. }
  54356. }
  54357. if( mutexOpen ){
  54358. assert( sqlite3_mutex_held(mutexOpen) );
  54359. sqlite3_mutex_leave(mutexOpen);
  54360. }
  54361. return rc;
  54362. }
  54363. /*
  54364. ** Decrement the BtShared.nRef counter. When it reaches zero,
  54365. ** remove the BtShared structure from the sharing list. Return
  54366. ** true if the BtShared.nRef counter reaches zero and return
  54367. ** false if it is still positive.
  54368. */
  54369. static int removeFromSharingList(BtShared *pBt){
  54370. #ifndef SQLITE_OMIT_SHARED_CACHE
  54371. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  54372. BtShared *pList;
  54373. int removed = 0;
  54374. assert( sqlite3_mutex_notheld(pBt->mutex) );
  54375. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  54376. sqlite3_mutex_enter(pMaster);
  54377. pBt->nRef--;
  54378. if( pBt->nRef<=0 ){
  54379. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  54380. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  54381. }else{
  54382. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  54383. while( ALWAYS(pList) && pList->pNext!=pBt ){
  54384. pList=pList->pNext;
  54385. }
  54386. if( ALWAYS(pList) ){
  54387. pList->pNext = pBt->pNext;
  54388. }
  54389. }
  54390. if( SQLITE_THREADSAFE ){
  54391. sqlite3_mutex_free(pBt->mutex);
  54392. }
  54393. removed = 1;
  54394. }
  54395. sqlite3_mutex_leave(pMaster);
  54396. return removed;
  54397. #else
  54398. return 1;
  54399. #endif
  54400. }
  54401. /*
  54402. ** Make sure pBt->pTmpSpace points to an allocation of
  54403. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  54404. ** pointer.
  54405. */
  54406. static void allocateTempSpace(BtShared *pBt){
  54407. if( !pBt->pTmpSpace ){
  54408. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  54409. /* One of the uses of pBt->pTmpSpace is to format cells before
  54410. ** inserting them into a leaf page (function fillInCell()). If
  54411. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  54412. ** by the various routines that manipulate binary cells. Which
  54413. ** can mean that fillInCell() only initializes the first 2 or 3
  54414. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  54415. ** it into a database page. This is not actually a problem, but it
  54416. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  54417. ** data is passed to system call write(). So to avoid this error,
  54418. ** zero the first 4 bytes of temp space here.
  54419. **
  54420. ** Also: Provide four bytes of initialized space before the
  54421. ** beginning of pTmpSpace as an area available to prepend the
  54422. ** left-child pointer to the beginning of a cell.
  54423. */
  54424. if( pBt->pTmpSpace ){
  54425. memset(pBt->pTmpSpace, 0, 8);
  54426. pBt->pTmpSpace += 4;
  54427. }
  54428. }
  54429. }
  54430. /*
  54431. ** Free the pBt->pTmpSpace allocation
  54432. */
  54433. static void freeTempSpace(BtShared *pBt){
  54434. if( pBt->pTmpSpace ){
  54435. pBt->pTmpSpace -= 4;
  54436. sqlite3PageFree(pBt->pTmpSpace);
  54437. pBt->pTmpSpace = 0;
  54438. }
  54439. }
  54440. /*
  54441. ** Close an open database and invalidate all cursors.
  54442. */
  54443. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  54444. BtShared *pBt = p->pBt;
  54445. BtCursor *pCur;
  54446. /* Close all cursors opened via this handle. */
  54447. assert( sqlite3_mutex_held(p->db->mutex) );
  54448. sqlite3BtreeEnter(p);
  54449. pCur = pBt->pCursor;
  54450. while( pCur ){
  54451. BtCursor *pTmp = pCur;
  54452. pCur = pCur->pNext;
  54453. if( pTmp->pBtree==p ){
  54454. sqlite3BtreeCloseCursor(pTmp);
  54455. }
  54456. }
  54457. /* Rollback any active transaction and free the handle structure.
  54458. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  54459. ** this handle.
  54460. */
  54461. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  54462. sqlite3BtreeLeave(p);
  54463. /* If there are still other outstanding references to the shared-btree
  54464. ** structure, return now. The remainder of this procedure cleans
  54465. ** up the shared-btree.
  54466. */
  54467. assert( p->wantToLock==0 && p->locked==0 );
  54468. if( !p->sharable || removeFromSharingList(pBt) ){
  54469. /* The pBt is no longer on the sharing list, so we can access
  54470. ** it without having to hold the mutex.
  54471. **
  54472. ** Clean out and delete the BtShared object.
  54473. */
  54474. assert( !pBt->pCursor );
  54475. sqlite3PagerClose(pBt->pPager);
  54476. if( pBt->xFreeSchema && pBt->pSchema ){
  54477. pBt->xFreeSchema(pBt->pSchema);
  54478. }
  54479. sqlite3DbFree(0, pBt->pSchema);
  54480. freeTempSpace(pBt);
  54481. sqlite3_free(pBt);
  54482. }
  54483. #ifndef SQLITE_OMIT_SHARED_CACHE
  54484. assert( p->wantToLock==0 );
  54485. assert( p->locked==0 );
  54486. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  54487. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  54488. #endif
  54489. sqlite3_free(p);
  54490. return SQLITE_OK;
  54491. }
  54492. /*
  54493. ** Change the "soft" limit on the number of pages in the cache.
  54494. ** Unused and unmodified pages will be recycled when the number of
  54495. ** pages in the cache exceeds this soft limit. But the size of the
  54496. ** cache is allowed to grow larger than this limit if it contains
  54497. ** dirty pages or pages still in active use.
  54498. */
  54499. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  54500. BtShared *pBt = p->pBt;
  54501. assert( sqlite3_mutex_held(p->db->mutex) );
  54502. sqlite3BtreeEnter(p);
  54503. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  54504. sqlite3BtreeLeave(p);
  54505. return SQLITE_OK;
  54506. }
  54507. /*
  54508. ** Change the "spill" limit on the number of pages in the cache.
  54509. ** If the number of pages exceeds this limit during a write transaction,
  54510. ** the pager might attempt to "spill" pages to the journal early in
  54511. ** order to free up memory.
  54512. **
  54513. ** The value returned is the current spill size. If zero is passed
  54514. ** as an argument, no changes are made to the spill size setting, so
  54515. ** using mxPage of 0 is a way to query the current spill size.
  54516. */
  54517. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  54518. BtShared *pBt = p->pBt;
  54519. int res;
  54520. assert( sqlite3_mutex_held(p->db->mutex) );
  54521. sqlite3BtreeEnter(p);
  54522. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  54523. sqlite3BtreeLeave(p);
  54524. return res;
  54525. }
  54526. #if SQLITE_MAX_MMAP_SIZE>0
  54527. /*
  54528. ** Change the limit on the amount of the database file that may be
  54529. ** memory mapped.
  54530. */
  54531. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  54532. BtShared *pBt = p->pBt;
  54533. assert( sqlite3_mutex_held(p->db->mutex) );
  54534. sqlite3BtreeEnter(p);
  54535. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  54536. sqlite3BtreeLeave(p);
  54537. return SQLITE_OK;
  54538. }
  54539. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  54540. /*
  54541. ** Change the way data is synced to disk in order to increase or decrease
  54542. ** how well the database resists damage due to OS crashes and power
  54543. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  54544. ** there is a high probability of damage) Level 2 is the default. There
  54545. ** is a very low but non-zero probability of damage. Level 3 reduces the
  54546. ** probability of damage to near zero but with a write performance reduction.
  54547. */
  54548. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  54549. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  54550. Btree *p, /* The btree to set the safety level on */
  54551. unsigned pgFlags /* Various PAGER_* flags */
  54552. ){
  54553. BtShared *pBt = p->pBt;
  54554. assert( sqlite3_mutex_held(p->db->mutex) );
  54555. sqlite3BtreeEnter(p);
  54556. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  54557. sqlite3BtreeLeave(p);
  54558. return SQLITE_OK;
  54559. }
  54560. #endif
  54561. /*
  54562. ** Change the default pages size and the number of reserved bytes per page.
  54563. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  54564. ** without changing anything.
  54565. **
  54566. ** The page size must be a power of 2 between 512 and 65536. If the page
  54567. ** size supplied does not meet this constraint then the page size is not
  54568. ** changed.
  54569. **
  54570. ** Page sizes are constrained to be a power of two so that the region
  54571. ** of the database file used for locking (beginning at PENDING_BYTE,
  54572. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  54573. ** at the beginning of a page.
  54574. **
  54575. ** If parameter nReserve is less than zero, then the number of reserved
  54576. ** bytes per page is left unchanged.
  54577. **
  54578. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  54579. ** and autovacuum mode can no longer be changed.
  54580. */
  54581. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  54582. int rc = SQLITE_OK;
  54583. BtShared *pBt = p->pBt;
  54584. assert( nReserve>=-1 && nReserve<=255 );
  54585. sqlite3BtreeEnter(p);
  54586. #if SQLITE_HAS_CODEC
  54587. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  54588. #endif
  54589. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  54590. sqlite3BtreeLeave(p);
  54591. return SQLITE_READONLY;
  54592. }
  54593. if( nReserve<0 ){
  54594. nReserve = pBt->pageSize - pBt->usableSize;
  54595. }
  54596. assert( nReserve>=0 && nReserve<=255 );
  54597. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  54598. ((pageSize-1)&pageSize)==0 ){
  54599. assert( (pageSize & 7)==0 );
  54600. assert( !pBt->pCursor );
  54601. pBt->pageSize = (u32)pageSize;
  54602. freeTempSpace(pBt);
  54603. }
  54604. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  54605. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  54606. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  54607. sqlite3BtreeLeave(p);
  54608. return rc;
  54609. }
  54610. /*
  54611. ** Return the currently defined page size
  54612. */
  54613. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  54614. return p->pBt->pageSize;
  54615. }
  54616. /*
  54617. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  54618. ** may only be called if it is guaranteed that the b-tree mutex is already
  54619. ** held.
  54620. **
  54621. ** This is useful in one special case in the backup API code where it is
  54622. ** known that the shared b-tree mutex is held, but the mutex on the
  54623. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  54624. ** were to be called, it might collide with some other operation on the
  54625. ** database handle that owns *p, causing undefined behavior.
  54626. */
  54627. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  54628. int n;
  54629. assert( sqlite3_mutex_held(p->pBt->mutex) );
  54630. n = p->pBt->pageSize - p->pBt->usableSize;
  54631. return n;
  54632. }
  54633. /*
  54634. ** Return the number of bytes of space at the end of every page that
  54635. ** are intentually left unused. This is the "reserved" space that is
  54636. ** sometimes used by extensions.
  54637. **
  54638. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  54639. ** greater of the current reserved space and the maximum requested
  54640. ** reserve space.
  54641. */
  54642. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  54643. int n;
  54644. sqlite3BtreeEnter(p);
  54645. n = sqlite3BtreeGetReserveNoMutex(p);
  54646. #ifdef SQLITE_HAS_CODEC
  54647. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  54648. #endif
  54649. sqlite3BtreeLeave(p);
  54650. return n;
  54651. }
  54652. /*
  54653. ** Set the maximum page count for a database if mxPage is positive.
  54654. ** No changes are made if mxPage is 0 or negative.
  54655. ** Regardless of the value of mxPage, return the maximum page count.
  54656. */
  54657. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  54658. int n;
  54659. sqlite3BtreeEnter(p);
  54660. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  54661. sqlite3BtreeLeave(p);
  54662. return n;
  54663. }
  54664. /*
  54665. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  54666. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  54667. ** setting after the change.
  54668. */
  54669. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  54670. int b;
  54671. if( p==0 ) return 0;
  54672. sqlite3BtreeEnter(p);
  54673. if( newFlag>=0 ){
  54674. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  54675. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  54676. }
  54677. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  54678. sqlite3BtreeLeave(p);
  54679. return b;
  54680. }
  54681. /*
  54682. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  54683. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  54684. ** is disabled. The default value for the auto-vacuum property is
  54685. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  54686. */
  54687. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  54688. #ifdef SQLITE_OMIT_AUTOVACUUM
  54689. return SQLITE_READONLY;
  54690. #else
  54691. BtShared *pBt = p->pBt;
  54692. int rc = SQLITE_OK;
  54693. u8 av = (u8)autoVacuum;
  54694. sqlite3BtreeEnter(p);
  54695. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  54696. rc = SQLITE_READONLY;
  54697. }else{
  54698. pBt->autoVacuum = av ?1:0;
  54699. pBt->incrVacuum = av==2 ?1:0;
  54700. }
  54701. sqlite3BtreeLeave(p);
  54702. return rc;
  54703. #endif
  54704. }
  54705. /*
  54706. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  54707. ** enabled 1 is returned. Otherwise 0.
  54708. */
  54709. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  54710. #ifdef SQLITE_OMIT_AUTOVACUUM
  54711. return BTREE_AUTOVACUUM_NONE;
  54712. #else
  54713. int rc;
  54714. sqlite3BtreeEnter(p);
  54715. rc = (
  54716. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  54717. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  54718. BTREE_AUTOVACUUM_INCR
  54719. );
  54720. sqlite3BtreeLeave(p);
  54721. return rc;
  54722. #endif
  54723. }
  54724. /*
  54725. ** Get a reference to pPage1 of the database file. This will
  54726. ** also acquire a readlock on that file.
  54727. **
  54728. ** SQLITE_OK is returned on success. If the file is not a
  54729. ** well-formed database file, then SQLITE_CORRUPT is returned.
  54730. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  54731. ** is returned if we run out of memory.
  54732. */
  54733. static int lockBtree(BtShared *pBt){
  54734. int rc; /* Result code from subfunctions */
  54735. MemPage *pPage1; /* Page 1 of the database file */
  54736. int nPage; /* Number of pages in the database */
  54737. int nPageFile = 0; /* Number of pages in the database file */
  54738. int nPageHeader; /* Number of pages in the database according to hdr */
  54739. assert( sqlite3_mutex_held(pBt->mutex) );
  54740. assert( pBt->pPage1==0 );
  54741. rc = sqlite3PagerSharedLock(pBt->pPager);
  54742. if( rc!=SQLITE_OK ) return rc;
  54743. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  54744. if( rc!=SQLITE_OK ) return rc;
  54745. /* Do some checking to help insure the file we opened really is
  54746. ** a valid database file.
  54747. */
  54748. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  54749. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  54750. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  54751. nPage = nPageFile;
  54752. }
  54753. if( nPage>0 ){
  54754. u32 pageSize;
  54755. u32 usableSize;
  54756. u8 *page1 = pPage1->aData;
  54757. rc = SQLITE_NOTADB;
  54758. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  54759. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  54760. ** 61 74 20 33 00. */
  54761. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  54762. goto page1_init_failed;
  54763. }
  54764. #ifdef SQLITE_OMIT_WAL
  54765. if( page1[18]>1 ){
  54766. pBt->btsFlags |= BTS_READ_ONLY;
  54767. }
  54768. if( page1[19]>1 ){
  54769. goto page1_init_failed;
  54770. }
  54771. #else
  54772. if( page1[18]>2 ){
  54773. pBt->btsFlags |= BTS_READ_ONLY;
  54774. }
  54775. if( page1[19]>2 ){
  54776. goto page1_init_failed;
  54777. }
  54778. /* If the write version is set to 2, this database should be accessed
  54779. ** in WAL mode. If the log is not already open, open it now. Then
  54780. ** return SQLITE_OK and return without populating BtShared.pPage1.
  54781. ** The caller detects this and calls this function again. This is
  54782. ** required as the version of page 1 currently in the page1 buffer
  54783. ** may not be the latest version - there may be a newer one in the log
  54784. ** file.
  54785. */
  54786. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  54787. int isOpen = 0;
  54788. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  54789. if( rc!=SQLITE_OK ){
  54790. goto page1_init_failed;
  54791. }else{
  54792. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
  54793. sqlite3 *db;
  54794. Db *pDb;
  54795. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  54796. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  54797. if( pDb->bSyncSet==0
  54798. && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
  54799. ){
  54800. pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
  54801. sqlite3PagerSetFlags(pBt->pPager,
  54802. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  54803. }
  54804. }
  54805. #endif
  54806. if( isOpen==0 ){
  54807. releasePage(pPage1);
  54808. return SQLITE_OK;
  54809. }
  54810. }
  54811. rc = SQLITE_NOTADB;
  54812. }
  54813. #endif
  54814. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  54815. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  54816. **
  54817. ** The original design allowed these amounts to vary, but as of
  54818. ** version 3.6.0, we require them to be fixed.
  54819. */
  54820. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  54821. goto page1_init_failed;
  54822. }
  54823. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  54824. ** determined by the 2-byte integer located at an offset of 16 bytes from
  54825. ** the beginning of the database file. */
  54826. pageSize = (page1[16]<<8) | (page1[17]<<16);
  54827. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  54828. ** between 512 and 65536 inclusive. */
  54829. if( ((pageSize-1)&pageSize)!=0
  54830. || pageSize>SQLITE_MAX_PAGE_SIZE
  54831. || pageSize<=256
  54832. ){
  54833. goto page1_init_failed;
  54834. }
  54835. assert( (pageSize & 7)==0 );
  54836. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  54837. ** integer at offset 20 is the number of bytes of space at the end of
  54838. ** each page to reserve for extensions.
  54839. **
  54840. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  54841. ** determined by the one-byte unsigned integer found at an offset of 20
  54842. ** into the database file header. */
  54843. usableSize = pageSize - page1[20];
  54844. if( (u32)pageSize!=pBt->pageSize ){
  54845. /* After reading the first page of the database assuming a page size
  54846. ** of BtShared.pageSize, we have discovered that the page-size is
  54847. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  54848. ** zero and return SQLITE_OK. The caller will call this function
  54849. ** again with the correct page-size.
  54850. */
  54851. releasePage(pPage1);
  54852. pBt->usableSize = usableSize;
  54853. pBt->pageSize = pageSize;
  54854. freeTempSpace(pBt);
  54855. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  54856. pageSize-usableSize);
  54857. return rc;
  54858. }
  54859. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  54860. rc = SQLITE_CORRUPT_BKPT;
  54861. goto page1_init_failed;
  54862. }
  54863. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  54864. ** be less than 480. In other words, if the page size is 512, then the
  54865. ** reserved space size cannot exceed 32. */
  54866. if( usableSize<480 ){
  54867. goto page1_init_failed;
  54868. }
  54869. pBt->pageSize = pageSize;
  54870. pBt->usableSize = usableSize;
  54871. #ifndef SQLITE_OMIT_AUTOVACUUM
  54872. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  54873. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  54874. #endif
  54875. }
  54876. /* maxLocal is the maximum amount of payload to store locally for
  54877. ** a cell. Make sure it is small enough so that at least minFanout
  54878. ** cells can will fit on one page. We assume a 10-byte page header.
  54879. ** Besides the payload, the cell must store:
  54880. ** 2-byte pointer to the cell
  54881. ** 4-byte child pointer
  54882. ** 9-byte nKey value
  54883. ** 4-byte nData value
  54884. ** 4-byte overflow page pointer
  54885. ** So a cell consists of a 2-byte pointer, a header which is as much as
  54886. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  54887. ** page pointer.
  54888. */
  54889. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  54890. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  54891. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  54892. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  54893. if( pBt->maxLocal>127 ){
  54894. pBt->max1bytePayload = 127;
  54895. }else{
  54896. pBt->max1bytePayload = (u8)pBt->maxLocal;
  54897. }
  54898. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  54899. pBt->pPage1 = pPage1;
  54900. pBt->nPage = nPage;
  54901. return SQLITE_OK;
  54902. page1_init_failed:
  54903. releasePage(pPage1);
  54904. pBt->pPage1 = 0;
  54905. return rc;
  54906. }
  54907. #ifndef NDEBUG
  54908. /*
  54909. ** Return the number of cursors open on pBt. This is for use
  54910. ** in assert() expressions, so it is only compiled if NDEBUG is not
  54911. ** defined.
  54912. **
  54913. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  54914. ** false then all cursors are counted.
  54915. **
  54916. ** For the purposes of this routine, a cursor is any cursor that
  54917. ** is capable of reading or writing to the database. Cursors that
  54918. ** have been tripped into the CURSOR_FAULT state are not counted.
  54919. */
  54920. static int countValidCursors(BtShared *pBt, int wrOnly){
  54921. BtCursor *pCur;
  54922. int r = 0;
  54923. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  54924. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  54925. && pCur->eState!=CURSOR_FAULT ) r++;
  54926. }
  54927. return r;
  54928. }
  54929. #endif
  54930. /*
  54931. ** If there are no outstanding cursors and we are not in the middle
  54932. ** of a transaction but there is a read lock on the database, then
  54933. ** this routine unrefs the first page of the database file which
  54934. ** has the effect of releasing the read lock.
  54935. **
  54936. ** If there is a transaction in progress, this routine is a no-op.
  54937. */
  54938. static void unlockBtreeIfUnused(BtShared *pBt){
  54939. assert( sqlite3_mutex_held(pBt->mutex) );
  54940. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  54941. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  54942. MemPage *pPage1 = pBt->pPage1;
  54943. assert( pPage1->aData );
  54944. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  54945. pBt->pPage1 = 0;
  54946. releasePageNotNull(pPage1);
  54947. }
  54948. }
  54949. /*
  54950. ** If pBt points to an empty file then convert that empty file
  54951. ** into a new empty database by initializing the first page of
  54952. ** the database.
  54953. */
  54954. static int newDatabase(BtShared *pBt){
  54955. MemPage *pP1;
  54956. unsigned char *data;
  54957. int rc;
  54958. assert( sqlite3_mutex_held(pBt->mutex) );
  54959. if( pBt->nPage>0 ){
  54960. return SQLITE_OK;
  54961. }
  54962. pP1 = pBt->pPage1;
  54963. assert( pP1!=0 );
  54964. data = pP1->aData;
  54965. rc = sqlite3PagerWrite(pP1->pDbPage);
  54966. if( rc ) return rc;
  54967. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  54968. assert( sizeof(zMagicHeader)==16 );
  54969. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  54970. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  54971. data[18] = 1;
  54972. data[19] = 1;
  54973. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  54974. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  54975. data[21] = 64;
  54976. data[22] = 32;
  54977. data[23] = 32;
  54978. memset(&data[24], 0, 100-24);
  54979. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  54980. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  54981. #ifndef SQLITE_OMIT_AUTOVACUUM
  54982. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  54983. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  54984. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  54985. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  54986. #endif
  54987. pBt->nPage = 1;
  54988. data[31] = 1;
  54989. return SQLITE_OK;
  54990. }
  54991. /*
  54992. ** Initialize the first page of the database file (creating a database
  54993. ** consisting of a single page and no schema objects). Return SQLITE_OK
  54994. ** if successful, or an SQLite error code otherwise.
  54995. */
  54996. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  54997. int rc;
  54998. sqlite3BtreeEnter(p);
  54999. p->pBt->nPage = 0;
  55000. rc = newDatabase(p->pBt);
  55001. sqlite3BtreeLeave(p);
  55002. return rc;
  55003. }
  55004. /*
  55005. ** Attempt to start a new transaction. A write-transaction
  55006. ** is started if the second argument is nonzero, otherwise a read-
  55007. ** transaction. If the second argument is 2 or more and exclusive
  55008. ** transaction is started, meaning that no other process is allowed
  55009. ** to access the database. A preexisting transaction may not be
  55010. ** upgraded to exclusive by calling this routine a second time - the
  55011. ** exclusivity flag only works for a new transaction.
  55012. **
  55013. ** A write-transaction must be started before attempting any
  55014. ** changes to the database. None of the following routines
  55015. ** will work unless a transaction is started first:
  55016. **
  55017. ** sqlite3BtreeCreateTable()
  55018. ** sqlite3BtreeCreateIndex()
  55019. ** sqlite3BtreeClearTable()
  55020. ** sqlite3BtreeDropTable()
  55021. ** sqlite3BtreeInsert()
  55022. ** sqlite3BtreeDelete()
  55023. ** sqlite3BtreeUpdateMeta()
  55024. **
  55025. ** If an initial attempt to acquire the lock fails because of lock contention
  55026. ** and the database was previously unlocked, then invoke the busy handler
  55027. ** if there is one. But if there was previously a read-lock, do not
  55028. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  55029. ** returned when there is already a read-lock in order to avoid a deadlock.
  55030. **
  55031. ** Suppose there are two processes A and B. A has a read lock and B has
  55032. ** a reserved lock. B tries to promote to exclusive but is blocked because
  55033. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  55034. ** One or the other of the two processes must give way or there can be
  55035. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  55036. ** when A already has a read lock, we encourage A to give up and let B
  55037. ** proceed.
  55038. */
  55039. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  55040. BtShared *pBt = p->pBt;
  55041. int rc = SQLITE_OK;
  55042. sqlite3BtreeEnter(p);
  55043. btreeIntegrity(p);
  55044. /* If the btree is already in a write-transaction, or it
  55045. ** is already in a read-transaction and a read-transaction
  55046. ** is requested, this is a no-op.
  55047. */
  55048. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  55049. goto trans_begun;
  55050. }
  55051. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  55052. /* Write transactions are not possible on a read-only database */
  55053. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  55054. rc = SQLITE_READONLY;
  55055. goto trans_begun;
  55056. }
  55057. #ifndef SQLITE_OMIT_SHARED_CACHE
  55058. {
  55059. sqlite3 *pBlock = 0;
  55060. /* If another database handle has already opened a write transaction
  55061. ** on this shared-btree structure and a second write transaction is
  55062. ** requested, return SQLITE_LOCKED.
  55063. */
  55064. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  55065. || (pBt->btsFlags & BTS_PENDING)!=0
  55066. ){
  55067. pBlock = pBt->pWriter->db;
  55068. }else if( wrflag>1 ){
  55069. BtLock *pIter;
  55070. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  55071. if( pIter->pBtree!=p ){
  55072. pBlock = pIter->pBtree->db;
  55073. break;
  55074. }
  55075. }
  55076. }
  55077. if( pBlock ){
  55078. sqlite3ConnectionBlocked(p->db, pBlock);
  55079. rc = SQLITE_LOCKED_SHAREDCACHE;
  55080. goto trans_begun;
  55081. }
  55082. }
  55083. #endif
  55084. /* Any read-only or read-write transaction implies a read-lock on
  55085. ** page 1. So if some other shared-cache client already has a write-lock
  55086. ** on page 1, the transaction cannot be opened. */
  55087. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  55088. if( SQLITE_OK!=rc ) goto trans_begun;
  55089. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  55090. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  55091. do {
  55092. /* Call lockBtree() until either pBt->pPage1 is populated or
  55093. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  55094. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  55095. ** reading page 1 it discovers that the page-size of the database
  55096. ** file is not pBt->pageSize. In this case lockBtree() will update
  55097. ** pBt->pageSize to the page-size of the file on disk.
  55098. */
  55099. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  55100. if( rc==SQLITE_OK && wrflag ){
  55101. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  55102. rc = SQLITE_READONLY;
  55103. }else{
  55104. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  55105. if( rc==SQLITE_OK ){
  55106. rc = newDatabase(pBt);
  55107. }
  55108. }
  55109. }
  55110. if( rc!=SQLITE_OK ){
  55111. unlockBtreeIfUnused(pBt);
  55112. }
  55113. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  55114. btreeInvokeBusyHandler(pBt) );
  55115. if( rc==SQLITE_OK ){
  55116. if( p->inTrans==TRANS_NONE ){
  55117. pBt->nTransaction++;
  55118. #ifndef SQLITE_OMIT_SHARED_CACHE
  55119. if( p->sharable ){
  55120. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  55121. p->lock.eLock = READ_LOCK;
  55122. p->lock.pNext = pBt->pLock;
  55123. pBt->pLock = &p->lock;
  55124. }
  55125. #endif
  55126. }
  55127. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  55128. if( p->inTrans>pBt->inTransaction ){
  55129. pBt->inTransaction = p->inTrans;
  55130. }
  55131. if( wrflag ){
  55132. MemPage *pPage1 = pBt->pPage1;
  55133. #ifndef SQLITE_OMIT_SHARED_CACHE
  55134. assert( !pBt->pWriter );
  55135. pBt->pWriter = p;
  55136. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  55137. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  55138. #endif
  55139. /* If the db-size header field is incorrect (as it may be if an old
  55140. ** client has been writing the database file), update it now. Doing
  55141. ** this sooner rather than later means the database size can safely
  55142. ** re-read the database size from page 1 if a savepoint or transaction
  55143. ** rollback occurs within the transaction.
  55144. */
  55145. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  55146. rc = sqlite3PagerWrite(pPage1->pDbPage);
  55147. if( rc==SQLITE_OK ){
  55148. put4byte(&pPage1->aData[28], pBt->nPage);
  55149. }
  55150. }
  55151. }
  55152. }
  55153. trans_begun:
  55154. if( rc==SQLITE_OK && wrflag ){
  55155. /* This call makes sure that the pager has the correct number of
  55156. ** open savepoints. If the second parameter is greater than 0 and
  55157. ** the sub-journal is not already open, then it will be opened here.
  55158. */
  55159. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  55160. }
  55161. btreeIntegrity(p);
  55162. sqlite3BtreeLeave(p);
  55163. return rc;
  55164. }
  55165. #ifndef SQLITE_OMIT_AUTOVACUUM
  55166. /*
  55167. ** Set the pointer-map entries for all children of page pPage. Also, if
  55168. ** pPage contains cells that point to overflow pages, set the pointer
  55169. ** map entries for the overflow pages as well.
  55170. */
  55171. static int setChildPtrmaps(MemPage *pPage){
  55172. int i; /* Counter variable */
  55173. int nCell; /* Number of cells in page pPage */
  55174. int rc; /* Return code */
  55175. BtShared *pBt = pPage->pBt;
  55176. u8 isInitOrig = pPage->isInit;
  55177. Pgno pgno = pPage->pgno;
  55178. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55179. rc = btreeInitPage(pPage);
  55180. if( rc!=SQLITE_OK ){
  55181. goto set_child_ptrmaps_out;
  55182. }
  55183. nCell = pPage->nCell;
  55184. for(i=0; i<nCell; i++){
  55185. u8 *pCell = findCell(pPage, i);
  55186. ptrmapPutOvflPtr(pPage, pCell, &rc);
  55187. if( !pPage->leaf ){
  55188. Pgno childPgno = get4byte(pCell);
  55189. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  55190. }
  55191. }
  55192. if( !pPage->leaf ){
  55193. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55194. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  55195. }
  55196. set_child_ptrmaps_out:
  55197. pPage->isInit = isInitOrig;
  55198. return rc;
  55199. }
  55200. /*
  55201. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  55202. ** that it points to iTo. Parameter eType describes the type of pointer to
  55203. ** be modified, as follows:
  55204. **
  55205. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  55206. ** page of pPage.
  55207. **
  55208. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  55209. ** page pointed to by one of the cells on pPage.
  55210. **
  55211. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  55212. ** overflow page in the list.
  55213. */
  55214. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  55215. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55216. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  55217. if( eType==PTRMAP_OVERFLOW2 ){
  55218. /* The pointer is always the first 4 bytes of the page in this case. */
  55219. if( get4byte(pPage->aData)!=iFrom ){
  55220. return SQLITE_CORRUPT_BKPT;
  55221. }
  55222. put4byte(pPage->aData, iTo);
  55223. }else{
  55224. u8 isInitOrig = pPage->isInit;
  55225. int i;
  55226. int nCell;
  55227. int rc;
  55228. rc = btreeInitPage(pPage);
  55229. if( rc ) return rc;
  55230. nCell = pPage->nCell;
  55231. for(i=0; i<nCell; i++){
  55232. u8 *pCell = findCell(pPage, i);
  55233. if( eType==PTRMAP_OVERFLOW1 ){
  55234. CellInfo info;
  55235. pPage->xParseCell(pPage, pCell, &info);
  55236. if( info.nLocal<info.nPayload
  55237. && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
  55238. && iFrom==get4byte(pCell+info.nSize-4)
  55239. ){
  55240. put4byte(pCell+info.nSize-4, iTo);
  55241. break;
  55242. }
  55243. }else{
  55244. if( get4byte(pCell)==iFrom ){
  55245. put4byte(pCell, iTo);
  55246. break;
  55247. }
  55248. }
  55249. }
  55250. if( i==nCell ){
  55251. if( eType!=PTRMAP_BTREE ||
  55252. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  55253. return SQLITE_CORRUPT_BKPT;
  55254. }
  55255. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  55256. }
  55257. pPage->isInit = isInitOrig;
  55258. }
  55259. return SQLITE_OK;
  55260. }
  55261. /*
  55262. ** Move the open database page pDbPage to location iFreePage in the
  55263. ** database. The pDbPage reference remains valid.
  55264. **
  55265. ** The isCommit flag indicates that there is no need to remember that
  55266. ** the journal needs to be sync()ed before database page pDbPage->pgno
  55267. ** can be written to. The caller has already promised not to write to that
  55268. ** page.
  55269. */
  55270. static int relocatePage(
  55271. BtShared *pBt, /* Btree */
  55272. MemPage *pDbPage, /* Open page to move */
  55273. u8 eType, /* Pointer map 'type' entry for pDbPage */
  55274. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  55275. Pgno iFreePage, /* The location to move pDbPage to */
  55276. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  55277. ){
  55278. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  55279. Pgno iDbPage = pDbPage->pgno;
  55280. Pager *pPager = pBt->pPager;
  55281. int rc;
  55282. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  55283. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  55284. assert( sqlite3_mutex_held(pBt->mutex) );
  55285. assert( pDbPage->pBt==pBt );
  55286. /* Move page iDbPage from its current location to page number iFreePage */
  55287. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  55288. iDbPage, iFreePage, iPtrPage, eType));
  55289. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  55290. if( rc!=SQLITE_OK ){
  55291. return rc;
  55292. }
  55293. pDbPage->pgno = iFreePage;
  55294. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  55295. ** that point to overflow pages. The pointer map entries for all these
  55296. ** pages need to be changed.
  55297. **
  55298. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  55299. ** pointer to a subsequent overflow page. If this is the case, then
  55300. ** the pointer map needs to be updated for the subsequent overflow page.
  55301. */
  55302. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  55303. rc = setChildPtrmaps(pDbPage);
  55304. if( rc!=SQLITE_OK ){
  55305. return rc;
  55306. }
  55307. }else{
  55308. Pgno nextOvfl = get4byte(pDbPage->aData);
  55309. if( nextOvfl!=0 ){
  55310. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  55311. if( rc!=SQLITE_OK ){
  55312. return rc;
  55313. }
  55314. }
  55315. }
  55316. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  55317. ** that it points at iFreePage. Also fix the pointer map entry for
  55318. ** iPtrPage.
  55319. */
  55320. if( eType!=PTRMAP_ROOTPAGE ){
  55321. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  55322. if( rc!=SQLITE_OK ){
  55323. return rc;
  55324. }
  55325. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  55326. if( rc!=SQLITE_OK ){
  55327. releasePage(pPtrPage);
  55328. return rc;
  55329. }
  55330. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  55331. releasePage(pPtrPage);
  55332. if( rc==SQLITE_OK ){
  55333. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  55334. }
  55335. }
  55336. return rc;
  55337. }
  55338. /* Forward declaration required by incrVacuumStep(). */
  55339. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  55340. /*
  55341. ** Perform a single step of an incremental-vacuum. If successful, return
  55342. ** SQLITE_OK. If there is no work to do (and therefore no point in
  55343. ** calling this function again), return SQLITE_DONE. Or, if an error
  55344. ** occurs, return some other error code.
  55345. **
  55346. ** More specifically, this function attempts to re-organize the database so
  55347. ** that the last page of the file currently in use is no longer in use.
  55348. **
  55349. ** Parameter nFin is the number of pages that this database would contain
  55350. ** were this function called until it returns SQLITE_DONE.
  55351. **
  55352. ** If the bCommit parameter is non-zero, this function assumes that the
  55353. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  55354. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  55355. ** operation, or false for an incremental vacuum.
  55356. */
  55357. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  55358. Pgno nFreeList; /* Number of pages still on the free-list */
  55359. int rc;
  55360. assert( sqlite3_mutex_held(pBt->mutex) );
  55361. assert( iLastPg>nFin );
  55362. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  55363. u8 eType;
  55364. Pgno iPtrPage;
  55365. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  55366. if( nFreeList==0 ){
  55367. return SQLITE_DONE;
  55368. }
  55369. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  55370. if( rc!=SQLITE_OK ){
  55371. return rc;
  55372. }
  55373. if( eType==PTRMAP_ROOTPAGE ){
  55374. return SQLITE_CORRUPT_BKPT;
  55375. }
  55376. if( eType==PTRMAP_FREEPAGE ){
  55377. if( bCommit==0 ){
  55378. /* Remove the page from the files free-list. This is not required
  55379. ** if bCommit is non-zero. In that case, the free-list will be
  55380. ** truncated to zero after this function returns, so it doesn't
  55381. ** matter if it still contains some garbage entries.
  55382. */
  55383. Pgno iFreePg;
  55384. MemPage *pFreePg;
  55385. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  55386. if( rc!=SQLITE_OK ){
  55387. return rc;
  55388. }
  55389. assert( iFreePg==iLastPg );
  55390. releasePage(pFreePg);
  55391. }
  55392. } else {
  55393. Pgno iFreePg; /* Index of free page to move pLastPg to */
  55394. MemPage *pLastPg;
  55395. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  55396. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  55397. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  55398. if( rc!=SQLITE_OK ){
  55399. return rc;
  55400. }
  55401. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  55402. ** is swapped with the first free page pulled off the free list.
  55403. **
  55404. ** On the other hand, if bCommit is greater than zero, then keep
  55405. ** looping until a free-page located within the first nFin pages
  55406. ** of the file is found.
  55407. */
  55408. if( bCommit==0 ){
  55409. eMode = BTALLOC_LE;
  55410. iNear = nFin;
  55411. }
  55412. do {
  55413. MemPage *pFreePg;
  55414. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  55415. if( rc!=SQLITE_OK ){
  55416. releasePage(pLastPg);
  55417. return rc;
  55418. }
  55419. releasePage(pFreePg);
  55420. }while( bCommit && iFreePg>nFin );
  55421. assert( iFreePg<iLastPg );
  55422. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  55423. releasePage(pLastPg);
  55424. if( rc!=SQLITE_OK ){
  55425. return rc;
  55426. }
  55427. }
  55428. }
  55429. if( bCommit==0 ){
  55430. do {
  55431. iLastPg--;
  55432. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  55433. pBt->bDoTruncate = 1;
  55434. pBt->nPage = iLastPg;
  55435. }
  55436. return SQLITE_OK;
  55437. }
  55438. /*
  55439. ** The database opened by the first argument is an auto-vacuum database
  55440. ** nOrig pages in size containing nFree free pages. Return the expected
  55441. ** size of the database in pages following an auto-vacuum operation.
  55442. */
  55443. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  55444. int nEntry; /* Number of entries on one ptrmap page */
  55445. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  55446. Pgno nFin; /* Return value */
  55447. nEntry = pBt->usableSize/5;
  55448. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  55449. nFin = nOrig - nFree - nPtrmap;
  55450. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  55451. nFin--;
  55452. }
  55453. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  55454. nFin--;
  55455. }
  55456. return nFin;
  55457. }
  55458. /*
  55459. ** A write-transaction must be opened before calling this function.
  55460. ** It performs a single unit of work towards an incremental vacuum.
  55461. **
  55462. ** If the incremental vacuum is finished after this function has run,
  55463. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  55464. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  55465. */
  55466. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  55467. int rc;
  55468. BtShared *pBt = p->pBt;
  55469. sqlite3BtreeEnter(p);
  55470. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  55471. if( !pBt->autoVacuum ){
  55472. rc = SQLITE_DONE;
  55473. }else{
  55474. Pgno nOrig = btreePagecount(pBt);
  55475. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  55476. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  55477. if( nOrig<nFin ){
  55478. rc = SQLITE_CORRUPT_BKPT;
  55479. }else if( nFree>0 ){
  55480. rc = saveAllCursors(pBt, 0, 0);
  55481. if( rc==SQLITE_OK ){
  55482. invalidateAllOverflowCache(pBt);
  55483. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  55484. }
  55485. if( rc==SQLITE_OK ){
  55486. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  55487. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  55488. }
  55489. }else{
  55490. rc = SQLITE_DONE;
  55491. }
  55492. }
  55493. sqlite3BtreeLeave(p);
  55494. return rc;
  55495. }
  55496. /*
  55497. ** This routine is called prior to sqlite3PagerCommit when a transaction
  55498. ** is committed for an auto-vacuum database.
  55499. **
  55500. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  55501. ** the database file should be truncated to during the commit process.
  55502. ** i.e. the database has been reorganized so that only the first *pnTrunc
  55503. ** pages are in use.
  55504. */
  55505. static int autoVacuumCommit(BtShared *pBt){
  55506. int rc = SQLITE_OK;
  55507. Pager *pPager = pBt->pPager;
  55508. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  55509. assert( sqlite3_mutex_held(pBt->mutex) );
  55510. invalidateAllOverflowCache(pBt);
  55511. assert(pBt->autoVacuum);
  55512. if( !pBt->incrVacuum ){
  55513. Pgno nFin; /* Number of pages in database after autovacuuming */
  55514. Pgno nFree; /* Number of pages on the freelist initially */
  55515. Pgno iFree; /* The next page to be freed */
  55516. Pgno nOrig; /* Database size before freeing */
  55517. nOrig = btreePagecount(pBt);
  55518. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  55519. /* It is not possible to create a database for which the final page
  55520. ** is either a pointer-map page or the pending-byte page. If one
  55521. ** is encountered, this indicates corruption.
  55522. */
  55523. return SQLITE_CORRUPT_BKPT;
  55524. }
  55525. nFree = get4byte(&pBt->pPage1->aData[36]);
  55526. nFin = finalDbSize(pBt, nOrig, nFree);
  55527. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  55528. if( nFin<nOrig ){
  55529. rc = saveAllCursors(pBt, 0, 0);
  55530. }
  55531. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  55532. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  55533. }
  55534. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  55535. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  55536. put4byte(&pBt->pPage1->aData[32], 0);
  55537. put4byte(&pBt->pPage1->aData[36], 0);
  55538. put4byte(&pBt->pPage1->aData[28], nFin);
  55539. pBt->bDoTruncate = 1;
  55540. pBt->nPage = nFin;
  55541. }
  55542. if( rc!=SQLITE_OK ){
  55543. sqlite3PagerRollback(pPager);
  55544. }
  55545. }
  55546. assert( nRef>=sqlite3PagerRefcount(pPager) );
  55547. return rc;
  55548. }
  55549. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  55550. # define setChildPtrmaps(x) SQLITE_OK
  55551. #endif
  55552. /*
  55553. ** This routine does the first phase of a two-phase commit. This routine
  55554. ** causes a rollback journal to be created (if it does not already exist)
  55555. ** and populated with enough information so that if a power loss occurs
  55556. ** the database can be restored to its original state by playing back
  55557. ** the journal. Then the contents of the journal are flushed out to
  55558. ** the disk. After the journal is safely on oxide, the changes to the
  55559. ** database are written into the database file and flushed to oxide.
  55560. ** At the end of this call, the rollback journal still exists on the
  55561. ** disk and we are still holding all locks, so the transaction has not
  55562. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  55563. ** commit process.
  55564. **
  55565. ** This call is a no-op if no write-transaction is currently active on pBt.
  55566. **
  55567. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  55568. ** the name of a master journal file that should be written into the
  55569. ** individual journal file, or is NULL, indicating no master journal file
  55570. ** (single database transaction).
  55571. **
  55572. ** When this is called, the master journal should already have been
  55573. ** created, populated with this journal pointer and synced to disk.
  55574. **
  55575. ** Once this is routine has returned, the only thing required to commit
  55576. ** the write-transaction for this database file is to delete the journal.
  55577. */
  55578. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  55579. int rc = SQLITE_OK;
  55580. if( p->inTrans==TRANS_WRITE ){
  55581. BtShared *pBt = p->pBt;
  55582. sqlite3BtreeEnter(p);
  55583. #ifndef SQLITE_OMIT_AUTOVACUUM
  55584. if( pBt->autoVacuum ){
  55585. rc = autoVacuumCommit(pBt);
  55586. if( rc!=SQLITE_OK ){
  55587. sqlite3BtreeLeave(p);
  55588. return rc;
  55589. }
  55590. }
  55591. if( pBt->bDoTruncate ){
  55592. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  55593. }
  55594. #endif
  55595. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  55596. sqlite3BtreeLeave(p);
  55597. }
  55598. return rc;
  55599. }
  55600. /*
  55601. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  55602. ** at the conclusion of a transaction.
  55603. */
  55604. static void btreeEndTransaction(Btree *p){
  55605. BtShared *pBt = p->pBt;
  55606. sqlite3 *db = p->db;
  55607. assert( sqlite3BtreeHoldsMutex(p) );
  55608. #ifndef SQLITE_OMIT_AUTOVACUUM
  55609. pBt->bDoTruncate = 0;
  55610. #endif
  55611. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  55612. /* If there are other active statements that belong to this database
  55613. ** handle, downgrade to a read-only transaction. The other statements
  55614. ** may still be reading from the database. */
  55615. downgradeAllSharedCacheTableLocks(p);
  55616. p->inTrans = TRANS_READ;
  55617. }else{
  55618. /* If the handle had any kind of transaction open, decrement the
  55619. ** transaction count of the shared btree. If the transaction count
  55620. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  55621. ** call below will unlock the pager. */
  55622. if( p->inTrans!=TRANS_NONE ){
  55623. clearAllSharedCacheTableLocks(p);
  55624. pBt->nTransaction--;
  55625. if( 0==pBt->nTransaction ){
  55626. pBt->inTransaction = TRANS_NONE;
  55627. }
  55628. }
  55629. /* Set the current transaction state to TRANS_NONE and unlock the
  55630. ** pager if this call closed the only read or write transaction. */
  55631. p->inTrans = TRANS_NONE;
  55632. unlockBtreeIfUnused(pBt);
  55633. }
  55634. btreeIntegrity(p);
  55635. }
  55636. /*
  55637. ** Commit the transaction currently in progress.
  55638. **
  55639. ** This routine implements the second phase of a 2-phase commit. The
  55640. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  55641. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  55642. ** routine did all the work of writing information out to disk and flushing the
  55643. ** contents so that they are written onto the disk platter. All this
  55644. ** routine has to do is delete or truncate or zero the header in the
  55645. ** the rollback journal (which causes the transaction to commit) and
  55646. ** drop locks.
  55647. **
  55648. ** Normally, if an error occurs while the pager layer is attempting to
  55649. ** finalize the underlying journal file, this function returns an error and
  55650. ** the upper layer will attempt a rollback. However, if the second argument
  55651. ** is non-zero then this b-tree transaction is part of a multi-file
  55652. ** transaction. In this case, the transaction has already been committed
  55653. ** (by deleting a master journal file) and the caller will ignore this
  55654. ** functions return code. So, even if an error occurs in the pager layer,
  55655. ** reset the b-tree objects internal state to indicate that the write
  55656. ** transaction has been closed. This is quite safe, as the pager will have
  55657. ** transitioned to the error state.
  55658. **
  55659. ** This will release the write lock on the database file. If there
  55660. ** are no active cursors, it also releases the read lock.
  55661. */
  55662. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  55663. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  55664. sqlite3BtreeEnter(p);
  55665. btreeIntegrity(p);
  55666. /* If the handle has a write-transaction open, commit the shared-btrees
  55667. ** transaction and set the shared state to TRANS_READ.
  55668. */
  55669. if( p->inTrans==TRANS_WRITE ){
  55670. int rc;
  55671. BtShared *pBt = p->pBt;
  55672. assert( pBt->inTransaction==TRANS_WRITE );
  55673. assert( pBt->nTransaction>0 );
  55674. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  55675. if( rc!=SQLITE_OK && bCleanup==0 ){
  55676. sqlite3BtreeLeave(p);
  55677. return rc;
  55678. }
  55679. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  55680. pBt->inTransaction = TRANS_READ;
  55681. btreeClearHasContent(pBt);
  55682. }
  55683. btreeEndTransaction(p);
  55684. sqlite3BtreeLeave(p);
  55685. return SQLITE_OK;
  55686. }
  55687. /*
  55688. ** Do both phases of a commit.
  55689. */
  55690. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  55691. int rc;
  55692. sqlite3BtreeEnter(p);
  55693. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  55694. if( rc==SQLITE_OK ){
  55695. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  55696. }
  55697. sqlite3BtreeLeave(p);
  55698. return rc;
  55699. }
  55700. /*
  55701. ** This routine sets the state to CURSOR_FAULT and the error
  55702. ** code to errCode for every cursor on any BtShared that pBtree
  55703. ** references. Or if the writeOnly flag is set to 1, then only
  55704. ** trip write cursors and leave read cursors unchanged.
  55705. **
  55706. ** Every cursor is a candidate to be tripped, including cursors
  55707. ** that belong to other database connections that happen to be
  55708. ** sharing the cache with pBtree.
  55709. **
  55710. ** This routine gets called when a rollback occurs. If the writeOnly
  55711. ** flag is true, then only write-cursors need be tripped - read-only
  55712. ** cursors save their current positions so that they may continue
  55713. ** following the rollback. Or, if writeOnly is false, all cursors are
  55714. ** tripped. In general, writeOnly is false if the transaction being
  55715. ** rolled back modified the database schema. In this case b-tree root
  55716. ** pages may be moved or deleted from the database altogether, making
  55717. ** it unsafe for read cursors to continue.
  55718. **
  55719. ** If the writeOnly flag is true and an error is encountered while
  55720. ** saving the current position of a read-only cursor, all cursors,
  55721. ** including all read-cursors are tripped.
  55722. **
  55723. ** SQLITE_OK is returned if successful, or if an error occurs while
  55724. ** saving a cursor position, an SQLite error code.
  55725. */
  55726. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  55727. BtCursor *p;
  55728. int rc = SQLITE_OK;
  55729. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  55730. if( pBtree ){
  55731. sqlite3BtreeEnter(pBtree);
  55732. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  55733. int i;
  55734. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  55735. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  55736. rc = saveCursorPosition(p);
  55737. if( rc!=SQLITE_OK ){
  55738. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  55739. break;
  55740. }
  55741. }
  55742. }else{
  55743. sqlite3BtreeClearCursor(p);
  55744. p->eState = CURSOR_FAULT;
  55745. p->skipNext = errCode;
  55746. }
  55747. for(i=0; i<=p->iPage; i++){
  55748. releasePage(p->apPage[i]);
  55749. p->apPage[i] = 0;
  55750. }
  55751. }
  55752. sqlite3BtreeLeave(pBtree);
  55753. }
  55754. return rc;
  55755. }
  55756. /*
  55757. ** Rollback the transaction in progress.
  55758. **
  55759. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  55760. ** Only write cursors are tripped if writeOnly is true but all cursors are
  55761. ** tripped if writeOnly is false. Any attempt to use
  55762. ** a tripped cursor will result in an error.
  55763. **
  55764. ** This will release the write lock on the database file. If there
  55765. ** are no active cursors, it also releases the read lock.
  55766. */
  55767. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  55768. int rc;
  55769. BtShared *pBt = p->pBt;
  55770. MemPage *pPage1;
  55771. assert( writeOnly==1 || writeOnly==0 );
  55772. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  55773. sqlite3BtreeEnter(p);
  55774. if( tripCode==SQLITE_OK ){
  55775. rc = tripCode = saveAllCursors(pBt, 0, 0);
  55776. if( rc ) writeOnly = 0;
  55777. }else{
  55778. rc = SQLITE_OK;
  55779. }
  55780. if( tripCode ){
  55781. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  55782. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  55783. if( rc2!=SQLITE_OK ) rc = rc2;
  55784. }
  55785. btreeIntegrity(p);
  55786. if( p->inTrans==TRANS_WRITE ){
  55787. int rc2;
  55788. assert( TRANS_WRITE==pBt->inTransaction );
  55789. rc2 = sqlite3PagerRollback(pBt->pPager);
  55790. if( rc2!=SQLITE_OK ){
  55791. rc = rc2;
  55792. }
  55793. /* The rollback may have destroyed the pPage1->aData value. So
  55794. ** call btreeGetPage() on page 1 again to make
  55795. ** sure pPage1->aData is set correctly. */
  55796. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  55797. int nPage = get4byte(28+(u8*)pPage1->aData);
  55798. testcase( nPage==0 );
  55799. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  55800. testcase( pBt->nPage!=nPage );
  55801. pBt->nPage = nPage;
  55802. releasePage(pPage1);
  55803. }
  55804. assert( countValidCursors(pBt, 1)==0 );
  55805. pBt->inTransaction = TRANS_READ;
  55806. btreeClearHasContent(pBt);
  55807. }
  55808. btreeEndTransaction(p);
  55809. sqlite3BtreeLeave(p);
  55810. return rc;
  55811. }
  55812. /*
  55813. ** Start a statement subtransaction. The subtransaction can be rolled
  55814. ** back independently of the main transaction. You must start a transaction
  55815. ** before starting a subtransaction. The subtransaction is ended automatically
  55816. ** if the main transaction commits or rolls back.
  55817. **
  55818. ** Statement subtransactions are used around individual SQL statements
  55819. ** that are contained within a BEGIN...COMMIT block. If a constraint
  55820. ** error occurs within the statement, the effect of that one statement
  55821. ** can be rolled back without having to rollback the entire transaction.
  55822. **
  55823. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  55824. ** value passed as the second parameter is the total number of savepoints,
  55825. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  55826. ** are no active savepoints and no other statement-transactions open,
  55827. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  55828. ** using the sqlite3BtreeSavepoint() function.
  55829. */
  55830. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  55831. int rc;
  55832. BtShared *pBt = p->pBt;
  55833. sqlite3BtreeEnter(p);
  55834. assert( p->inTrans==TRANS_WRITE );
  55835. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55836. assert( iStatement>0 );
  55837. assert( iStatement>p->db->nSavepoint );
  55838. assert( pBt->inTransaction==TRANS_WRITE );
  55839. /* At the pager level, a statement transaction is a savepoint with
  55840. ** an index greater than all savepoints created explicitly using
  55841. ** SQL statements. It is illegal to open, release or rollback any
  55842. ** such savepoints while the statement transaction savepoint is active.
  55843. */
  55844. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  55845. sqlite3BtreeLeave(p);
  55846. return rc;
  55847. }
  55848. /*
  55849. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  55850. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  55851. ** savepoint identified by parameter iSavepoint, depending on the value
  55852. ** of op.
  55853. **
  55854. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  55855. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  55856. ** contents of the entire transaction are rolled back. This is different
  55857. ** from a normal transaction rollback, as no locks are released and the
  55858. ** transaction remains open.
  55859. */
  55860. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  55861. int rc = SQLITE_OK;
  55862. if( p && p->inTrans==TRANS_WRITE ){
  55863. BtShared *pBt = p->pBt;
  55864. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  55865. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  55866. sqlite3BtreeEnter(p);
  55867. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  55868. if( rc==SQLITE_OK ){
  55869. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  55870. pBt->nPage = 0;
  55871. }
  55872. rc = newDatabase(pBt);
  55873. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  55874. /* The database size was written into the offset 28 of the header
  55875. ** when the transaction started, so we know that the value at offset
  55876. ** 28 is nonzero. */
  55877. assert( pBt->nPage>0 );
  55878. }
  55879. sqlite3BtreeLeave(p);
  55880. }
  55881. return rc;
  55882. }
  55883. /*
  55884. ** Create a new cursor for the BTree whose root is on the page
  55885. ** iTable. If a read-only cursor is requested, it is assumed that
  55886. ** the caller already has at least a read-only transaction open
  55887. ** on the database already. If a write-cursor is requested, then
  55888. ** the caller is assumed to have an open write transaction.
  55889. **
  55890. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  55891. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  55892. ** can be used for reading or for writing if other conditions for writing
  55893. ** are also met. These are the conditions that must be met in order
  55894. ** for writing to be allowed:
  55895. **
  55896. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  55897. **
  55898. ** 2: Other database connections that share the same pager cache
  55899. ** but which are not in the READ_UNCOMMITTED state may not have
  55900. ** cursors open with wrFlag==0 on the same table. Otherwise
  55901. ** the changes made by this write cursor would be visible to
  55902. ** the read cursors in the other database connection.
  55903. **
  55904. ** 3: The database must be writable (not on read-only media)
  55905. **
  55906. ** 4: There must be an active transaction.
  55907. **
  55908. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  55909. ** is set. If FORDELETE is set, that is a hint to the implementation that
  55910. ** this cursor will only be used to seek to and delete entries of an index
  55911. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  55912. ** this implementation. But in a hypothetical alternative storage engine
  55913. ** in which index entries are automatically deleted when corresponding table
  55914. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  55915. ** operations on this cursor can be no-ops and all READ operations can
  55916. ** return a null row (2-bytes: 0x01 0x00).
  55917. **
  55918. ** No checking is done to make sure that page iTable really is the
  55919. ** root page of a b-tree. If it is not, then the cursor acquired
  55920. ** will not work correctly.
  55921. **
  55922. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  55923. ** on pCur to initialize the memory space prior to invoking this routine.
  55924. */
  55925. static int btreeCursor(
  55926. Btree *p, /* The btree */
  55927. int iTable, /* Root page of table to open */
  55928. int wrFlag, /* 1 to write. 0 read-only */
  55929. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  55930. BtCursor *pCur /* Space for new cursor */
  55931. ){
  55932. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  55933. BtCursor *pX; /* Looping over other all cursors */
  55934. assert( sqlite3BtreeHoldsMutex(p) );
  55935. assert( wrFlag==0
  55936. || wrFlag==BTREE_WRCSR
  55937. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  55938. );
  55939. /* The following assert statements verify that if this is a sharable
  55940. ** b-tree database, the connection is holding the required table locks,
  55941. ** and that no other connection has any open cursor that conflicts with
  55942. ** this lock. */
  55943. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  55944. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  55945. /* Assert that the caller has opened the required transaction. */
  55946. assert( p->inTrans>TRANS_NONE );
  55947. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  55948. assert( pBt->pPage1 && pBt->pPage1->aData );
  55949. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55950. if( wrFlag ){
  55951. allocateTempSpace(pBt);
  55952. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  55953. }
  55954. if( iTable==1 && btreePagecount(pBt)==0 ){
  55955. assert( wrFlag==0 );
  55956. iTable = 0;
  55957. }
  55958. /* Now that no other errors can occur, finish filling in the BtCursor
  55959. ** variables and link the cursor into the BtShared list. */
  55960. pCur->pgnoRoot = (Pgno)iTable;
  55961. pCur->iPage = -1;
  55962. pCur->pKeyInfo = pKeyInfo;
  55963. pCur->pBtree = p;
  55964. pCur->pBt = pBt;
  55965. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  55966. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  55967. /* If there are two or more cursors on the same btree, then all such
  55968. ** cursors *must* have the BTCF_Multiple flag set. */
  55969. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  55970. if( pX->pgnoRoot==(Pgno)iTable ){
  55971. pX->curFlags |= BTCF_Multiple;
  55972. pCur->curFlags |= BTCF_Multiple;
  55973. }
  55974. }
  55975. pCur->pNext = pBt->pCursor;
  55976. pBt->pCursor = pCur;
  55977. pCur->eState = CURSOR_INVALID;
  55978. return SQLITE_OK;
  55979. }
  55980. SQLITE_PRIVATE int sqlite3BtreeCursor(
  55981. Btree *p, /* The btree */
  55982. int iTable, /* Root page of table to open */
  55983. int wrFlag, /* 1 to write. 0 read-only */
  55984. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  55985. BtCursor *pCur /* Write new cursor here */
  55986. ){
  55987. int rc;
  55988. if( iTable<1 ){
  55989. rc = SQLITE_CORRUPT_BKPT;
  55990. }else{
  55991. sqlite3BtreeEnter(p);
  55992. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  55993. sqlite3BtreeLeave(p);
  55994. }
  55995. return rc;
  55996. }
  55997. /*
  55998. ** Return the size of a BtCursor object in bytes.
  55999. **
  56000. ** This interfaces is needed so that users of cursors can preallocate
  56001. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  56002. ** to users so they cannot do the sizeof() themselves - they must call
  56003. ** this routine.
  56004. */
  56005. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  56006. return ROUND8(sizeof(BtCursor));
  56007. }
  56008. /*
  56009. ** Initialize memory that will be converted into a BtCursor object.
  56010. **
  56011. ** The simple approach here would be to memset() the entire object
  56012. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  56013. ** do not need to be zeroed and they are large, so we can save a lot
  56014. ** of run-time by skipping the initialization of those elements.
  56015. */
  56016. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  56017. memset(p, 0, offsetof(BtCursor, iPage));
  56018. }
  56019. /*
  56020. ** Close a cursor. The read lock on the database file is released
  56021. ** when the last cursor is closed.
  56022. */
  56023. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  56024. Btree *pBtree = pCur->pBtree;
  56025. if( pBtree ){
  56026. int i;
  56027. BtShared *pBt = pCur->pBt;
  56028. sqlite3BtreeEnter(pBtree);
  56029. sqlite3BtreeClearCursor(pCur);
  56030. assert( pBt->pCursor!=0 );
  56031. if( pBt->pCursor==pCur ){
  56032. pBt->pCursor = pCur->pNext;
  56033. }else{
  56034. BtCursor *pPrev = pBt->pCursor;
  56035. do{
  56036. if( pPrev->pNext==pCur ){
  56037. pPrev->pNext = pCur->pNext;
  56038. break;
  56039. }
  56040. pPrev = pPrev->pNext;
  56041. }while( ALWAYS(pPrev) );
  56042. }
  56043. for(i=0; i<=pCur->iPage; i++){
  56044. releasePage(pCur->apPage[i]);
  56045. }
  56046. unlockBtreeIfUnused(pBt);
  56047. sqlite3_free(pCur->aOverflow);
  56048. /* sqlite3_free(pCur); */
  56049. sqlite3BtreeLeave(pBtree);
  56050. }
  56051. return SQLITE_OK;
  56052. }
  56053. /*
  56054. ** Make sure the BtCursor* given in the argument has a valid
  56055. ** BtCursor.info structure. If it is not already valid, call
  56056. ** btreeParseCell() to fill it in.
  56057. **
  56058. ** BtCursor.info is a cache of the information in the current cell.
  56059. ** Using this cache reduces the number of calls to btreeParseCell().
  56060. */
  56061. #ifndef NDEBUG
  56062. static void assertCellInfo(BtCursor *pCur){
  56063. CellInfo info;
  56064. int iPage = pCur->iPage;
  56065. memset(&info, 0, sizeof(info));
  56066. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  56067. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  56068. }
  56069. #else
  56070. #define assertCellInfo(x)
  56071. #endif
  56072. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  56073. if( pCur->info.nSize==0 ){
  56074. int iPage = pCur->iPage;
  56075. pCur->curFlags |= BTCF_ValidNKey;
  56076. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  56077. }else{
  56078. assertCellInfo(pCur);
  56079. }
  56080. }
  56081. #ifndef NDEBUG /* The next routine used only within assert() statements */
  56082. /*
  56083. ** Return true if the given BtCursor is valid. A valid cursor is one
  56084. ** that is currently pointing to a row in a (non-empty) table.
  56085. ** This is a verification routine is used only within assert() statements.
  56086. */
  56087. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  56088. return pCur && pCur->eState==CURSOR_VALID;
  56089. }
  56090. #endif /* NDEBUG */
  56091. /*
  56092. ** Set *pSize to the size of the buffer needed to hold the value of
  56093. ** the key for the current entry. If the cursor is not pointing
  56094. ** to a valid entry, *pSize is set to 0.
  56095. **
  56096. ** For a table with the INTKEY flag set, this routine returns the key
  56097. ** itself, not the number of bytes in the key.
  56098. **
  56099. ** The caller must position the cursor prior to invoking this routine.
  56100. **
  56101. ** This routine cannot fail. It always returns SQLITE_OK.
  56102. */
  56103. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  56104. assert( cursorHoldsMutex(pCur) );
  56105. assert( pCur->eState==CURSOR_VALID );
  56106. getCellInfo(pCur);
  56107. *pSize = pCur->info.nKey;
  56108. return SQLITE_OK;
  56109. }
  56110. /*
  56111. ** Set *pSize to the number of bytes of data in the entry the
  56112. ** cursor currently points to.
  56113. **
  56114. ** The caller must guarantee that the cursor is pointing to a non-NULL
  56115. ** valid entry. In other words, the calling procedure must guarantee
  56116. ** that the cursor has Cursor.eState==CURSOR_VALID.
  56117. **
  56118. ** Failure is not possible. This function always returns SQLITE_OK.
  56119. ** It might just as well be a procedure (returning void) but we continue
  56120. ** to return an integer result code for historical reasons.
  56121. */
  56122. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  56123. assert( cursorOwnsBtShared(pCur) );
  56124. assert( pCur->eState==CURSOR_VALID );
  56125. assert( pCur->iPage>=0 );
  56126. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  56127. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  56128. getCellInfo(pCur);
  56129. *pSize = pCur->info.nPayload;
  56130. return SQLITE_OK;
  56131. }
  56132. /*
  56133. ** Given the page number of an overflow page in the database (parameter
  56134. ** ovfl), this function finds the page number of the next page in the
  56135. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  56136. ** pointer-map data instead of reading the content of page ovfl to do so.
  56137. **
  56138. ** If an error occurs an SQLite error code is returned. Otherwise:
  56139. **
  56140. ** The page number of the next overflow page in the linked list is
  56141. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  56142. ** list, *pPgnoNext is set to zero.
  56143. **
  56144. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  56145. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  56146. ** reference. It is the responsibility of the caller to call releasePage()
  56147. ** on *ppPage to free the reference. In no reference was obtained (because
  56148. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  56149. ** *ppPage is set to zero.
  56150. */
  56151. static int getOverflowPage(
  56152. BtShared *pBt, /* The database file */
  56153. Pgno ovfl, /* Current overflow page number */
  56154. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  56155. Pgno *pPgnoNext /* OUT: Next overflow page number */
  56156. ){
  56157. Pgno next = 0;
  56158. MemPage *pPage = 0;
  56159. int rc = SQLITE_OK;
  56160. assert( sqlite3_mutex_held(pBt->mutex) );
  56161. assert(pPgnoNext);
  56162. #ifndef SQLITE_OMIT_AUTOVACUUM
  56163. /* Try to find the next page in the overflow list using the
  56164. ** autovacuum pointer-map pages. Guess that the next page in
  56165. ** the overflow list is page number (ovfl+1). If that guess turns
  56166. ** out to be wrong, fall back to loading the data of page
  56167. ** number ovfl to determine the next page number.
  56168. */
  56169. if( pBt->autoVacuum ){
  56170. Pgno pgno;
  56171. Pgno iGuess = ovfl+1;
  56172. u8 eType;
  56173. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  56174. iGuess++;
  56175. }
  56176. if( iGuess<=btreePagecount(pBt) ){
  56177. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  56178. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  56179. next = iGuess;
  56180. rc = SQLITE_DONE;
  56181. }
  56182. }
  56183. }
  56184. #endif
  56185. assert( next==0 || rc==SQLITE_DONE );
  56186. if( rc==SQLITE_OK ){
  56187. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  56188. assert( rc==SQLITE_OK || pPage==0 );
  56189. if( rc==SQLITE_OK ){
  56190. next = get4byte(pPage->aData);
  56191. }
  56192. }
  56193. *pPgnoNext = next;
  56194. if( ppPage ){
  56195. *ppPage = pPage;
  56196. }else{
  56197. releasePage(pPage);
  56198. }
  56199. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  56200. }
  56201. /*
  56202. ** Copy data from a buffer to a page, or from a page to a buffer.
  56203. **
  56204. ** pPayload is a pointer to data stored on database page pDbPage.
  56205. ** If argument eOp is false, then nByte bytes of data are copied
  56206. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  56207. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  56208. ** of data are copied from the buffer pBuf to pPayload.
  56209. **
  56210. ** SQLITE_OK is returned on success, otherwise an error code.
  56211. */
  56212. static int copyPayload(
  56213. void *pPayload, /* Pointer to page data */
  56214. void *pBuf, /* Pointer to buffer */
  56215. int nByte, /* Number of bytes to copy */
  56216. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  56217. DbPage *pDbPage /* Page containing pPayload */
  56218. ){
  56219. if( eOp ){
  56220. /* Copy data from buffer to page (a write operation) */
  56221. int rc = sqlite3PagerWrite(pDbPage);
  56222. if( rc!=SQLITE_OK ){
  56223. return rc;
  56224. }
  56225. memcpy(pPayload, pBuf, nByte);
  56226. }else{
  56227. /* Copy data from page to buffer (a read operation) */
  56228. memcpy(pBuf, pPayload, nByte);
  56229. }
  56230. return SQLITE_OK;
  56231. }
  56232. /*
  56233. ** This function is used to read or overwrite payload information
  56234. ** for the entry that the pCur cursor is pointing to. The eOp
  56235. ** argument is interpreted as follows:
  56236. **
  56237. ** 0: The operation is a read. Populate the overflow cache.
  56238. ** 1: The operation is a write. Populate the overflow cache.
  56239. ** 2: The operation is a read. Do not populate the overflow cache.
  56240. **
  56241. ** A total of "amt" bytes are read or written beginning at "offset".
  56242. ** Data is read to or from the buffer pBuf.
  56243. **
  56244. ** The content being read or written might appear on the main page
  56245. ** or be scattered out on multiple overflow pages.
  56246. **
  56247. ** If the current cursor entry uses one or more overflow pages and the
  56248. ** eOp argument is not 2, this function may allocate space for and lazily
  56249. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  56250. ** Subsequent calls use this cache to make seeking to the supplied offset
  56251. ** more efficient.
  56252. **
  56253. ** Once an overflow page-list cache has been allocated, it may be
  56254. ** invalidated if some other cursor writes to the same table, or if
  56255. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  56256. ** mode, the following events may invalidate an overflow page-list cache.
  56257. **
  56258. ** * An incremental vacuum,
  56259. ** * A commit in auto_vacuum="full" mode,
  56260. ** * Creating a table (may require moving an overflow page).
  56261. */
  56262. static int accessPayload(
  56263. BtCursor *pCur, /* Cursor pointing to entry to read from */
  56264. u32 offset, /* Begin reading this far into payload */
  56265. u32 amt, /* Read this many bytes */
  56266. unsigned char *pBuf, /* Write the bytes into this buffer */
  56267. int eOp /* zero to read. non-zero to write. */
  56268. ){
  56269. unsigned char *aPayload;
  56270. int rc = SQLITE_OK;
  56271. int iIdx = 0;
  56272. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  56273. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  56274. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  56275. unsigned char * const pBufStart = pBuf;
  56276. int bEnd; /* True if reading to end of data */
  56277. #endif
  56278. assert( pPage );
  56279. assert( pCur->eState==CURSOR_VALID );
  56280. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  56281. assert( cursorHoldsMutex(pCur) );
  56282. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  56283. getCellInfo(pCur);
  56284. aPayload = pCur->info.pPayload;
  56285. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  56286. bEnd = offset+amt==pCur->info.nPayload;
  56287. #endif
  56288. assert( offset+amt <= pCur->info.nPayload );
  56289. assert( aPayload > pPage->aData );
  56290. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  56291. /* Trying to read or write past the end of the data is an error. The
  56292. ** conditional above is really:
  56293. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  56294. ** but is recast into its current form to avoid integer overflow problems
  56295. */
  56296. return SQLITE_CORRUPT_BKPT;
  56297. }
  56298. /* Check if data must be read/written to/from the btree page itself. */
  56299. if( offset<pCur->info.nLocal ){
  56300. int a = amt;
  56301. if( a+offset>pCur->info.nLocal ){
  56302. a = pCur->info.nLocal - offset;
  56303. }
  56304. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  56305. offset = 0;
  56306. pBuf += a;
  56307. amt -= a;
  56308. }else{
  56309. offset -= pCur->info.nLocal;
  56310. }
  56311. if( rc==SQLITE_OK && amt>0 ){
  56312. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  56313. Pgno nextPage;
  56314. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  56315. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  56316. ** Except, do not allocate aOverflow[] for eOp==2.
  56317. **
  56318. ** The aOverflow[] array is sized at one entry for each overflow page
  56319. ** in the overflow chain. The page number of the first overflow page is
  56320. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  56321. ** means "not yet known" (the cache is lazily populated).
  56322. */
  56323. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  56324. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  56325. if( nOvfl>pCur->nOvflAlloc ){
  56326. Pgno *aNew = (Pgno*)sqlite3Realloc(
  56327. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  56328. );
  56329. if( aNew==0 ){
  56330. rc = SQLITE_NOMEM_BKPT;
  56331. }else{
  56332. pCur->nOvflAlloc = nOvfl*2;
  56333. pCur->aOverflow = aNew;
  56334. }
  56335. }
  56336. if( rc==SQLITE_OK ){
  56337. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  56338. pCur->curFlags |= BTCF_ValidOvfl;
  56339. }
  56340. }
  56341. /* If the overflow page-list cache has been allocated and the
  56342. ** entry for the first required overflow page is valid, skip
  56343. ** directly to it.
  56344. */
  56345. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  56346. && pCur->aOverflow[offset/ovflSize]
  56347. ){
  56348. iIdx = (offset/ovflSize);
  56349. nextPage = pCur->aOverflow[iIdx];
  56350. offset = (offset%ovflSize);
  56351. }
  56352. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  56353. /* If required, populate the overflow page-list cache. */
  56354. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  56355. assert( pCur->aOverflow[iIdx]==0
  56356. || pCur->aOverflow[iIdx]==nextPage
  56357. || CORRUPT_DB );
  56358. pCur->aOverflow[iIdx] = nextPage;
  56359. }
  56360. if( offset>=ovflSize ){
  56361. /* The only reason to read this page is to obtain the page
  56362. ** number for the next page in the overflow chain. The page
  56363. ** data is not required. So first try to lookup the overflow
  56364. ** page-list cache, if any, then fall back to the getOverflowPage()
  56365. ** function.
  56366. **
  56367. ** Note that the aOverflow[] array must be allocated because eOp!=2
  56368. ** here. If eOp==2, then offset==0 and this branch is never taken.
  56369. */
  56370. assert( eOp!=2 );
  56371. assert( pCur->curFlags & BTCF_ValidOvfl );
  56372. assert( pCur->pBtree->db==pBt->db );
  56373. if( pCur->aOverflow[iIdx+1] ){
  56374. nextPage = pCur->aOverflow[iIdx+1];
  56375. }else{
  56376. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  56377. }
  56378. offset -= ovflSize;
  56379. }else{
  56380. /* Need to read this page properly. It contains some of the
  56381. ** range of data that is being read (eOp==0) or written (eOp!=0).
  56382. */
  56383. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  56384. sqlite3_file *fd;
  56385. #endif
  56386. int a = amt;
  56387. if( a + offset > ovflSize ){
  56388. a = ovflSize - offset;
  56389. }
  56390. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  56391. /* If all the following are true:
  56392. **
  56393. ** 1) this is a read operation, and
  56394. ** 2) data is required from the start of this overflow page, and
  56395. ** 3) the database is file-backed, and
  56396. ** 4) there is no open write-transaction, and
  56397. ** 5) the database is not a WAL database,
  56398. ** 6) all data from the page is being read.
  56399. ** 7) at least 4 bytes have already been read into the output buffer
  56400. **
  56401. ** then data can be read directly from the database file into the
  56402. ** output buffer, bypassing the page-cache altogether. This speeds
  56403. ** up loading large records that span many overflow pages.
  56404. */
  56405. if( (eOp&0x01)==0 /* (1) */
  56406. && offset==0 /* (2) */
  56407. && (bEnd || a==ovflSize) /* (6) */
  56408. && pBt->inTransaction==TRANS_READ /* (4) */
  56409. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  56410. && pBt->pPage1->aData[19]==0x01 /* (5) */
  56411. && &pBuf[-4]>=pBufStart /* (7) */
  56412. ){
  56413. u8 aSave[4];
  56414. u8 *aWrite = &pBuf[-4];
  56415. assert( aWrite>=pBufStart ); /* hence (7) */
  56416. memcpy(aSave, aWrite, 4);
  56417. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  56418. nextPage = get4byte(aWrite);
  56419. memcpy(aWrite, aSave, 4);
  56420. }else
  56421. #endif
  56422. {
  56423. DbPage *pDbPage;
  56424. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  56425. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  56426. );
  56427. if( rc==SQLITE_OK ){
  56428. aPayload = sqlite3PagerGetData(pDbPage);
  56429. nextPage = get4byte(aPayload);
  56430. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  56431. sqlite3PagerUnref(pDbPage);
  56432. offset = 0;
  56433. }
  56434. }
  56435. amt -= a;
  56436. pBuf += a;
  56437. }
  56438. }
  56439. }
  56440. if( rc==SQLITE_OK && amt>0 ){
  56441. return SQLITE_CORRUPT_BKPT;
  56442. }
  56443. return rc;
  56444. }
  56445. /*
  56446. ** Read part of the key associated with cursor pCur. Exactly
  56447. ** "amt" bytes will be transferred into pBuf[]. The transfer
  56448. ** begins at "offset".
  56449. **
  56450. ** The caller must ensure that pCur is pointing to a valid row
  56451. ** in the table.
  56452. **
  56453. ** Return SQLITE_OK on success or an error code if anything goes
  56454. ** wrong. An error is returned if "offset+amt" is larger than
  56455. ** the available payload.
  56456. */
  56457. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  56458. assert( cursorHoldsMutex(pCur) );
  56459. assert( pCur->eState==CURSOR_VALID );
  56460. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  56461. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  56462. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  56463. }
  56464. /*
  56465. ** Read part of the data associated with cursor pCur. Exactly
  56466. ** "amt" bytes will be transfered into pBuf[]. The transfer
  56467. ** begins at "offset".
  56468. **
  56469. ** Return SQLITE_OK on success or an error code if anything goes
  56470. ** wrong. An error is returned if "offset+amt" is larger than
  56471. ** the available payload.
  56472. */
  56473. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  56474. int rc;
  56475. #ifndef SQLITE_OMIT_INCRBLOB
  56476. if ( pCur->eState==CURSOR_INVALID ){
  56477. return SQLITE_ABORT;
  56478. }
  56479. #endif
  56480. assert( cursorOwnsBtShared(pCur) );
  56481. rc = restoreCursorPosition(pCur);
  56482. if( rc==SQLITE_OK ){
  56483. assert( pCur->eState==CURSOR_VALID );
  56484. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  56485. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  56486. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  56487. }
  56488. return rc;
  56489. }
  56490. /*
  56491. ** Return a pointer to payload information from the entry that the
  56492. ** pCur cursor is pointing to. The pointer is to the beginning of
  56493. ** the key if index btrees (pPage->intKey==0) and is the data for
  56494. ** table btrees (pPage->intKey==1). The number of bytes of available
  56495. ** key/data is written into *pAmt. If *pAmt==0, then the value
  56496. ** returned will not be a valid pointer.
  56497. **
  56498. ** This routine is an optimization. It is common for the entire key
  56499. ** and data to fit on the local page and for there to be no overflow
  56500. ** pages. When that is so, this routine can be used to access the
  56501. ** key and data without making a copy. If the key and/or data spills
  56502. ** onto overflow pages, then accessPayload() must be used to reassemble
  56503. ** the key/data and copy it into a preallocated buffer.
  56504. **
  56505. ** The pointer returned by this routine looks directly into the cached
  56506. ** page of the database. The data might change or move the next time
  56507. ** any btree routine is called.
  56508. */
  56509. static const void *fetchPayload(
  56510. BtCursor *pCur, /* Cursor pointing to entry to read from */
  56511. u32 *pAmt /* Write the number of available bytes here */
  56512. ){
  56513. u32 amt;
  56514. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  56515. assert( pCur->eState==CURSOR_VALID );
  56516. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56517. assert( cursorOwnsBtShared(pCur) );
  56518. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  56519. assert( pCur->info.nSize>0 );
  56520. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  56521. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  56522. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  56523. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  56524. *pAmt = amt;
  56525. return (void*)pCur->info.pPayload;
  56526. }
  56527. /*
  56528. ** For the entry that cursor pCur is point to, return as
  56529. ** many bytes of the key or data as are available on the local
  56530. ** b-tree page. Write the number of available bytes into *pAmt.
  56531. **
  56532. ** The pointer returned is ephemeral. The key/data may move
  56533. ** or be destroyed on the next call to any Btree routine,
  56534. ** including calls from other threads against the same cache.
  56535. ** Hence, a mutex on the BtShared should be held prior to calling
  56536. ** this routine.
  56537. **
  56538. ** These routines is used to get quick access to key and data
  56539. ** in the common case where no overflow pages are used.
  56540. */
  56541. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  56542. return fetchPayload(pCur, pAmt);
  56543. }
  56544. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  56545. return fetchPayload(pCur, pAmt);
  56546. }
  56547. /*
  56548. ** Move the cursor down to a new child page. The newPgno argument is the
  56549. ** page number of the child page to move to.
  56550. **
  56551. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  56552. ** the new child page does not match the flags field of the parent (i.e.
  56553. ** if an intkey page appears to be the parent of a non-intkey page, or
  56554. ** vice-versa).
  56555. */
  56556. static int moveToChild(BtCursor *pCur, u32 newPgno){
  56557. BtShared *pBt = pCur->pBt;
  56558. assert( cursorOwnsBtShared(pCur) );
  56559. assert( pCur->eState==CURSOR_VALID );
  56560. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  56561. assert( pCur->iPage>=0 );
  56562. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  56563. return SQLITE_CORRUPT_BKPT;
  56564. }
  56565. pCur->info.nSize = 0;
  56566. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  56567. pCur->iPage++;
  56568. pCur->aiIdx[pCur->iPage] = 0;
  56569. return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
  56570. pCur, pCur->curPagerFlags);
  56571. }
  56572. #if SQLITE_DEBUG
  56573. /*
  56574. ** Page pParent is an internal (non-leaf) tree page. This function
  56575. ** asserts that page number iChild is the left-child if the iIdx'th
  56576. ** cell in page pParent. Or, if iIdx is equal to the total number of
  56577. ** cells in pParent, that page number iChild is the right-child of
  56578. ** the page.
  56579. */
  56580. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  56581. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  56582. ** in a corrupt database */
  56583. assert( iIdx<=pParent->nCell );
  56584. if( iIdx==pParent->nCell ){
  56585. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  56586. }else{
  56587. assert( get4byte(findCell(pParent, iIdx))==iChild );
  56588. }
  56589. }
  56590. #else
  56591. # define assertParentIndex(x,y,z)
  56592. #endif
  56593. /*
  56594. ** Move the cursor up to the parent page.
  56595. **
  56596. ** pCur->idx is set to the cell index that contains the pointer
  56597. ** to the page we are coming from. If we are coming from the
  56598. ** right-most child page then pCur->idx is set to one more than
  56599. ** the largest cell index.
  56600. */
  56601. static void moveToParent(BtCursor *pCur){
  56602. assert( cursorOwnsBtShared(pCur) );
  56603. assert( pCur->eState==CURSOR_VALID );
  56604. assert( pCur->iPage>0 );
  56605. assert( pCur->apPage[pCur->iPage] );
  56606. assertParentIndex(
  56607. pCur->apPage[pCur->iPage-1],
  56608. pCur->aiIdx[pCur->iPage-1],
  56609. pCur->apPage[pCur->iPage]->pgno
  56610. );
  56611. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  56612. pCur->info.nSize = 0;
  56613. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  56614. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  56615. }
  56616. /*
  56617. ** Move the cursor to point to the root page of its b-tree structure.
  56618. **
  56619. ** If the table has a virtual root page, then the cursor is moved to point
  56620. ** to the virtual root page instead of the actual root page. A table has a
  56621. ** virtual root page when the actual root page contains no cells and a
  56622. ** single child page. This can only happen with the table rooted at page 1.
  56623. **
  56624. ** If the b-tree structure is empty, the cursor state is set to
  56625. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  56626. ** cell located on the root (or virtual root) page and the cursor state
  56627. ** is set to CURSOR_VALID.
  56628. **
  56629. ** If this function returns successfully, it may be assumed that the
  56630. ** page-header flags indicate that the [virtual] root-page is the expected
  56631. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  56632. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  56633. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  56634. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  56635. ** b-tree).
  56636. */
  56637. static int moveToRoot(BtCursor *pCur){
  56638. MemPage *pRoot;
  56639. int rc = SQLITE_OK;
  56640. assert( cursorOwnsBtShared(pCur) );
  56641. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  56642. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  56643. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  56644. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  56645. if( pCur->eState==CURSOR_FAULT ){
  56646. assert( pCur->skipNext!=SQLITE_OK );
  56647. return pCur->skipNext;
  56648. }
  56649. sqlite3BtreeClearCursor(pCur);
  56650. }
  56651. if( pCur->iPage>=0 ){
  56652. while( pCur->iPage ){
  56653. assert( pCur->apPage[pCur->iPage]!=0 );
  56654. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  56655. }
  56656. }else if( pCur->pgnoRoot==0 ){
  56657. pCur->eState = CURSOR_INVALID;
  56658. return SQLITE_OK;
  56659. }else{
  56660. assert( pCur->iPage==(-1) );
  56661. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  56662. 0, pCur->curPagerFlags);
  56663. if( rc!=SQLITE_OK ){
  56664. pCur->eState = CURSOR_INVALID;
  56665. return rc;
  56666. }
  56667. pCur->iPage = 0;
  56668. pCur->curIntKey = pCur->apPage[0]->intKey;
  56669. }
  56670. pRoot = pCur->apPage[0];
  56671. assert( pRoot->pgno==pCur->pgnoRoot );
  56672. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  56673. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  56674. ** NULL, the caller expects a table b-tree. If this is not the case,
  56675. ** return an SQLITE_CORRUPT error.
  56676. **
  56677. ** Earlier versions of SQLite assumed that this test could not fail
  56678. ** if the root page was already loaded when this function was called (i.e.
  56679. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  56680. ** in such a way that page pRoot is linked into a second b-tree table
  56681. ** (or the freelist). */
  56682. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  56683. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  56684. return SQLITE_CORRUPT_BKPT;
  56685. }
  56686. pCur->aiIdx[0] = 0;
  56687. pCur->info.nSize = 0;
  56688. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  56689. if( pRoot->nCell>0 ){
  56690. pCur->eState = CURSOR_VALID;
  56691. }else if( !pRoot->leaf ){
  56692. Pgno subpage;
  56693. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  56694. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  56695. pCur->eState = CURSOR_VALID;
  56696. rc = moveToChild(pCur, subpage);
  56697. }else{
  56698. pCur->eState = CURSOR_INVALID;
  56699. }
  56700. return rc;
  56701. }
  56702. /*
  56703. ** Move the cursor down to the left-most leaf entry beneath the
  56704. ** entry to which it is currently pointing.
  56705. **
  56706. ** The left-most leaf is the one with the smallest key - the first
  56707. ** in ascending order.
  56708. */
  56709. static int moveToLeftmost(BtCursor *pCur){
  56710. Pgno pgno;
  56711. int rc = SQLITE_OK;
  56712. MemPage *pPage;
  56713. assert( cursorOwnsBtShared(pCur) );
  56714. assert( pCur->eState==CURSOR_VALID );
  56715. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  56716. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  56717. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  56718. rc = moveToChild(pCur, pgno);
  56719. }
  56720. return rc;
  56721. }
  56722. /*
  56723. ** Move the cursor down to the right-most leaf entry beneath the
  56724. ** page to which it is currently pointing. Notice the difference
  56725. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  56726. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  56727. ** finds the right-most entry beneath the *page*.
  56728. **
  56729. ** The right-most entry is the one with the largest key - the last
  56730. ** key in ascending order.
  56731. */
  56732. static int moveToRightmost(BtCursor *pCur){
  56733. Pgno pgno;
  56734. int rc = SQLITE_OK;
  56735. MemPage *pPage = 0;
  56736. assert( cursorOwnsBtShared(pCur) );
  56737. assert( pCur->eState==CURSOR_VALID );
  56738. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  56739. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  56740. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  56741. rc = moveToChild(pCur, pgno);
  56742. if( rc ) return rc;
  56743. }
  56744. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  56745. assert( pCur->info.nSize==0 );
  56746. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  56747. return SQLITE_OK;
  56748. }
  56749. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  56750. ** on success. Set *pRes to 0 if the cursor actually points to something
  56751. ** or set *pRes to 1 if the table is empty.
  56752. */
  56753. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  56754. int rc;
  56755. assert( cursorOwnsBtShared(pCur) );
  56756. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56757. rc = moveToRoot(pCur);
  56758. if( rc==SQLITE_OK ){
  56759. if( pCur->eState==CURSOR_INVALID ){
  56760. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  56761. *pRes = 1;
  56762. }else{
  56763. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  56764. *pRes = 0;
  56765. rc = moveToLeftmost(pCur);
  56766. }
  56767. }
  56768. return rc;
  56769. }
  56770. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  56771. ** on success. Set *pRes to 0 if the cursor actually points to something
  56772. ** or set *pRes to 1 if the table is empty.
  56773. */
  56774. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  56775. int rc;
  56776. assert( cursorOwnsBtShared(pCur) );
  56777. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56778. /* If the cursor already points to the last entry, this is a no-op. */
  56779. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  56780. #ifdef SQLITE_DEBUG
  56781. /* This block serves to assert() that the cursor really does point
  56782. ** to the last entry in the b-tree. */
  56783. int ii;
  56784. for(ii=0; ii<pCur->iPage; ii++){
  56785. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  56786. }
  56787. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  56788. assert( pCur->apPage[pCur->iPage]->leaf );
  56789. #endif
  56790. return SQLITE_OK;
  56791. }
  56792. rc = moveToRoot(pCur);
  56793. if( rc==SQLITE_OK ){
  56794. if( CURSOR_INVALID==pCur->eState ){
  56795. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  56796. *pRes = 1;
  56797. }else{
  56798. assert( pCur->eState==CURSOR_VALID );
  56799. *pRes = 0;
  56800. rc = moveToRightmost(pCur);
  56801. if( rc==SQLITE_OK ){
  56802. pCur->curFlags |= BTCF_AtLast;
  56803. }else{
  56804. pCur->curFlags &= ~BTCF_AtLast;
  56805. }
  56806. }
  56807. }
  56808. return rc;
  56809. }
  56810. /* Move the cursor so that it points to an entry near the key
  56811. ** specified by pIdxKey or intKey. Return a success code.
  56812. **
  56813. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  56814. ** must be NULL. For index tables, pIdxKey is used and intKey
  56815. ** is ignored.
  56816. **
  56817. ** If an exact match is not found, then the cursor is always
  56818. ** left pointing at a leaf page which would hold the entry if it
  56819. ** were present. The cursor might point to an entry that comes
  56820. ** before or after the key.
  56821. **
  56822. ** An integer is written into *pRes which is the result of
  56823. ** comparing the key with the entry to which the cursor is
  56824. ** pointing. The meaning of the integer written into
  56825. ** *pRes is as follows:
  56826. **
  56827. ** *pRes<0 The cursor is left pointing at an entry that
  56828. ** is smaller than intKey/pIdxKey or if the table is empty
  56829. ** and the cursor is therefore left point to nothing.
  56830. **
  56831. ** *pRes==0 The cursor is left pointing at an entry that
  56832. ** exactly matches intKey/pIdxKey.
  56833. **
  56834. ** *pRes>0 The cursor is left pointing at an entry that
  56835. ** is larger than intKey/pIdxKey.
  56836. **
  56837. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  56838. ** exists an entry in the table that exactly matches pIdxKey.
  56839. */
  56840. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  56841. BtCursor *pCur, /* The cursor to be moved */
  56842. UnpackedRecord *pIdxKey, /* Unpacked index key */
  56843. i64 intKey, /* The table key */
  56844. int biasRight, /* If true, bias the search to the high end */
  56845. int *pRes /* Write search results here */
  56846. ){
  56847. int rc;
  56848. RecordCompare xRecordCompare;
  56849. assert( cursorOwnsBtShared(pCur) );
  56850. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56851. assert( pRes );
  56852. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  56853. /* If the cursor is already positioned at the point we are trying
  56854. ** to move to, then just return without doing any work */
  56855. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  56856. && pCur->curIntKey
  56857. ){
  56858. if( pCur->info.nKey==intKey ){
  56859. *pRes = 0;
  56860. return SQLITE_OK;
  56861. }
  56862. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  56863. *pRes = -1;
  56864. return SQLITE_OK;
  56865. }
  56866. }
  56867. if( pIdxKey ){
  56868. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  56869. pIdxKey->errCode = 0;
  56870. assert( pIdxKey->default_rc==1
  56871. || pIdxKey->default_rc==0
  56872. || pIdxKey->default_rc==-1
  56873. );
  56874. }else{
  56875. xRecordCompare = 0; /* All keys are integers */
  56876. }
  56877. rc = moveToRoot(pCur);
  56878. if( rc ){
  56879. return rc;
  56880. }
  56881. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  56882. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  56883. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  56884. if( pCur->eState==CURSOR_INVALID ){
  56885. *pRes = -1;
  56886. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  56887. return SQLITE_OK;
  56888. }
  56889. assert( pCur->apPage[0]->intKey==pCur->curIntKey );
  56890. assert( pCur->curIntKey || pIdxKey );
  56891. for(;;){
  56892. int lwr, upr, idx, c;
  56893. Pgno chldPg;
  56894. MemPage *pPage = pCur->apPage[pCur->iPage];
  56895. u8 *pCell; /* Pointer to current cell in pPage */
  56896. /* pPage->nCell must be greater than zero. If this is the root-page
  56897. ** the cursor would have been INVALID above and this for(;;) loop
  56898. ** not run. If this is not the root-page, then the moveToChild() routine
  56899. ** would have already detected db corruption. Similarly, pPage must
  56900. ** be the right kind (index or table) of b-tree page. Otherwise
  56901. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  56902. assert( pPage->nCell>0 );
  56903. assert( pPage->intKey==(pIdxKey==0) );
  56904. lwr = 0;
  56905. upr = pPage->nCell-1;
  56906. assert( biasRight==0 || biasRight==1 );
  56907. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  56908. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56909. if( xRecordCompare==0 ){
  56910. for(;;){
  56911. i64 nCellKey;
  56912. pCell = findCellPastPtr(pPage, idx);
  56913. if( pPage->intKeyLeaf ){
  56914. while( 0x80 <= *(pCell++) ){
  56915. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  56916. }
  56917. }
  56918. getVarint(pCell, (u64*)&nCellKey);
  56919. if( nCellKey<intKey ){
  56920. lwr = idx+1;
  56921. if( lwr>upr ){ c = -1; break; }
  56922. }else if( nCellKey>intKey ){
  56923. upr = idx-1;
  56924. if( lwr>upr ){ c = +1; break; }
  56925. }else{
  56926. assert( nCellKey==intKey );
  56927. pCur->curFlags |= BTCF_ValidNKey;
  56928. pCur->info.nKey = nCellKey;
  56929. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56930. if( !pPage->leaf ){
  56931. lwr = idx;
  56932. goto moveto_next_layer;
  56933. }else{
  56934. *pRes = 0;
  56935. rc = SQLITE_OK;
  56936. goto moveto_finish;
  56937. }
  56938. }
  56939. assert( lwr+upr>=0 );
  56940. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  56941. }
  56942. }else{
  56943. for(;;){
  56944. int nCell; /* Size of the pCell cell in bytes */
  56945. pCell = findCellPastPtr(pPage, idx);
  56946. /* The maximum supported page-size is 65536 bytes. This means that
  56947. ** the maximum number of record bytes stored on an index B-Tree
  56948. ** page is less than 16384 bytes and may be stored as a 2-byte
  56949. ** varint. This information is used to attempt to avoid parsing
  56950. ** the entire cell by checking for the cases where the record is
  56951. ** stored entirely within the b-tree page by inspecting the first
  56952. ** 2 bytes of the cell.
  56953. */
  56954. nCell = pCell[0];
  56955. if( nCell<=pPage->max1bytePayload ){
  56956. /* This branch runs if the record-size field of the cell is a
  56957. ** single byte varint and the record fits entirely on the main
  56958. ** b-tree page. */
  56959. testcase( pCell+nCell+1==pPage->aDataEnd );
  56960. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  56961. }else if( !(pCell[1] & 0x80)
  56962. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  56963. ){
  56964. /* The record-size field is a 2 byte varint and the record
  56965. ** fits entirely on the main b-tree page. */
  56966. testcase( pCell+nCell+2==pPage->aDataEnd );
  56967. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  56968. }else{
  56969. /* The record flows over onto one or more overflow pages. In
  56970. ** this case the whole cell needs to be parsed, a buffer allocated
  56971. ** and accessPayload() used to retrieve the record into the
  56972. ** buffer before VdbeRecordCompare() can be called.
  56973. **
  56974. ** If the record is corrupt, the xRecordCompare routine may read
  56975. ** up to two varints past the end of the buffer. An extra 18
  56976. ** bytes of padding is allocated at the end of the buffer in
  56977. ** case this happens. */
  56978. void *pCellKey;
  56979. u8 * const pCellBody = pCell - pPage->childPtrSize;
  56980. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  56981. nCell = (int)pCur->info.nKey;
  56982. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  56983. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  56984. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  56985. testcase( nCell==2 ); /* Minimum legal index key size */
  56986. if( nCell<2 ){
  56987. rc = SQLITE_CORRUPT_BKPT;
  56988. goto moveto_finish;
  56989. }
  56990. pCellKey = sqlite3Malloc( nCell+18 );
  56991. if( pCellKey==0 ){
  56992. rc = SQLITE_NOMEM_BKPT;
  56993. goto moveto_finish;
  56994. }
  56995. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56996. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  56997. if( rc ){
  56998. sqlite3_free(pCellKey);
  56999. goto moveto_finish;
  57000. }
  57001. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  57002. sqlite3_free(pCellKey);
  57003. }
  57004. assert(
  57005. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  57006. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  57007. );
  57008. if( c<0 ){
  57009. lwr = idx+1;
  57010. }else if( c>0 ){
  57011. upr = idx-1;
  57012. }else{
  57013. assert( c==0 );
  57014. *pRes = 0;
  57015. rc = SQLITE_OK;
  57016. pCur->aiIdx[pCur->iPage] = (u16)idx;
  57017. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  57018. goto moveto_finish;
  57019. }
  57020. if( lwr>upr ) break;
  57021. assert( lwr+upr>=0 );
  57022. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  57023. }
  57024. }
  57025. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  57026. assert( pPage->isInit );
  57027. if( pPage->leaf ){
  57028. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  57029. pCur->aiIdx[pCur->iPage] = (u16)idx;
  57030. *pRes = c;
  57031. rc = SQLITE_OK;
  57032. goto moveto_finish;
  57033. }
  57034. moveto_next_layer:
  57035. if( lwr>=pPage->nCell ){
  57036. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  57037. }else{
  57038. chldPg = get4byte(findCell(pPage, lwr));
  57039. }
  57040. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  57041. rc = moveToChild(pCur, chldPg);
  57042. if( rc ) break;
  57043. }
  57044. moveto_finish:
  57045. pCur->info.nSize = 0;
  57046. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  57047. return rc;
  57048. }
  57049. /*
  57050. ** Return TRUE if the cursor is not pointing at an entry of the table.
  57051. **
  57052. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  57053. ** past the last entry in the table or sqlite3BtreePrev() moves past
  57054. ** the first entry. TRUE is also returned if the table is empty.
  57055. */
  57056. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  57057. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  57058. ** have been deleted? This API will need to change to return an error code
  57059. ** as well as the boolean result value.
  57060. */
  57061. return (CURSOR_VALID!=pCur->eState);
  57062. }
  57063. /*
  57064. ** Advance the cursor to the next entry in the database. If
  57065. ** successful then set *pRes=0. If the cursor
  57066. ** was already pointing to the last entry in the database before
  57067. ** this routine was called, then set *pRes=1.
  57068. **
  57069. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  57070. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  57071. ** to the next cell on the current page. The (slower) btreeNext() helper
  57072. ** routine is called when it is necessary to move to a different page or
  57073. ** to restore the cursor.
  57074. **
  57075. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  57076. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  57077. ** if this routine could have been skipped if that SQL index had been
  57078. ** a unique index. Otherwise the caller will have set *pRes to zero.
  57079. ** Zero is the common case. The btree implementation is free to use the
  57080. ** initial *pRes value as a hint to improve performance, but the current
  57081. ** SQLite btree implementation does not. (Note that the comdb2 btree
  57082. ** implementation does use this hint, however.)
  57083. */
  57084. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  57085. int rc;
  57086. int idx;
  57087. MemPage *pPage;
  57088. assert( cursorOwnsBtShared(pCur) );
  57089. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  57090. assert( *pRes==0 );
  57091. if( pCur->eState!=CURSOR_VALID ){
  57092. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  57093. rc = restoreCursorPosition(pCur);
  57094. if( rc!=SQLITE_OK ){
  57095. return rc;
  57096. }
  57097. if( CURSOR_INVALID==pCur->eState ){
  57098. *pRes = 1;
  57099. return SQLITE_OK;
  57100. }
  57101. if( pCur->skipNext ){
  57102. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  57103. pCur->eState = CURSOR_VALID;
  57104. if( pCur->skipNext>0 ){
  57105. pCur->skipNext = 0;
  57106. return SQLITE_OK;
  57107. }
  57108. pCur->skipNext = 0;
  57109. }
  57110. }
  57111. pPage = pCur->apPage[pCur->iPage];
  57112. idx = ++pCur->aiIdx[pCur->iPage];
  57113. assert( pPage->isInit );
  57114. /* If the database file is corrupt, it is possible for the value of idx
  57115. ** to be invalid here. This can only occur if a second cursor modifies
  57116. ** the page while cursor pCur is holding a reference to it. Which can
  57117. ** only happen if the database is corrupt in such a way as to link the
  57118. ** page into more than one b-tree structure. */
  57119. testcase( idx>pPage->nCell );
  57120. if( idx>=pPage->nCell ){
  57121. if( !pPage->leaf ){
  57122. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  57123. if( rc ) return rc;
  57124. return moveToLeftmost(pCur);
  57125. }
  57126. do{
  57127. if( pCur->iPage==0 ){
  57128. *pRes = 1;
  57129. pCur->eState = CURSOR_INVALID;
  57130. return SQLITE_OK;
  57131. }
  57132. moveToParent(pCur);
  57133. pPage = pCur->apPage[pCur->iPage];
  57134. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  57135. if( pPage->intKey ){
  57136. return sqlite3BtreeNext(pCur, pRes);
  57137. }else{
  57138. return SQLITE_OK;
  57139. }
  57140. }
  57141. if( pPage->leaf ){
  57142. return SQLITE_OK;
  57143. }else{
  57144. return moveToLeftmost(pCur);
  57145. }
  57146. }
  57147. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  57148. MemPage *pPage;
  57149. assert( cursorOwnsBtShared(pCur) );
  57150. assert( pRes!=0 );
  57151. assert( *pRes==0 || *pRes==1 );
  57152. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  57153. pCur->info.nSize = 0;
  57154. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  57155. *pRes = 0;
  57156. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  57157. pPage = pCur->apPage[pCur->iPage];
  57158. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  57159. pCur->aiIdx[pCur->iPage]--;
  57160. return btreeNext(pCur, pRes);
  57161. }
  57162. if( pPage->leaf ){
  57163. return SQLITE_OK;
  57164. }else{
  57165. return moveToLeftmost(pCur);
  57166. }
  57167. }
  57168. /*
  57169. ** Step the cursor to the back to the previous entry in the database. If
  57170. ** successful then set *pRes=0. If the cursor
  57171. ** was already pointing to the first entry in the database before
  57172. ** this routine was called, then set *pRes=1.
  57173. **
  57174. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  57175. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  57176. ** to the previous cell on the current page. The (slower) btreePrevious()
  57177. ** helper routine is called when it is necessary to move to a different page
  57178. ** or to restore the cursor.
  57179. **
  57180. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  57181. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  57182. ** if this routine could have been skipped if that SQL index had been
  57183. ** a unique index. Otherwise the caller will have set *pRes to zero.
  57184. ** Zero is the common case. The btree implementation is free to use the
  57185. ** initial *pRes value as a hint to improve performance, but the current
  57186. ** SQLite btree implementation does not. (Note that the comdb2 btree
  57187. ** implementation does use this hint, however.)
  57188. */
  57189. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  57190. int rc;
  57191. MemPage *pPage;
  57192. assert( cursorOwnsBtShared(pCur) );
  57193. assert( pRes!=0 );
  57194. assert( *pRes==0 );
  57195. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  57196. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  57197. assert( pCur->info.nSize==0 );
  57198. if( pCur->eState!=CURSOR_VALID ){
  57199. rc = restoreCursorPosition(pCur);
  57200. if( rc!=SQLITE_OK ){
  57201. return rc;
  57202. }
  57203. if( CURSOR_INVALID==pCur->eState ){
  57204. *pRes = 1;
  57205. return SQLITE_OK;
  57206. }
  57207. if( pCur->skipNext ){
  57208. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  57209. pCur->eState = CURSOR_VALID;
  57210. if( pCur->skipNext<0 ){
  57211. pCur->skipNext = 0;
  57212. return SQLITE_OK;
  57213. }
  57214. pCur->skipNext = 0;
  57215. }
  57216. }
  57217. pPage = pCur->apPage[pCur->iPage];
  57218. assert( pPage->isInit );
  57219. if( !pPage->leaf ){
  57220. int idx = pCur->aiIdx[pCur->iPage];
  57221. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  57222. if( rc ) return rc;
  57223. rc = moveToRightmost(pCur);
  57224. }else{
  57225. while( pCur->aiIdx[pCur->iPage]==0 ){
  57226. if( pCur->iPage==0 ){
  57227. pCur->eState = CURSOR_INVALID;
  57228. *pRes = 1;
  57229. return SQLITE_OK;
  57230. }
  57231. moveToParent(pCur);
  57232. }
  57233. assert( pCur->info.nSize==0 );
  57234. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  57235. pCur->aiIdx[pCur->iPage]--;
  57236. pPage = pCur->apPage[pCur->iPage];
  57237. if( pPage->intKey && !pPage->leaf ){
  57238. rc = sqlite3BtreePrevious(pCur, pRes);
  57239. }else{
  57240. rc = SQLITE_OK;
  57241. }
  57242. }
  57243. return rc;
  57244. }
  57245. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  57246. assert( cursorOwnsBtShared(pCur) );
  57247. assert( pRes!=0 );
  57248. assert( *pRes==0 || *pRes==1 );
  57249. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  57250. *pRes = 0;
  57251. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  57252. pCur->info.nSize = 0;
  57253. if( pCur->eState!=CURSOR_VALID
  57254. || pCur->aiIdx[pCur->iPage]==0
  57255. || pCur->apPage[pCur->iPage]->leaf==0
  57256. ){
  57257. return btreePrevious(pCur, pRes);
  57258. }
  57259. pCur->aiIdx[pCur->iPage]--;
  57260. return SQLITE_OK;
  57261. }
  57262. /*
  57263. ** Allocate a new page from the database file.
  57264. **
  57265. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  57266. ** has already been called on the new page.) The new page has also
  57267. ** been referenced and the calling routine is responsible for calling
  57268. ** sqlite3PagerUnref() on the new page when it is done.
  57269. **
  57270. ** SQLITE_OK is returned on success. Any other return value indicates
  57271. ** an error. *ppPage is set to NULL in the event of an error.
  57272. **
  57273. ** If the "nearby" parameter is not 0, then an effort is made to
  57274. ** locate a page close to the page number "nearby". This can be used in an
  57275. ** attempt to keep related pages close to each other in the database file,
  57276. ** which in turn can make database access faster.
  57277. **
  57278. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  57279. ** anywhere on the free-list, then it is guaranteed to be returned. If
  57280. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  57281. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  57282. ** are no restrictions on which page is returned.
  57283. */
  57284. static int allocateBtreePage(
  57285. BtShared *pBt, /* The btree */
  57286. MemPage **ppPage, /* Store pointer to the allocated page here */
  57287. Pgno *pPgno, /* Store the page number here */
  57288. Pgno nearby, /* Search for a page near this one */
  57289. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  57290. ){
  57291. MemPage *pPage1;
  57292. int rc;
  57293. u32 n; /* Number of pages on the freelist */
  57294. u32 k; /* Number of leaves on the trunk of the freelist */
  57295. MemPage *pTrunk = 0;
  57296. MemPage *pPrevTrunk = 0;
  57297. Pgno mxPage; /* Total size of the database file */
  57298. assert( sqlite3_mutex_held(pBt->mutex) );
  57299. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  57300. pPage1 = pBt->pPage1;
  57301. mxPage = btreePagecount(pBt);
  57302. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  57303. ** stores stores the total number of pages on the freelist. */
  57304. n = get4byte(&pPage1->aData[36]);
  57305. testcase( n==mxPage-1 );
  57306. if( n>=mxPage ){
  57307. return SQLITE_CORRUPT_BKPT;
  57308. }
  57309. if( n>0 ){
  57310. /* There are pages on the freelist. Reuse one of those pages. */
  57311. Pgno iTrunk;
  57312. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  57313. u32 nSearch = 0; /* Count of the number of search attempts */
  57314. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  57315. ** shows that the page 'nearby' is somewhere on the free-list, then
  57316. ** the entire-list will be searched for that page.
  57317. */
  57318. #ifndef SQLITE_OMIT_AUTOVACUUM
  57319. if( eMode==BTALLOC_EXACT ){
  57320. if( nearby<=mxPage ){
  57321. u8 eType;
  57322. assert( nearby>0 );
  57323. assert( pBt->autoVacuum );
  57324. rc = ptrmapGet(pBt, nearby, &eType, 0);
  57325. if( rc ) return rc;
  57326. if( eType==PTRMAP_FREEPAGE ){
  57327. searchList = 1;
  57328. }
  57329. }
  57330. }else if( eMode==BTALLOC_LE ){
  57331. searchList = 1;
  57332. }
  57333. #endif
  57334. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  57335. ** first free-list trunk page. iPrevTrunk is initially 1.
  57336. */
  57337. rc = sqlite3PagerWrite(pPage1->pDbPage);
  57338. if( rc ) return rc;
  57339. put4byte(&pPage1->aData[36], n-1);
  57340. /* The code within this loop is run only once if the 'searchList' variable
  57341. ** is not true. Otherwise, it runs once for each trunk-page on the
  57342. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  57343. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  57344. */
  57345. do {
  57346. pPrevTrunk = pTrunk;
  57347. if( pPrevTrunk ){
  57348. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  57349. ** is the page number of the next freelist trunk page in the list or
  57350. ** zero if this is the last freelist trunk page. */
  57351. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  57352. }else{
  57353. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  57354. ** stores the page number of the first page of the freelist, or zero if
  57355. ** the freelist is empty. */
  57356. iTrunk = get4byte(&pPage1->aData[32]);
  57357. }
  57358. testcase( iTrunk==mxPage );
  57359. if( iTrunk>mxPage || nSearch++ > n ){
  57360. rc = SQLITE_CORRUPT_BKPT;
  57361. }else{
  57362. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  57363. }
  57364. if( rc ){
  57365. pTrunk = 0;
  57366. goto end_allocate_page;
  57367. }
  57368. assert( pTrunk!=0 );
  57369. assert( pTrunk->aData!=0 );
  57370. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  57371. ** is the number of leaf page pointers to follow. */
  57372. k = get4byte(&pTrunk->aData[4]);
  57373. if( k==0 && !searchList ){
  57374. /* The trunk has no leaves and the list is not being searched.
  57375. ** So extract the trunk page itself and use it as the newly
  57376. ** allocated page */
  57377. assert( pPrevTrunk==0 );
  57378. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  57379. if( rc ){
  57380. goto end_allocate_page;
  57381. }
  57382. *pPgno = iTrunk;
  57383. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  57384. *ppPage = pTrunk;
  57385. pTrunk = 0;
  57386. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  57387. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  57388. /* Value of k is out of range. Database corruption */
  57389. rc = SQLITE_CORRUPT_BKPT;
  57390. goto end_allocate_page;
  57391. #ifndef SQLITE_OMIT_AUTOVACUUM
  57392. }else if( searchList
  57393. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  57394. ){
  57395. /* The list is being searched and this trunk page is the page
  57396. ** to allocate, regardless of whether it has leaves.
  57397. */
  57398. *pPgno = iTrunk;
  57399. *ppPage = pTrunk;
  57400. searchList = 0;
  57401. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  57402. if( rc ){
  57403. goto end_allocate_page;
  57404. }
  57405. if( k==0 ){
  57406. if( !pPrevTrunk ){
  57407. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  57408. }else{
  57409. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  57410. if( rc!=SQLITE_OK ){
  57411. goto end_allocate_page;
  57412. }
  57413. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  57414. }
  57415. }else{
  57416. /* The trunk page is required by the caller but it contains
  57417. ** pointers to free-list leaves. The first leaf becomes a trunk
  57418. ** page in this case.
  57419. */
  57420. MemPage *pNewTrunk;
  57421. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  57422. if( iNewTrunk>mxPage ){
  57423. rc = SQLITE_CORRUPT_BKPT;
  57424. goto end_allocate_page;
  57425. }
  57426. testcase( iNewTrunk==mxPage );
  57427. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  57428. if( rc!=SQLITE_OK ){
  57429. goto end_allocate_page;
  57430. }
  57431. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  57432. if( rc!=SQLITE_OK ){
  57433. releasePage(pNewTrunk);
  57434. goto end_allocate_page;
  57435. }
  57436. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  57437. put4byte(&pNewTrunk->aData[4], k-1);
  57438. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  57439. releasePage(pNewTrunk);
  57440. if( !pPrevTrunk ){
  57441. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  57442. put4byte(&pPage1->aData[32], iNewTrunk);
  57443. }else{
  57444. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  57445. if( rc ){
  57446. goto end_allocate_page;
  57447. }
  57448. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  57449. }
  57450. }
  57451. pTrunk = 0;
  57452. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  57453. #endif
  57454. }else if( k>0 ){
  57455. /* Extract a leaf from the trunk */
  57456. u32 closest;
  57457. Pgno iPage;
  57458. unsigned char *aData = pTrunk->aData;
  57459. if( nearby>0 ){
  57460. u32 i;
  57461. closest = 0;
  57462. if( eMode==BTALLOC_LE ){
  57463. for(i=0; i<k; i++){
  57464. iPage = get4byte(&aData[8+i*4]);
  57465. if( iPage<=nearby ){
  57466. closest = i;
  57467. break;
  57468. }
  57469. }
  57470. }else{
  57471. int dist;
  57472. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  57473. for(i=1; i<k; i++){
  57474. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  57475. if( d2<dist ){
  57476. closest = i;
  57477. dist = d2;
  57478. }
  57479. }
  57480. }
  57481. }else{
  57482. closest = 0;
  57483. }
  57484. iPage = get4byte(&aData[8+closest*4]);
  57485. testcase( iPage==mxPage );
  57486. if( iPage>mxPage ){
  57487. rc = SQLITE_CORRUPT_BKPT;
  57488. goto end_allocate_page;
  57489. }
  57490. testcase( iPage==mxPage );
  57491. if( !searchList
  57492. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  57493. ){
  57494. int noContent;
  57495. *pPgno = iPage;
  57496. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  57497. ": %d more free pages\n",
  57498. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  57499. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  57500. if( rc ) goto end_allocate_page;
  57501. if( closest<k-1 ){
  57502. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  57503. }
  57504. put4byte(&aData[4], k-1);
  57505. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  57506. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  57507. if( rc==SQLITE_OK ){
  57508. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  57509. if( rc!=SQLITE_OK ){
  57510. releasePage(*ppPage);
  57511. *ppPage = 0;
  57512. }
  57513. }
  57514. searchList = 0;
  57515. }
  57516. }
  57517. releasePage(pPrevTrunk);
  57518. pPrevTrunk = 0;
  57519. }while( searchList );
  57520. }else{
  57521. /* There are no pages on the freelist, so append a new page to the
  57522. ** database image.
  57523. **
  57524. ** Normally, new pages allocated by this block can be requested from the
  57525. ** pager layer with the 'no-content' flag set. This prevents the pager
  57526. ** from trying to read the pages content from disk. However, if the
  57527. ** current transaction has already run one or more incremental-vacuum
  57528. ** steps, then the page we are about to allocate may contain content
  57529. ** that is required in the event of a rollback. In this case, do
  57530. ** not set the no-content flag. This causes the pager to load and journal
  57531. ** the current page content before overwriting it.
  57532. **
  57533. ** Note that the pager will not actually attempt to load or journal
  57534. ** content for any page that really does lie past the end of the database
  57535. ** file on disk. So the effects of disabling the no-content optimization
  57536. ** here are confined to those pages that lie between the end of the
  57537. ** database image and the end of the database file.
  57538. */
  57539. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  57540. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  57541. if( rc ) return rc;
  57542. pBt->nPage++;
  57543. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  57544. #ifndef SQLITE_OMIT_AUTOVACUUM
  57545. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  57546. /* If *pPgno refers to a pointer-map page, allocate two new pages
  57547. ** at the end of the file instead of one. The first allocated page
  57548. ** becomes a new pointer-map page, the second is used by the caller.
  57549. */
  57550. MemPage *pPg = 0;
  57551. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  57552. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  57553. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  57554. if( rc==SQLITE_OK ){
  57555. rc = sqlite3PagerWrite(pPg->pDbPage);
  57556. releasePage(pPg);
  57557. }
  57558. if( rc ) return rc;
  57559. pBt->nPage++;
  57560. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  57561. }
  57562. #endif
  57563. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  57564. *pPgno = pBt->nPage;
  57565. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  57566. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  57567. if( rc ) return rc;
  57568. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  57569. if( rc!=SQLITE_OK ){
  57570. releasePage(*ppPage);
  57571. *ppPage = 0;
  57572. }
  57573. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  57574. }
  57575. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  57576. end_allocate_page:
  57577. releasePage(pTrunk);
  57578. releasePage(pPrevTrunk);
  57579. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  57580. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  57581. return rc;
  57582. }
  57583. /*
  57584. ** This function is used to add page iPage to the database file free-list.
  57585. ** It is assumed that the page is not already a part of the free-list.
  57586. **
  57587. ** The value passed as the second argument to this function is optional.
  57588. ** If the caller happens to have a pointer to the MemPage object
  57589. ** corresponding to page iPage handy, it may pass it as the second value.
  57590. ** Otherwise, it may pass NULL.
  57591. **
  57592. ** If a pointer to a MemPage object is passed as the second argument,
  57593. ** its reference count is not altered by this function.
  57594. */
  57595. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  57596. MemPage *pTrunk = 0; /* Free-list trunk page */
  57597. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  57598. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  57599. MemPage *pPage; /* Page being freed. May be NULL. */
  57600. int rc; /* Return Code */
  57601. int nFree; /* Initial number of pages on free-list */
  57602. assert( sqlite3_mutex_held(pBt->mutex) );
  57603. assert( CORRUPT_DB || iPage>1 );
  57604. assert( !pMemPage || pMemPage->pgno==iPage );
  57605. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  57606. if( pMemPage ){
  57607. pPage = pMemPage;
  57608. sqlite3PagerRef(pPage->pDbPage);
  57609. }else{
  57610. pPage = btreePageLookup(pBt, iPage);
  57611. }
  57612. /* Increment the free page count on pPage1 */
  57613. rc = sqlite3PagerWrite(pPage1->pDbPage);
  57614. if( rc ) goto freepage_out;
  57615. nFree = get4byte(&pPage1->aData[36]);
  57616. put4byte(&pPage1->aData[36], nFree+1);
  57617. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  57618. /* If the secure_delete option is enabled, then
  57619. ** always fully overwrite deleted information with zeros.
  57620. */
  57621. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  57622. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  57623. ){
  57624. goto freepage_out;
  57625. }
  57626. memset(pPage->aData, 0, pPage->pBt->pageSize);
  57627. }
  57628. /* If the database supports auto-vacuum, write an entry in the pointer-map
  57629. ** to indicate that the page is free.
  57630. */
  57631. if( ISAUTOVACUUM ){
  57632. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  57633. if( rc ) goto freepage_out;
  57634. }
  57635. /* Now manipulate the actual database free-list structure. There are two
  57636. ** possibilities. If the free-list is currently empty, or if the first
  57637. ** trunk page in the free-list is full, then this page will become a
  57638. ** new free-list trunk page. Otherwise, it will become a leaf of the
  57639. ** first trunk page in the current free-list. This block tests if it
  57640. ** is possible to add the page as a new free-list leaf.
  57641. */
  57642. if( nFree!=0 ){
  57643. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  57644. iTrunk = get4byte(&pPage1->aData[32]);
  57645. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  57646. if( rc!=SQLITE_OK ){
  57647. goto freepage_out;
  57648. }
  57649. nLeaf = get4byte(&pTrunk->aData[4]);
  57650. assert( pBt->usableSize>32 );
  57651. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  57652. rc = SQLITE_CORRUPT_BKPT;
  57653. goto freepage_out;
  57654. }
  57655. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  57656. /* In this case there is room on the trunk page to insert the page
  57657. ** being freed as a new leaf.
  57658. **
  57659. ** Note that the trunk page is not really full until it contains
  57660. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  57661. ** coded. But due to a coding error in versions of SQLite prior to
  57662. ** 3.6.0, databases with freelist trunk pages holding more than
  57663. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  57664. ** to maintain backwards compatibility with older versions of SQLite,
  57665. ** we will continue to restrict the number of entries to usableSize/4 - 8
  57666. ** for now. At some point in the future (once everyone has upgraded
  57667. ** to 3.6.0 or later) we should consider fixing the conditional above
  57668. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  57669. **
  57670. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  57671. ** avoid using the last six entries in the freelist trunk page array in
  57672. ** order that database files created by newer versions of SQLite can be
  57673. ** read by older versions of SQLite.
  57674. */
  57675. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  57676. if( rc==SQLITE_OK ){
  57677. put4byte(&pTrunk->aData[4], nLeaf+1);
  57678. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  57679. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  57680. sqlite3PagerDontWrite(pPage->pDbPage);
  57681. }
  57682. rc = btreeSetHasContent(pBt, iPage);
  57683. }
  57684. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  57685. goto freepage_out;
  57686. }
  57687. }
  57688. /* If control flows to this point, then it was not possible to add the
  57689. ** the page being freed as a leaf page of the first trunk in the free-list.
  57690. ** Possibly because the free-list is empty, or possibly because the
  57691. ** first trunk in the free-list is full. Either way, the page being freed
  57692. ** will become the new first trunk page in the free-list.
  57693. */
  57694. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  57695. goto freepage_out;
  57696. }
  57697. rc = sqlite3PagerWrite(pPage->pDbPage);
  57698. if( rc!=SQLITE_OK ){
  57699. goto freepage_out;
  57700. }
  57701. put4byte(pPage->aData, iTrunk);
  57702. put4byte(&pPage->aData[4], 0);
  57703. put4byte(&pPage1->aData[32], iPage);
  57704. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  57705. freepage_out:
  57706. if( pPage ){
  57707. pPage->isInit = 0;
  57708. }
  57709. releasePage(pPage);
  57710. releasePage(pTrunk);
  57711. return rc;
  57712. }
  57713. static void freePage(MemPage *pPage, int *pRC){
  57714. if( (*pRC)==SQLITE_OK ){
  57715. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  57716. }
  57717. }
  57718. /*
  57719. ** Free any overflow pages associated with the given Cell. Write the
  57720. ** local Cell size (the number of bytes on the original page, omitting
  57721. ** overflow) into *pnSize.
  57722. */
  57723. static int clearCell(
  57724. MemPage *pPage, /* The page that contains the Cell */
  57725. unsigned char *pCell, /* First byte of the Cell */
  57726. u16 *pnSize /* Write the size of the Cell here */
  57727. ){
  57728. BtShared *pBt = pPage->pBt;
  57729. CellInfo info;
  57730. Pgno ovflPgno;
  57731. int rc;
  57732. int nOvfl;
  57733. u32 ovflPageSize;
  57734. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57735. pPage->xParseCell(pPage, pCell, &info);
  57736. *pnSize = info.nSize;
  57737. if( info.nLocal==info.nPayload ){
  57738. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  57739. }
  57740. if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
  57741. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  57742. }
  57743. ovflPgno = get4byte(pCell + info.nSize - 4);
  57744. assert( pBt->usableSize > 4 );
  57745. ovflPageSize = pBt->usableSize - 4;
  57746. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  57747. assert( nOvfl>0 ||
  57748. (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
  57749. );
  57750. while( nOvfl-- ){
  57751. Pgno iNext = 0;
  57752. MemPage *pOvfl = 0;
  57753. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  57754. /* 0 is not a legal page number and page 1 cannot be an
  57755. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  57756. ** file the database must be corrupt. */
  57757. return SQLITE_CORRUPT_BKPT;
  57758. }
  57759. if( nOvfl ){
  57760. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  57761. if( rc ) return rc;
  57762. }
  57763. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  57764. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  57765. ){
  57766. /* There is no reason any cursor should have an outstanding reference
  57767. ** to an overflow page belonging to a cell that is being deleted/updated.
  57768. ** So if there exists more than one reference to this page, then it
  57769. ** must not really be an overflow page and the database must be corrupt.
  57770. ** It is helpful to detect this before calling freePage2(), as
  57771. ** freePage2() may zero the page contents if secure-delete mode is
  57772. ** enabled. If this 'overflow' page happens to be a page that the
  57773. ** caller is iterating through or using in some other way, this
  57774. ** can be problematic.
  57775. */
  57776. rc = SQLITE_CORRUPT_BKPT;
  57777. }else{
  57778. rc = freePage2(pBt, pOvfl, ovflPgno);
  57779. }
  57780. if( pOvfl ){
  57781. sqlite3PagerUnref(pOvfl->pDbPage);
  57782. }
  57783. if( rc ) return rc;
  57784. ovflPgno = iNext;
  57785. }
  57786. return SQLITE_OK;
  57787. }
  57788. /*
  57789. ** Create the byte sequence used to represent a cell on page pPage
  57790. ** and write that byte sequence into pCell[]. Overflow pages are
  57791. ** allocated and filled in as necessary. The calling procedure
  57792. ** is responsible for making sure sufficient space has been allocated
  57793. ** for pCell[].
  57794. **
  57795. ** Note that pCell does not necessary need to point to the pPage->aData
  57796. ** area. pCell might point to some temporary storage. The cell will
  57797. ** be constructed in this temporary area then copied into pPage->aData
  57798. ** later.
  57799. */
  57800. static int fillInCell(
  57801. MemPage *pPage, /* The page that contains the cell */
  57802. unsigned char *pCell, /* Complete text of the cell */
  57803. const void *pKey, i64 nKey, /* The key */
  57804. const void *pData,int nData, /* The data */
  57805. int nZero, /* Extra zero bytes to append to pData */
  57806. int *pnSize /* Write cell size here */
  57807. ){
  57808. int nPayload;
  57809. const u8 *pSrc;
  57810. int nSrc, n, rc;
  57811. int spaceLeft;
  57812. MemPage *pOvfl = 0;
  57813. MemPage *pToRelease = 0;
  57814. unsigned char *pPrior;
  57815. unsigned char *pPayload;
  57816. BtShared *pBt = pPage->pBt;
  57817. Pgno pgnoOvfl = 0;
  57818. int nHeader;
  57819. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57820. /* pPage is not necessarily writeable since pCell might be auxiliary
  57821. ** buffer space that is separate from the pPage buffer area */
  57822. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  57823. || sqlite3PagerIswriteable(pPage->pDbPage) );
  57824. /* Fill in the header. */
  57825. nHeader = pPage->childPtrSize;
  57826. nPayload = nData + nZero;
  57827. if( pPage->intKeyLeaf ){
  57828. nHeader += putVarint32(&pCell[nHeader], nPayload);
  57829. }else{
  57830. assert( nData==0 );
  57831. assert( nZero==0 );
  57832. }
  57833. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  57834. /* Fill in the payload size */
  57835. if( pPage->intKey ){
  57836. pSrc = pData;
  57837. nSrc = nData;
  57838. nData = 0;
  57839. }else{
  57840. assert( nKey<=0x7fffffff && pKey!=0 );
  57841. nPayload = (int)nKey;
  57842. pSrc = pKey;
  57843. nSrc = (int)nKey;
  57844. }
  57845. if( nPayload<=pPage->maxLocal ){
  57846. n = nHeader + nPayload;
  57847. testcase( n==3 );
  57848. testcase( n==4 );
  57849. if( n<4 ) n = 4;
  57850. *pnSize = n;
  57851. spaceLeft = nPayload;
  57852. pPrior = pCell;
  57853. }else{
  57854. int mn = pPage->minLocal;
  57855. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  57856. testcase( n==pPage->maxLocal );
  57857. testcase( n==pPage->maxLocal+1 );
  57858. if( n > pPage->maxLocal ) n = mn;
  57859. spaceLeft = n;
  57860. *pnSize = n + nHeader + 4;
  57861. pPrior = &pCell[nHeader+n];
  57862. }
  57863. pPayload = &pCell[nHeader];
  57864. /* At this point variables should be set as follows:
  57865. **
  57866. ** nPayload Total payload size in bytes
  57867. ** pPayload Begin writing payload here
  57868. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  57869. ** that means content must spill into overflow pages.
  57870. ** *pnSize Size of the local cell (not counting overflow pages)
  57871. ** pPrior Where to write the pgno of the first overflow page
  57872. **
  57873. ** Use a call to btreeParseCellPtr() to verify that the values above
  57874. ** were computed correctly.
  57875. */
  57876. #if SQLITE_DEBUG
  57877. {
  57878. CellInfo info;
  57879. pPage->xParseCell(pPage, pCell, &info);
  57880. assert( nHeader==(int)(info.pPayload - pCell) );
  57881. assert( info.nKey==nKey );
  57882. assert( *pnSize == info.nSize );
  57883. assert( spaceLeft == info.nLocal );
  57884. }
  57885. #endif
  57886. /* Write the payload into the local Cell and any extra into overflow pages */
  57887. while( nPayload>0 ){
  57888. if( spaceLeft==0 ){
  57889. #ifndef SQLITE_OMIT_AUTOVACUUM
  57890. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  57891. if( pBt->autoVacuum ){
  57892. do{
  57893. pgnoOvfl++;
  57894. } while(
  57895. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  57896. );
  57897. }
  57898. #endif
  57899. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  57900. #ifndef SQLITE_OMIT_AUTOVACUUM
  57901. /* If the database supports auto-vacuum, and the second or subsequent
  57902. ** overflow page is being allocated, add an entry to the pointer-map
  57903. ** for that page now.
  57904. **
  57905. ** If this is the first overflow page, then write a partial entry
  57906. ** to the pointer-map. If we write nothing to this pointer-map slot,
  57907. ** then the optimistic overflow chain processing in clearCell()
  57908. ** may misinterpret the uninitialized values and delete the
  57909. ** wrong pages from the database.
  57910. */
  57911. if( pBt->autoVacuum && rc==SQLITE_OK ){
  57912. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  57913. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  57914. if( rc ){
  57915. releasePage(pOvfl);
  57916. }
  57917. }
  57918. #endif
  57919. if( rc ){
  57920. releasePage(pToRelease);
  57921. return rc;
  57922. }
  57923. /* If pToRelease is not zero than pPrior points into the data area
  57924. ** of pToRelease. Make sure pToRelease is still writeable. */
  57925. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  57926. /* If pPrior is part of the data area of pPage, then make sure pPage
  57927. ** is still writeable */
  57928. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  57929. || sqlite3PagerIswriteable(pPage->pDbPage) );
  57930. put4byte(pPrior, pgnoOvfl);
  57931. releasePage(pToRelease);
  57932. pToRelease = pOvfl;
  57933. pPrior = pOvfl->aData;
  57934. put4byte(pPrior, 0);
  57935. pPayload = &pOvfl->aData[4];
  57936. spaceLeft = pBt->usableSize - 4;
  57937. }
  57938. n = nPayload;
  57939. if( n>spaceLeft ) n = spaceLeft;
  57940. /* If pToRelease is not zero than pPayload points into the data area
  57941. ** of pToRelease. Make sure pToRelease is still writeable. */
  57942. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  57943. /* If pPayload is part of the data area of pPage, then make sure pPage
  57944. ** is still writeable */
  57945. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  57946. || sqlite3PagerIswriteable(pPage->pDbPage) );
  57947. if( nSrc>0 ){
  57948. if( n>nSrc ) n = nSrc;
  57949. assert( pSrc );
  57950. memcpy(pPayload, pSrc, n);
  57951. }else{
  57952. memset(pPayload, 0, n);
  57953. }
  57954. nPayload -= n;
  57955. pPayload += n;
  57956. pSrc += n;
  57957. nSrc -= n;
  57958. spaceLeft -= n;
  57959. if( nSrc==0 ){
  57960. nSrc = nData;
  57961. pSrc = pData;
  57962. }
  57963. }
  57964. releasePage(pToRelease);
  57965. return SQLITE_OK;
  57966. }
  57967. /*
  57968. ** Remove the i-th cell from pPage. This routine effects pPage only.
  57969. ** The cell content is not freed or deallocated. It is assumed that
  57970. ** the cell content has been copied someplace else. This routine just
  57971. ** removes the reference to the cell from pPage.
  57972. **
  57973. ** "sz" must be the number of bytes in the cell.
  57974. */
  57975. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  57976. u32 pc; /* Offset to cell content of cell being deleted */
  57977. u8 *data; /* pPage->aData */
  57978. u8 *ptr; /* Used to move bytes around within data[] */
  57979. int rc; /* The return code */
  57980. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  57981. if( *pRC ) return;
  57982. assert( idx>=0 && idx<pPage->nCell );
  57983. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  57984. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57985. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57986. data = pPage->aData;
  57987. ptr = &pPage->aCellIdx[2*idx];
  57988. pc = get2byte(ptr);
  57989. hdr = pPage->hdrOffset;
  57990. testcase( pc==get2byte(&data[hdr+5]) );
  57991. testcase( pc+sz==pPage->pBt->usableSize );
  57992. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  57993. *pRC = SQLITE_CORRUPT_BKPT;
  57994. return;
  57995. }
  57996. rc = freeSpace(pPage, pc, sz);
  57997. if( rc ){
  57998. *pRC = rc;
  57999. return;
  58000. }
  58001. pPage->nCell--;
  58002. if( pPage->nCell==0 ){
  58003. memset(&data[hdr+1], 0, 4);
  58004. data[hdr+7] = 0;
  58005. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  58006. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  58007. - pPage->childPtrSize - 8;
  58008. }else{
  58009. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  58010. put2byte(&data[hdr+3], pPage->nCell);
  58011. pPage->nFree += 2;
  58012. }
  58013. }
  58014. /*
  58015. ** Insert a new cell on pPage at cell index "i". pCell points to the
  58016. ** content of the cell.
  58017. **
  58018. ** If the cell content will fit on the page, then put it there. If it
  58019. ** will not fit, then make a copy of the cell content into pTemp if
  58020. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  58021. ** in pPage->apOvfl[] and make it point to the cell content (either
  58022. ** in pTemp or the original pCell) and also record its index.
  58023. ** Allocating a new entry in pPage->aCell[] implies that
  58024. ** pPage->nOverflow is incremented.
  58025. */
  58026. static void insertCell(
  58027. MemPage *pPage, /* Page into which we are copying */
  58028. int i, /* New cell becomes the i-th cell of the page */
  58029. u8 *pCell, /* Content of the new cell */
  58030. int sz, /* Bytes of content in pCell */
  58031. u8 *pTemp, /* Temp storage space for pCell, if needed */
  58032. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  58033. int *pRC /* Read and write return code from here */
  58034. ){
  58035. int idx = 0; /* Where to write new cell content in data[] */
  58036. int j; /* Loop counter */
  58037. u8 *data; /* The content of the whole page */
  58038. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  58039. if( *pRC ) return;
  58040. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  58041. assert( MX_CELL(pPage->pBt)<=10921 );
  58042. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  58043. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  58044. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  58045. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58046. /* The cell should normally be sized correctly. However, when moving a
  58047. ** malformed cell from a leaf page to an interior page, if the cell size
  58048. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  58049. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  58050. ** the term after the || in the following assert(). */
  58051. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  58052. if( pPage->nOverflow || sz+2>pPage->nFree ){
  58053. if( pTemp ){
  58054. memcpy(pTemp, pCell, sz);
  58055. pCell = pTemp;
  58056. }
  58057. if( iChild ){
  58058. put4byte(pCell, iChild);
  58059. }
  58060. j = pPage->nOverflow++;
  58061. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  58062. pPage->apOvfl[j] = pCell;
  58063. pPage->aiOvfl[j] = (u16)i;
  58064. /* When multiple overflows occur, they are always sequential and in
  58065. ** sorted order. This invariants arise because multiple overflows can
  58066. ** only occur when inserting divider cells into the parent page during
  58067. ** balancing, and the dividers are adjacent and sorted.
  58068. */
  58069. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  58070. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  58071. }else{
  58072. int rc = sqlite3PagerWrite(pPage->pDbPage);
  58073. if( rc!=SQLITE_OK ){
  58074. *pRC = rc;
  58075. return;
  58076. }
  58077. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  58078. data = pPage->aData;
  58079. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  58080. rc = allocateSpace(pPage, sz, &idx);
  58081. if( rc ){ *pRC = rc; return; }
  58082. /* The allocateSpace() routine guarantees the following properties
  58083. ** if it returns successfully */
  58084. assert( idx >= 0 );
  58085. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  58086. assert( idx+sz <= (int)pPage->pBt->usableSize );
  58087. pPage->nFree -= (u16)(2 + sz);
  58088. memcpy(&data[idx], pCell, sz);
  58089. if( iChild ){
  58090. put4byte(&data[idx], iChild);
  58091. }
  58092. pIns = pPage->aCellIdx + i*2;
  58093. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  58094. put2byte(pIns, idx);
  58095. pPage->nCell++;
  58096. /* increment the cell count */
  58097. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  58098. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  58099. #ifndef SQLITE_OMIT_AUTOVACUUM
  58100. if( pPage->pBt->autoVacuum ){
  58101. /* The cell may contain a pointer to an overflow page. If so, write
  58102. ** the entry for the overflow page into the pointer map.
  58103. */
  58104. ptrmapPutOvflPtr(pPage, pCell, pRC);
  58105. }
  58106. #endif
  58107. }
  58108. }
  58109. /*
  58110. ** A CellArray object contains a cache of pointers and sizes for a
  58111. ** consecutive sequence of cells that might be held multiple pages.
  58112. */
  58113. typedef struct CellArray CellArray;
  58114. struct CellArray {
  58115. int nCell; /* Number of cells in apCell[] */
  58116. MemPage *pRef; /* Reference page */
  58117. u8 **apCell; /* All cells begin balanced */
  58118. u16 *szCell; /* Local size of all cells in apCell[] */
  58119. };
  58120. /*
  58121. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  58122. ** computed.
  58123. */
  58124. static void populateCellCache(CellArray *p, int idx, int N){
  58125. assert( idx>=0 && idx+N<=p->nCell );
  58126. while( N>0 ){
  58127. assert( p->apCell[idx]!=0 );
  58128. if( p->szCell[idx]==0 ){
  58129. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  58130. }else{
  58131. assert( CORRUPT_DB ||
  58132. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  58133. }
  58134. idx++;
  58135. N--;
  58136. }
  58137. }
  58138. /*
  58139. ** Return the size of the Nth element of the cell array
  58140. */
  58141. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  58142. assert( N>=0 && N<p->nCell );
  58143. assert( p->szCell[N]==0 );
  58144. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  58145. return p->szCell[N];
  58146. }
  58147. static u16 cachedCellSize(CellArray *p, int N){
  58148. assert( N>=0 && N<p->nCell );
  58149. if( p->szCell[N] ) return p->szCell[N];
  58150. return computeCellSize(p, N);
  58151. }
  58152. /*
  58153. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  58154. ** szCell[] array contains the size in bytes of each cell. This function
  58155. ** replaces the current contents of page pPg with the contents of the cell
  58156. ** array.
  58157. **
  58158. ** Some of the cells in apCell[] may currently be stored in pPg. This
  58159. ** function works around problems caused by this by making a copy of any
  58160. ** such cells before overwriting the page data.
  58161. **
  58162. ** The MemPage.nFree field is invalidated by this function. It is the
  58163. ** responsibility of the caller to set it correctly.
  58164. */
  58165. static int rebuildPage(
  58166. MemPage *pPg, /* Edit this page */
  58167. int nCell, /* Final number of cells on page */
  58168. u8 **apCell, /* Array of cells */
  58169. u16 *szCell /* Array of cell sizes */
  58170. ){
  58171. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  58172. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  58173. const int usableSize = pPg->pBt->usableSize;
  58174. u8 * const pEnd = &aData[usableSize];
  58175. int i;
  58176. u8 *pCellptr = pPg->aCellIdx;
  58177. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  58178. u8 *pData;
  58179. i = get2byte(&aData[hdr+5]);
  58180. memcpy(&pTmp[i], &aData[i], usableSize - i);
  58181. pData = pEnd;
  58182. for(i=0; i<nCell; i++){
  58183. u8 *pCell = apCell[i];
  58184. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  58185. pCell = &pTmp[pCell - aData];
  58186. }
  58187. pData -= szCell[i];
  58188. put2byte(pCellptr, (pData - aData));
  58189. pCellptr += 2;
  58190. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  58191. memcpy(pData, pCell, szCell[i]);
  58192. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  58193. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  58194. }
  58195. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  58196. pPg->nCell = nCell;
  58197. pPg->nOverflow = 0;
  58198. put2byte(&aData[hdr+1], 0);
  58199. put2byte(&aData[hdr+3], pPg->nCell);
  58200. put2byte(&aData[hdr+5], pData - aData);
  58201. aData[hdr+7] = 0x00;
  58202. return SQLITE_OK;
  58203. }
  58204. /*
  58205. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  58206. ** contains the size in bytes of each such cell. This function attempts to
  58207. ** add the cells stored in the array to page pPg. If it cannot (because
  58208. ** the page needs to be defragmented before the cells will fit), non-zero
  58209. ** is returned. Otherwise, if the cells are added successfully, zero is
  58210. ** returned.
  58211. **
  58212. ** Argument pCellptr points to the first entry in the cell-pointer array
  58213. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  58214. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  58215. ** cell in the array. It is the responsibility of the caller to ensure
  58216. ** that it is safe to overwrite this part of the cell-pointer array.
  58217. **
  58218. ** When this function is called, *ppData points to the start of the
  58219. ** content area on page pPg. If the size of the content area is extended,
  58220. ** *ppData is updated to point to the new start of the content area
  58221. ** before returning.
  58222. **
  58223. ** Finally, argument pBegin points to the byte immediately following the
  58224. ** end of the space required by this page for the cell-pointer area (for
  58225. ** all cells - not just those inserted by the current call). If the content
  58226. ** area must be extended to before this point in order to accomodate all
  58227. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  58228. */
  58229. static int pageInsertArray(
  58230. MemPage *pPg, /* Page to add cells to */
  58231. u8 *pBegin, /* End of cell-pointer array */
  58232. u8 **ppData, /* IN/OUT: Page content -area pointer */
  58233. u8 *pCellptr, /* Pointer to cell-pointer area */
  58234. int iFirst, /* Index of first cell to add */
  58235. int nCell, /* Number of cells to add to pPg */
  58236. CellArray *pCArray /* Array of cells */
  58237. ){
  58238. int i;
  58239. u8 *aData = pPg->aData;
  58240. u8 *pData = *ppData;
  58241. int iEnd = iFirst + nCell;
  58242. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  58243. for(i=iFirst; i<iEnd; i++){
  58244. int sz, rc;
  58245. u8 *pSlot;
  58246. sz = cachedCellSize(pCArray, i);
  58247. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  58248. pData -= sz;
  58249. if( pData<pBegin ) return 1;
  58250. pSlot = pData;
  58251. }
  58252. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  58253. ** database. But they might for a corrupt database. Hence use memmove()
  58254. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  58255. assert( (pSlot+sz)<=pCArray->apCell[i]
  58256. || pSlot>=(pCArray->apCell[i]+sz)
  58257. || CORRUPT_DB );
  58258. memmove(pSlot, pCArray->apCell[i], sz);
  58259. put2byte(pCellptr, (pSlot - aData));
  58260. pCellptr += 2;
  58261. }
  58262. *ppData = pData;
  58263. return 0;
  58264. }
  58265. /*
  58266. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  58267. ** contains the size in bytes of each such cell. This function adds the
  58268. ** space associated with each cell in the array that is currently stored
  58269. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  58270. ** fields of the page are not updated.
  58271. **
  58272. ** This function returns the total number of cells added to the free-list.
  58273. */
  58274. static int pageFreeArray(
  58275. MemPage *pPg, /* Page to edit */
  58276. int iFirst, /* First cell to delete */
  58277. int nCell, /* Cells to delete */
  58278. CellArray *pCArray /* Array of cells */
  58279. ){
  58280. u8 * const aData = pPg->aData;
  58281. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  58282. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  58283. int nRet = 0;
  58284. int i;
  58285. int iEnd = iFirst + nCell;
  58286. u8 *pFree = 0;
  58287. int szFree = 0;
  58288. for(i=iFirst; i<iEnd; i++){
  58289. u8 *pCell = pCArray->apCell[i];
  58290. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  58291. int sz;
  58292. /* No need to use cachedCellSize() here. The sizes of all cells that
  58293. ** are to be freed have already been computing while deciding which
  58294. ** cells need freeing */
  58295. sz = pCArray->szCell[i]; assert( sz>0 );
  58296. if( pFree!=(pCell + sz) ){
  58297. if( pFree ){
  58298. assert( pFree>aData && (pFree - aData)<65536 );
  58299. freeSpace(pPg, (u16)(pFree - aData), szFree);
  58300. }
  58301. pFree = pCell;
  58302. szFree = sz;
  58303. if( pFree+sz>pEnd ) return 0;
  58304. }else{
  58305. pFree = pCell;
  58306. szFree += sz;
  58307. }
  58308. nRet++;
  58309. }
  58310. }
  58311. if( pFree ){
  58312. assert( pFree>aData && (pFree - aData)<65536 );
  58313. freeSpace(pPg, (u16)(pFree - aData), szFree);
  58314. }
  58315. return nRet;
  58316. }
  58317. /*
  58318. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  58319. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  58320. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  58321. ** starting at apCell[iNew].
  58322. **
  58323. ** This routine makes the necessary adjustments to pPg so that it contains
  58324. ** the correct cells after being balanced.
  58325. **
  58326. ** The pPg->nFree field is invalid when this function returns. It is the
  58327. ** responsibility of the caller to set it correctly.
  58328. */
  58329. static int editPage(
  58330. MemPage *pPg, /* Edit this page */
  58331. int iOld, /* Index of first cell currently on page */
  58332. int iNew, /* Index of new first cell on page */
  58333. int nNew, /* Final number of cells on page */
  58334. CellArray *pCArray /* Array of cells and sizes */
  58335. ){
  58336. u8 * const aData = pPg->aData;
  58337. const int hdr = pPg->hdrOffset;
  58338. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  58339. int nCell = pPg->nCell; /* Cells stored on pPg */
  58340. u8 *pData;
  58341. u8 *pCellptr;
  58342. int i;
  58343. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  58344. int iNewEnd = iNew + nNew;
  58345. #ifdef SQLITE_DEBUG
  58346. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  58347. memcpy(pTmp, aData, pPg->pBt->usableSize);
  58348. #endif
  58349. /* Remove cells from the start and end of the page */
  58350. if( iOld<iNew ){
  58351. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  58352. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  58353. nCell -= nShift;
  58354. }
  58355. if( iNewEnd < iOldEnd ){
  58356. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  58357. }
  58358. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  58359. if( pData<pBegin ) goto editpage_fail;
  58360. /* Add cells to the start of the page */
  58361. if( iNew<iOld ){
  58362. int nAdd = MIN(nNew,iOld-iNew);
  58363. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  58364. pCellptr = pPg->aCellIdx;
  58365. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  58366. if( pageInsertArray(
  58367. pPg, pBegin, &pData, pCellptr,
  58368. iNew, nAdd, pCArray
  58369. ) ) goto editpage_fail;
  58370. nCell += nAdd;
  58371. }
  58372. /* Add any overflow cells */
  58373. for(i=0; i<pPg->nOverflow; i++){
  58374. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  58375. if( iCell>=0 && iCell<nNew ){
  58376. pCellptr = &pPg->aCellIdx[iCell * 2];
  58377. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  58378. nCell++;
  58379. if( pageInsertArray(
  58380. pPg, pBegin, &pData, pCellptr,
  58381. iCell+iNew, 1, pCArray
  58382. ) ) goto editpage_fail;
  58383. }
  58384. }
  58385. /* Append cells to the end of the page */
  58386. pCellptr = &pPg->aCellIdx[nCell*2];
  58387. if( pageInsertArray(
  58388. pPg, pBegin, &pData, pCellptr,
  58389. iNew+nCell, nNew-nCell, pCArray
  58390. ) ) goto editpage_fail;
  58391. pPg->nCell = nNew;
  58392. pPg->nOverflow = 0;
  58393. put2byte(&aData[hdr+3], pPg->nCell);
  58394. put2byte(&aData[hdr+5], pData - aData);
  58395. #ifdef SQLITE_DEBUG
  58396. for(i=0; i<nNew && !CORRUPT_DB; i++){
  58397. u8 *pCell = pCArray->apCell[i+iNew];
  58398. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  58399. if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
  58400. pCell = &pTmp[pCell - aData];
  58401. }
  58402. assert( 0==memcmp(pCell, &aData[iOff],
  58403. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  58404. }
  58405. #endif
  58406. return SQLITE_OK;
  58407. editpage_fail:
  58408. /* Unable to edit this page. Rebuild it from scratch instead. */
  58409. populateCellCache(pCArray, iNew, nNew);
  58410. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  58411. }
  58412. /*
  58413. ** The following parameters determine how many adjacent pages get involved
  58414. ** in a balancing operation. NN is the number of neighbors on either side
  58415. ** of the page that participate in the balancing operation. NB is the
  58416. ** total number of pages that participate, including the target page and
  58417. ** NN neighbors on either side.
  58418. **
  58419. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  58420. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  58421. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  58422. ** The value of NN appears to give the best results overall.
  58423. */
  58424. #define NN 1 /* Number of neighbors on either side of pPage */
  58425. #define NB (NN*2+1) /* Total pages involved in the balance */
  58426. #ifndef SQLITE_OMIT_QUICKBALANCE
  58427. /*
  58428. ** This version of balance() handles the common special case where
  58429. ** a new entry is being inserted on the extreme right-end of the
  58430. ** tree, in other words, when the new entry will become the largest
  58431. ** entry in the tree.
  58432. **
  58433. ** Instead of trying to balance the 3 right-most leaf pages, just add
  58434. ** a new page to the right-hand side and put the one new entry in
  58435. ** that page. This leaves the right side of the tree somewhat
  58436. ** unbalanced. But odds are that we will be inserting new entries
  58437. ** at the end soon afterwards so the nearly empty page will quickly
  58438. ** fill up. On average.
  58439. **
  58440. ** pPage is the leaf page which is the right-most page in the tree.
  58441. ** pParent is its parent. pPage must have a single overflow entry
  58442. ** which is also the right-most entry on the page.
  58443. **
  58444. ** The pSpace buffer is used to store a temporary copy of the divider
  58445. ** cell that will be inserted into pParent. Such a cell consists of a 4
  58446. ** byte page number followed by a variable length integer. In other
  58447. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  58448. ** least 13 bytes in size.
  58449. */
  58450. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  58451. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  58452. MemPage *pNew; /* Newly allocated page */
  58453. int rc; /* Return Code */
  58454. Pgno pgnoNew; /* Page number of pNew */
  58455. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58456. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  58457. assert( pPage->nOverflow==1 );
  58458. /* This error condition is now caught prior to reaching this function */
  58459. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  58460. /* Allocate a new page. This page will become the right-sibling of
  58461. ** pPage. Make the parent page writable, so that the new divider cell
  58462. ** may be inserted. If both these operations are successful, proceed.
  58463. */
  58464. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  58465. if( rc==SQLITE_OK ){
  58466. u8 *pOut = &pSpace[4];
  58467. u8 *pCell = pPage->apOvfl[0];
  58468. u16 szCell = pPage->xCellSize(pPage, pCell);
  58469. u8 *pStop;
  58470. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  58471. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  58472. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  58473. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  58474. if( NEVER(rc) ) return rc;
  58475. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  58476. /* If this is an auto-vacuum database, update the pointer map
  58477. ** with entries for the new page, and any pointer from the
  58478. ** cell on the page to an overflow page. If either of these
  58479. ** operations fails, the return code is set, but the contents
  58480. ** of the parent page are still manipulated by thh code below.
  58481. ** That is Ok, at this point the parent page is guaranteed to
  58482. ** be marked as dirty. Returning an error code will cause a
  58483. ** rollback, undoing any changes made to the parent page.
  58484. */
  58485. if( ISAUTOVACUUM ){
  58486. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  58487. if( szCell>pNew->minLocal ){
  58488. ptrmapPutOvflPtr(pNew, pCell, &rc);
  58489. }
  58490. }
  58491. /* Create a divider cell to insert into pParent. The divider cell
  58492. ** consists of a 4-byte page number (the page number of pPage) and
  58493. ** a variable length key value (which must be the same value as the
  58494. ** largest key on pPage).
  58495. **
  58496. ** To find the largest key value on pPage, first find the right-most
  58497. ** cell on pPage. The first two fields of this cell are the
  58498. ** record-length (a variable length integer at most 32-bits in size)
  58499. ** and the key value (a variable length integer, may have any value).
  58500. ** The first of the while(...) loops below skips over the record-length
  58501. ** field. The second while(...) loop copies the key value from the
  58502. ** cell on pPage into the pSpace buffer.
  58503. */
  58504. pCell = findCell(pPage, pPage->nCell-1);
  58505. pStop = &pCell[9];
  58506. while( (*(pCell++)&0x80) && pCell<pStop );
  58507. pStop = &pCell[9];
  58508. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  58509. /* Insert the new divider cell into pParent. */
  58510. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  58511. 0, pPage->pgno, &rc);
  58512. /* Set the right-child pointer of pParent to point to the new page. */
  58513. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  58514. /* Release the reference to the new page. */
  58515. releasePage(pNew);
  58516. }
  58517. return rc;
  58518. }
  58519. #endif /* SQLITE_OMIT_QUICKBALANCE */
  58520. #if 0
  58521. /*
  58522. ** This function does not contribute anything to the operation of SQLite.
  58523. ** it is sometimes activated temporarily while debugging code responsible
  58524. ** for setting pointer-map entries.
  58525. */
  58526. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  58527. int i, j;
  58528. for(i=0; i<nPage; i++){
  58529. Pgno n;
  58530. u8 e;
  58531. MemPage *pPage = apPage[i];
  58532. BtShared *pBt = pPage->pBt;
  58533. assert( pPage->isInit );
  58534. for(j=0; j<pPage->nCell; j++){
  58535. CellInfo info;
  58536. u8 *z;
  58537. z = findCell(pPage, j);
  58538. pPage->xParseCell(pPage, z, &info);
  58539. if( info.nLocal<info.nPayload ){
  58540. Pgno ovfl = get4byte(&z[info.nSize-4]);
  58541. ptrmapGet(pBt, ovfl, &e, &n);
  58542. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  58543. }
  58544. if( !pPage->leaf ){
  58545. Pgno child = get4byte(z);
  58546. ptrmapGet(pBt, child, &e, &n);
  58547. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  58548. }
  58549. }
  58550. if( !pPage->leaf ){
  58551. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  58552. ptrmapGet(pBt, child, &e, &n);
  58553. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  58554. }
  58555. }
  58556. return 1;
  58557. }
  58558. #endif
  58559. /*
  58560. ** This function is used to copy the contents of the b-tree node stored
  58561. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  58562. ** the pointer-map entries for each child page are updated so that the
  58563. ** parent page stored in the pointer map is page pTo. If pFrom contained
  58564. ** any cells with overflow page pointers, then the corresponding pointer
  58565. ** map entries are also updated so that the parent page is page pTo.
  58566. **
  58567. ** If pFrom is currently carrying any overflow cells (entries in the
  58568. ** MemPage.apOvfl[] array), they are not copied to pTo.
  58569. **
  58570. ** Before returning, page pTo is reinitialized using btreeInitPage().
  58571. **
  58572. ** The performance of this function is not critical. It is only used by
  58573. ** the balance_shallower() and balance_deeper() procedures, neither of
  58574. ** which are called often under normal circumstances.
  58575. */
  58576. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  58577. if( (*pRC)==SQLITE_OK ){
  58578. BtShared * const pBt = pFrom->pBt;
  58579. u8 * const aFrom = pFrom->aData;
  58580. u8 * const aTo = pTo->aData;
  58581. int const iFromHdr = pFrom->hdrOffset;
  58582. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  58583. int rc;
  58584. int iData;
  58585. assert( pFrom->isInit );
  58586. assert( pFrom->nFree>=iToHdr );
  58587. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  58588. /* Copy the b-tree node content from page pFrom to page pTo. */
  58589. iData = get2byte(&aFrom[iFromHdr+5]);
  58590. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  58591. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  58592. /* Reinitialize page pTo so that the contents of the MemPage structure
  58593. ** match the new data. The initialization of pTo can actually fail under
  58594. ** fairly obscure circumstances, even though it is a copy of initialized
  58595. ** page pFrom.
  58596. */
  58597. pTo->isInit = 0;
  58598. rc = btreeInitPage(pTo);
  58599. if( rc!=SQLITE_OK ){
  58600. *pRC = rc;
  58601. return;
  58602. }
  58603. /* If this is an auto-vacuum database, update the pointer-map entries
  58604. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  58605. */
  58606. if( ISAUTOVACUUM ){
  58607. *pRC = setChildPtrmaps(pTo);
  58608. }
  58609. }
  58610. }
  58611. /*
  58612. ** This routine redistributes cells on the iParentIdx'th child of pParent
  58613. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  58614. ** same amount of free space. Usually a single sibling on either side of the
  58615. ** page are used in the balancing, though both siblings might come from one
  58616. ** side if the page is the first or last child of its parent. If the page
  58617. ** has fewer than 2 siblings (something which can only happen if the page
  58618. ** is a root page or a child of a root page) then all available siblings
  58619. ** participate in the balancing.
  58620. **
  58621. ** The number of siblings of the page might be increased or decreased by
  58622. ** one or two in an effort to keep pages nearly full but not over full.
  58623. **
  58624. ** Note that when this routine is called, some of the cells on the page
  58625. ** might not actually be stored in MemPage.aData[]. This can happen
  58626. ** if the page is overfull. This routine ensures that all cells allocated
  58627. ** to the page and its siblings fit into MemPage.aData[] before returning.
  58628. **
  58629. ** In the course of balancing the page and its siblings, cells may be
  58630. ** inserted into or removed from the parent page (pParent). Doing so
  58631. ** may cause the parent page to become overfull or underfull. If this
  58632. ** happens, it is the responsibility of the caller to invoke the correct
  58633. ** balancing routine to fix this problem (see the balance() routine).
  58634. **
  58635. ** If this routine fails for any reason, it might leave the database
  58636. ** in a corrupted state. So if this routine fails, the database should
  58637. ** be rolled back.
  58638. **
  58639. ** The third argument to this function, aOvflSpace, is a pointer to a
  58640. ** buffer big enough to hold one page. If while inserting cells into the parent
  58641. ** page (pParent) the parent page becomes overfull, this buffer is
  58642. ** used to store the parent's overflow cells. Because this function inserts
  58643. ** a maximum of four divider cells into the parent page, and the maximum
  58644. ** size of a cell stored within an internal node is always less than 1/4
  58645. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  58646. ** enough for all overflow cells.
  58647. **
  58648. ** If aOvflSpace is set to a null pointer, this function returns
  58649. ** SQLITE_NOMEM.
  58650. */
  58651. static int balance_nonroot(
  58652. MemPage *pParent, /* Parent page of siblings being balanced */
  58653. int iParentIdx, /* Index of "the page" in pParent */
  58654. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  58655. int isRoot, /* True if pParent is a root-page */
  58656. int bBulk /* True if this call is part of a bulk load */
  58657. ){
  58658. BtShared *pBt; /* The whole database */
  58659. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  58660. int nNew = 0; /* Number of pages in apNew[] */
  58661. int nOld; /* Number of pages in apOld[] */
  58662. int i, j, k; /* Loop counters */
  58663. int nxDiv; /* Next divider slot in pParent->aCell[] */
  58664. int rc = SQLITE_OK; /* The return code */
  58665. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  58666. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  58667. int usableSpace; /* Bytes in pPage beyond the header */
  58668. int pageFlags; /* Value of pPage->aData[0] */
  58669. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  58670. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  58671. int szScratch; /* Size of scratch memory requested */
  58672. MemPage *apOld[NB]; /* pPage and up to two siblings */
  58673. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  58674. u8 *pRight; /* Location in parent of right-sibling pointer */
  58675. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  58676. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  58677. int cntOld[NB+2]; /* Old index in b.apCell[] */
  58678. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  58679. u8 *aSpace1; /* Space for copies of dividers cells */
  58680. Pgno pgno; /* Temp var to store a page number in */
  58681. u8 abDone[NB+2]; /* True after i'th new page is populated */
  58682. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  58683. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  58684. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  58685. CellArray b; /* Parsed information on cells being balanced */
  58686. memset(abDone, 0, sizeof(abDone));
  58687. b.nCell = 0;
  58688. b.apCell = 0;
  58689. pBt = pParent->pBt;
  58690. assert( sqlite3_mutex_held(pBt->mutex) );
  58691. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  58692. #if 0
  58693. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  58694. #endif
  58695. /* At this point pParent may have at most one overflow cell. And if
  58696. ** this overflow cell is present, it must be the cell with
  58697. ** index iParentIdx. This scenario comes about when this function
  58698. ** is called (indirectly) from sqlite3BtreeDelete().
  58699. */
  58700. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  58701. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  58702. if( !aOvflSpace ){
  58703. return SQLITE_NOMEM_BKPT;
  58704. }
  58705. /* Find the sibling pages to balance. Also locate the cells in pParent
  58706. ** that divide the siblings. An attempt is made to find NN siblings on
  58707. ** either side of pPage. More siblings are taken from one side, however,
  58708. ** if there are fewer than NN siblings on the other side. If pParent
  58709. ** has NB or fewer children then all children of pParent are taken.
  58710. **
  58711. ** This loop also drops the divider cells from the parent page. This
  58712. ** way, the remainder of the function does not have to deal with any
  58713. ** overflow cells in the parent page, since if any existed they will
  58714. ** have already been removed.
  58715. */
  58716. i = pParent->nOverflow + pParent->nCell;
  58717. if( i<2 ){
  58718. nxDiv = 0;
  58719. }else{
  58720. assert( bBulk==0 || bBulk==1 );
  58721. if( iParentIdx==0 ){
  58722. nxDiv = 0;
  58723. }else if( iParentIdx==i ){
  58724. nxDiv = i-2+bBulk;
  58725. }else{
  58726. nxDiv = iParentIdx-1;
  58727. }
  58728. i = 2-bBulk;
  58729. }
  58730. nOld = i+1;
  58731. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  58732. pRight = &pParent->aData[pParent->hdrOffset+8];
  58733. }else{
  58734. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  58735. }
  58736. pgno = get4byte(pRight);
  58737. while( 1 ){
  58738. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  58739. if( rc ){
  58740. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  58741. goto balance_cleanup;
  58742. }
  58743. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  58744. if( (i--)==0 ) break;
  58745. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  58746. apDiv[i] = pParent->apOvfl[0];
  58747. pgno = get4byte(apDiv[i]);
  58748. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  58749. pParent->nOverflow = 0;
  58750. }else{
  58751. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  58752. pgno = get4byte(apDiv[i]);
  58753. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  58754. /* Drop the cell from the parent page. apDiv[i] still points to
  58755. ** the cell within the parent, even though it has been dropped.
  58756. ** This is safe because dropping a cell only overwrites the first
  58757. ** four bytes of it, and this function does not need the first
  58758. ** four bytes of the divider cell. So the pointer is safe to use
  58759. ** later on.
  58760. **
  58761. ** But not if we are in secure-delete mode. In secure-delete mode,
  58762. ** the dropCell() routine will overwrite the entire cell with zeroes.
  58763. ** In this case, temporarily copy the cell into the aOvflSpace[]
  58764. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  58765. ** is allocated. */
  58766. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  58767. int iOff;
  58768. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  58769. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  58770. rc = SQLITE_CORRUPT_BKPT;
  58771. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  58772. goto balance_cleanup;
  58773. }else{
  58774. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  58775. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  58776. }
  58777. }
  58778. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  58779. }
  58780. }
  58781. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  58782. ** alignment */
  58783. nMaxCells = (nMaxCells + 3)&~3;
  58784. /*
  58785. ** Allocate space for memory structures
  58786. */
  58787. szScratch =
  58788. nMaxCells*sizeof(u8*) /* b.apCell */
  58789. + nMaxCells*sizeof(u16) /* b.szCell */
  58790. + pBt->pageSize; /* aSpace1 */
  58791. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  58792. ** that is more than 6 times the database page size. */
  58793. assert( szScratch<=6*(int)pBt->pageSize );
  58794. b.apCell = sqlite3ScratchMalloc( szScratch );
  58795. if( b.apCell==0 ){
  58796. rc = SQLITE_NOMEM_BKPT;
  58797. goto balance_cleanup;
  58798. }
  58799. b.szCell = (u16*)&b.apCell[nMaxCells];
  58800. aSpace1 = (u8*)&b.szCell[nMaxCells];
  58801. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  58802. /*
  58803. ** Load pointers to all cells on sibling pages and the divider cells
  58804. ** into the local b.apCell[] array. Make copies of the divider cells
  58805. ** into space obtained from aSpace1[]. The divider cells have already
  58806. ** been removed from pParent.
  58807. **
  58808. ** If the siblings are on leaf pages, then the child pointers of the
  58809. ** divider cells are stripped from the cells before they are copied
  58810. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  58811. ** child pointers. If siblings are not leaves, then all cell in
  58812. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  58813. ** are alike.
  58814. **
  58815. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  58816. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  58817. */
  58818. b.pRef = apOld[0];
  58819. leafCorrection = b.pRef->leaf*4;
  58820. leafData = b.pRef->intKeyLeaf;
  58821. for(i=0; i<nOld; i++){
  58822. MemPage *pOld = apOld[i];
  58823. int limit = pOld->nCell;
  58824. u8 *aData = pOld->aData;
  58825. u16 maskPage = pOld->maskPage;
  58826. u8 *piCell = aData + pOld->cellOffset;
  58827. u8 *piEnd;
  58828. /* Verify that all sibling pages are of the same "type" (table-leaf,
  58829. ** table-interior, index-leaf, or index-interior).
  58830. */
  58831. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  58832. rc = SQLITE_CORRUPT_BKPT;
  58833. goto balance_cleanup;
  58834. }
  58835. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  58836. ** constains overflow cells, include them in the b.apCell[] array
  58837. ** in the correct spot.
  58838. **
  58839. ** Note that when there are multiple overflow cells, it is always the
  58840. ** case that they are sequential and adjacent. This invariant arises
  58841. ** because multiple overflows can only occurs when inserting divider
  58842. ** cells into a parent on a prior balance, and divider cells are always
  58843. ** adjacent and are inserted in order. There is an assert() tagged
  58844. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  58845. ** invariant.
  58846. **
  58847. ** This must be done in advance. Once the balance starts, the cell
  58848. ** offset section of the btree page will be overwritten and we will no
  58849. ** long be able to find the cells if a pointer to each cell is not saved
  58850. ** first.
  58851. */
  58852. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  58853. if( pOld->nOverflow>0 ){
  58854. limit = pOld->aiOvfl[0];
  58855. for(j=0; j<limit; j++){
  58856. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  58857. piCell += 2;
  58858. b.nCell++;
  58859. }
  58860. for(k=0; k<pOld->nOverflow; k++){
  58861. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  58862. b.apCell[b.nCell] = pOld->apOvfl[k];
  58863. b.nCell++;
  58864. }
  58865. }
  58866. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  58867. while( piCell<piEnd ){
  58868. assert( b.nCell<nMaxCells );
  58869. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  58870. piCell += 2;
  58871. b.nCell++;
  58872. }
  58873. cntOld[i] = b.nCell;
  58874. if( i<nOld-1 && !leafData){
  58875. u16 sz = (u16)szNew[i];
  58876. u8 *pTemp;
  58877. assert( b.nCell<nMaxCells );
  58878. b.szCell[b.nCell] = sz;
  58879. pTemp = &aSpace1[iSpace1];
  58880. iSpace1 += sz;
  58881. assert( sz<=pBt->maxLocal+23 );
  58882. assert( iSpace1 <= (int)pBt->pageSize );
  58883. memcpy(pTemp, apDiv[i], sz);
  58884. b.apCell[b.nCell] = pTemp+leafCorrection;
  58885. assert( leafCorrection==0 || leafCorrection==4 );
  58886. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  58887. if( !pOld->leaf ){
  58888. assert( leafCorrection==0 );
  58889. assert( pOld->hdrOffset==0 );
  58890. /* The right pointer of the child page pOld becomes the left
  58891. ** pointer of the divider cell */
  58892. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  58893. }else{
  58894. assert( leafCorrection==4 );
  58895. while( b.szCell[b.nCell]<4 ){
  58896. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  58897. ** does exist, pad it with 0x00 bytes. */
  58898. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  58899. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  58900. aSpace1[iSpace1++] = 0x00;
  58901. b.szCell[b.nCell]++;
  58902. }
  58903. }
  58904. b.nCell++;
  58905. }
  58906. }
  58907. /*
  58908. ** Figure out the number of pages needed to hold all b.nCell cells.
  58909. ** Store this number in "k". Also compute szNew[] which is the total
  58910. ** size of all cells on the i-th page and cntNew[] which is the index
  58911. ** in b.apCell[] of the cell that divides page i from page i+1.
  58912. ** cntNew[k] should equal b.nCell.
  58913. **
  58914. ** Values computed by this block:
  58915. **
  58916. ** k: The total number of sibling pages
  58917. ** szNew[i]: Spaced used on the i-th sibling page.
  58918. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  58919. ** the right of the i-th sibling page.
  58920. ** usableSpace: Number of bytes of space available on each sibling.
  58921. **
  58922. */
  58923. usableSpace = pBt->usableSize - 12 + leafCorrection;
  58924. for(i=0; i<nOld; i++){
  58925. MemPage *p = apOld[i];
  58926. szNew[i] = usableSpace - p->nFree;
  58927. if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  58928. for(j=0; j<p->nOverflow; j++){
  58929. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  58930. }
  58931. cntNew[i] = cntOld[i];
  58932. }
  58933. k = nOld;
  58934. for(i=0; i<k; i++){
  58935. int sz;
  58936. while( szNew[i]>usableSpace ){
  58937. if( i+1>=k ){
  58938. k = i+2;
  58939. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  58940. szNew[k-1] = 0;
  58941. cntNew[k-1] = b.nCell;
  58942. }
  58943. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  58944. szNew[i] -= sz;
  58945. if( !leafData ){
  58946. if( cntNew[i]<b.nCell ){
  58947. sz = 2 + cachedCellSize(&b, cntNew[i]);
  58948. }else{
  58949. sz = 0;
  58950. }
  58951. }
  58952. szNew[i+1] += sz;
  58953. cntNew[i]--;
  58954. }
  58955. while( cntNew[i]<b.nCell ){
  58956. sz = 2 + cachedCellSize(&b, cntNew[i]);
  58957. if( szNew[i]+sz>usableSpace ) break;
  58958. szNew[i] += sz;
  58959. cntNew[i]++;
  58960. if( !leafData ){
  58961. if( cntNew[i]<b.nCell ){
  58962. sz = 2 + cachedCellSize(&b, cntNew[i]);
  58963. }else{
  58964. sz = 0;
  58965. }
  58966. }
  58967. szNew[i+1] -= sz;
  58968. }
  58969. if( cntNew[i]>=b.nCell ){
  58970. k = i+1;
  58971. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  58972. rc = SQLITE_CORRUPT_BKPT;
  58973. goto balance_cleanup;
  58974. }
  58975. }
  58976. /*
  58977. ** The packing computed by the previous block is biased toward the siblings
  58978. ** on the left side (siblings with smaller keys). The left siblings are
  58979. ** always nearly full, while the right-most sibling might be nearly empty.
  58980. ** The next block of code attempts to adjust the packing of siblings to
  58981. ** get a better balance.
  58982. **
  58983. ** This adjustment is more than an optimization. The packing above might
  58984. ** be so out of balance as to be illegal. For example, the right-most
  58985. ** sibling might be completely empty. This adjustment is not optional.
  58986. */
  58987. for(i=k-1; i>0; i--){
  58988. int szRight = szNew[i]; /* Size of sibling on the right */
  58989. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  58990. int r; /* Index of right-most cell in left sibling */
  58991. int d; /* Index of first cell to the left of right sibling */
  58992. r = cntNew[i-1] - 1;
  58993. d = r + 1 - leafData;
  58994. (void)cachedCellSize(&b, d);
  58995. do{
  58996. assert( d<nMaxCells );
  58997. assert( r<nMaxCells );
  58998. (void)cachedCellSize(&b, r);
  58999. if( szRight!=0
  59000. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
  59001. break;
  59002. }
  59003. szRight += b.szCell[d] + 2;
  59004. szLeft -= b.szCell[r] + 2;
  59005. cntNew[i-1] = r;
  59006. r--;
  59007. d--;
  59008. }while( r>=0 );
  59009. szNew[i] = szRight;
  59010. szNew[i-1] = szLeft;
  59011. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  59012. rc = SQLITE_CORRUPT_BKPT;
  59013. goto balance_cleanup;
  59014. }
  59015. }
  59016. /* Sanity check: For a non-corrupt database file one of the follwing
  59017. ** must be true:
  59018. ** (1) We found one or more cells (cntNew[0])>0), or
  59019. ** (2) pPage is a virtual root page. A virtual root page is when
  59020. ** the real root page is page 1 and we are the only child of
  59021. ** that page.
  59022. */
  59023. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  59024. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  59025. apOld[0]->pgno, apOld[0]->nCell,
  59026. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  59027. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  59028. ));
  59029. /*
  59030. ** Allocate k new pages. Reuse old pages where possible.
  59031. */
  59032. pageFlags = apOld[0]->aData[0];
  59033. for(i=0; i<k; i++){
  59034. MemPage *pNew;
  59035. if( i<nOld ){
  59036. pNew = apNew[i] = apOld[i];
  59037. apOld[i] = 0;
  59038. rc = sqlite3PagerWrite(pNew->pDbPage);
  59039. nNew++;
  59040. if( rc ) goto balance_cleanup;
  59041. }else{
  59042. assert( i>0 );
  59043. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  59044. if( rc ) goto balance_cleanup;
  59045. zeroPage(pNew, pageFlags);
  59046. apNew[i] = pNew;
  59047. nNew++;
  59048. cntOld[i] = b.nCell;
  59049. /* Set the pointer-map entry for the new sibling page. */
  59050. if( ISAUTOVACUUM ){
  59051. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  59052. if( rc!=SQLITE_OK ){
  59053. goto balance_cleanup;
  59054. }
  59055. }
  59056. }
  59057. }
  59058. /*
  59059. ** Reassign page numbers so that the new pages are in ascending order.
  59060. ** This helps to keep entries in the disk file in order so that a scan
  59061. ** of the table is closer to a linear scan through the file. That in turn
  59062. ** helps the operating system to deliver pages from the disk more rapidly.
  59063. **
  59064. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  59065. ** than (NB+2) (a small constant), that should not be a problem.
  59066. **
  59067. ** When NB==3, this one optimization makes the database about 25% faster
  59068. ** for large insertions and deletions.
  59069. */
  59070. for(i=0; i<nNew; i++){
  59071. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  59072. aPgFlags[i] = apNew[i]->pDbPage->flags;
  59073. for(j=0; j<i; j++){
  59074. if( aPgno[j]==aPgno[i] ){
  59075. /* This branch is taken if the set of sibling pages somehow contains
  59076. ** duplicate entries. This can happen if the database is corrupt.
  59077. ** It would be simpler to detect this as part of the loop below, but
  59078. ** we do the detection here in order to avoid populating the pager
  59079. ** cache with two separate objects associated with the same
  59080. ** page number. */
  59081. assert( CORRUPT_DB );
  59082. rc = SQLITE_CORRUPT_BKPT;
  59083. goto balance_cleanup;
  59084. }
  59085. }
  59086. }
  59087. for(i=0; i<nNew; i++){
  59088. int iBest = 0; /* aPgno[] index of page number to use */
  59089. for(j=1; j<nNew; j++){
  59090. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  59091. }
  59092. pgno = aPgOrder[iBest];
  59093. aPgOrder[iBest] = 0xffffffff;
  59094. if( iBest!=i ){
  59095. if( iBest>i ){
  59096. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  59097. }
  59098. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  59099. apNew[i]->pgno = pgno;
  59100. }
  59101. }
  59102. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  59103. "%d(%d nc=%d) %d(%d nc=%d)\n",
  59104. apNew[0]->pgno, szNew[0], cntNew[0],
  59105. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  59106. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  59107. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  59108. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  59109. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  59110. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  59111. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  59112. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  59113. ));
  59114. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  59115. put4byte(pRight, apNew[nNew-1]->pgno);
  59116. /* If the sibling pages are not leaves, ensure that the right-child pointer
  59117. ** of the right-most new sibling page is set to the value that was
  59118. ** originally in the same field of the right-most old sibling page. */
  59119. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  59120. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  59121. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  59122. }
  59123. /* Make any required updates to pointer map entries associated with
  59124. ** cells stored on sibling pages following the balance operation. Pointer
  59125. ** map entries associated with divider cells are set by the insertCell()
  59126. ** routine. The associated pointer map entries are:
  59127. **
  59128. ** a) if the cell contains a reference to an overflow chain, the
  59129. ** entry associated with the first page in the overflow chain, and
  59130. **
  59131. ** b) if the sibling pages are not leaves, the child page associated
  59132. ** with the cell.
  59133. **
  59134. ** If the sibling pages are not leaves, then the pointer map entry
  59135. ** associated with the right-child of each sibling may also need to be
  59136. ** updated. This happens below, after the sibling pages have been
  59137. ** populated, not here.
  59138. */
  59139. if( ISAUTOVACUUM ){
  59140. MemPage *pNew = apNew[0];
  59141. u8 *aOld = pNew->aData;
  59142. int cntOldNext = pNew->nCell + pNew->nOverflow;
  59143. int usableSize = pBt->usableSize;
  59144. int iNew = 0;
  59145. int iOld = 0;
  59146. for(i=0; i<b.nCell; i++){
  59147. u8 *pCell = b.apCell[i];
  59148. if( i==cntOldNext ){
  59149. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  59150. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  59151. aOld = pOld->aData;
  59152. }
  59153. if( i==cntNew[iNew] ){
  59154. pNew = apNew[++iNew];
  59155. if( !leafData ) continue;
  59156. }
  59157. /* Cell pCell is destined for new sibling page pNew. Originally, it
  59158. ** was either part of sibling page iOld (possibly an overflow cell),
  59159. ** or else the divider cell to the left of sibling page iOld. So,
  59160. ** if sibling page iOld had the same page number as pNew, and if
  59161. ** pCell really was a part of sibling page iOld (not a divider or
  59162. ** overflow cell), we can skip updating the pointer map entries. */
  59163. if( iOld>=nNew
  59164. || pNew->pgno!=aPgno[iOld]
  59165. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  59166. ){
  59167. if( !leafCorrection ){
  59168. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  59169. }
  59170. if( cachedCellSize(&b,i)>pNew->minLocal ){
  59171. ptrmapPutOvflPtr(pNew, pCell, &rc);
  59172. }
  59173. if( rc ) goto balance_cleanup;
  59174. }
  59175. }
  59176. }
  59177. /* Insert new divider cells into pParent. */
  59178. for(i=0; i<nNew-1; i++){
  59179. u8 *pCell;
  59180. u8 *pTemp;
  59181. int sz;
  59182. MemPage *pNew = apNew[i];
  59183. j = cntNew[i];
  59184. assert( j<nMaxCells );
  59185. assert( b.apCell[j]!=0 );
  59186. pCell = b.apCell[j];
  59187. sz = b.szCell[j] + leafCorrection;
  59188. pTemp = &aOvflSpace[iOvflSpace];
  59189. if( !pNew->leaf ){
  59190. memcpy(&pNew->aData[8], pCell, 4);
  59191. }else if( leafData ){
  59192. /* If the tree is a leaf-data tree, and the siblings are leaves,
  59193. ** then there is no divider cell in b.apCell[]. Instead, the divider
  59194. ** cell consists of the integer key for the right-most cell of
  59195. ** the sibling-page assembled above only.
  59196. */
  59197. CellInfo info;
  59198. j--;
  59199. pNew->xParseCell(pNew, b.apCell[j], &info);
  59200. pCell = pTemp;
  59201. sz = 4 + putVarint(&pCell[4], info.nKey);
  59202. pTemp = 0;
  59203. }else{
  59204. pCell -= 4;
  59205. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  59206. ** previously stored on a leaf node, and its reported size was 4
  59207. ** bytes, then it may actually be smaller than this
  59208. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  59209. ** any cell). But it is important to pass the correct size to
  59210. ** insertCell(), so reparse the cell now.
  59211. **
  59212. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  59213. ** and WITHOUT ROWID tables with exactly one column which is the
  59214. ** primary key.
  59215. */
  59216. if( b.szCell[j]==4 ){
  59217. assert(leafCorrection==4);
  59218. sz = pParent->xCellSize(pParent, pCell);
  59219. }
  59220. }
  59221. iOvflSpace += sz;
  59222. assert( sz<=pBt->maxLocal+23 );
  59223. assert( iOvflSpace <= (int)pBt->pageSize );
  59224. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  59225. if( rc!=SQLITE_OK ) goto balance_cleanup;
  59226. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  59227. }
  59228. /* Now update the actual sibling pages. The order in which they are updated
  59229. ** is important, as this code needs to avoid disrupting any page from which
  59230. ** cells may still to be read. In practice, this means:
  59231. **
  59232. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  59233. ** then it is not safe to update page apNew[iPg] until after
  59234. ** the left-hand sibling apNew[iPg-1] has been updated.
  59235. **
  59236. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  59237. ** then it is not safe to update page apNew[iPg] until after
  59238. ** the right-hand sibling apNew[iPg+1] has been updated.
  59239. **
  59240. ** If neither of the above apply, the page is safe to update.
  59241. **
  59242. ** The iPg value in the following loop starts at nNew-1 goes down
  59243. ** to 0, then back up to nNew-1 again, thus making two passes over
  59244. ** the pages. On the initial downward pass, only condition (1) above
  59245. ** needs to be tested because (2) will always be true from the previous
  59246. ** step. On the upward pass, both conditions are always true, so the
  59247. ** upwards pass simply processes pages that were missed on the downward
  59248. ** pass.
  59249. */
  59250. for(i=1-nNew; i<nNew; i++){
  59251. int iPg = i<0 ? -i : i;
  59252. assert( iPg>=0 && iPg<nNew );
  59253. if( abDone[iPg] ) continue; /* Skip pages already processed */
  59254. if( i>=0 /* On the upwards pass, or... */
  59255. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  59256. ){
  59257. int iNew;
  59258. int iOld;
  59259. int nNewCell;
  59260. /* Verify condition (1): If cells are moving left, update iPg
  59261. ** only after iPg-1 has already been updated. */
  59262. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  59263. /* Verify condition (2): If cells are moving right, update iPg
  59264. ** only after iPg+1 has already been updated. */
  59265. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  59266. if( iPg==0 ){
  59267. iNew = iOld = 0;
  59268. nNewCell = cntNew[0];
  59269. }else{
  59270. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  59271. iNew = cntNew[iPg-1] + !leafData;
  59272. nNewCell = cntNew[iPg] - iNew;
  59273. }
  59274. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  59275. if( rc ) goto balance_cleanup;
  59276. abDone[iPg]++;
  59277. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  59278. assert( apNew[iPg]->nOverflow==0 );
  59279. assert( apNew[iPg]->nCell==nNewCell );
  59280. }
  59281. }
  59282. /* All pages have been processed exactly once */
  59283. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  59284. assert( nOld>0 );
  59285. assert( nNew>0 );
  59286. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  59287. /* The root page of the b-tree now contains no cells. The only sibling
  59288. ** page is the right-child of the parent. Copy the contents of the
  59289. ** child page into the parent, decreasing the overall height of the
  59290. ** b-tree structure by one. This is described as the "balance-shallower"
  59291. ** sub-algorithm in some documentation.
  59292. **
  59293. ** If this is an auto-vacuum database, the call to copyNodeContent()
  59294. ** sets all pointer-map entries corresponding to database image pages
  59295. ** for which the pointer is stored within the content being copied.
  59296. **
  59297. ** It is critical that the child page be defragmented before being
  59298. ** copied into the parent, because if the parent is page 1 then it will
  59299. ** by smaller than the child due to the database header, and so all the
  59300. ** free space needs to be up front.
  59301. */
  59302. assert( nNew==1 || CORRUPT_DB );
  59303. rc = defragmentPage(apNew[0]);
  59304. testcase( rc!=SQLITE_OK );
  59305. assert( apNew[0]->nFree ==
  59306. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  59307. || rc!=SQLITE_OK
  59308. );
  59309. copyNodeContent(apNew[0], pParent, &rc);
  59310. freePage(apNew[0], &rc);
  59311. }else if( ISAUTOVACUUM && !leafCorrection ){
  59312. /* Fix the pointer map entries associated with the right-child of each
  59313. ** sibling page. All other pointer map entries have already been taken
  59314. ** care of. */
  59315. for(i=0; i<nNew; i++){
  59316. u32 key = get4byte(&apNew[i]->aData[8]);
  59317. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  59318. }
  59319. }
  59320. assert( pParent->isInit );
  59321. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  59322. nOld, nNew, b.nCell));
  59323. /* Free any old pages that were not reused as new pages.
  59324. */
  59325. for(i=nNew; i<nOld; i++){
  59326. freePage(apOld[i], &rc);
  59327. }
  59328. #if 0
  59329. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  59330. /* The ptrmapCheckPages() contains assert() statements that verify that
  59331. ** all pointer map pages are set correctly. This is helpful while
  59332. ** debugging. This is usually disabled because a corrupt database may
  59333. ** cause an assert() statement to fail. */
  59334. ptrmapCheckPages(apNew, nNew);
  59335. ptrmapCheckPages(&pParent, 1);
  59336. }
  59337. #endif
  59338. /*
  59339. ** Cleanup before returning.
  59340. */
  59341. balance_cleanup:
  59342. sqlite3ScratchFree(b.apCell);
  59343. for(i=0; i<nOld; i++){
  59344. releasePage(apOld[i]);
  59345. }
  59346. for(i=0; i<nNew; i++){
  59347. releasePage(apNew[i]);
  59348. }
  59349. return rc;
  59350. }
  59351. /*
  59352. ** This function is called when the root page of a b-tree structure is
  59353. ** overfull (has one or more overflow pages).
  59354. **
  59355. ** A new child page is allocated and the contents of the current root
  59356. ** page, including overflow cells, are copied into the child. The root
  59357. ** page is then overwritten to make it an empty page with the right-child
  59358. ** pointer pointing to the new page.
  59359. **
  59360. ** Before returning, all pointer-map entries corresponding to pages
  59361. ** that the new child-page now contains pointers to are updated. The
  59362. ** entry corresponding to the new right-child pointer of the root
  59363. ** page is also updated.
  59364. **
  59365. ** If successful, *ppChild is set to contain a reference to the child
  59366. ** page and SQLITE_OK is returned. In this case the caller is required
  59367. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  59368. ** an error code is returned and *ppChild is set to 0.
  59369. */
  59370. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  59371. int rc; /* Return value from subprocedures */
  59372. MemPage *pChild = 0; /* Pointer to a new child page */
  59373. Pgno pgnoChild = 0; /* Page number of the new child page */
  59374. BtShared *pBt = pRoot->pBt; /* The BTree */
  59375. assert( pRoot->nOverflow>0 );
  59376. assert( sqlite3_mutex_held(pBt->mutex) );
  59377. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  59378. ** page that will become the new right-child of pPage. Copy the contents
  59379. ** of the node stored on pRoot into the new child page.
  59380. */
  59381. rc = sqlite3PagerWrite(pRoot->pDbPage);
  59382. if( rc==SQLITE_OK ){
  59383. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  59384. copyNodeContent(pRoot, pChild, &rc);
  59385. if( ISAUTOVACUUM ){
  59386. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  59387. }
  59388. }
  59389. if( rc ){
  59390. *ppChild = 0;
  59391. releasePage(pChild);
  59392. return rc;
  59393. }
  59394. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  59395. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  59396. assert( pChild->nCell==pRoot->nCell );
  59397. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  59398. /* Copy the overflow cells from pRoot to pChild */
  59399. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  59400. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  59401. memcpy(pChild->apOvfl, pRoot->apOvfl,
  59402. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  59403. pChild->nOverflow = pRoot->nOverflow;
  59404. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  59405. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  59406. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  59407. *ppChild = pChild;
  59408. return SQLITE_OK;
  59409. }
  59410. /*
  59411. ** The page that pCur currently points to has just been modified in
  59412. ** some way. This function figures out if this modification means the
  59413. ** tree needs to be balanced, and if so calls the appropriate balancing
  59414. ** routine. Balancing routines are:
  59415. **
  59416. ** balance_quick()
  59417. ** balance_deeper()
  59418. ** balance_nonroot()
  59419. */
  59420. static int balance(BtCursor *pCur){
  59421. int rc = SQLITE_OK;
  59422. const int nMin = pCur->pBt->usableSize * 2 / 3;
  59423. u8 aBalanceQuickSpace[13];
  59424. u8 *pFree = 0;
  59425. VVA_ONLY( int balance_quick_called = 0 );
  59426. VVA_ONLY( int balance_deeper_called = 0 );
  59427. do {
  59428. int iPage = pCur->iPage;
  59429. MemPage *pPage = pCur->apPage[iPage];
  59430. if( iPage==0 ){
  59431. if( pPage->nOverflow ){
  59432. /* The root page of the b-tree is overfull. In this case call the
  59433. ** balance_deeper() function to create a new child for the root-page
  59434. ** and copy the current contents of the root-page to it. The
  59435. ** next iteration of the do-loop will balance the child page.
  59436. */
  59437. assert( balance_deeper_called==0 );
  59438. VVA_ONLY( balance_deeper_called++ );
  59439. rc = balance_deeper(pPage, &pCur->apPage[1]);
  59440. if( rc==SQLITE_OK ){
  59441. pCur->iPage = 1;
  59442. pCur->aiIdx[0] = 0;
  59443. pCur->aiIdx[1] = 0;
  59444. assert( pCur->apPage[1]->nOverflow );
  59445. }
  59446. }else{
  59447. break;
  59448. }
  59449. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  59450. break;
  59451. }else{
  59452. MemPage * const pParent = pCur->apPage[iPage-1];
  59453. int const iIdx = pCur->aiIdx[iPage-1];
  59454. rc = sqlite3PagerWrite(pParent->pDbPage);
  59455. if( rc==SQLITE_OK ){
  59456. #ifndef SQLITE_OMIT_QUICKBALANCE
  59457. if( pPage->intKeyLeaf
  59458. && pPage->nOverflow==1
  59459. && pPage->aiOvfl[0]==pPage->nCell
  59460. && pParent->pgno!=1
  59461. && pParent->nCell==iIdx
  59462. ){
  59463. /* Call balance_quick() to create a new sibling of pPage on which
  59464. ** to store the overflow cell. balance_quick() inserts a new cell
  59465. ** into pParent, which may cause pParent overflow. If this
  59466. ** happens, the next iteration of the do-loop will balance pParent
  59467. ** use either balance_nonroot() or balance_deeper(). Until this
  59468. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  59469. ** buffer.
  59470. **
  59471. ** The purpose of the following assert() is to check that only a
  59472. ** single call to balance_quick() is made for each call to this
  59473. ** function. If this were not verified, a subtle bug involving reuse
  59474. ** of the aBalanceQuickSpace[] might sneak in.
  59475. */
  59476. assert( balance_quick_called==0 );
  59477. VVA_ONLY( balance_quick_called++ );
  59478. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  59479. }else
  59480. #endif
  59481. {
  59482. /* In this case, call balance_nonroot() to redistribute cells
  59483. ** between pPage and up to 2 of its sibling pages. This involves
  59484. ** modifying the contents of pParent, which may cause pParent to
  59485. ** become overfull or underfull. The next iteration of the do-loop
  59486. ** will balance the parent page to correct this.
  59487. **
  59488. ** If the parent page becomes overfull, the overflow cell or cells
  59489. ** are stored in the pSpace buffer allocated immediately below.
  59490. ** A subsequent iteration of the do-loop will deal with this by
  59491. ** calling balance_nonroot() (balance_deeper() may be called first,
  59492. ** but it doesn't deal with overflow cells - just moves them to a
  59493. ** different page). Once this subsequent call to balance_nonroot()
  59494. ** has completed, it is safe to release the pSpace buffer used by
  59495. ** the previous call, as the overflow cell data will have been
  59496. ** copied either into the body of a database page or into the new
  59497. ** pSpace buffer passed to the latter call to balance_nonroot().
  59498. */
  59499. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  59500. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  59501. pCur->hints&BTREE_BULKLOAD);
  59502. if( pFree ){
  59503. /* If pFree is not NULL, it points to the pSpace buffer used
  59504. ** by a previous call to balance_nonroot(). Its contents are
  59505. ** now stored either on real database pages or within the
  59506. ** new pSpace buffer, so it may be safely freed here. */
  59507. sqlite3PageFree(pFree);
  59508. }
  59509. /* The pSpace buffer will be freed after the next call to
  59510. ** balance_nonroot(), or just before this function returns, whichever
  59511. ** comes first. */
  59512. pFree = pSpace;
  59513. }
  59514. }
  59515. pPage->nOverflow = 0;
  59516. /* The next iteration of the do-loop balances the parent page. */
  59517. releasePage(pPage);
  59518. pCur->iPage--;
  59519. assert( pCur->iPage>=0 );
  59520. }
  59521. }while( rc==SQLITE_OK );
  59522. if( pFree ){
  59523. sqlite3PageFree(pFree);
  59524. }
  59525. return rc;
  59526. }
  59527. /*
  59528. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  59529. ** and the data is given by (pData,nData). The cursor is used only to
  59530. ** define what table the record should be inserted into. The cursor
  59531. ** is left pointing at a random location.
  59532. **
  59533. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  59534. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  59535. **
  59536. ** If the seekResult parameter is non-zero, then a successful call to
  59537. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  59538. ** been performed. seekResult is the search result returned (a negative
  59539. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  59540. ** a positive value if pCur points at an entry that is larger than
  59541. ** (pKey, nKey)).
  59542. **
  59543. ** If the seekResult parameter is non-zero, then the caller guarantees that
  59544. ** cursor pCur is pointing at the existing copy of a row that is to be
  59545. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  59546. ** point to any entry or to no entry at all and so this function has to seek
  59547. ** the cursor before the new key can be inserted.
  59548. */
  59549. SQLITE_PRIVATE int sqlite3BtreeInsert(
  59550. BtCursor *pCur, /* Insert data into the table of this cursor */
  59551. const void *pKey, i64 nKey, /* The key of the new record */
  59552. const void *pData, int nData, /* The data of the new record */
  59553. int nZero, /* Number of extra 0 bytes to append to data */
  59554. int appendBias, /* True if this is likely an append */
  59555. int seekResult /* Result of prior MovetoUnpacked() call */
  59556. ){
  59557. int rc;
  59558. int loc = seekResult; /* -1: before desired location +1: after */
  59559. int szNew = 0;
  59560. int idx;
  59561. MemPage *pPage;
  59562. Btree *p = pCur->pBtree;
  59563. BtShared *pBt = p->pBt;
  59564. unsigned char *oldCell;
  59565. unsigned char *newCell = 0;
  59566. if( pCur->eState==CURSOR_FAULT ){
  59567. assert( pCur->skipNext!=SQLITE_OK );
  59568. return pCur->skipNext;
  59569. }
  59570. assert( cursorOwnsBtShared(pCur) );
  59571. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  59572. && pBt->inTransaction==TRANS_WRITE
  59573. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59574. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  59575. /* Assert that the caller has been consistent. If this cursor was opened
  59576. ** expecting an index b-tree, then the caller should be inserting blob
  59577. ** keys with no associated data. If the cursor was opened expecting an
  59578. ** intkey table, the caller should be inserting integer keys with a
  59579. ** blob of associated data. */
  59580. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  59581. /* Save the positions of any other cursors open on this table.
  59582. **
  59583. ** In some cases, the call to btreeMoveto() below is a no-op. For
  59584. ** example, when inserting data into a table with auto-generated integer
  59585. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  59586. ** integer key to use. It then calls this function to actually insert the
  59587. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  59588. ** that the cursor is already where it needs to be and returns without
  59589. ** doing any work. To avoid thwarting these optimizations, it is important
  59590. ** not to clear the cursor here.
  59591. */
  59592. if( pCur->curFlags & BTCF_Multiple ){
  59593. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  59594. if( rc ) return rc;
  59595. }
  59596. if( pCur->pKeyInfo==0 ){
  59597. assert( pKey==0 );
  59598. /* If this is an insert into a table b-tree, invalidate any incrblob
  59599. ** cursors open on the row being replaced */
  59600. invalidateIncrblobCursors(p, nKey, 0);
  59601. /* If the cursor is currently on the last row and we are appending a
  59602. ** new row onto the end, set the "loc" to avoid an unnecessary
  59603. ** btreeMoveto() call */
  59604. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  59605. && pCur->info.nKey==nKey-1 ){
  59606. loc = -1;
  59607. }else if( loc==0 ){
  59608. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
  59609. if( rc ) return rc;
  59610. }
  59611. }else if( loc==0 ){
  59612. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  59613. if( rc ) return rc;
  59614. }
  59615. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  59616. pPage = pCur->apPage[pCur->iPage];
  59617. assert( pPage->intKey || nKey>=0 );
  59618. assert( pPage->leaf || !pPage->intKey );
  59619. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  59620. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  59621. loc==0 ? "overwrite" : "new entry"));
  59622. assert( pPage->isInit );
  59623. newCell = pBt->pTmpSpace;
  59624. assert( newCell!=0 );
  59625. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  59626. if( rc ) goto end_insert;
  59627. assert( szNew==pPage->xCellSize(pPage, newCell) );
  59628. assert( szNew <= MX_CELL_SIZE(pBt) );
  59629. idx = pCur->aiIdx[pCur->iPage];
  59630. if( loc==0 ){
  59631. u16 szOld;
  59632. assert( idx<pPage->nCell );
  59633. rc = sqlite3PagerWrite(pPage->pDbPage);
  59634. if( rc ){
  59635. goto end_insert;
  59636. }
  59637. oldCell = findCell(pPage, idx);
  59638. if( !pPage->leaf ){
  59639. memcpy(newCell, oldCell, 4);
  59640. }
  59641. rc = clearCell(pPage, oldCell, &szOld);
  59642. dropCell(pPage, idx, szOld, &rc);
  59643. if( rc ) goto end_insert;
  59644. }else if( loc<0 && pPage->nCell>0 ){
  59645. assert( pPage->leaf );
  59646. idx = ++pCur->aiIdx[pCur->iPage];
  59647. }else{
  59648. assert( pPage->leaf );
  59649. }
  59650. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  59651. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  59652. /* If no error has occurred and pPage has an overflow cell, call balance()
  59653. ** to redistribute the cells within the tree. Since balance() may move
  59654. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  59655. ** variables.
  59656. **
  59657. ** Previous versions of SQLite called moveToRoot() to move the cursor
  59658. ** back to the root page as balance() used to invalidate the contents
  59659. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  59660. ** set the cursor state to "invalid". This makes common insert operations
  59661. ** slightly faster.
  59662. **
  59663. ** There is a subtle but important optimization here too. When inserting
  59664. ** multiple records into an intkey b-tree using a single cursor (as can
  59665. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  59666. ** is advantageous to leave the cursor pointing to the last entry in
  59667. ** the b-tree if possible. If the cursor is left pointing to the last
  59668. ** entry in the table, and the next row inserted has an integer key
  59669. ** larger than the largest existing key, it is possible to insert the
  59670. ** row without seeking the cursor. This can be a big performance boost.
  59671. */
  59672. pCur->info.nSize = 0;
  59673. if( rc==SQLITE_OK && pPage->nOverflow ){
  59674. pCur->curFlags &= ~(BTCF_ValidNKey);
  59675. rc = balance(pCur);
  59676. /* Must make sure nOverflow is reset to zero even if the balance()
  59677. ** fails. Internal data structure corruption will result otherwise.
  59678. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  59679. ** from trying to save the current position of the cursor. */
  59680. pCur->apPage[pCur->iPage]->nOverflow = 0;
  59681. pCur->eState = CURSOR_INVALID;
  59682. }
  59683. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  59684. end_insert:
  59685. return rc;
  59686. }
  59687. /*
  59688. ** Delete the entry that the cursor is pointing to.
  59689. **
  59690. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  59691. ** the cursor is left pointing at an arbitrary location after the delete.
  59692. ** But if that bit is set, then the cursor is left in a state such that
  59693. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  59694. ** as it would have been on if the call to BtreeDelete() had been omitted.
  59695. **
  59696. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  59697. ** associated with a single table entry and its indexes. Only one of those
  59698. ** deletes is considered the "primary" delete. The primary delete occurs
  59699. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  59700. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  59701. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  59702. ** but which might be used by alternative storage engines.
  59703. */
  59704. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  59705. Btree *p = pCur->pBtree;
  59706. BtShared *pBt = p->pBt;
  59707. int rc; /* Return code */
  59708. MemPage *pPage; /* Page to delete cell from */
  59709. unsigned char *pCell; /* Pointer to cell to delete */
  59710. int iCellIdx; /* Index of cell to delete */
  59711. int iCellDepth; /* Depth of node containing pCell */
  59712. u16 szCell; /* Size of the cell being deleted */
  59713. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  59714. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  59715. assert( cursorOwnsBtShared(pCur) );
  59716. assert( pBt->inTransaction==TRANS_WRITE );
  59717. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59718. assert( pCur->curFlags & BTCF_WriteFlag );
  59719. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  59720. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  59721. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  59722. assert( pCur->eState==CURSOR_VALID );
  59723. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  59724. iCellDepth = pCur->iPage;
  59725. iCellIdx = pCur->aiIdx[iCellDepth];
  59726. pPage = pCur->apPage[iCellDepth];
  59727. pCell = findCell(pPage, iCellIdx);
  59728. /* If the page containing the entry to delete is not a leaf page, move
  59729. ** the cursor to the largest entry in the tree that is smaller than
  59730. ** the entry being deleted. This cell will replace the cell being deleted
  59731. ** from the internal node. The 'previous' entry is used for this instead
  59732. ** of the 'next' entry, as the previous entry is always a part of the
  59733. ** sub-tree headed by the child page of the cell being deleted. This makes
  59734. ** balancing the tree following the delete operation easier. */
  59735. if( !pPage->leaf ){
  59736. int notUsed = 0;
  59737. rc = sqlite3BtreePrevious(pCur, &notUsed);
  59738. if( rc ) return rc;
  59739. }
  59740. /* Save the positions of any other cursors open on this table before
  59741. ** making any modifications. */
  59742. if( pCur->curFlags & BTCF_Multiple ){
  59743. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  59744. if( rc ) return rc;
  59745. }
  59746. /* If this is a delete operation to remove a row from a table b-tree,
  59747. ** invalidate any incrblob cursors open on the row being deleted. */
  59748. if( pCur->pKeyInfo==0 ){
  59749. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  59750. }
  59751. /* If the bPreserve flag is set to true, then the cursor position must
  59752. ** be preserved following this delete operation. If the current delete
  59753. ** will cause a b-tree rebalance, then this is done by saving the cursor
  59754. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  59755. ** returning.
  59756. **
  59757. ** Or, if the current delete will not cause a rebalance, then the cursor
  59758. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  59759. ** before or after the deleted entry. In this case set bSkipnext to true. */
  59760. if( bPreserve ){
  59761. if( !pPage->leaf
  59762. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  59763. ){
  59764. /* A b-tree rebalance will be required after deleting this entry.
  59765. ** Save the cursor key. */
  59766. rc = saveCursorKey(pCur);
  59767. if( rc ) return rc;
  59768. }else{
  59769. bSkipnext = 1;
  59770. }
  59771. }
  59772. /* Make the page containing the entry to be deleted writable. Then free any
  59773. ** overflow pages associated with the entry and finally remove the cell
  59774. ** itself from within the page. */
  59775. rc = sqlite3PagerWrite(pPage->pDbPage);
  59776. if( rc ) return rc;
  59777. rc = clearCell(pPage, pCell, &szCell);
  59778. dropCell(pPage, iCellIdx, szCell, &rc);
  59779. if( rc ) return rc;
  59780. /* If the cell deleted was not located on a leaf page, then the cursor
  59781. ** is currently pointing to the largest entry in the sub-tree headed
  59782. ** by the child-page of the cell that was just deleted from an internal
  59783. ** node. The cell from the leaf node needs to be moved to the internal
  59784. ** node to replace the deleted cell. */
  59785. if( !pPage->leaf ){
  59786. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  59787. int nCell;
  59788. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  59789. unsigned char *pTmp;
  59790. pCell = findCell(pLeaf, pLeaf->nCell-1);
  59791. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  59792. nCell = pLeaf->xCellSize(pLeaf, pCell);
  59793. assert( MX_CELL_SIZE(pBt) >= nCell );
  59794. pTmp = pBt->pTmpSpace;
  59795. assert( pTmp!=0 );
  59796. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  59797. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  59798. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  59799. if( rc ) return rc;
  59800. }
  59801. /* Balance the tree. If the entry deleted was located on a leaf page,
  59802. ** then the cursor still points to that page. In this case the first
  59803. ** call to balance() repairs the tree, and the if(...) condition is
  59804. ** never true.
  59805. **
  59806. ** Otherwise, if the entry deleted was on an internal node page, then
  59807. ** pCur is pointing to the leaf page from which a cell was removed to
  59808. ** replace the cell deleted from the internal node. This is slightly
  59809. ** tricky as the leaf node may be underfull, and the internal node may
  59810. ** be either under or overfull. In this case run the balancing algorithm
  59811. ** on the leaf node first. If the balance proceeds far enough up the
  59812. ** tree that we can be sure that any problem in the internal node has
  59813. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  59814. ** walk the cursor up the tree to the internal node and balance it as
  59815. ** well. */
  59816. rc = balance(pCur);
  59817. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  59818. while( pCur->iPage>iCellDepth ){
  59819. releasePage(pCur->apPage[pCur->iPage--]);
  59820. }
  59821. rc = balance(pCur);
  59822. }
  59823. if( rc==SQLITE_OK ){
  59824. if( bSkipnext ){
  59825. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  59826. assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
  59827. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  59828. pCur->eState = CURSOR_SKIPNEXT;
  59829. if( iCellIdx>=pPage->nCell ){
  59830. pCur->skipNext = -1;
  59831. pCur->aiIdx[iCellDepth] = pPage->nCell-1;
  59832. }else{
  59833. pCur->skipNext = 1;
  59834. }
  59835. }else{
  59836. rc = moveToRoot(pCur);
  59837. if( bPreserve ){
  59838. pCur->eState = CURSOR_REQUIRESEEK;
  59839. }
  59840. }
  59841. }
  59842. return rc;
  59843. }
  59844. /*
  59845. ** Create a new BTree table. Write into *piTable the page
  59846. ** number for the root page of the new table.
  59847. **
  59848. ** The type of type is determined by the flags parameter. Only the
  59849. ** following values of flags are currently in use. Other values for
  59850. ** flags might not work:
  59851. **
  59852. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  59853. ** BTREE_ZERODATA Used for SQL indices
  59854. */
  59855. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  59856. BtShared *pBt = p->pBt;
  59857. MemPage *pRoot;
  59858. Pgno pgnoRoot;
  59859. int rc;
  59860. int ptfFlags; /* Page-type flage for the root page of new table */
  59861. assert( sqlite3BtreeHoldsMutex(p) );
  59862. assert( pBt->inTransaction==TRANS_WRITE );
  59863. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59864. #ifdef SQLITE_OMIT_AUTOVACUUM
  59865. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  59866. if( rc ){
  59867. return rc;
  59868. }
  59869. #else
  59870. if( pBt->autoVacuum ){
  59871. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  59872. MemPage *pPageMove; /* The page to move to. */
  59873. /* Creating a new table may probably require moving an existing database
  59874. ** to make room for the new tables root page. In case this page turns
  59875. ** out to be an overflow page, delete all overflow page-map caches
  59876. ** held by open cursors.
  59877. */
  59878. invalidateAllOverflowCache(pBt);
  59879. /* Read the value of meta[3] from the database to determine where the
  59880. ** root page of the new table should go. meta[3] is the largest root-page
  59881. ** created so far, so the new root-page is (meta[3]+1).
  59882. */
  59883. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  59884. pgnoRoot++;
  59885. /* The new root-page may not be allocated on a pointer-map page, or the
  59886. ** PENDING_BYTE page.
  59887. */
  59888. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  59889. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  59890. pgnoRoot++;
  59891. }
  59892. assert( pgnoRoot>=3 || CORRUPT_DB );
  59893. testcase( pgnoRoot<3 );
  59894. /* Allocate a page. The page that currently resides at pgnoRoot will
  59895. ** be moved to the allocated page (unless the allocated page happens
  59896. ** to reside at pgnoRoot).
  59897. */
  59898. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  59899. if( rc!=SQLITE_OK ){
  59900. return rc;
  59901. }
  59902. if( pgnoMove!=pgnoRoot ){
  59903. /* pgnoRoot is the page that will be used for the root-page of
  59904. ** the new table (assuming an error did not occur). But we were
  59905. ** allocated pgnoMove. If required (i.e. if it was not allocated
  59906. ** by extending the file), the current page at position pgnoMove
  59907. ** is already journaled.
  59908. */
  59909. u8 eType = 0;
  59910. Pgno iPtrPage = 0;
  59911. /* Save the positions of any open cursors. This is required in
  59912. ** case they are holding a reference to an xFetch reference
  59913. ** corresponding to page pgnoRoot. */
  59914. rc = saveAllCursors(pBt, 0, 0);
  59915. releasePage(pPageMove);
  59916. if( rc!=SQLITE_OK ){
  59917. return rc;
  59918. }
  59919. /* Move the page currently at pgnoRoot to pgnoMove. */
  59920. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  59921. if( rc!=SQLITE_OK ){
  59922. return rc;
  59923. }
  59924. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  59925. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  59926. rc = SQLITE_CORRUPT_BKPT;
  59927. }
  59928. if( rc!=SQLITE_OK ){
  59929. releasePage(pRoot);
  59930. return rc;
  59931. }
  59932. assert( eType!=PTRMAP_ROOTPAGE );
  59933. assert( eType!=PTRMAP_FREEPAGE );
  59934. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  59935. releasePage(pRoot);
  59936. /* Obtain the page at pgnoRoot */
  59937. if( rc!=SQLITE_OK ){
  59938. return rc;
  59939. }
  59940. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  59941. if( rc!=SQLITE_OK ){
  59942. return rc;
  59943. }
  59944. rc = sqlite3PagerWrite(pRoot->pDbPage);
  59945. if( rc!=SQLITE_OK ){
  59946. releasePage(pRoot);
  59947. return rc;
  59948. }
  59949. }else{
  59950. pRoot = pPageMove;
  59951. }
  59952. /* Update the pointer-map and meta-data with the new root-page number. */
  59953. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  59954. if( rc ){
  59955. releasePage(pRoot);
  59956. return rc;
  59957. }
  59958. /* When the new root page was allocated, page 1 was made writable in
  59959. ** order either to increase the database filesize, or to decrement the
  59960. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  59961. */
  59962. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  59963. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  59964. if( NEVER(rc) ){
  59965. releasePage(pRoot);
  59966. return rc;
  59967. }
  59968. }else{
  59969. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  59970. if( rc ) return rc;
  59971. }
  59972. #endif
  59973. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  59974. if( createTabFlags & BTREE_INTKEY ){
  59975. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  59976. }else{
  59977. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  59978. }
  59979. zeroPage(pRoot, ptfFlags);
  59980. sqlite3PagerUnref(pRoot->pDbPage);
  59981. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  59982. *piTable = (int)pgnoRoot;
  59983. return SQLITE_OK;
  59984. }
  59985. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  59986. int rc;
  59987. sqlite3BtreeEnter(p);
  59988. rc = btreeCreateTable(p, piTable, flags);
  59989. sqlite3BtreeLeave(p);
  59990. return rc;
  59991. }
  59992. /*
  59993. ** Erase the given database page and all its children. Return
  59994. ** the page to the freelist.
  59995. */
  59996. static int clearDatabasePage(
  59997. BtShared *pBt, /* The BTree that contains the table */
  59998. Pgno pgno, /* Page number to clear */
  59999. int freePageFlag, /* Deallocate page if true */
  60000. int *pnChange /* Add number of Cells freed to this counter */
  60001. ){
  60002. MemPage *pPage;
  60003. int rc;
  60004. unsigned char *pCell;
  60005. int i;
  60006. int hdr;
  60007. u16 szCell;
  60008. assert( sqlite3_mutex_held(pBt->mutex) );
  60009. if( pgno>btreePagecount(pBt) ){
  60010. return SQLITE_CORRUPT_BKPT;
  60011. }
  60012. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  60013. if( rc ) return rc;
  60014. if( pPage->bBusy ){
  60015. rc = SQLITE_CORRUPT_BKPT;
  60016. goto cleardatabasepage_out;
  60017. }
  60018. pPage->bBusy = 1;
  60019. hdr = pPage->hdrOffset;
  60020. for(i=0; i<pPage->nCell; i++){
  60021. pCell = findCell(pPage, i);
  60022. if( !pPage->leaf ){
  60023. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  60024. if( rc ) goto cleardatabasepage_out;
  60025. }
  60026. rc = clearCell(pPage, pCell, &szCell);
  60027. if( rc ) goto cleardatabasepage_out;
  60028. }
  60029. if( !pPage->leaf ){
  60030. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  60031. if( rc ) goto cleardatabasepage_out;
  60032. }else if( pnChange ){
  60033. assert( pPage->intKey || CORRUPT_DB );
  60034. testcase( !pPage->intKey );
  60035. *pnChange += pPage->nCell;
  60036. }
  60037. if( freePageFlag ){
  60038. freePage(pPage, &rc);
  60039. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  60040. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  60041. }
  60042. cleardatabasepage_out:
  60043. pPage->bBusy = 0;
  60044. releasePage(pPage);
  60045. return rc;
  60046. }
  60047. /*
  60048. ** Delete all information from a single table in the database. iTable is
  60049. ** the page number of the root of the table. After this routine returns,
  60050. ** the root page is empty, but still exists.
  60051. **
  60052. ** This routine will fail with SQLITE_LOCKED if there are any open
  60053. ** read cursors on the table. Open write cursors are moved to the
  60054. ** root of the table.
  60055. **
  60056. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  60057. ** integer value pointed to by pnChange is incremented by the number of
  60058. ** entries in the table.
  60059. */
  60060. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  60061. int rc;
  60062. BtShared *pBt = p->pBt;
  60063. sqlite3BtreeEnter(p);
  60064. assert( p->inTrans==TRANS_WRITE );
  60065. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  60066. if( SQLITE_OK==rc ){
  60067. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  60068. ** is the root of a table b-tree - if it is not, the following call is
  60069. ** a no-op). */
  60070. invalidateIncrblobCursors(p, 0, 1);
  60071. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  60072. }
  60073. sqlite3BtreeLeave(p);
  60074. return rc;
  60075. }
  60076. /*
  60077. ** Delete all information from the single table that pCur is open on.
  60078. **
  60079. ** This routine only work for pCur on an ephemeral table.
  60080. */
  60081. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  60082. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  60083. }
  60084. /*
  60085. ** Erase all information in a table and add the root of the table to
  60086. ** the freelist. Except, the root of the principle table (the one on
  60087. ** page 1) is never added to the freelist.
  60088. **
  60089. ** This routine will fail with SQLITE_LOCKED if there are any open
  60090. ** cursors on the table.
  60091. **
  60092. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  60093. ** root page in the database file, then the last root page
  60094. ** in the database file is moved into the slot formerly occupied by
  60095. ** iTable and that last slot formerly occupied by the last root page
  60096. ** is added to the freelist instead of iTable. In this say, all
  60097. ** root pages are kept at the beginning of the database file, which
  60098. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  60099. ** page number that used to be the last root page in the file before
  60100. ** the move. If no page gets moved, *piMoved is set to 0.
  60101. ** The last root page is recorded in meta[3] and the value of
  60102. ** meta[3] is updated by this procedure.
  60103. */
  60104. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  60105. int rc;
  60106. MemPage *pPage = 0;
  60107. BtShared *pBt = p->pBt;
  60108. assert( sqlite3BtreeHoldsMutex(p) );
  60109. assert( p->inTrans==TRANS_WRITE );
  60110. /* It is illegal to drop a table if any cursors are open on the
  60111. ** database. This is because in auto-vacuum mode the backend may
  60112. ** need to move another root-page to fill a gap left by the deleted
  60113. ** root page. If an open cursor was using this page a problem would
  60114. ** occur.
  60115. **
  60116. ** This error is caught long before control reaches this point.
  60117. */
  60118. if( NEVER(pBt->pCursor) ){
  60119. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  60120. return SQLITE_LOCKED_SHAREDCACHE;
  60121. }
  60122. /*
  60123. ** It is illegal to drop the sqlite_master table on page 1. But again,
  60124. ** this error is caught long before reaching this point.
  60125. */
  60126. if( NEVER(iTable<2) ){
  60127. return SQLITE_CORRUPT_BKPT;
  60128. }
  60129. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  60130. if( rc ) return rc;
  60131. rc = sqlite3BtreeClearTable(p, iTable, 0);
  60132. if( rc ){
  60133. releasePage(pPage);
  60134. return rc;
  60135. }
  60136. *piMoved = 0;
  60137. #ifdef SQLITE_OMIT_AUTOVACUUM
  60138. freePage(pPage, &rc);
  60139. releasePage(pPage);
  60140. #else
  60141. if( pBt->autoVacuum ){
  60142. Pgno maxRootPgno;
  60143. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  60144. if( iTable==maxRootPgno ){
  60145. /* If the table being dropped is the table with the largest root-page
  60146. ** number in the database, put the root page on the free list.
  60147. */
  60148. freePage(pPage, &rc);
  60149. releasePage(pPage);
  60150. if( rc!=SQLITE_OK ){
  60151. return rc;
  60152. }
  60153. }else{
  60154. /* The table being dropped does not have the largest root-page
  60155. ** number in the database. So move the page that does into the
  60156. ** gap left by the deleted root-page.
  60157. */
  60158. MemPage *pMove;
  60159. releasePage(pPage);
  60160. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  60161. if( rc!=SQLITE_OK ){
  60162. return rc;
  60163. }
  60164. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  60165. releasePage(pMove);
  60166. if( rc!=SQLITE_OK ){
  60167. return rc;
  60168. }
  60169. pMove = 0;
  60170. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  60171. freePage(pMove, &rc);
  60172. releasePage(pMove);
  60173. if( rc!=SQLITE_OK ){
  60174. return rc;
  60175. }
  60176. *piMoved = maxRootPgno;
  60177. }
  60178. /* Set the new 'max-root-page' value in the database header. This
  60179. ** is the old value less one, less one more if that happens to
  60180. ** be a root-page number, less one again if that is the
  60181. ** PENDING_BYTE_PAGE.
  60182. */
  60183. maxRootPgno--;
  60184. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  60185. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  60186. maxRootPgno--;
  60187. }
  60188. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  60189. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  60190. }else{
  60191. freePage(pPage, &rc);
  60192. releasePage(pPage);
  60193. }
  60194. #endif
  60195. return rc;
  60196. }
  60197. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  60198. int rc;
  60199. sqlite3BtreeEnter(p);
  60200. rc = btreeDropTable(p, iTable, piMoved);
  60201. sqlite3BtreeLeave(p);
  60202. return rc;
  60203. }
  60204. /*
  60205. ** This function may only be called if the b-tree connection already
  60206. ** has a read or write transaction open on the database.
  60207. **
  60208. ** Read the meta-information out of a database file. Meta[0]
  60209. ** is the number of free pages currently in the database. Meta[1]
  60210. ** through meta[15] are available for use by higher layers. Meta[0]
  60211. ** is read-only, the others are read/write.
  60212. **
  60213. ** The schema layer numbers meta values differently. At the schema
  60214. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  60215. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  60216. **
  60217. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  60218. ** of reading the value out of the header, it instead loads the "DataVersion"
  60219. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  60220. ** database file. It is a number computed by the pager. But its access
  60221. ** pattern is the same as header meta values, and so it is convenient to
  60222. ** read it from this routine.
  60223. */
  60224. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  60225. BtShared *pBt = p->pBt;
  60226. sqlite3BtreeEnter(p);
  60227. assert( p->inTrans>TRANS_NONE );
  60228. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  60229. assert( pBt->pPage1 );
  60230. assert( idx>=0 && idx<=15 );
  60231. if( idx==BTREE_DATA_VERSION ){
  60232. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  60233. }else{
  60234. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  60235. }
  60236. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  60237. ** database, mark the database as read-only. */
  60238. #ifdef SQLITE_OMIT_AUTOVACUUM
  60239. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  60240. pBt->btsFlags |= BTS_READ_ONLY;
  60241. }
  60242. #endif
  60243. sqlite3BtreeLeave(p);
  60244. }
  60245. /*
  60246. ** Write meta-information back into the database. Meta[0] is
  60247. ** read-only and may not be written.
  60248. */
  60249. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  60250. BtShared *pBt = p->pBt;
  60251. unsigned char *pP1;
  60252. int rc;
  60253. assert( idx>=1 && idx<=15 );
  60254. sqlite3BtreeEnter(p);
  60255. assert( p->inTrans==TRANS_WRITE );
  60256. assert( pBt->pPage1!=0 );
  60257. pP1 = pBt->pPage1->aData;
  60258. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  60259. if( rc==SQLITE_OK ){
  60260. put4byte(&pP1[36 + idx*4], iMeta);
  60261. #ifndef SQLITE_OMIT_AUTOVACUUM
  60262. if( idx==BTREE_INCR_VACUUM ){
  60263. assert( pBt->autoVacuum || iMeta==0 );
  60264. assert( iMeta==0 || iMeta==1 );
  60265. pBt->incrVacuum = (u8)iMeta;
  60266. }
  60267. #endif
  60268. }
  60269. sqlite3BtreeLeave(p);
  60270. return rc;
  60271. }
  60272. #ifndef SQLITE_OMIT_BTREECOUNT
  60273. /*
  60274. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  60275. ** number of entries in the b-tree and write the result to *pnEntry.
  60276. **
  60277. ** SQLITE_OK is returned if the operation is successfully executed.
  60278. ** Otherwise, if an error is encountered (i.e. an IO error or database
  60279. ** corruption) an SQLite error code is returned.
  60280. */
  60281. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  60282. i64 nEntry = 0; /* Value to return in *pnEntry */
  60283. int rc; /* Return code */
  60284. if( pCur->pgnoRoot==0 ){
  60285. *pnEntry = 0;
  60286. return SQLITE_OK;
  60287. }
  60288. rc = moveToRoot(pCur);
  60289. /* Unless an error occurs, the following loop runs one iteration for each
  60290. ** page in the B-Tree structure (not including overflow pages).
  60291. */
  60292. while( rc==SQLITE_OK ){
  60293. int iIdx; /* Index of child node in parent */
  60294. MemPage *pPage; /* Current page of the b-tree */
  60295. /* If this is a leaf page or the tree is not an int-key tree, then
  60296. ** this page contains countable entries. Increment the entry counter
  60297. ** accordingly.
  60298. */
  60299. pPage = pCur->apPage[pCur->iPage];
  60300. if( pPage->leaf || !pPage->intKey ){
  60301. nEntry += pPage->nCell;
  60302. }
  60303. /* pPage is a leaf node. This loop navigates the cursor so that it
  60304. ** points to the first interior cell that it points to the parent of
  60305. ** the next page in the tree that has not yet been visited. The
  60306. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  60307. ** of the page, or to the number of cells in the page if the next page
  60308. ** to visit is the right-child of its parent.
  60309. **
  60310. ** If all pages in the tree have been visited, return SQLITE_OK to the
  60311. ** caller.
  60312. */
  60313. if( pPage->leaf ){
  60314. do {
  60315. if( pCur->iPage==0 ){
  60316. /* All pages of the b-tree have been visited. Return successfully. */
  60317. *pnEntry = nEntry;
  60318. return moveToRoot(pCur);
  60319. }
  60320. moveToParent(pCur);
  60321. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  60322. pCur->aiIdx[pCur->iPage]++;
  60323. pPage = pCur->apPage[pCur->iPage];
  60324. }
  60325. /* Descend to the child node of the cell that the cursor currently
  60326. ** points at. This is the right-child if (iIdx==pPage->nCell).
  60327. */
  60328. iIdx = pCur->aiIdx[pCur->iPage];
  60329. if( iIdx==pPage->nCell ){
  60330. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  60331. }else{
  60332. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  60333. }
  60334. }
  60335. /* An error has occurred. Return an error code. */
  60336. return rc;
  60337. }
  60338. #endif
  60339. /*
  60340. ** Return the pager associated with a BTree. This routine is used for
  60341. ** testing and debugging only.
  60342. */
  60343. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  60344. return p->pBt->pPager;
  60345. }
  60346. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  60347. /*
  60348. ** Append a message to the error message string.
  60349. */
  60350. static void checkAppendMsg(
  60351. IntegrityCk *pCheck,
  60352. const char *zFormat,
  60353. ...
  60354. ){
  60355. va_list ap;
  60356. if( !pCheck->mxErr ) return;
  60357. pCheck->mxErr--;
  60358. pCheck->nErr++;
  60359. va_start(ap, zFormat);
  60360. if( pCheck->errMsg.nChar ){
  60361. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  60362. }
  60363. if( pCheck->zPfx ){
  60364. sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  60365. }
  60366. sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
  60367. va_end(ap);
  60368. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  60369. pCheck->mallocFailed = 1;
  60370. }
  60371. }
  60372. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  60373. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  60374. /*
  60375. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  60376. ** corresponds to page iPg is already set.
  60377. */
  60378. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  60379. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  60380. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  60381. }
  60382. /*
  60383. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  60384. */
  60385. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  60386. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  60387. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  60388. }
  60389. /*
  60390. ** Add 1 to the reference count for page iPage. If this is the second
  60391. ** reference to the page, add an error message to pCheck->zErrMsg.
  60392. ** Return 1 if there are 2 or more references to the page and 0 if
  60393. ** if this is the first reference to the page.
  60394. **
  60395. ** Also check that the page number is in bounds.
  60396. */
  60397. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  60398. if( iPage==0 ) return 1;
  60399. if( iPage>pCheck->nPage ){
  60400. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  60401. return 1;
  60402. }
  60403. if( getPageReferenced(pCheck, iPage) ){
  60404. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  60405. return 1;
  60406. }
  60407. setPageReferenced(pCheck, iPage);
  60408. return 0;
  60409. }
  60410. #ifndef SQLITE_OMIT_AUTOVACUUM
  60411. /*
  60412. ** Check that the entry in the pointer-map for page iChild maps to
  60413. ** page iParent, pointer type ptrType. If not, append an error message
  60414. ** to pCheck.
  60415. */
  60416. static void checkPtrmap(
  60417. IntegrityCk *pCheck, /* Integrity check context */
  60418. Pgno iChild, /* Child page number */
  60419. u8 eType, /* Expected pointer map type */
  60420. Pgno iParent /* Expected pointer map parent page number */
  60421. ){
  60422. int rc;
  60423. u8 ePtrmapType;
  60424. Pgno iPtrmapParent;
  60425. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  60426. if( rc!=SQLITE_OK ){
  60427. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  60428. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  60429. return;
  60430. }
  60431. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  60432. checkAppendMsg(pCheck,
  60433. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  60434. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  60435. }
  60436. }
  60437. #endif
  60438. /*
  60439. ** Check the integrity of the freelist or of an overflow page list.
  60440. ** Verify that the number of pages on the list is N.
  60441. */
  60442. static void checkList(
  60443. IntegrityCk *pCheck, /* Integrity checking context */
  60444. int isFreeList, /* True for a freelist. False for overflow page list */
  60445. int iPage, /* Page number for first page in the list */
  60446. int N /* Expected number of pages in the list */
  60447. ){
  60448. int i;
  60449. int expected = N;
  60450. int iFirst = iPage;
  60451. while( N-- > 0 && pCheck->mxErr ){
  60452. DbPage *pOvflPage;
  60453. unsigned char *pOvflData;
  60454. if( iPage<1 ){
  60455. checkAppendMsg(pCheck,
  60456. "%d of %d pages missing from overflow list starting at %d",
  60457. N+1, expected, iFirst);
  60458. break;
  60459. }
  60460. if( checkRef(pCheck, iPage) ) break;
  60461. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  60462. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  60463. break;
  60464. }
  60465. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  60466. if( isFreeList ){
  60467. int n = get4byte(&pOvflData[4]);
  60468. #ifndef SQLITE_OMIT_AUTOVACUUM
  60469. if( pCheck->pBt->autoVacuum ){
  60470. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  60471. }
  60472. #endif
  60473. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  60474. checkAppendMsg(pCheck,
  60475. "freelist leaf count too big on page %d", iPage);
  60476. N--;
  60477. }else{
  60478. for(i=0; i<n; i++){
  60479. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  60480. #ifndef SQLITE_OMIT_AUTOVACUUM
  60481. if( pCheck->pBt->autoVacuum ){
  60482. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  60483. }
  60484. #endif
  60485. checkRef(pCheck, iFreePage);
  60486. }
  60487. N -= n;
  60488. }
  60489. }
  60490. #ifndef SQLITE_OMIT_AUTOVACUUM
  60491. else{
  60492. /* If this database supports auto-vacuum and iPage is not the last
  60493. ** page in this overflow list, check that the pointer-map entry for
  60494. ** the following page matches iPage.
  60495. */
  60496. if( pCheck->pBt->autoVacuum && N>0 ){
  60497. i = get4byte(pOvflData);
  60498. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  60499. }
  60500. }
  60501. #endif
  60502. iPage = get4byte(pOvflData);
  60503. sqlite3PagerUnref(pOvflPage);
  60504. if( isFreeList && N<(iPage!=0) ){
  60505. checkAppendMsg(pCheck, "free-page count in header is too small");
  60506. }
  60507. }
  60508. }
  60509. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  60510. /*
  60511. ** An implementation of a min-heap.
  60512. **
  60513. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  60514. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  60515. ** and aHeap[N*2+1].
  60516. **
  60517. ** The heap property is this: Every node is less than or equal to both
  60518. ** of its daughter nodes. A consequence of the heap property is that the
  60519. ** root node aHeap[1] is always the minimum value currently in the heap.
  60520. **
  60521. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  60522. ** the heap, preserving the heap property. The btreeHeapPull() routine
  60523. ** removes the root element from the heap (the minimum value in the heap)
  60524. ** and then moves other nodes around as necessary to preserve the heap
  60525. ** property.
  60526. **
  60527. ** This heap is used for cell overlap and coverage testing. Each u32
  60528. ** entry represents the span of a cell or freeblock on a btree page.
  60529. ** The upper 16 bits are the index of the first byte of a range and the
  60530. ** lower 16 bits are the index of the last byte of that range.
  60531. */
  60532. static void btreeHeapInsert(u32 *aHeap, u32 x){
  60533. u32 j, i = ++aHeap[0];
  60534. aHeap[i] = x;
  60535. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  60536. x = aHeap[j];
  60537. aHeap[j] = aHeap[i];
  60538. aHeap[i] = x;
  60539. i = j;
  60540. }
  60541. }
  60542. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  60543. u32 j, i, x;
  60544. if( (x = aHeap[0])==0 ) return 0;
  60545. *pOut = aHeap[1];
  60546. aHeap[1] = aHeap[x];
  60547. aHeap[x] = 0xffffffff;
  60548. aHeap[0]--;
  60549. i = 1;
  60550. while( (j = i*2)<=aHeap[0] ){
  60551. if( aHeap[j]>aHeap[j+1] ) j++;
  60552. if( aHeap[i]<aHeap[j] ) break;
  60553. x = aHeap[i];
  60554. aHeap[i] = aHeap[j];
  60555. aHeap[j] = x;
  60556. i = j;
  60557. }
  60558. return 1;
  60559. }
  60560. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  60561. /*
  60562. ** Do various sanity checks on a single page of a tree. Return
  60563. ** the tree depth. Root pages return 0. Parents of root pages
  60564. ** return 1, and so forth.
  60565. **
  60566. ** These checks are done:
  60567. **
  60568. ** 1. Make sure that cells and freeblocks do not overlap
  60569. ** but combine to completely cover the page.
  60570. ** 2. Make sure integer cell keys are in order.
  60571. ** 3. Check the integrity of overflow pages.
  60572. ** 4. Recursively call checkTreePage on all children.
  60573. ** 5. Verify that the depth of all children is the same.
  60574. */
  60575. static int checkTreePage(
  60576. IntegrityCk *pCheck, /* Context for the sanity check */
  60577. int iPage, /* Page number of the page to check */
  60578. i64 *piMinKey, /* Write minimum integer primary key here */
  60579. i64 maxKey /* Error if integer primary key greater than this */
  60580. ){
  60581. MemPage *pPage = 0; /* The page being analyzed */
  60582. int i; /* Loop counter */
  60583. int rc; /* Result code from subroutine call */
  60584. int depth = -1, d2; /* Depth of a subtree */
  60585. int pgno; /* Page number */
  60586. int nFrag; /* Number of fragmented bytes on the page */
  60587. int hdr; /* Offset to the page header */
  60588. int cellStart; /* Offset to the start of the cell pointer array */
  60589. int nCell; /* Number of cells */
  60590. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  60591. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  60592. ** False if IPK must be strictly less than maxKey */
  60593. u8 *data; /* Page content */
  60594. u8 *pCell; /* Cell content */
  60595. u8 *pCellIdx; /* Next element of the cell pointer array */
  60596. BtShared *pBt; /* The BtShared object that owns pPage */
  60597. u32 pc; /* Address of a cell */
  60598. u32 usableSize; /* Usable size of the page */
  60599. u32 contentOffset; /* Offset to the start of the cell content area */
  60600. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  60601. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  60602. const char *saved_zPfx = pCheck->zPfx;
  60603. int saved_v1 = pCheck->v1;
  60604. int saved_v2 = pCheck->v2;
  60605. u8 savedIsInit = 0;
  60606. /* Check that the page exists
  60607. */
  60608. pBt = pCheck->pBt;
  60609. usableSize = pBt->usableSize;
  60610. if( iPage==0 ) return 0;
  60611. if( checkRef(pCheck, iPage) ) return 0;
  60612. pCheck->zPfx = "Page %d: ";
  60613. pCheck->v1 = iPage;
  60614. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  60615. checkAppendMsg(pCheck,
  60616. "unable to get the page. error code=%d", rc);
  60617. goto end_of_check;
  60618. }
  60619. /* Clear MemPage.isInit to make sure the corruption detection code in
  60620. ** btreeInitPage() is executed. */
  60621. savedIsInit = pPage->isInit;
  60622. pPage->isInit = 0;
  60623. if( (rc = btreeInitPage(pPage))!=0 ){
  60624. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  60625. checkAppendMsg(pCheck,
  60626. "btreeInitPage() returns error code %d", rc);
  60627. goto end_of_check;
  60628. }
  60629. data = pPage->aData;
  60630. hdr = pPage->hdrOffset;
  60631. /* Set up for cell analysis */
  60632. pCheck->zPfx = "On tree page %d cell %d: ";
  60633. contentOffset = get2byteNotZero(&data[hdr+5]);
  60634. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  60635. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  60636. ** number of cells on the page. */
  60637. nCell = get2byte(&data[hdr+3]);
  60638. assert( pPage->nCell==nCell );
  60639. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  60640. ** immediately follows the b-tree page header. */
  60641. cellStart = hdr + 12 - 4*pPage->leaf;
  60642. assert( pPage->aCellIdx==&data[cellStart] );
  60643. pCellIdx = &data[cellStart + 2*(nCell-1)];
  60644. if( !pPage->leaf ){
  60645. /* Analyze the right-child page of internal pages */
  60646. pgno = get4byte(&data[hdr+8]);
  60647. #ifndef SQLITE_OMIT_AUTOVACUUM
  60648. if( pBt->autoVacuum ){
  60649. pCheck->zPfx = "On page %d at right child: ";
  60650. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  60651. }
  60652. #endif
  60653. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  60654. keyCanBeEqual = 0;
  60655. }else{
  60656. /* For leaf pages, the coverage check will occur in the same loop
  60657. ** as the other cell checks, so initialize the heap. */
  60658. heap = pCheck->heap;
  60659. heap[0] = 0;
  60660. }
  60661. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  60662. ** integer offsets to the cell contents. */
  60663. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  60664. CellInfo info;
  60665. /* Check cell size */
  60666. pCheck->v2 = i;
  60667. assert( pCellIdx==&data[cellStart + i*2] );
  60668. pc = get2byteAligned(pCellIdx);
  60669. pCellIdx -= 2;
  60670. if( pc<contentOffset || pc>usableSize-4 ){
  60671. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  60672. pc, contentOffset, usableSize-4);
  60673. doCoverageCheck = 0;
  60674. continue;
  60675. }
  60676. pCell = &data[pc];
  60677. pPage->xParseCell(pPage, pCell, &info);
  60678. if( pc+info.nSize>usableSize ){
  60679. checkAppendMsg(pCheck, "Extends off end of page");
  60680. doCoverageCheck = 0;
  60681. continue;
  60682. }
  60683. /* Check for integer primary key out of range */
  60684. if( pPage->intKey ){
  60685. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  60686. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  60687. }
  60688. maxKey = info.nKey;
  60689. }
  60690. /* Check the content overflow list */
  60691. if( info.nPayload>info.nLocal ){
  60692. int nPage; /* Number of pages on the overflow chain */
  60693. Pgno pgnoOvfl; /* First page of the overflow chain */
  60694. assert( pc + info.nSize - 4 <= usableSize );
  60695. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  60696. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  60697. #ifndef SQLITE_OMIT_AUTOVACUUM
  60698. if( pBt->autoVacuum ){
  60699. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  60700. }
  60701. #endif
  60702. checkList(pCheck, 0, pgnoOvfl, nPage);
  60703. }
  60704. if( !pPage->leaf ){
  60705. /* Check sanity of left child page for internal pages */
  60706. pgno = get4byte(pCell);
  60707. #ifndef SQLITE_OMIT_AUTOVACUUM
  60708. if( pBt->autoVacuum ){
  60709. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  60710. }
  60711. #endif
  60712. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  60713. keyCanBeEqual = 0;
  60714. if( d2!=depth ){
  60715. checkAppendMsg(pCheck, "Child page depth differs");
  60716. depth = d2;
  60717. }
  60718. }else{
  60719. /* Populate the coverage-checking heap for leaf pages */
  60720. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  60721. }
  60722. }
  60723. *piMinKey = maxKey;
  60724. /* Check for complete coverage of the page
  60725. */
  60726. pCheck->zPfx = 0;
  60727. if( doCoverageCheck && pCheck->mxErr>0 ){
  60728. /* For leaf pages, the min-heap has already been initialized and the
  60729. ** cells have already been inserted. But for internal pages, that has
  60730. ** not yet been done, so do it now */
  60731. if( !pPage->leaf ){
  60732. heap = pCheck->heap;
  60733. heap[0] = 0;
  60734. for(i=nCell-1; i>=0; i--){
  60735. u32 size;
  60736. pc = get2byteAligned(&data[cellStart+i*2]);
  60737. size = pPage->xCellSize(pPage, &data[pc]);
  60738. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  60739. }
  60740. }
  60741. /* Add the freeblocks to the min-heap
  60742. **
  60743. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  60744. ** is the offset of the first freeblock, or zero if there are no
  60745. ** freeblocks on the page.
  60746. */
  60747. i = get2byte(&data[hdr+1]);
  60748. while( i>0 ){
  60749. int size, j;
  60750. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  60751. size = get2byte(&data[i+2]);
  60752. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  60753. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  60754. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  60755. ** big-endian integer which is the offset in the b-tree page of the next
  60756. ** freeblock in the chain, or zero if the freeblock is the last on the
  60757. ** chain. */
  60758. j = get2byte(&data[i]);
  60759. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  60760. ** increasing offset. */
  60761. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  60762. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  60763. i = j;
  60764. }
  60765. /* Analyze the min-heap looking for overlap between cells and/or
  60766. ** freeblocks, and counting the number of untracked bytes in nFrag.
  60767. **
  60768. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  60769. ** There is an implied first entry the covers the page header, the cell
  60770. ** pointer index, and the gap between the cell pointer index and the start
  60771. ** of cell content.
  60772. **
  60773. ** The loop below pulls entries from the min-heap in order and compares
  60774. ** the start_address against the previous end_address. If there is an
  60775. ** overlap, that means bytes are used multiple times. If there is a gap,
  60776. ** that gap is added to the fragmentation count.
  60777. */
  60778. nFrag = 0;
  60779. prev = contentOffset - 1; /* Implied first min-heap entry */
  60780. while( btreeHeapPull(heap,&x) ){
  60781. if( (prev&0xffff)>=(x>>16) ){
  60782. checkAppendMsg(pCheck,
  60783. "Multiple uses for byte %u of page %d", x>>16, iPage);
  60784. break;
  60785. }else{
  60786. nFrag += (x>>16) - (prev&0xffff) - 1;
  60787. prev = x;
  60788. }
  60789. }
  60790. nFrag += usableSize - (prev&0xffff) - 1;
  60791. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  60792. ** is stored in the fifth field of the b-tree page header.
  60793. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  60794. ** number of fragmented free bytes within the cell content area.
  60795. */
  60796. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  60797. checkAppendMsg(pCheck,
  60798. "Fragmentation of %d bytes reported as %d on page %d",
  60799. nFrag, data[hdr+7], iPage);
  60800. }
  60801. }
  60802. end_of_check:
  60803. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  60804. releasePage(pPage);
  60805. pCheck->zPfx = saved_zPfx;
  60806. pCheck->v1 = saved_v1;
  60807. pCheck->v2 = saved_v2;
  60808. return depth+1;
  60809. }
  60810. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  60811. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  60812. /*
  60813. ** This routine does a complete check of the given BTree file. aRoot[] is
  60814. ** an array of pages numbers were each page number is the root page of
  60815. ** a table. nRoot is the number of entries in aRoot.
  60816. **
  60817. ** A read-only or read-write transaction must be opened before calling
  60818. ** this function.
  60819. **
  60820. ** Write the number of error seen in *pnErr. Except for some memory
  60821. ** allocation errors, an error message held in memory obtained from
  60822. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  60823. ** returned. If a memory allocation error occurs, NULL is returned.
  60824. */
  60825. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  60826. Btree *p, /* The btree to be checked */
  60827. int *aRoot, /* An array of root pages numbers for individual trees */
  60828. int nRoot, /* Number of entries in aRoot[] */
  60829. int mxErr, /* Stop reporting errors after this many */
  60830. int *pnErr /* Write number of errors seen to this variable */
  60831. ){
  60832. Pgno i;
  60833. IntegrityCk sCheck;
  60834. BtShared *pBt = p->pBt;
  60835. int savedDbFlags = pBt->db->flags;
  60836. char zErr[100];
  60837. VVA_ONLY( int nRef );
  60838. sqlite3BtreeEnter(p);
  60839. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  60840. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  60841. assert( nRef>=0 );
  60842. sCheck.pBt = pBt;
  60843. sCheck.pPager = pBt->pPager;
  60844. sCheck.nPage = btreePagecount(sCheck.pBt);
  60845. sCheck.mxErr = mxErr;
  60846. sCheck.nErr = 0;
  60847. sCheck.mallocFailed = 0;
  60848. sCheck.zPfx = 0;
  60849. sCheck.v1 = 0;
  60850. sCheck.v2 = 0;
  60851. sCheck.aPgRef = 0;
  60852. sCheck.heap = 0;
  60853. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  60854. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  60855. if( sCheck.nPage==0 ){
  60856. goto integrity_ck_cleanup;
  60857. }
  60858. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  60859. if( !sCheck.aPgRef ){
  60860. sCheck.mallocFailed = 1;
  60861. goto integrity_ck_cleanup;
  60862. }
  60863. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  60864. if( sCheck.heap==0 ){
  60865. sCheck.mallocFailed = 1;
  60866. goto integrity_ck_cleanup;
  60867. }
  60868. i = PENDING_BYTE_PAGE(pBt);
  60869. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  60870. /* Check the integrity of the freelist
  60871. */
  60872. sCheck.zPfx = "Main freelist: ";
  60873. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  60874. get4byte(&pBt->pPage1->aData[36]));
  60875. sCheck.zPfx = 0;
  60876. /* Check all the tables.
  60877. */
  60878. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  60879. pBt->db->flags &= ~SQLITE_CellSizeCk;
  60880. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  60881. i64 notUsed;
  60882. if( aRoot[i]==0 ) continue;
  60883. #ifndef SQLITE_OMIT_AUTOVACUUM
  60884. if( pBt->autoVacuum && aRoot[i]>1 ){
  60885. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  60886. }
  60887. #endif
  60888. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  60889. }
  60890. pBt->db->flags = savedDbFlags;
  60891. /* Make sure every page in the file is referenced
  60892. */
  60893. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  60894. #ifdef SQLITE_OMIT_AUTOVACUUM
  60895. if( getPageReferenced(&sCheck, i)==0 ){
  60896. checkAppendMsg(&sCheck, "Page %d is never used", i);
  60897. }
  60898. #else
  60899. /* If the database supports auto-vacuum, make sure no tables contain
  60900. ** references to pointer-map pages.
  60901. */
  60902. if( getPageReferenced(&sCheck, i)==0 &&
  60903. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  60904. checkAppendMsg(&sCheck, "Page %d is never used", i);
  60905. }
  60906. if( getPageReferenced(&sCheck, i)!=0 &&
  60907. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  60908. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  60909. }
  60910. #endif
  60911. }
  60912. /* Clean up and report errors.
  60913. */
  60914. integrity_ck_cleanup:
  60915. sqlite3PageFree(sCheck.heap);
  60916. sqlite3_free(sCheck.aPgRef);
  60917. if( sCheck.mallocFailed ){
  60918. sqlite3StrAccumReset(&sCheck.errMsg);
  60919. sCheck.nErr++;
  60920. }
  60921. *pnErr = sCheck.nErr;
  60922. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  60923. /* Make sure this analysis did not leave any unref() pages. */
  60924. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  60925. sqlite3BtreeLeave(p);
  60926. return sqlite3StrAccumFinish(&sCheck.errMsg);
  60927. }
  60928. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  60929. /*
  60930. ** Return the full pathname of the underlying database file. Return
  60931. ** an empty string if the database is in-memory or a TEMP database.
  60932. **
  60933. ** The pager filename is invariant as long as the pager is
  60934. ** open so it is safe to access without the BtShared mutex.
  60935. */
  60936. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  60937. assert( p->pBt->pPager!=0 );
  60938. return sqlite3PagerFilename(p->pBt->pPager, 1);
  60939. }
  60940. /*
  60941. ** Return the pathname of the journal file for this database. The return
  60942. ** value of this routine is the same regardless of whether the journal file
  60943. ** has been created or not.
  60944. **
  60945. ** The pager journal filename is invariant as long as the pager is
  60946. ** open so it is safe to access without the BtShared mutex.
  60947. */
  60948. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  60949. assert( p->pBt->pPager!=0 );
  60950. return sqlite3PagerJournalname(p->pBt->pPager);
  60951. }
  60952. /*
  60953. ** Return non-zero if a transaction is active.
  60954. */
  60955. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  60956. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  60957. return (p && (p->inTrans==TRANS_WRITE));
  60958. }
  60959. #ifndef SQLITE_OMIT_WAL
  60960. /*
  60961. ** Run a checkpoint on the Btree passed as the first argument.
  60962. **
  60963. ** Return SQLITE_LOCKED if this or any other connection has an open
  60964. ** transaction on the shared-cache the argument Btree is connected to.
  60965. **
  60966. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  60967. */
  60968. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  60969. int rc = SQLITE_OK;
  60970. if( p ){
  60971. BtShared *pBt = p->pBt;
  60972. sqlite3BtreeEnter(p);
  60973. if( pBt->inTransaction!=TRANS_NONE ){
  60974. rc = SQLITE_LOCKED;
  60975. }else{
  60976. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  60977. }
  60978. sqlite3BtreeLeave(p);
  60979. }
  60980. return rc;
  60981. }
  60982. #endif
  60983. /*
  60984. ** Return non-zero if a read (or write) transaction is active.
  60985. */
  60986. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  60987. assert( p );
  60988. assert( sqlite3_mutex_held(p->db->mutex) );
  60989. return p->inTrans!=TRANS_NONE;
  60990. }
  60991. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  60992. assert( p );
  60993. assert( sqlite3_mutex_held(p->db->mutex) );
  60994. return p->nBackup!=0;
  60995. }
  60996. /*
  60997. ** This function returns a pointer to a blob of memory associated with
  60998. ** a single shared-btree. The memory is used by client code for its own
  60999. ** purposes (for example, to store a high-level schema associated with
  61000. ** the shared-btree). The btree layer manages reference counting issues.
  61001. **
  61002. ** The first time this is called on a shared-btree, nBytes bytes of memory
  61003. ** are allocated, zeroed, and returned to the caller. For each subsequent
  61004. ** call the nBytes parameter is ignored and a pointer to the same blob
  61005. ** of memory returned.
  61006. **
  61007. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  61008. ** allocated, a null pointer is returned. If the blob has already been
  61009. ** allocated, it is returned as normal.
  61010. **
  61011. ** Just before the shared-btree is closed, the function passed as the
  61012. ** xFree argument when the memory allocation was made is invoked on the
  61013. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  61014. ** on the memory, the btree layer does that.
  61015. */
  61016. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  61017. BtShared *pBt = p->pBt;
  61018. sqlite3BtreeEnter(p);
  61019. if( !pBt->pSchema && nBytes ){
  61020. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  61021. pBt->xFreeSchema = xFree;
  61022. }
  61023. sqlite3BtreeLeave(p);
  61024. return pBt->pSchema;
  61025. }
  61026. /*
  61027. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  61028. ** btree as the argument handle holds an exclusive lock on the
  61029. ** sqlite_master table. Otherwise SQLITE_OK.
  61030. */
  61031. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  61032. int rc;
  61033. assert( sqlite3_mutex_held(p->db->mutex) );
  61034. sqlite3BtreeEnter(p);
  61035. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  61036. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  61037. sqlite3BtreeLeave(p);
  61038. return rc;
  61039. }
  61040. #ifndef SQLITE_OMIT_SHARED_CACHE
  61041. /*
  61042. ** Obtain a lock on the table whose root page is iTab. The
  61043. ** lock is a write lock if isWritelock is true or a read lock
  61044. ** if it is false.
  61045. */
  61046. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  61047. int rc = SQLITE_OK;
  61048. assert( p->inTrans!=TRANS_NONE );
  61049. if( p->sharable ){
  61050. u8 lockType = READ_LOCK + isWriteLock;
  61051. assert( READ_LOCK+1==WRITE_LOCK );
  61052. assert( isWriteLock==0 || isWriteLock==1 );
  61053. sqlite3BtreeEnter(p);
  61054. rc = querySharedCacheTableLock(p, iTab, lockType);
  61055. if( rc==SQLITE_OK ){
  61056. rc = setSharedCacheTableLock(p, iTab, lockType);
  61057. }
  61058. sqlite3BtreeLeave(p);
  61059. }
  61060. return rc;
  61061. }
  61062. #endif
  61063. #ifndef SQLITE_OMIT_INCRBLOB
  61064. /*
  61065. ** Argument pCsr must be a cursor opened for writing on an
  61066. ** INTKEY table currently pointing at a valid table entry.
  61067. ** This function modifies the data stored as part of that entry.
  61068. **
  61069. ** Only the data content may only be modified, it is not possible to
  61070. ** change the length of the data stored. If this function is called with
  61071. ** parameters that attempt to write past the end of the existing data,
  61072. ** no modifications are made and SQLITE_CORRUPT is returned.
  61073. */
  61074. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  61075. int rc;
  61076. assert( cursorOwnsBtShared(pCsr) );
  61077. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  61078. assert( pCsr->curFlags & BTCF_Incrblob );
  61079. rc = restoreCursorPosition(pCsr);
  61080. if( rc!=SQLITE_OK ){
  61081. return rc;
  61082. }
  61083. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  61084. if( pCsr->eState!=CURSOR_VALID ){
  61085. return SQLITE_ABORT;
  61086. }
  61087. /* Save the positions of all other cursors open on this table. This is
  61088. ** required in case any of them are holding references to an xFetch
  61089. ** version of the b-tree page modified by the accessPayload call below.
  61090. **
  61091. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  61092. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  61093. ** saveAllCursors can only return SQLITE_OK.
  61094. */
  61095. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  61096. assert( rc==SQLITE_OK );
  61097. /* Check some assumptions:
  61098. ** (a) the cursor is open for writing,
  61099. ** (b) there is a read/write transaction open,
  61100. ** (c) the connection holds a write-lock on the table (if required),
  61101. ** (d) there are no conflicting read-locks, and
  61102. ** (e) the cursor points at a valid row of an intKey table.
  61103. */
  61104. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  61105. return SQLITE_READONLY;
  61106. }
  61107. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  61108. && pCsr->pBt->inTransaction==TRANS_WRITE );
  61109. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  61110. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  61111. assert( pCsr->apPage[pCsr->iPage]->intKey );
  61112. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  61113. }
  61114. /*
  61115. ** Mark this cursor as an incremental blob cursor.
  61116. */
  61117. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  61118. pCur->curFlags |= BTCF_Incrblob;
  61119. pCur->pBtree->hasIncrblobCur = 1;
  61120. }
  61121. #endif
  61122. /*
  61123. ** Set both the "read version" (single byte at byte offset 18) and
  61124. ** "write version" (single byte at byte offset 19) fields in the database
  61125. ** header to iVersion.
  61126. */
  61127. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  61128. BtShared *pBt = pBtree->pBt;
  61129. int rc; /* Return code */
  61130. assert( iVersion==1 || iVersion==2 );
  61131. /* If setting the version fields to 1, do not automatically open the
  61132. ** WAL connection, even if the version fields are currently set to 2.
  61133. */
  61134. pBt->btsFlags &= ~BTS_NO_WAL;
  61135. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  61136. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  61137. if( rc==SQLITE_OK ){
  61138. u8 *aData = pBt->pPage1->aData;
  61139. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  61140. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  61141. if( rc==SQLITE_OK ){
  61142. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  61143. if( rc==SQLITE_OK ){
  61144. aData[18] = (u8)iVersion;
  61145. aData[19] = (u8)iVersion;
  61146. }
  61147. }
  61148. }
  61149. }
  61150. pBt->btsFlags &= ~BTS_NO_WAL;
  61151. return rc;
  61152. }
  61153. /*
  61154. ** Return true if the cursor has a hint specified. This routine is
  61155. ** only used from within assert() statements
  61156. */
  61157. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  61158. return (pCsr->hints & mask)!=0;
  61159. }
  61160. /*
  61161. ** Return true if the given Btree is read-only.
  61162. */
  61163. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  61164. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  61165. }
  61166. /*
  61167. ** Return the size of the header added to each page by this module.
  61168. */
  61169. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  61170. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  61171. /*
  61172. ** Return true if the Btree passed as the only argument is sharable.
  61173. */
  61174. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  61175. return p->sharable;
  61176. }
  61177. #endif
  61178. /************** End of btree.c ***********************************************/
  61179. /************** Begin file backup.c ******************************************/
  61180. /*
  61181. ** 2009 January 28
  61182. **
  61183. ** The author disclaims copyright to this source code. In place of
  61184. ** a legal notice, here is a blessing:
  61185. **
  61186. ** May you do good and not evil.
  61187. ** May you find forgiveness for yourself and forgive others.
  61188. ** May you share freely, never taking more than you give.
  61189. **
  61190. *************************************************************************
  61191. ** This file contains the implementation of the sqlite3_backup_XXX()
  61192. ** API functions and the related features.
  61193. */
  61194. /* #include "sqliteInt.h" */
  61195. /* #include "btreeInt.h" */
  61196. /*
  61197. ** Structure allocated for each backup operation.
  61198. */
  61199. struct sqlite3_backup {
  61200. sqlite3* pDestDb; /* Destination database handle */
  61201. Btree *pDest; /* Destination b-tree file */
  61202. u32 iDestSchema; /* Original schema cookie in destination */
  61203. int bDestLocked; /* True once a write-transaction is open on pDest */
  61204. Pgno iNext; /* Page number of the next source page to copy */
  61205. sqlite3* pSrcDb; /* Source database handle */
  61206. Btree *pSrc; /* Source b-tree file */
  61207. int rc; /* Backup process error code */
  61208. /* These two variables are set by every call to backup_step(). They are
  61209. ** read by calls to backup_remaining() and backup_pagecount().
  61210. */
  61211. Pgno nRemaining; /* Number of pages left to copy */
  61212. Pgno nPagecount; /* Total number of pages to copy */
  61213. int isAttached; /* True once backup has been registered with pager */
  61214. sqlite3_backup *pNext; /* Next backup associated with source pager */
  61215. };
  61216. /*
  61217. ** THREAD SAFETY NOTES:
  61218. **
  61219. ** Once it has been created using backup_init(), a single sqlite3_backup
  61220. ** structure may be accessed via two groups of thread-safe entry points:
  61221. **
  61222. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  61223. ** backup_finish(). Both these functions obtain the source database
  61224. ** handle mutex and the mutex associated with the source BtShared
  61225. ** structure, in that order.
  61226. **
  61227. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  61228. ** invoked by the pager layer to report various state changes in
  61229. ** the page cache associated with the source database. The mutex
  61230. ** associated with the source database BtShared structure will always
  61231. ** be held when either of these functions are invoked.
  61232. **
  61233. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  61234. ** backup_pagecount() are not thread-safe functions. If they are called
  61235. ** while some other thread is calling backup_step() or backup_finish(),
  61236. ** the values returned may be invalid. There is no way for a call to
  61237. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  61238. ** or backup_pagecount().
  61239. **
  61240. ** Depending on the SQLite configuration, the database handles and/or
  61241. ** the Btree objects may have their own mutexes that require locking.
  61242. ** Non-sharable Btrees (in-memory databases for example), do not have
  61243. ** associated mutexes.
  61244. */
  61245. /*
  61246. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  61247. ** in connection handle pDb. If such a database cannot be found, return
  61248. ** a NULL pointer and write an error message to pErrorDb.
  61249. **
  61250. ** If the "temp" database is requested, it may need to be opened by this
  61251. ** function. If an error occurs while doing so, return 0 and write an
  61252. ** error message to pErrorDb.
  61253. */
  61254. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  61255. int i = sqlite3FindDbName(pDb, zDb);
  61256. if( i==1 ){
  61257. Parse *pParse;
  61258. int rc = 0;
  61259. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  61260. if( pParse==0 ){
  61261. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  61262. rc = SQLITE_NOMEM_BKPT;
  61263. }else{
  61264. pParse->db = pDb;
  61265. if( sqlite3OpenTempDatabase(pParse) ){
  61266. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  61267. rc = SQLITE_ERROR;
  61268. }
  61269. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  61270. sqlite3ParserReset(pParse);
  61271. sqlite3StackFree(pErrorDb, pParse);
  61272. }
  61273. if( rc ){
  61274. return 0;
  61275. }
  61276. }
  61277. if( i<0 ){
  61278. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  61279. return 0;
  61280. }
  61281. return pDb->aDb[i].pBt;
  61282. }
  61283. /*
  61284. ** Attempt to set the page size of the destination to match the page size
  61285. ** of the source.
  61286. */
  61287. static int setDestPgsz(sqlite3_backup *p){
  61288. int rc;
  61289. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  61290. return rc;
  61291. }
  61292. /*
  61293. ** Check that there is no open read-transaction on the b-tree passed as the
  61294. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  61295. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  61296. ** message in database handle db.
  61297. */
  61298. static int checkReadTransaction(sqlite3 *db, Btree *p){
  61299. if( sqlite3BtreeIsInReadTrans(p) ){
  61300. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  61301. return SQLITE_ERROR;
  61302. }
  61303. return SQLITE_OK;
  61304. }
  61305. /*
  61306. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  61307. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  61308. ** a pointer to the new sqlite3_backup object.
  61309. **
  61310. ** If an error occurs, NULL is returned and an error code and error message
  61311. ** stored in database handle pDestDb.
  61312. */
  61313. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  61314. sqlite3* pDestDb, /* Database to write to */
  61315. const char *zDestDb, /* Name of database within pDestDb */
  61316. sqlite3* pSrcDb, /* Database connection to read from */
  61317. const char *zSrcDb /* Name of database within pSrcDb */
  61318. ){
  61319. sqlite3_backup *p; /* Value to return */
  61320. #ifdef SQLITE_ENABLE_API_ARMOR
  61321. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  61322. (void)SQLITE_MISUSE_BKPT;
  61323. return 0;
  61324. }
  61325. #endif
  61326. /* Lock the source database handle. The destination database
  61327. ** handle is not locked in this routine, but it is locked in
  61328. ** sqlite3_backup_step(). The user is required to ensure that no
  61329. ** other thread accesses the destination handle for the duration
  61330. ** of the backup operation. Any attempt to use the destination
  61331. ** database connection while a backup is in progress may cause
  61332. ** a malfunction or a deadlock.
  61333. */
  61334. sqlite3_mutex_enter(pSrcDb->mutex);
  61335. sqlite3_mutex_enter(pDestDb->mutex);
  61336. if( pSrcDb==pDestDb ){
  61337. sqlite3ErrorWithMsg(
  61338. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  61339. );
  61340. p = 0;
  61341. }else {
  61342. /* Allocate space for a new sqlite3_backup object...
  61343. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  61344. ** call to sqlite3_backup_init() and is destroyed by a call to
  61345. ** sqlite3_backup_finish(). */
  61346. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  61347. if( !p ){
  61348. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  61349. }
  61350. }
  61351. /* If the allocation succeeded, populate the new object. */
  61352. if( p ){
  61353. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  61354. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  61355. p->pDestDb = pDestDb;
  61356. p->pSrcDb = pSrcDb;
  61357. p->iNext = 1;
  61358. p->isAttached = 0;
  61359. if( 0==p->pSrc || 0==p->pDest
  61360. || setDestPgsz(p)==SQLITE_NOMEM
  61361. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  61362. ){
  61363. /* One (or both) of the named databases did not exist or an OOM
  61364. ** error was hit. Or there is a transaction open on the destination
  61365. ** database. The error has already been written into the pDestDb
  61366. ** handle. All that is left to do here is free the sqlite3_backup
  61367. ** structure. */
  61368. sqlite3_free(p);
  61369. p = 0;
  61370. }
  61371. }
  61372. if( p ){
  61373. p->pSrc->nBackup++;
  61374. }
  61375. sqlite3_mutex_leave(pDestDb->mutex);
  61376. sqlite3_mutex_leave(pSrcDb->mutex);
  61377. return p;
  61378. }
  61379. /*
  61380. ** Argument rc is an SQLite error code. Return true if this error is
  61381. ** considered fatal if encountered during a backup operation. All errors
  61382. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  61383. */
  61384. static int isFatalError(int rc){
  61385. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  61386. }
  61387. /*
  61388. ** Parameter zSrcData points to a buffer containing the data for
  61389. ** page iSrcPg from the source database. Copy this data into the
  61390. ** destination database.
  61391. */
  61392. static int backupOnePage(
  61393. sqlite3_backup *p, /* Backup handle */
  61394. Pgno iSrcPg, /* Source database page to backup */
  61395. const u8 *zSrcData, /* Source database page data */
  61396. int bUpdate /* True for an update, false otherwise */
  61397. ){
  61398. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  61399. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  61400. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  61401. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  61402. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  61403. #ifdef SQLITE_HAS_CODEC
  61404. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  61405. ** guaranteed that the shared-mutex is held by this thread, handle
  61406. ** p->pSrc may not actually be the owner. */
  61407. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  61408. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  61409. #endif
  61410. int rc = SQLITE_OK;
  61411. i64 iOff;
  61412. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  61413. assert( p->bDestLocked );
  61414. assert( !isFatalError(p->rc) );
  61415. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  61416. assert( zSrcData );
  61417. /* Catch the case where the destination is an in-memory database and the
  61418. ** page sizes of the source and destination differ.
  61419. */
  61420. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  61421. rc = SQLITE_READONLY;
  61422. }
  61423. #ifdef SQLITE_HAS_CODEC
  61424. /* Backup is not possible if the page size of the destination is changing
  61425. ** and a codec is in use.
  61426. */
  61427. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  61428. rc = SQLITE_READONLY;
  61429. }
  61430. /* Backup is not possible if the number of bytes of reserve space differ
  61431. ** between source and destination. If there is a difference, try to
  61432. ** fix the destination to agree with the source. If that is not possible,
  61433. ** then the backup cannot proceed.
  61434. */
  61435. if( nSrcReserve!=nDestReserve ){
  61436. u32 newPgsz = nSrcPgsz;
  61437. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  61438. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  61439. }
  61440. #endif
  61441. /* This loop runs once for each destination page spanned by the source
  61442. ** page. For each iteration, variable iOff is set to the byte offset
  61443. ** of the destination page.
  61444. */
  61445. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  61446. DbPage *pDestPg = 0;
  61447. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  61448. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  61449. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  61450. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  61451. ){
  61452. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  61453. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  61454. u8 *zOut = &zDestData[iOff%nDestPgsz];
  61455. /* Copy the data from the source page into the destination page.
  61456. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  61457. ** and the pager code use this trick (clearing the first byte
  61458. ** of the page 'extra' space to invalidate the Btree layers
  61459. ** cached parse of the page). MemPage.isInit is marked
  61460. ** "MUST BE FIRST" for this purpose.
  61461. */
  61462. memcpy(zOut, zIn, nCopy);
  61463. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  61464. if( iOff==0 && bUpdate==0 ){
  61465. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  61466. }
  61467. }
  61468. sqlite3PagerUnref(pDestPg);
  61469. }
  61470. return rc;
  61471. }
  61472. /*
  61473. ** If pFile is currently larger than iSize bytes, then truncate it to
  61474. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  61475. ** this function is a no-op.
  61476. **
  61477. ** Return SQLITE_OK if everything is successful, or an SQLite error
  61478. ** code if an error occurs.
  61479. */
  61480. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  61481. i64 iCurrent;
  61482. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  61483. if( rc==SQLITE_OK && iCurrent>iSize ){
  61484. rc = sqlite3OsTruncate(pFile, iSize);
  61485. }
  61486. return rc;
  61487. }
  61488. /*
  61489. ** Register this backup object with the associated source pager for
  61490. ** callbacks when pages are changed or the cache invalidated.
  61491. */
  61492. static void attachBackupObject(sqlite3_backup *p){
  61493. sqlite3_backup **pp;
  61494. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  61495. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  61496. p->pNext = *pp;
  61497. *pp = p;
  61498. p->isAttached = 1;
  61499. }
  61500. /*
  61501. ** Copy nPage pages from the source b-tree to the destination.
  61502. */
  61503. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
  61504. int rc;
  61505. int destMode; /* Destination journal mode */
  61506. int pgszSrc = 0; /* Source page size */
  61507. int pgszDest = 0; /* Destination page size */
  61508. #ifdef SQLITE_ENABLE_API_ARMOR
  61509. if( p==0 ) return SQLITE_MISUSE_BKPT;
  61510. #endif
  61511. sqlite3_mutex_enter(p->pSrcDb->mutex);
  61512. sqlite3BtreeEnter(p->pSrc);
  61513. if( p->pDestDb ){
  61514. sqlite3_mutex_enter(p->pDestDb->mutex);
  61515. }
  61516. rc = p->rc;
  61517. if( !isFatalError(rc) ){
  61518. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  61519. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  61520. int ii; /* Iterator variable */
  61521. int nSrcPage = -1; /* Size of source db in pages */
  61522. int bCloseTrans = 0; /* True if src db requires unlocking */
  61523. /* If the source pager is currently in a write-transaction, return
  61524. ** SQLITE_BUSY immediately.
  61525. */
  61526. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  61527. rc = SQLITE_BUSY;
  61528. }else{
  61529. rc = SQLITE_OK;
  61530. }
  61531. /* Lock the destination database, if it is not locked already. */
  61532. if( SQLITE_OK==rc && p->bDestLocked==0
  61533. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  61534. ){
  61535. p->bDestLocked = 1;
  61536. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  61537. }
  61538. /* If there is no open read-transaction on the source database, open
  61539. ** one now. If a transaction is opened here, then it will be closed
  61540. ** before this function exits.
  61541. */
  61542. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  61543. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  61544. bCloseTrans = 1;
  61545. }
  61546. /* Do not allow backup if the destination database is in WAL mode
  61547. ** and the page sizes are different between source and destination */
  61548. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  61549. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  61550. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  61551. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  61552. rc = SQLITE_READONLY;
  61553. }
  61554. /* Now that there is a read-lock on the source database, query the
  61555. ** source pager for the number of pages in the database.
  61556. */
  61557. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  61558. assert( nSrcPage>=0 );
  61559. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  61560. const Pgno iSrcPg = p->iNext; /* Source page number */
  61561. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  61562. DbPage *pSrcPg; /* Source page object */
  61563. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  61564. if( rc==SQLITE_OK ){
  61565. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  61566. sqlite3PagerUnref(pSrcPg);
  61567. }
  61568. }
  61569. p->iNext++;
  61570. }
  61571. if( rc==SQLITE_OK ){
  61572. p->nPagecount = nSrcPage;
  61573. p->nRemaining = nSrcPage+1-p->iNext;
  61574. if( p->iNext>(Pgno)nSrcPage ){
  61575. rc = SQLITE_DONE;
  61576. }else if( !p->isAttached ){
  61577. attachBackupObject(p);
  61578. }
  61579. }
  61580. /* Update the schema version field in the destination database. This
  61581. ** is to make sure that the schema-version really does change in
  61582. ** the case where the source and destination databases have the
  61583. ** same schema version.
  61584. */
  61585. if( rc==SQLITE_DONE ){
  61586. if( nSrcPage==0 ){
  61587. rc = sqlite3BtreeNewDb(p->pDest);
  61588. nSrcPage = 1;
  61589. }
  61590. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  61591. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  61592. }
  61593. if( rc==SQLITE_OK ){
  61594. if( p->pDestDb ){
  61595. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  61596. }
  61597. if( destMode==PAGER_JOURNALMODE_WAL ){
  61598. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  61599. }
  61600. }
  61601. if( rc==SQLITE_OK ){
  61602. int nDestTruncate;
  61603. /* Set nDestTruncate to the final number of pages in the destination
  61604. ** database. The complication here is that the destination page
  61605. ** size may be different to the source page size.
  61606. **
  61607. ** If the source page size is smaller than the destination page size,
  61608. ** round up. In this case the call to sqlite3OsTruncate() below will
  61609. ** fix the size of the file. However it is important to call
  61610. ** sqlite3PagerTruncateImage() here so that any pages in the
  61611. ** destination file that lie beyond the nDestTruncate page mark are
  61612. ** journalled by PagerCommitPhaseOne() before they are destroyed
  61613. ** by the file truncation.
  61614. */
  61615. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  61616. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  61617. if( pgszSrc<pgszDest ){
  61618. int ratio = pgszDest/pgszSrc;
  61619. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  61620. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  61621. nDestTruncate--;
  61622. }
  61623. }else{
  61624. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  61625. }
  61626. assert( nDestTruncate>0 );
  61627. if( pgszSrc<pgszDest ){
  61628. /* If the source page-size is smaller than the destination page-size,
  61629. ** two extra things may need to happen:
  61630. **
  61631. ** * The destination may need to be truncated, and
  61632. **
  61633. ** * Data stored on the pages immediately following the
  61634. ** pending-byte page in the source database may need to be
  61635. ** copied into the destination database.
  61636. */
  61637. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  61638. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  61639. Pgno iPg;
  61640. int nDstPage;
  61641. i64 iOff;
  61642. i64 iEnd;
  61643. assert( pFile );
  61644. assert( nDestTruncate==0
  61645. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  61646. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  61647. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  61648. ));
  61649. /* This block ensures that all data required to recreate the original
  61650. ** database has been stored in the journal for pDestPager and the
  61651. ** journal synced to disk. So at this point we may safely modify
  61652. ** the database file in any way, knowing that if a power failure
  61653. ** occurs, the original database will be reconstructed from the
  61654. ** journal file. */
  61655. sqlite3PagerPagecount(pDestPager, &nDstPage);
  61656. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  61657. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  61658. DbPage *pPg;
  61659. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  61660. if( rc==SQLITE_OK ){
  61661. rc = sqlite3PagerWrite(pPg);
  61662. sqlite3PagerUnref(pPg);
  61663. }
  61664. }
  61665. }
  61666. if( rc==SQLITE_OK ){
  61667. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  61668. }
  61669. /* Write the extra pages and truncate the database file as required */
  61670. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  61671. for(
  61672. iOff=PENDING_BYTE+pgszSrc;
  61673. rc==SQLITE_OK && iOff<iEnd;
  61674. iOff+=pgszSrc
  61675. ){
  61676. PgHdr *pSrcPg = 0;
  61677. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  61678. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  61679. if( rc==SQLITE_OK ){
  61680. u8 *zData = sqlite3PagerGetData(pSrcPg);
  61681. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  61682. }
  61683. sqlite3PagerUnref(pSrcPg);
  61684. }
  61685. if( rc==SQLITE_OK ){
  61686. rc = backupTruncateFile(pFile, iSize);
  61687. }
  61688. /* Sync the database file to disk. */
  61689. if( rc==SQLITE_OK ){
  61690. rc = sqlite3PagerSync(pDestPager, 0);
  61691. }
  61692. }else{
  61693. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  61694. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  61695. }
  61696. /* Finish committing the transaction to the destination database. */
  61697. if( SQLITE_OK==rc
  61698. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  61699. ){
  61700. rc = SQLITE_DONE;
  61701. }
  61702. }
  61703. }
  61704. /* If bCloseTrans is true, then this function opened a read transaction
  61705. ** on the source database. Close the read transaction here. There is
  61706. ** no need to check the return values of the btree methods here, as
  61707. ** "committing" a read-only transaction cannot fail.
  61708. */
  61709. if( bCloseTrans ){
  61710. TESTONLY( int rc2 );
  61711. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  61712. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  61713. assert( rc2==SQLITE_OK );
  61714. }
  61715. if( rc==SQLITE_IOERR_NOMEM ){
  61716. rc = SQLITE_NOMEM_BKPT;
  61717. }
  61718. p->rc = rc;
  61719. }
  61720. if( p->pDestDb ){
  61721. sqlite3_mutex_leave(p->pDestDb->mutex);
  61722. }
  61723. sqlite3BtreeLeave(p->pSrc);
  61724. sqlite3_mutex_leave(p->pSrcDb->mutex);
  61725. return rc;
  61726. }
  61727. /*
  61728. ** Release all resources associated with an sqlite3_backup* handle.
  61729. */
  61730. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
  61731. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  61732. sqlite3 *pSrcDb; /* Source database connection */
  61733. int rc; /* Value to return */
  61734. /* Enter the mutexes */
  61735. if( p==0 ) return SQLITE_OK;
  61736. pSrcDb = p->pSrcDb;
  61737. sqlite3_mutex_enter(pSrcDb->mutex);
  61738. sqlite3BtreeEnter(p->pSrc);
  61739. if( p->pDestDb ){
  61740. sqlite3_mutex_enter(p->pDestDb->mutex);
  61741. }
  61742. /* Detach this backup from the source pager. */
  61743. if( p->pDestDb ){
  61744. p->pSrc->nBackup--;
  61745. }
  61746. if( p->isAttached ){
  61747. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  61748. while( *pp!=p ){
  61749. pp = &(*pp)->pNext;
  61750. }
  61751. *pp = p->pNext;
  61752. }
  61753. /* If a transaction is still open on the Btree, roll it back. */
  61754. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  61755. /* Set the error code of the destination database handle. */
  61756. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  61757. if( p->pDestDb ){
  61758. sqlite3Error(p->pDestDb, rc);
  61759. /* Exit the mutexes and free the backup context structure. */
  61760. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  61761. }
  61762. sqlite3BtreeLeave(p->pSrc);
  61763. if( p->pDestDb ){
  61764. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  61765. ** call to sqlite3_backup_init() and is destroyed by a call to
  61766. ** sqlite3_backup_finish(). */
  61767. sqlite3_free(p);
  61768. }
  61769. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  61770. return rc;
  61771. }
  61772. /*
  61773. ** Return the number of pages still to be backed up as of the most recent
  61774. ** call to sqlite3_backup_step().
  61775. */
  61776. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
  61777. #ifdef SQLITE_ENABLE_API_ARMOR
  61778. if( p==0 ){
  61779. (void)SQLITE_MISUSE_BKPT;
  61780. return 0;
  61781. }
  61782. #endif
  61783. return p->nRemaining;
  61784. }
  61785. /*
  61786. ** Return the total number of pages in the source database as of the most
  61787. ** recent call to sqlite3_backup_step().
  61788. */
  61789. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
  61790. #ifdef SQLITE_ENABLE_API_ARMOR
  61791. if( p==0 ){
  61792. (void)SQLITE_MISUSE_BKPT;
  61793. return 0;
  61794. }
  61795. #endif
  61796. return p->nPagecount;
  61797. }
  61798. /*
  61799. ** This function is called after the contents of page iPage of the
  61800. ** source database have been modified. If page iPage has already been
  61801. ** copied into the destination database, then the data written to the
  61802. ** destination is now invalidated. The destination copy of iPage needs
  61803. ** to be updated with the new data before the backup operation is
  61804. ** complete.
  61805. **
  61806. ** It is assumed that the mutex associated with the BtShared object
  61807. ** corresponding to the source database is held when this function is
  61808. ** called.
  61809. */
  61810. static SQLITE_NOINLINE void backupUpdate(
  61811. sqlite3_backup *p,
  61812. Pgno iPage,
  61813. const u8 *aData
  61814. ){
  61815. assert( p!=0 );
  61816. do{
  61817. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  61818. if( !isFatalError(p->rc) && iPage<p->iNext ){
  61819. /* The backup process p has already copied page iPage. But now it
  61820. ** has been modified by a transaction on the source pager. Copy
  61821. ** the new data into the backup.
  61822. */
  61823. int rc;
  61824. assert( p->pDestDb );
  61825. sqlite3_mutex_enter(p->pDestDb->mutex);
  61826. rc = backupOnePage(p, iPage, aData, 1);
  61827. sqlite3_mutex_leave(p->pDestDb->mutex);
  61828. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  61829. if( rc!=SQLITE_OK ){
  61830. p->rc = rc;
  61831. }
  61832. }
  61833. }while( (p = p->pNext)!=0 );
  61834. }
  61835. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  61836. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  61837. }
  61838. /*
  61839. ** Restart the backup process. This is called when the pager layer
  61840. ** detects that the database has been modified by an external database
  61841. ** connection. In this case there is no way of knowing which of the
  61842. ** pages that have been copied into the destination database are still
  61843. ** valid and which are not, so the entire process needs to be restarted.
  61844. **
  61845. ** It is assumed that the mutex associated with the BtShared object
  61846. ** corresponding to the source database is held when this function is
  61847. ** called.
  61848. */
  61849. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  61850. sqlite3_backup *p; /* Iterator variable */
  61851. for(p=pBackup; p; p=p->pNext){
  61852. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  61853. p->iNext = 1;
  61854. }
  61855. }
  61856. #ifndef SQLITE_OMIT_VACUUM
  61857. /*
  61858. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  61859. ** must be active for both files.
  61860. **
  61861. ** The size of file pTo may be reduced by this operation. If anything
  61862. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  61863. ** transaction is committed before returning.
  61864. */
  61865. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  61866. int rc;
  61867. sqlite3_file *pFd; /* File descriptor for database pTo */
  61868. sqlite3_backup b;
  61869. sqlite3BtreeEnter(pTo);
  61870. sqlite3BtreeEnter(pFrom);
  61871. assert( sqlite3BtreeIsInTrans(pTo) );
  61872. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  61873. if( pFd->pMethods ){
  61874. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  61875. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  61876. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  61877. if( rc ) goto copy_finished;
  61878. }
  61879. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  61880. ** to 0. This is used by the implementations of sqlite3_backup_step()
  61881. ** and sqlite3_backup_finish() to detect that they are being called
  61882. ** from this function, not directly by the user.
  61883. */
  61884. memset(&b, 0, sizeof(b));
  61885. b.pSrcDb = pFrom->db;
  61886. b.pSrc = pFrom;
  61887. b.pDest = pTo;
  61888. b.iNext = 1;
  61889. #ifdef SQLITE_HAS_CODEC
  61890. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  61891. #endif
  61892. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  61893. ** file. By passing this as the number of pages to copy to
  61894. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  61895. ** within a single call (unless an error occurs). The assert() statement
  61896. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  61897. ** or an error code.
  61898. */
  61899. sqlite3_backup_step(&b, 0x7FFFFFFF);
  61900. assert( b.rc!=SQLITE_OK );
  61901. rc = sqlite3_backup_finish(&b);
  61902. if( rc==SQLITE_OK ){
  61903. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  61904. }else{
  61905. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  61906. }
  61907. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  61908. copy_finished:
  61909. sqlite3BtreeLeave(pFrom);
  61910. sqlite3BtreeLeave(pTo);
  61911. return rc;
  61912. }
  61913. #endif /* SQLITE_OMIT_VACUUM */
  61914. /************** End of backup.c **********************************************/
  61915. /************** Begin file vdbemem.c *****************************************/
  61916. /*
  61917. ** 2004 May 26
  61918. **
  61919. ** The author disclaims copyright to this source code. In place of
  61920. ** a legal notice, here is a blessing:
  61921. **
  61922. ** May you do good and not evil.
  61923. ** May you find forgiveness for yourself and forgive others.
  61924. ** May you share freely, never taking more than you give.
  61925. **
  61926. *************************************************************************
  61927. **
  61928. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  61929. ** stores a single value in the VDBE. Mem is an opaque structure visible
  61930. ** only within the VDBE. Interface routines refer to a Mem using the
  61931. ** name sqlite_value
  61932. */
  61933. /* #include "sqliteInt.h" */
  61934. /* #include "vdbeInt.h" */
  61935. #ifdef SQLITE_DEBUG
  61936. /*
  61937. ** Check invariants on a Mem object.
  61938. **
  61939. ** This routine is intended for use inside of assert() statements, like
  61940. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  61941. */
  61942. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  61943. /* If MEM_Dyn is set then Mem.xDel!=0.
  61944. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  61945. */
  61946. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  61947. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  61948. ** ensure that if Mem.szMalloc>0 then it is safe to do
  61949. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  61950. ** That saves a few cycles in inner loops. */
  61951. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  61952. /* Cannot be both MEM_Int and MEM_Real at the same time */
  61953. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  61954. /* The szMalloc field holds the correct memory allocation size */
  61955. assert( p->szMalloc==0
  61956. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  61957. /* If p holds a string or blob, the Mem.z must point to exactly
  61958. ** one of the following:
  61959. **
  61960. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  61961. ** (2) Memory to be freed using Mem.xDel
  61962. ** (3) An ephemeral string or blob
  61963. ** (4) A static string or blob
  61964. */
  61965. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  61966. assert(
  61967. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  61968. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  61969. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  61970. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  61971. );
  61972. }
  61973. return 1;
  61974. }
  61975. #endif
  61976. /*
  61977. ** If pMem is an object with a valid string representation, this routine
  61978. ** ensures the internal encoding for the string representation is
  61979. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  61980. **
  61981. ** If pMem is not a string object, or the encoding of the string
  61982. ** representation is already stored using the requested encoding, then this
  61983. ** routine is a no-op.
  61984. **
  61985. ** SQLITE_OK is returned if the conversion is successful (or not required).
  61986. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  61987. ** between formats.
  61988. */
  61989. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  61990. #ifndef SQLITE_OMIT_UTF16
  61991. int rc;
  61992. #endif
  61993. assert( (pMem->flags&MEM_RowSet)==0 );
  61994. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  61995. || desiredEnc==SQLITE_UTF16BE );
  61996. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  61997. return SQLITE_OK;
  61998. }
  61999. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62000. #ifdef SQLITE_OMIT_UTF16
  62001. return SQLITE_ERROR;
  62002. #else
  62003. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  62004. ** then the encoding of the value may not have changed.
  62005. */
  62006. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  62007. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  62008. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  62009. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  62010. return rc;
  62011. #endif
  62012. }
  62013. /*
  62014. ** Make sure pMem->z points to a writable allocation of at least
  62015. ** min(n,32) bytes.
  62016. **
  62017. ** If the bPreserve argument is true, then copy of the content of
  62018. ** pMem->z into the new allocation. pMem must be either a string or
  62019. ** blob if bPreserve is true. If bPreserve is false, any prior content
  62020. ** in pMem->z is discarded.
  62021. */
  62022. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  62023. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  62024. assert( (pMem->flags&MEM_RowSet)==0 );
  62025. testcase( pMem->db==0 );
  62026. /* If the bPreserve flag is set to true, then the memory cell must already
  62027. ** contain a valid string or blob value. */
  62028. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  62029. testcase( bPreserve && pMem->z==0 );
  62030. assert( pMem->szMalloc==0
  62031. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  62032. if( pMem->szMalloc<n ){
  62033. if( n<32 ) n = 32;
  62034. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  62035. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  62036. bPreserve = 0;
  62037. }else{
  62038. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  62039. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  62040. }
  62041. if( pMem->zMalloc==0 ){
  62042. sqlite3VdbeMemSetNull(pMem);
  62043. pMem->z = 0;
  62044. pMem->szMalloc = 0;
  62045. return SQLITE_NOMEM_BKPT;
  62046. }else{
  62047. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  62048. }
  62049. }
  62050. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  62051. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  62052. }
  62053. if( (pMem->flags&MEM_Dyn)!=0 ){
  62054. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  62055. pMem->xDel((void *)(pMem->z));
  62056. }
  62057. pMem->z = pMem->zMalloc;
  62058. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  62059. return SQLITE_OK;
  62060. }
  62061. /*
  62062. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  62063. ** If pMem->zMalloc already meets or exceeds the requested size, this
  62064. ** routine is a no-op.
  62065. **
  62066. ** Any prior string or blob content in the pMem object may be discarded.
  62067. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  62068. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  62069. ** values are preserved.
  62070. **
  62071. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  62072. ** if unable to complete the resizing.
  62073. */
  62074. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  62075. assert( szNew>0 );
  62076. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  62077. if( pMem->szMalloc<szNew ){
  62078. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  62079. }
  62080. assert( (pMem->flags & MEM_Dyn)==0 );
  62081. pMem->z = pMem->zMalloc;
  62082. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  62083. return SQLITE_OK;
  62084. }
  62085. /*
  62086. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  62087. ** MEM.zMalloc, where it can be safely written.
  62088. **
  62089. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  62090. */
  62091. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  62092. int f;
  62093. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62094. assert( (pMem->flags&MEM_RowSet)==0 );
  62095. ExpandBlob(pMem);
  62096. f = pMem->flags;
  62097. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  62098. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  62099. return SQLITE_NOMEM_BKPT;
  62100. }
  62101. pMem->z[pMem->n] = 0;
  62102. pMem->z[pMem->n+1] = 0;
  62103. pMem->flags |= MEM_Term;
  62104. }
  62105. pMem->flags &= ~MEM_Ephem;
  62106. #ifdef SQLITE_DEBUG
  62107. pMem->pScopyFrom = 0;
  62108. #endif
  62109. return SQLITE_OK;
  62110. }
  62111. /*
  62112. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  62113. ** blob stored in dynamically allocated space.
  62114. */
  62115. #ifndef SQLITE_OMIT_INCRBLOB
  62116. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  62117. if( pMem->flags & MEM_Zero ){
  62118. int nByte;
  62119. assert( pMem->flags&MEM_Blob );
  62120. assert( (pMem->flags&MEM_RowSet)==0 );
  62121. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62122. /* Set nByte to the number of bytes required to store the expanded blob. */
  62123. nByte = pMem->n + pMem->u.nZero;
  62124. if( nByte<=0 ){
  62125. nByte = 1;
  62126. }
  62127. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  62128. return SQLITE_NOMEM_BKPT;
  62129. }
  62130. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  62131. pMem->n += pMem->u.nZero;
  62132. pMem->flags &= ~(MEM_Zero|MEM_Term);
  62133. }
  62134. return SQLITE_OK;
  62135. }
  62136. #endif
  62137. /*
  62138. ** It is already known that pMem contains an unterminated string.
  62139. ** Add the zero terminator.
  62140. */
  62141. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  62142. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  62143. return SQLITE_NOMEM_BKPT;
  62144. }
  62145. pMem->z[pMem->n] = 0;
  62146. pMem->z[pMem->n+1] = 0;
  62147. pMem->flags |= MEM_Term;
  62148. return SQLITE_OK;
  62149. }
  62150. /*
  62151. ** Make sure the given Mem is \u0000 terminated.
  62152. */
  62153. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  62154. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62155. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  62156. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  62157. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  62158. return SQLITE_OK; /* Nothing to do */
  62159. }else{
  62160. return vdbeMemAddTerminator(pMem);
  62161. }
  62162. }
  62163. /*
  62164. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  62165. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  62166. ** is a no-op.
  62167. **
  62168. ** Existing representations MEM_Int and MEM_Real are invalidated if
  62169. ** bForce is true but are retained if bForce is false.
  62170. **
  62171. ** A MEM_Null value will never be passed to this function. This function is
  62172. ** used for converting values to text for returning to the user (i.e. via
  62173. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  62174. ** keys are strings. In the former case a NULL pointer is returned the
  62175. ** user and the latter is an internal programming error.
  62176. */
  62177. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  62178. int fg = pMem->flags;
  62179. const int nByte = 32;
  62180. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62181. assert( !(fg&MEM_Zero) );
  62182. assert( !(fg&(MEM_Str|MEM_Blob)) );
  62183. assert( fg&(MEM_Int|MEM_Real) );
  62184. assert( (pMem->flags&MEM_RowSet)==0 );
  62185. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62186. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  62187. return SQLITE_NOMEM_BKPT;
  62188. }
  62189. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  62190. ** string representation of the value. Then, if the required encoding
  62191. ** is UTF-16le or UTF-16be do a translation.
  62192. **
  62193. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  62194. */
  62195. if( fg & MEM_Int ){
  62196. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  62197. }else{
  62198. assert( fg & MEM_Real );
  62199. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  62200. }
  62201. pMem->n = sqlite3Strlen30(pMem->z);
  62202. pMem->enc = SQLITE_UTF8;
  62203. pMem->flags |= MEM_Str|MEM_Term;
  62204. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  62205. sqlite3VdbeChangeEncoding(pMem, enc);
  62206. return SQLITE_OK;
  62207. }
  62208. /*
  62209. ** Memory cell pMem contains the context of an aggregate function.
  62210. ** This routine calls the finalize method for that function. The
  62211. ** result of the aggregate is stored back into pMem.
  62212. **
  62213. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  62214. ** otherwise.
  62215. */
  62216. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  62217. int rc = SQLITE_OK;
  62218. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  62219. sqlite3_context ctx;
  62220. Mem t;
  62221. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  62222. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62223. memset(&ctx, 0, sizeof(ctx));
  62224. memset(&t, 0, sizeof(t));
  62225. t.flags = MEM_Null;
  62226. t.db = pMem->db;
  62227. ctx.pOut = &t;
  62228. ctx.pMem = pMem;
  62229. ctx.pFunc = pFunc;
  62230. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  62231. assert( (pMem->flags & MEM_Dyn)==0 );
  62232. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  62233. memcpy(pMem, &t, sizeof(t));
  62234. rc = ctx.isError;
  62235. }
  62236. return rc;
  62237. }
  62238. /*
  62239. ** If the memory cell contains a value that must be freed by
  62240. ** invoking the external callback in Mem.xDel, then this routine
  62241. ** will free that value. It also sets Mem.flags to MEM_Null.
  62242. **
  62243. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  62244. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  62245. ** entry point for releasing Mem resources.
  62246. */
  62247. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  62248. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  62249. assert( VdbeMemDynamic(p) );
  62250. if( p->flags&MEM_Agg ){
  62251. sqlite3VdbeMemFinalize(p, p->u.pDef);
  62252. assert( (p->flags & MEM_Agg)==0 );
  62253. testcase( p->flags & MEM_Dyn );
  62254. }
  62255. if( p->flags&MEM_Dyn ){
  62256. assert( (p->flags&MEM_RowSet)==0 );
  62257. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  62258. p->xDel((void *)p->z);
  62259. }else if( p->flags&MEM_RowSet ){
  62260. sqlite3RowSetClear(p->u.pRowSet);
  62261. }else if( p->flags&MEM_Frame ){
  62262. VdbeFrame *pFrame = p->u.pFrame;
  62263. pFrame->pParent = pFrame->v->pDelFrame;
  62264. pFrame->v->pDelFrame = pFrame;
  62265. }
  62266. p->flags = MEM_Null;
  62267. }
  62268. /*
  62269. ** Release memory held by the Mem p, both external memory cleared
  62270. ** by p->xDel and memory in p->zMalloc.
  62271. **
  62272. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  62273. ** the unusual case where there really is memory in p that needs
  62274. ** to be freed.
  62275. */
  62276. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  62277. if( VdbeMemDynamic(p) ){
  62278. vdbeMemClearExternAndSetNull(p);
  62279. }
  62280. if( p->szMalloc ){
  62281. sqlite3DbFree(p->db, p->zMalloc);
  62282. p->szMalloc = 0;
  62283. }
  62284. p->z = 0;
  62285. }
  62286. /*
  62287. ** Release any memory resources held by the Mem. Both the memory that is
  62288. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  62289. **
  62290. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  62291. ** reset a Mem back to its minimum memory utilization.
  62292. **
  62293. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  62294. ** prior to inserting new content into the Mem.
  62295. */
  62296. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  62297. assert( sqlite3VdbeCheckMemInvariants(p) );
  62298. if( VdbeMemDynamic(p) || p->szMalloc ){
  62299. vdbeMemClear(p);
  62300. }
  62301. }
  62302. /*
  62303. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  62304. ** If the double is out of range of a 64-bit signed integer then
  62305. ** return the closest available 64-bit signed integer.
  62306. */
  62307. static i64 doubleToInt64(double r){
  62308. #ifdef SQLITE_OMIT_FLOATING_POINT
  62309. /* When floating-point is omitted, double and int64 are the same thing */
  62310. return r;
  62311. #else
  62312. /*
  62313. ** Many compilers we encounter do not define constants for the
  62314. ** minimum and maximum 64-bit integers, or they define them
  62315. ** inconsistently. And many do not understand the "LL" notation.
  62316. ** So we define our own static constants here using nothing
  62317. ** larger than a 32-bit integer constant.
  62318. */
  62319. static const i64 maxInt = LARGEST_INT64;
  62320. static const i64 minInt = SMALLEST_INT64;
  62321. if( r<=(double)minInt ){
  62322. return minInt;
  62323. }else if( r>=(double)maxInt ){
  62324. return maxInt;
  62325. }else{
  62326. return (i64)r;
  62327. }
  62328. #endif
  62329. }
  62330. /*
  62331. ** Return some kind of integer value which is the best we can do
  62332. ** at representing the value that *pMem describes as an integer.
  62333. ** If pMem is an integer, then the value is exact. If pMem is
  62334. ** a floating-point then the value returned is the integer part.
  62335. ** If pMem is a string or blob, then we make an attempt to convert
  62336. ** it into an integer and return that. If pMem represents an
  62337. ** an SQL-NULL value, return 0.
  62338. **
  62339. ** If pMem represents a string value, its encoding might be changed.
  62340. */
  62341. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  62342. int flags;
  62343. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62344. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62345. flags = pMem->flags;
  62346. if( flags & MEM_Int ){
  62347. return pMem->u.i;
  62348. }else if( flags & MEM_Real ){
  62349. return doubleToInt64(pMem->u.r);
  62350. }else if( flags & (MEM_Str|MEM_Blob) ){
  62351. i64 value = 0;
  62352. assert( pMem->z || pMem->n==0 );
  62353. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  62354. return value;
  62355. }else{
  62356. return 0;
  62357. }
  62358. }
  62359. /*
  62360. ** Return the best representation of pMem that we can get into a
  62361. ** double. If pMem is already a double or an integer, return its
  62362. ** value. If it is a string or blob, try to convert it to a double.
  62363. ** If it is a NULL, return 0.0.
  62364. */
  62365. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  62366. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62367. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62368. if( pMem->flags & MEM_Real ){
  62369. return pMem->u.r;
  62370. }else if( pMem->flags & MEM_Int ){
  62371. return (double)pMem->u.i;
  62372. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  62373. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  62374. double val = (double)0;
  62375. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  62376. return val;
  62377. }else{
  62378. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  62379. return (double)0;
  62380. }
  62381. }
  62382. /*
  62383. ** The MEM structure is already a MEM_Real. Try to also make it a
  62384. ** MEM_Int if we can.
  62385. */
  62386. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  62387. i64 ix;
  62388. assert( pMem->flags & MEM_Real );
  62389. assert( (pMem->flags & MEM_RowSet)==0 );
  62390. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62391. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62392. ix = doubleToInt64(pMem->u.r);
  62393. /* Only mark the value as an integer if
  62394. **
  62395. ** (1) the round-trip conversion real->int->real is a no-op, and
  62396. ** (2) The integer is neither the largest nor the smallest
  62397. ** possible integer (ticket #3922)
  62398. **
  62399. ** The second and third terms in the following conditional enforces
  62400. ** the second condition under the assumption that addition overflow causes
  62401. ** values to wrap around.
  62402. */
  62403. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  62404. pMem->u.i = ix;
  62405. MemSetTypeFlag(pMem, MEM_Int);
  62406. }
  62407. }
  62408. /*
  62409. ** Convert pMem to type integer. Invalidate any prior representations.
  62410. */
  62411. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  62412. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62413. assert( (pMem->flags & MEM_RowSet)==0 );
  62414. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62415. pMem->u.i = sqlite3VdbeIntValue(pMem);
  62416. MemSetTypeFlag(pMem, MEM_Int);
  62417. return SQLITE_OK;
  62418. }
  62419. /*
  62420. ** Convert pMem so that it is of type MEM_Real.
  62421. ** Invalidate any prior representations.
  62422. */
  62423. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  62424. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62425. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62426. pMem->u.r = sqlite3VdbeRealValue(pMem);
  62427. MemSetTypeFlag(pMem, MEM_Real);
  62428. return SQLITE_OK;
  62429. }
  62430. /*
  62431. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  62432. ** Invalidate any prior representations.
  62433. **
  62434. ** Every effort is made to force the conversion, even if the input
  62435. ** is a string that does not look completely like a number. Convert
  62436. ** as much of the string as we can and ignore the rest.
  62437. */
  62438. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  62439. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  62440. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  62441. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62442. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  62443. MemSetTypeFlag(pMem, MEM_Int);
  62444. }else{
  62445. pMem->u.r = sqlite3VdbeRealValue(pMem);
  62446. MemSetTypeFlag(pMem, MEM_Real);
  62447. sqlite3VdbeIntegerAffinity(pMem);
  62448. }
  62449. }
  62450. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  62451. pMem->flags &= ~(MEM_Str|MEM_Blob);
  62452. return SQLITE_OK;
  62453. }
  62454. /*
  62455. ** Cast the datatype of the value in pMem according to the affinity
  62456. ** "aff". Casting is different from applying affinity in that a cast
  62457. ** is forced. In other words, the value is converted into the desired
  62458. ** affinity even if that results in loss of data. This routine is
  62459. ** used (for example) to implement the SQL "cast()" operator.
  62460. */
  62461. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  62462. if( pMem->flags & MEM_Null ) return;
  62463. switch( aff ){
  62464. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  62465. if( (pMem->flags & MEM_Blob)==0 ){
  62466. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  62467. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  62468. MemSetTypeFlag(pMem, MEM_Blob);
  62469. }else{
  62470. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  62471. }
  62472. break;
  62473. }
  62474. case SQLITE_AFF_NUMERIC: {
  62475. sqlite3VdbeMemNumerify(pMem);
  62476. break;
  62477. }
  62478. case SQLITE_AFF_INTEGER: {
  62479. sqlite3VdbeMemIntegerify(pMem);
  62480. break;
  62481. }
  62482. case SQLITE_AFF_REAL: {
  62483. sqlite3VdbeMemRealify(pMem);
  62484. break;
  62485. }
  62486. default: {
  62487. assert( aff==SQLITE_AFF_TEXT );
  62488. assert( MEM_Str==(MEM_Blob>>3) );
  62489. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  62490. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  62491. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  62492. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  62493. break;
  62494. }
  62495. }
  62496. }
  62497. /*
  62498. ** Initialize bulk memory to be a consistent Mem object.
  62499. **
  62500. ** The minimum amount of initialization feasible is performed.
  62501. */
  62502. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  62503. assert( (flags & ~MEM_TypeMask)==0 );
  62504. pMem->flags = flags;
  62505. pMem->db = db;
  62506. pMem->szMalloc = 0;
  62507. }
  62508. /*
  62509. ** Delete any previous value and set the value stored in *pMem to NULL.
  62510. **
  62511. ** This routine calls the Mem.xDel destructor to dispose of values that
  62512. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  62513. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  62514. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  62515. **
  62516. ** Use this routine to reset the Mem prior to insert a new value.
  62517. **
  62518. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  62519. */
  62520. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  62521. if( VdbeMemDynamic(pMem) ){
  62522. vdbeMemClearExternAndSetNull(pMem);
  62523. }else{
  62524. pMem->flags = MEM_Null;
  62525. }
  62526. }
  62527. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  62528. sqlite3VdbeMemSetNull((Mem*)p);
  62529. }
  62530. /*
  62531. ** Delete any previous value and set the value to be a BLOB of length
  62532. ** n containing all zeros.
  62533. */
  62534. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  62535. sqlite3VdbeMemRelease(pMem);
  62536. pMem->flags = MEM_Blob|MEM_Zero;
  62537. pMem->n = 0;
  62538. if( n<0 ) n = 0;
  62539. pMem->u.nZero = n;
  62540. pMem->enc = SQLITE_UTF8;
  62541. pMem->z = 0;
  62542. }
  62543. /*
  62544. ** The pMem is known to contain content that needs to be destroyed prior
  62545. ** to a value change. So invoke the destructor, then set the value to
  62546. ** a 64-bit integer.
  62547. */
  62548. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  62549. sqlite3VdbeMemSetNull(pMem);
  62550. pMem->u.i = val;
  62551. pMem->flags = MEM_Int;
  62552. }
  62553. /*
  62554. ** Delete any previous value and set the value stored in *pMem to val,
  62555. ** manifest type INTEGER.
  62556. */
  62557. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  62558. if( VdbeMemDynamic(pMem) ){
  62559. vdbeReleaseAndSetInt64(pMem, val);
  62560. }else{
  62561. pMem->u.i = val;
  62562. pMem->flags = MEM_Int;
  62563. }
  62564. }
  62565. #ifndef SQLITE_OMIT_FLOATING_POINT
  62566. /*
  62567. ** Delete any previous value and set the value stored in *pMem to val,
  62568. ** manifest type REAL.
  62569. */
  62570. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  62571. sqlite3VdbeMemSetNull(pMem);
  62572. if( !sqlite3IsNaN(val) ){
  62573. pMem->u.r = val;
  62574. pMem->flags = MEM_Real;
  62575. }
  62576. }
  62577. #endif
  62578. /*
  62579. ** Delete any previous value and set the value of pMem to be an
  62580. ** empty boolean index.
  62581. */
  62582. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  62583. sqlite3 *db = pMem->db;
  62584. assert( db!=0 );
  62585. assert( (pMem->flags & MEM_RowSet)==0 );
  62586. sqlite3VdbeMemRelease(pMem);
  62587. pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
  62588. if( db->mallocFailed ){
  62589. pMem->flags = MEM_Null;
  62590. pMem->szMalloc = 0;
  62591. }else{
  62592. assert( pMem->zMalloc );
  62593. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  62594. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  62595. assert( pMem->u.pRowSet!=0 );
  62596. pMem->flags = MEM_RowSet;
  62597. }
  62598. }
  62599. /*
  62600. ** Return true if the Mem object contains a TEXT or BLOB that is
  62601. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  62602. */
  62603. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  62604. assert( p->db!=0 );
  62605. if( p->flags & (MEM_Str|MEM_Blob) ){
  62606. int n = p->n;
  62607. if( p->flags & MEM_Zero ){
  62608. n += p->u.nZero;
  62609. }
  62610. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  62611. }
  62612. return 0;
  62613. }
  62614. #ifdef SQLITE_DEBUG
  62615. /*
  62616. ** This routine prepares a memory cell for modification by breaking
  62617. ** its link to a shallow copy and by marking any current shallow
  62618. ** copies of this cell as invalid.
  62619. **
  62620. ** This is used for testing and debugging only - to make sure shallow
  62621. ** copies are not misused.
  62622. */
  62623. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  62624. int i;
  62625. Mem *pX;
  62626. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  62627. if( pX->pScopyFrom==pMem ){
  62628. pX->flags |= MEM_Undefined;
  62629. pX->pScopyFrom = 0;
  62630. }
  62631. }
  62632. pMem->pScopyFrom = 0;
  62633. }
  62634. #endif /* SQLITE_DEBUG */
  62635. /*
  62636. ** Make an shallow copy of pFrom into pTo. Prior contents of
  62637. ** pTo are freed. The pFrom->z field is not duplicated. If
  62638. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  62639. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  62640. */
  62641. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  62642. vdbeMemClearExternAndSetNull(pTo);
  62643. assert( !VdbeMemDynamic(pTo) );
  62644. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  62645. }
  62646. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  62647. assert( (pFrom->flags & MEM_RowSet)==0 );
  62648. assert( pTo->db==pFrom->db );
  62649. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  62650. memcpy(pTo, pFrom, MEMCELLSIZE);
  62651. if( (pFrom->flags&MEM_Static)==0 ){
  62652. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  62653. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  62654. pTo->flags |= srcType;
  62655. }
  62656. }
  62657. /*
  62658. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  62659. ** freed before the copy is made.
  62660. */
  62661. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  62662. int rc = SQLITE_OK;
  62663. /* The pFrom==0 case in the following assert() is when an sqlite3_value
  62664. ** from sqlite3_value_dup() is used as the argument
  62665. ** to sqlite3_result_value(). */
  62666. assert( pTo->db==pFrom->db || pFrom->db==0 );
  62667. assert( (pFrom->flags & MEM_RowSet)==0 );
  62668. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  62669. memcpy(pTo, pFrom, MEMCELLSIZE);
  62670. pTo->flags &= ~MEM_Dyn;
  62671. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  62672. if( 0==(pFrom->flags&MEM_Static) ){
  62673. pTo->flags |= MEM_Ephem;
  62674. rc = sqlite3VdbeMemMakeWriteable(pTo);
  62675. }
  62676. }
  62677. return rc;
  62678. }
  62679. /*
  62680. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  62681. ** freed. If pFrom contains ephemeral data, a copy is made.
  62682. **
  62683. ** pFrom contains an SQL NULL when this routine returns.
  62684. */
  62685. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  62686. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  62687. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  62688. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  62689. sqlite3VdbeMemRelease(pTo);
  62690. memcpy(pTo, pFrom, sizeof(Mem));
  62691. pFrom->flags = MEM_Null;
  62692. pFrom->szMalloc = 0;
  62693. }
  62694. /*
  62695. ** Change the value of a Mem to be a string or a BLOB.
  62696. **
  62697. ** The memory management strategy depends on the value of the xDel
  62698. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  62699. ** string is copied into a (possibly existing) buffer managed by the
  62700. ** Mem structure. Otherwise, any existing buffer is freed and the
  62701. ** pointer copied.
  62702. **
  62703. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  62704. ** size limit) then no memory allocation occurs. If the string can be
  62705. ** stored without allocating memory, then it is. If a memory allocation
  62706. ** is required to store the string, then value of pMem is unchanged. In
  62707. ** either case, SQLITE_TOOBIG is returned.
  62708. */
  62709. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  62710. Mem *pMem, /* Memory cell to set to string value */
  62711. const char *z, /* String pointer */
  62712. int n, /* Bytes in string, or negative */
  62713. u8 enc, /* Encoding of z. 0 for BLOBs */
  62714. void (*xDel)(void*) /* Destructor function */
  62715. ){
  62716. int nByte = n; /* New value for pMem->n */
  62717. int iLimit; /* Maximum allowed string or blob size */
  62718. u16 flags = 0; /* New value for pMem->flags */
  62719. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62720. assert( (pMem->flags & MEM_RowSet)==0 );
  62721. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  62722. if( !z ){
  62723. sqlite3VdbeMemSetNull(pMem);
  62724. return SQLITE_OK;
  62725. }
  62726. if( pMem->db ){
  62727. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  62728. }else{
  62729. iLimit = SQLITE_MAX_LENGTH;
  62730. }
  62731. flags = (enc==0?MEM_Blob:MEM_Str);
  62732. if( nByte<0 ){
  62733. assert( enc!=0 );
  62734. if( enc==SQLITE_UTF8 ){
  62735. nByte = sqlite3Strlen30(z);
  62736. if( nByte>iLimit ) nByte = iLimit+1;
  62737. }else{
  62738. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  62739. }
  62740. flags |= MEM_Term;
  62741. }
  62742. /* The following block sets the new values of Mem.z and Mem.xDel. It
  62743. ** also sets a flag in local variable "flags" to indicate the memory
  62744. ** management (one of MEM_Dyn or MEM_Static).
  62745. */
  62746. if( xDel==SQLITE_TRANSIENT ){
  62747. int nAlloc = nByte;
  62748. if( flags&MEM_Term ){
  62749. nAlloc += (enc==SQLITE_UTF8?1:2);
  62750. }
  62751. if( nByte>iLimit ){
  62752. return SQLITE_TOOBIG;
  62753. }
  62754. testcase( nAlloc==0 );
  62755. testcase( nAlloc==31 );
  62756. testcase( nAlloc==32 );
  62757. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  62758. return SQLITE_NOMEM_BKPT;
  62759. }
  62760. memcpy(pMem->z, z, nAlloc);
  62761. }else if( xDel==SQLITE_DYNAMIC ){
  62762. sqlite3VdbeMemRelease(pMem);
  62763. pMem->zMalloc = pMem->z = (char *)z;
  62764. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  62765. }else{
  62766. sqlite3VdbeMemRelease(pMem);
  62767. pMem->z = (char *)z;
  62768. pMem->xDel = xDel;
  62769. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  62770. }
  62771. pMem->n = nByte;
  62772. pMem->flags = flags;
  62773. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  62774. #ifndef SQLITE_OMIT_UTF16
  62775. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  62776. return SQLITE_NOMEM_BKPT;
  62777. }
  62778. #endif
  62779. if( nByte>iLimit ){
  62780. return SQLITE_TOOBIG;
  62781. }
  62782. return SQLITE_OK;
  62783. }
  62784. /*
  62785. ** Move data out of a btree key or data field and into a Mem structure.
  62786. ** The data or key is taken from the entry that pCur is currently pointing
  62787. ** to. offset and amt determine what portion of the data or key to retrieve.
  62788. ** key is true to get the key or false to get data. The result is written
  62789. ** into the pMem element.
  62790. **
  62791. ** The pMem object must have been initialized. This routine will use
  62792. ** pMem->zMalloc to hold the content from the btree, if possible. New
  62793. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  62794. ** is responsible for making sure that the pMem object is eventually
  62795. ** destroyed.
  62796. **
  62797. ** If this routine fails for any reason (malloc returns NULL or unable
  62798. ** to read from the disk) then the pMem is left in an inconsistent state.
  62799. */
  62800. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  62801. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  62802. u32 offset, /* Offset from the start of data to return bytes from. */
  62803. u32 amt, /* Number of bytes to return. */
  62804. int key, /* If true, retrieve from the btree key, not data. */
  62805. Mem *pMem /* OUT: Return data in this Mem structure. */
  62806. ){
  62807. int rc;
  62808. pMem->flags = MEM_Null;
  62809. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  62810. if( key ){
  62811. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  62812. }else{
  62813. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  62814. }
  62815. if( rc==SQLITE_OK ){
  62816. pMem->z[amt] = 0;
  62817. pMem->z[amt+1] = 0;
  62818. pMem->flags = MEM_Blob|MEM_Term;
  62819. pMem->n = (int)amt;
  62820. }else{
  62821. sqlite3VdbeMemRelease(pMem);
  62822. }
  62823. }
  62824. return rc;
  62825. }
  62826. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  62827. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  62828. u32 offset, /* Offset from the start of data to return bytes from. */
  62829. u32 amt, /* Number of bytes to return. */
  62830. int key, /* If true, retrieve from the btree key, not data. */
  62831. Mem *pMem /* OUT: Return data in this Mem structure. */
  62832. ){
  62833. char *zData; /* Data from the btree layer */
  62834. u32 available = 0; /* Number of bytes available on the local btree page */
  62835. int rc = SQLITE_OK; /* Return code */
  62836. assert( sqlite3BtreeCursorIsValid(pCur) );
  62837. assert( !VdbeMemDynamic(pMem) );
  62838. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  62839. ** that both the BtShared and database handle mutexes are held. */
  62840. assert( (pMem->flags & MEM_RowSet)==0 );
  62841. if( key ){
  62842. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  62843. }else{
  62844. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  62845. }
  62846. assert( zData!=0 );
  62847. if( offset+amt<=available ){
  62848. pMem->z = &zData[offset];
  62849. pMem->flags = MEM_Blob|MEM_Ephem;
  62850. pMem->n = (int)amt;
  62851. }else{
  62852. rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
  62853. }
  62854. return rc;
  62855. }
  62856. /*
  62857. ** The pVal argument is known to be a value other than NULL.
  62858. ** Convert it into a string with encoding enc and return a pointer
  62859. ** to a zero-terminated version of that string.
  62860. */
  62861. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  62862. assert( pVal!=0 );
  62863. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  62864. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  62865. assert( (pVal->flags & MEM_RowSet)==0 );
  62866. assert( (pVal->flags & (MEM_Null))==0 );
  62867. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  62868. pVal->flags |= MEM_Str;
  62869. if( pVal->flags & MEM_Zero ){
  62870. sqlite3VdbeMemExpandBlob(pVal);
  62871. }
  62872. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  62873. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  62874. }
  62875. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  62876. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  62877. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  62878. return 0;
  62879. }
  62880. }
  62881. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  62882. }else{
  62883. sqlite3VdbeMemStringify(pVal, enc, 0);
  62884. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  62885. }
  62886. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  62887. || pVal->db->mallocFailed );
  62888. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  62889. return pVal->z;
  62890. }else{
  62891. return 0;
  62892. }
  62893. }
  62894. /* This function is only available internally, it is not part of the
  62895. ** external API. It works in a similar way to sqlite3_value_text(),
  62896. ** except the data returned is in the encoding specified by the second
  62897. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  62898. ** SQLITE_UTF8.
  62899. **
  62900. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  62901. ** If that is the case, then the result must be aligned on an even byte
  62902. ** boundary.
  62903. */
  62904. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  62905. if( !pVal ) return 0;
  62906. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  62907. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  62908. assert( (pVal->flags & MEM_RowSet)==0 );
  62909. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  62910. return pVal->z;
  62911. }
  62912. if( pVal->flags&MEM_Null ){
  62913. return 0;
  62914. }
  62915. return valueToText(pVal, enc);
  62916. }
  62917. /*
  62918. ** Create a new sqlite3_value object.
  62919. */
  62920. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  62921. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  62922. if( p ){
  62923. p->flags = MEM_Null;
  62924. p->db = db;
  62925. }
  62926. return p;
  62927. }
  62928. /*
  62929. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  62930. ** valueNew(). See comments above valueNew() for details.
  62931. */
  62932. struct ValueNewStat4Ctx {
  62933. Parse *pParse;
  62934. Index *pIdx;
  62935. UnpackedRecord **ppRec;
  62936. int iVal;
  62937. };
  62938. /*
  62939. ** Allocate and return a pointer to a new sqlite3_value object. If
  62940. ** the second argument to this function is NULL, the object is allocated
  62941. ** by calling sqlite3ValueNew().
  62942. **
  62943. ** Otherwise, if the second argument is non-zero, then this function is
  62944. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  62945. ** already been allocated, allocate the UnpackedRecord structure that
  62946. ** that function will return to its caller here. Then return a pointer to
  62947. ** an sqlite3_value within the UnpackedRecord.a[] array.
  62948. */
  62949. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  62950. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  62951. if( p ){
  62952. UnpackedRecord *pRec = p->ppRec[0];
  62953. if( pRec==0 ){
  62954. Index *pIdx = p->pIdx; /* Index being probed */
  62955. int nByte; /* Bytes of space to allocate */
  62956. int i; /* Counter variable */
  62957. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  62958. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  62959. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  62960. if( pRec ){
  62961. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  62962. if( pRec->pKeyInfo ){
  62963. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  62964. assert( pRec->pKeyInfo->enc==ENC(db) );
  62965. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  62966. for(i=0; i<nCol; i++){
  62967. pRec->aMem[i].flags = MEM_Null;
  62968. pRec->aMem[i].db = db;
  62969. }
  62970. }else{
  62971. sqlite3DbFree(db, pRec);
  62972. pRec = 0;
  62973. }
  62974. }
  62975. if( pRec==0 ) return 0;
  62976. p->ppRec[0] = pRec;
  62977. }
  62978. pRec->nField = p->iVal+1;
  62979. return &pRec->aMem[p->iVal];
  62980. }
  62981. #else
  62982. UNUSED_PARAMETER(p);
  62983. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  62984. return sqlite3ValueNew(db);
  62985. }
  62986. /*
  62987. ** The expression object indicated by the second argument is guaranteed
  62988. ** to be a scalar SQL function. If
  62989. **
  62990. ** * all function arguments are SQL literals,
  62991. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  62992. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  62993. **
  62994. ** then this routine attempts to invoke the SQL function. Assuming no
  62995. ** error occurs, output parameter (*ppVal) is set to point to a value
  62996. ** object containing the result before returning SQLITE_OK.
  62997. **
  62998. ** Affinity aff is applied to the result of the function before returning.
  62999. ** If the result is a text value, the sqlite3_value object uses encoding
  63000. ** enc.
  63001. **
  63002. ** If the conditions above are not met, this function returns SQLITE_OK
  63003. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  63004. ** NULL and an SQLite error code returned.
  63005. */
  63006. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  63007. static int valueFromFunction(
  63008. sqlite3 *db, /* The database connection */
  63009. Expr *p, /* The expression to evaluate */
  63010. u8 enc, /* Encoding to use */
  63011. u8 aff, /* Affinity to use */
  63012. sqlite3_value **ppVal, /* Write the new value here */
  63013. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  63014. ){
  63015. sqlite3_context ctx; /* Context object for function invocation */
  63016. sqlite3_value **apVal = 0; /* Function arguments */
  63017. int nVal = 0; /* Size of apVal[] array */
  63018. FuncDef *pFunc = 0; /* Function definition */
  63019. sqlite3_value *pVal = 0; /* New value */
  63020. int rc = SQLITE_OK; /* Return code */
  63021. ExprList *pList = 0; /* Function arguments */
  63022. int i; /* Iterator variable */
  63023. assert( pCtx!=0 );
  63024. assert( (p->flags & EP_TokenOnly)==0 );
  63025. pList = p->x.pList;
  63026. if( pList ) nVal = pList->nExpr;
  63027. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  63028. assert( pFunc );
  63029. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  63030. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  63031. ){
  63032. return SQLITE_OK;
  63033. }
  63034. if( pList ){
  63035. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  63036. if( apVal==0 ){
  63037. rc = SQLITE_NOMEM_BKPT;
  63038. goto value_from_function_out;
  63039. }
  63040. for(i=0; i<nVal; i++){
  63041. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  63042. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  63043. }
  63044. }
  63045. pVal = valueNew(db, pCtx);
  63046. if( pVal==0 ){
  63047. rc = SQLITE_NOMEM_BKPT;
  63048. goto value_from_function_out;
  63049. }
  63050. assert( pCtx->pParse->rc==SQLITE_OK );
  63051. memset(&ctx, 0, sizeof(ctx));
  63052. ctx.pOut = pVal;
  63053. ctx.pFunc = pFunc;
  63054. pFunc->xSFunc(&ctx, nVal, apVal);
  63055. if( ctx.isError ){
  63056. rc = ctx.isError;
  63057. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  63058. }else{
  63059. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  63060. assert( rc==SQLITE_OK );
  63061. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  63062. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  63063. rc = SQLITE_TOOBIG;
  63064. pCtx->pParse->nErr++;
  63065. }
  63066. }
  63067. pCtx->pParse->rc = rc;
  63068. value_from_function_out:
  63069. if( rc!=SQLITE_OK ){
  63070. pVal = 0;
  63071. }
  63072. if( apVal ){
  63073. for(i=0; i<nVal; i++){
  63074. sqlite3ValueFree(apVal[i]);
  63075. }
  63076. sqlite3DbFree(db, apVal);
  63077. }
  63078. *ppVal = pVal;
  63079. return rc;
  63080. }
  63081. #else
  63082. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  63083. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  63084. /*
  63085. ** Extract a value from the supplied expression in the manner described
  63086. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  63087. ** using valueNew().
  63088. **
  63089. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  63090. ** has been allocated, it is freed before returning. Or, if pCtx is not
  63091. ** NULL, it is assumed that the caller will free any allocated object
  63092. ** in all cases.
  63093. */
  63094. static int valueFromExpr(
  63095. sqlite3 *db, /* The database connection */
  63096. Expr *pExpr, /* The expression to evaluate */
  63097. u8 enc, /* Encoding to use */
  63098. u8 affinity, /* Affinity to use */
  63099. sqlite3_value **ppVal, /* Write the new value here */
  63100. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  63101. ){
  63102. int op;
  63103. char *zVal = 0;
  63104. sqlite3_value *pVal = 0;
  63105. int negInt = 1;
  63106. const char *zNeg = "";
  63107. int rc = SQLITE_OK;
  63108. if( !pExpr ){
  63109. *ppVal = 0;
  63110. return SQLITE_OK;
  63111. }
  63112. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  63113. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  63114. /* Compressed expressions only appear when parsing the DEFAULT clause
  63115. ** on a table column definition, and hence only when pCtx==0. This
  63116. ** check ensures that an EP_TokenOnly expression is never passed down
  63117. ** into valueFromFunction(). */
  63118. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  63119. if( op==TK_CAST ){
  63120. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  63121. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  63122. testcase( rc!=SQLITE_OK );
  63123. if( *ppVal ){
  63124. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  63125. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  63126. }
  63127. return rc;
  63128. }
  63129. /* Handle negative integers in a single step. This is needed in the
  63130. ** case when the value is -9223372036854775808.
  63131. */
  63132. if( op==TK_UMINUS
  63133. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  63134. pExpr = pExpr->pLeft;
  63135. op = pExpr->op;
  63136. negInt = -1;
  63137. zNeg = "-";
  63138. }
  63139. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  63140. pVal = valueNew(db, pCtx);
  63141. if( pVal==0 ) goto no_mem;
  63142. if( ExprHasProperty(pExpr, EP_IntValue) ){
  63143. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  63144. }else{
  63145. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  63146. if( zVal==0 ) goto no_mem;
  63147. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  63148. }
  63149. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  63150. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  63151. }else{
  63152. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  63153. }
  63154. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  63155. if( enc!=SQLITE_UTF8 ){
  63156. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  63157. }
  63158. }else if( op==TK_UMINUS ) {
  63159. /* This branch happens for multiple negative signs. Ex: -(-5) */
  63160. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  63161. && pVal!=0
  63162. ){
  63163. sqlite3VdbeMemNumerify(pVal);
  63164. if( pVal->flags & MEM_Real ){
  63165. pVal->u.r = -pVal->u.r;
  63166. }else if( pVal->u.i==SMALLEST_INT64 ){
  63167. pVal->u.r = -(double)SMALLEST_INT64;
  63168. MemSetTypeFlag(pVal, MEM_Real);
  63169. }else{
  63170. pVal->u.i = -pVal->u.i;
  63171. }
  63172. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  63173. }
  63174. }else if( op==TK_NULL ){
  63175. pVal = valueNew(db, pCtx);
  63176. if( pVal==0 ) goto no_mem;
  63177. }
  63178. #ifndef SQLITE_OMIT_BLOB_LITERAL
  63179. else if( op==TK_BLOB ){
  63180. int nVal;
  63181. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  63182. assert( pExpr->u.zToken[1]=='\'' );
  63183. pVal = valueNew(db, pCtx);
  63184. if( !pVal ) goto no_mem;
  63185. zVal = &pExpr->u.zToken[2];
  63186. nVal = sqlite3Strlen30(zVal)-1;
  63187. assert( zVal[nVal]=='\'' );
  63188. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  63189. 0, SQLITE_DYNAMIC);
  63190. }
  63191. #endif
  63192. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  63193. else if( op==TK_FUNCTION && pCtx!=0 ){
  63194. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  63195. }
  63196. #endif
  63197. *ppVal = pVal;
  63198. return rc;
  63199. no_mem:
  63200. sqlite3OomFault(db);
  63201. sqlite3DbFree(db, zVal);
  63202. assert( *ppVal==0 );
  63203. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  63204. if( pCtx==0 ) sqlite3ValueFree(pVal);
  63205. #else
  63206. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  63207. #endif
  63208. return SQLITE_NOMEM_BKPT;
  63209. }
  63210. /*
  63211. ** Create a new sqlite3_value object, containing the value of pExpr.
  63212. **
  63213. ** This only works for very simple expressions that consist of one constant
  63214. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  63215. ** be converted directly into a value, then the value is allocated and
  63216. ** a pointer written to *ppVal. The caller is responsible for deallocating
  63217. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  63218. ** cannot be converted to a value, then *ppVal is set to NULL.
  63219. */
  63220. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  63221. sqlite3 *db, /* The database connection */
  63222. Expr *pExpr, /* The expression to evaluate */
  63223. u8 enc, /* Encoding to use */
  63224. u8 affinity, /* Affinity to use */
  63225. sqlite3_value **ppVal /* Write the new value here */
  63226. ){
  63227. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  63228. }
  63229. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  63230. /*
  63231. ** The implementation of the sqlite_record() function. This function accepts
  63232. ** a single argument of any type. The return value is a formatted database
  63233. ** record (a blob) containing the argument value.
  63234. **
  63235. ** This is used to convert the value stored in the 'sample' column of the
  63236. ** sqlite_stat3 table to the record format SQLite uses internally.
  63237. */
  63238. static void recordFunc(
  63239. sqlite3_context *context,
  63240. int argc,
  63241. sqlite3_value **argv
  63242. ){
  63243. const int file_format = 1;
  63244. u32 iSerial; /* Serial type */
  63245. int nSerial; /* Bytes of space for iSerial as varint */
  63246. u32 nVal; /* Bytes of space required for argv[0] */
  63247. int nRet;
  63248. sqlite3 *db;
  63249. u8 *aRet;
  63250. UNUSED_PARAMETER( argc );
  63251. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  63252. nSerial = sqlite3VarintLen(iSerial);
  63253. db = sqlite3_context_db_handle(context);
  63254. nRet = 1 + nSerial + nVal;
  63255. aRet = sqlite3DbMallocRawNN(db, nRet);
  63256. if( aRet==0 ){
  63257. sqlite3_result_error_nomem(context);
  63258. }else{
  63259. aRet[0] = nSerial+1;
  63260. putVarint32(&aRet[1], iSerial);
  63261. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  63262. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  63263. sqlite3DbFree(db, aRet);
  63264. }
  63265. }
  63266. /*
  63267. ** Register built-in functions used to help read ANALYZE data.
  63268. */
  63269. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  63270. static FuncDef aAnalyzeTableFuncs[] = {
  63271. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  63272. };
  63273. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  63274. }
  63275. /*
  63276. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  63277. **
  63278. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  63279. ** pAlloc if one does not exist and the new value is added to the
  63280. ** UnpackedRecord object.
  63281. **
  63282. ** A value is extracted in the following cases:
  63283. **
  63284. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  63285. **
  63286. ** * The expression is a bound variable, and this is a reprepare, or
  63287. **
  63288. ** * The expression is a literal value.
  63289. **
  63290. ** On success, *ppVal is made to point to the extracted value. The caller
  63291. ** is responsible for ensuring that the value is eventually freed.
  63292. */
  63293. static int stat4ValueFromExpr(
  63294. Parse *pParse, /* Parse context */
  63295. Expr *pExpr, /* The expression to extract a value from */
  63296. u8 affinity, /* Affinity to use */
  63297. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  63298. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  63299. ){
  63300. int rc = SQLITE_OK;
  63301. sqlite3_value *pVal = 0;
  63302. sqlite3 *db = pParse->db;
  63303. /* Skip over any TK_COLLATE nodes */
  63304. pExpr = sqlite3ExprSkipCollate(pExpr);
  63305. if( !pExpr ){
  63306. pVal = valueNew(db, pAlloc);
  63307. if( pVal ){
  63308. sqlite3VdbeMemSetNull((Mem*)pVal);
  63309. }
  63310. }else if( pExpr->op==TK_VARIABLE
  63311. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  63312. ){
  63313. Vdbe *v;
  63314. int iBindVar = pExpr->iColumn;
  63315. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  63316. if( (v = pParse->pReprepare)!=0 ){
  63317. pVal = valueNew(db, pAlloc);
  63318. if( pVal ){
  63319. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  63320. if( rc==SQLITE_OK ){
  63321. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  63322. }
  63323. pVal->db = pParse->db;
  63324. }
  63325. }
  63326. }else{
  63327. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  63328. }
  63329. assert( pVal==0 || pVal->db==db );
  63330. *ppVal = pVal;
  63331. return rc;
  63332. }
  63333. /*
  63334. ** This function is used to allocate and populate UnpackedRecord
  63335. ** structures intended to be compared against sample index keys stored
  63336. ** in the sqlite_stat4 table.
  63337. **
  63338. ** A single call to this function attempts to populates field iVal (leftmost
  63339. ** is 0 etc.) of the unpacked record with a value extracted from expression
  63340. ** pExpr. Extraction of values is possible if:
  63341. **
  63342. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  63343. **
  63344. ** * The expression is a bound variable, and this is a reprepare, or
  63345. **
  63346. ** * The sqlite3ValueFromExpr() function is able to extract a value
  63347. ** from the expression (i.e. the expression is a literal value).
  63348. **
  63349. ** If a value can be extracted, the affinity passed as the 5th argument
  63350. ** is applied to it before it is copied into the UnpackedRecord. Output
  63351. ** parameter *pbOk is set to true if a value is extracted, or false
  63352. ** otherwise.
  63353. **
  63354. ** When this function is called, *ppRec must either point to an object
  63355. ** allocated by an earlier call to this function, or must be NULL. If it
  63356. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  63357. ** is allocated (and *ppRec set to point to it) before returning.
  63358. **
  63359. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  63360. ** error if a value cannot be extracted from pExpr. If an error does
  63361. ** occur, an SQLite error code is returned.
  63362. */
  63363. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  63364. Parse *pParse, /* Parse context */
  63365. Index *pIdx, /* Index being probed */
  63366. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  63367. Expr *pExpr, /* The expression to extract a value from */
  63368. u8 affinity, /* Affinity to use */
  63369. int iVal, /* Array element to populate */
  63370. int *pbOk /* OUT: True if value was extracted */
  63371. ){
  63372. int rc;
  63373. sqlite3_value *pVal = 0;
  63374. struct ValueNewStat4Ctx alloc;
  63375. alloc.pParse = pParse;
  63376. alloc.pIdx = pIdx;
  63377. alloc.ppRec = ppRec;
  63378. alloc.iVal = iVal;
  63379. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  63380. assert( pVal==0 || pVal->db==pParse->db );
  63381. *pbOk = (pVal!=0);
  63382. return rc;
  63383. }
  63384. /*
  63385. ** Attempt to extract a value from expression pExpr using the methods
  63386. ** as described for sqlite3Stat4ProbeSetValue() above.
  63387. **
  63388. ** If successful, set *ppVal to point to a new value object and return
  63389. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  63390. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  63391. ** does occur, return an SQLite error code. The final value of *ppVal
  63392. ** is undefined in this case.
  63393. */
  63394. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  63395. Parse *pParse, /* Parse context */
  63396. Expr *pExpr, /* The expression to extract a value from */
  63397. u8 affinity, /* Affinity to use */
  63398. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  63399. ){
  63400. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  63401. }
  63402. /*
  63403. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  63404. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  63405. ** sqlite3_value object is allocated.
  63406. **
  63407. ** If *ppVal is initially NULL then the caller is responsible for
  63408. ** ensuring that the value written into *ppVal is eventually freed.
  63409. */
  63410. SQLITE_PRIVATE int sqlite3Stat4Column(
  63411. sqlite3 *db, /* Database handle */
  63412. const void *pRec, /* Pointer to buffer containing record */
  63413. int nRec, /* Size of buffer pRec in bytes */
  63414. int iCol, /* Column to extract */
  63415. sqlite3_value **ppVal /* OUT: Extracted value */
  63416. ){
  63417. u32 t; /* a column type code */
  63418. int nHdr; /* Size of the header in the record */
  63419. int iHdr; /* Next unread header byte */
  63420. int iField; /* Next unread data byte */
  63421. int szField; /* Size of the current data field */
  63422. int i; /* Column index */
  63423. u8 *a = (u8*)pRec; /* Typecast byte array */
  63424. Mem *pMem = *ppVal; /* Write result into this Mem object */
  63425. assert( iCol>0 );
  63426. iHdr = getVarint32(a, nHdr);
  63427. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  63428. iField = nHdr;
  63429. for(i=0; i<=iCol; i++){
  63430. iHdr += getVarint32(&a[iHdr], t);
  63431. testcase( iHdr==nHdr );
  63432. testcase( iHdr==nHdr+1 );
  63433. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  63434. szField = sqlite3VdbeSerialTypeLen(t);
  63435. iField += szField;
  63436. }
  63437. testcase( iField==nRec );
  63438. testcase( iField==nRec+1 );
  63439. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  63440. if( pMem==0 ){
  63441. pMem = *ppVal = sqlite3ValueNew(db);
  63442. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  63443. }
  63444. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  63445. pMem->enc = ENC(db);
  63446. return SQLITE_OK;
  63447. }
  63448. /*
  63449. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  63450. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  63451. ** the object.
  63452. */
  63453. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  63454. if( pRec ){
  63455. int i;
  63456. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  63457. Mem *aMem = pRec->aMem;
  63458. sqlite3 *db = aMem[0].db;
  63459. for(i=0; i<nCol; i++){
  63460. sqlite3VdbeMemRelease(&aMem[i]);
  63461. }
  63462. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  63463. sqlite3DbFree(db, pRec);
  63464. }
  63465. }
  63466. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  63467. /*
  63468. ** Change the string value of an sqlite3_value object
  63469. */
  63470. SQLITE_PRIVATE void sqlite3ValueSetStr(
  63471. sqlite3_value *v, /* Value to be set */
  63472. int n, /* Length of string z */
  63473. const void *z, /* Text of the new string */
  63474. u8 enc, /* Encoding to use */
  63475. void (*xDel)(void*) /* Destructor for the string */
  63476. ){
  63477. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  63478. }
  63479. /*
  63480. ** Free an sqlite3_value object
  63481. */
  63482. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  63483. if( !v ) return;
  63484. sqlite3VdbeMemRelease((Mem *)v);
  63485. sqlite3DbFree(((Mem*)v)->db, v);
  63486. }
  63487. /*
  63488. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  63489. ** sqlite3_value object assuming that it uses the encoding "enc".
  63490. ** The valueBytes() routine is a helper function.
  63491. */
  63492. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  63493. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  63494. }
  63495. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  63496. Mem *p = (Mem*)pVal;
  63497. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  63498. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  63499. return p->n;
  63500. }
  63501. if( (p->flags & MEM_Blob)!=0 ){
  63502. if( p->flags & MEM_Zero ){
  63503. return p->n + p->u.nZero;
  63504. }else{
  63505. return p->n;
  63506. }
  63507. }
  63508. if( p->flags & MEM_Null ) return 0;
  63509. return valueBytes(pVal, enc);
  63510. }
  63511. /************** End of vdbemem.c *********************************************/
  63512. /************** Begin file vdbeaux.c *****************************************/
  63513. /*
  63514. ** 2003 September 6
  63515. **
  63516. ** The author disclaims copyright to this source code. In place of
  63517. ** a legal notice, here is a blessing:
  63518. **
  63519. ** May you do good and not evil.
  63520. ** May you find forgiveness for yourself and forgive others.
  63521. ** May you share freely, never taking more than you give.
  63522. **
  63523. *************************************************************************
  63524. ** This file contains code used for creating, destroying, and populating
  63525. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  63526. */
  63527. /* #include "sqliteInt.h" */
  63528. /* #include "vdbeInt.h" */
  63529. /*
  63530. ** Create a new virtual database engine.
  63531. */
  63532. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  63533. sqlite3 *db = pParse->db;
  63534. Vdbe *p;
  63535. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  63536. if( p==0 ) return 0;
  63537. p->db = db;
  63538. if( db->pVdbe ){
  63539. db->pVdbe->pPrev = p;
  63540. }
  63541. p->pNext = db->pVdbe;
  63542. p->pPrev = 0;
  63543. db->pVdbe = p;
  63544. p->magic = VDBE_MAGIC_INIT;
  63545. p->pParse = pParse;
  63546. assert( pParse->aLabel==0 );
  63547. assert( pParse->nLabel==0 );
  63548. assert( pParse->nOpAlloc==0 );
  63549. assert( pParse->szOpAlloc==0 );
  63550. return p;
  63551. }
  63552. /*
  63553. ** Change the error string stored in Vdbe.zErrMsg
  63554. */
  63555. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  63556. va_list ap;
  63557. sqlite3DbFree(p->db, p->zErrMsg);
  63558. va_start(ap, zFormat);
  63559. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  63560. va_end(ap);
  63561. }
  63562. /*
  63563. ** Remember the SQL string for a prepared statement.
  63564. */
  63565. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  63566. assert( isPrepareV2==1 || isPrepareV2==0 );
  63567. if( p==0 ) return;
  63568. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  63569. if( !isPrepareV2 ) return;
  63570. #endif
  63571. assert( p->zSql==0 );
  63572. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  63573. p->isPrepareV2 = (u8)isPrepareV2;
  63574. }
  63575. /*
  63576. ** Return the SQL associated with a prepared statement
  63577. */
  63578. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
  63579. Vdbe *p = (Vdbe *)pStmt;
  63580. return p ? p->zSql : 0;
  63581. }
  63582. /*
  63583. ** Swap all content between two VDBE structures.
  63584. */
  63585. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  63586. Vdbe tmp, *pTmp;
  63587. char *zTmp;
  63588. tmp = *pA;
  63589. *pA = *pB;
  63590. *pB = tmp;
  63591. pTmp = pA->pNext;
  63592. pA->pNext = pB->pNext;
  63593. pB->pNext = pTmp;
  63594. pTmp = pA->pPrev;
  63595. pA->pPrev = pB->pPrev;
  63596. pB->pPrev = pTmp;
  63597. zTmp = pA->zSql;
  63598. pA->zSql = pB->zSql;
  63599. pB->zSql = zTmp;
  63600. pB->isPrepareV2 = pA->isPrepareV2;
  63601. }
  63602. /*
  63603. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  63604. ** than its current size. nOp is guaranteed to be less than or equal
  63605. ** to 1024/sizeof(Op).
  63606. **
  63607. ** If an out-of-memory error occurs while resizing the array, return
  63608. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  63609. ** unchanged (this is so that any opcodes already allocated can be
  63610. ** correctly deallocated along with the rest of the Vdbe).
  63611. */
  63612. static int growOpArray(Vdbe *v, int nOp){
  63613. VdbeOp *pNew;
  63614. Parse *p = v->pParse;
  63615. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  63616. ** more frequent reallocs and hence provide more opportunities for
  63617. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  63618. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  63619. ** by the minimum* amount required until the size reaches 512. Normal
  63620. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  63621. ** size of the op array or add 1KB of space, whichever is smaller. */
  63622. #ifdef SQLITE_TEST_REALLOC_STRESS
  63623. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  63624. #else
  63625. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  63626. UNUSED_PARAMETER(nOp);
  63627. #endif
  63628. assert( nOp<=(1024/sizeof(Op)) );
  63629. assert( nNew>=(p->nOpAlloc+nOp) );
  63630. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  63631. if( pNew ){
  63632. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  63633. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  63634. v->aOp = pNew;
  63635. }
  63636. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  63637. }
  63638. #ifdef SQLITE_DEBUG
  63639. /* This routine is just a convenient place to set a breakpoint that will
  63640. ** fire after each opcode is inserted and displayed using
  63641. ** "PRAGMA vdbe_addoptrace=on".
  63642. */
  63643. static void test_addop_breakpoint(void){
  63644. static int n = 0;
  63645. n++;
  63646. }
  63647. #endif
  63648. /*
  63649. ** Add a new instruction to the list of instructions current in the
  63650. ** VDBE. Return the address of the new instruction.
  63651. **
  63652. ** Parameters:
  63653. **
  63654. ** p Pointer to the VDBE
  63655. **
  63656. ** op The opcode for this instruction
  63657. **
  63658. ** p1, p2, p3 Operands
  63659. **
  63660. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  63661. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  63662. ** operand.
  63663. */
  63664. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  63665. assert( p->pParse->nOpAlloc<=p->nOp );
  63666. if( growOpArray(p, 1) ) return 1;
  63667. assert( p->pParse->nOpAlloc>p->nOp );
  63668. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  63669. }
  63670. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  63671. int i;
  63672. VdbeOp *pOp;
  63673. i = p->nOp;
  63674. assert( p->magic==VDBE_MAGIC_INIT );
  63675. assert( op>=0 && op<0xff );
  63676. if( p->pParse->nOpAlloc<=i ){
  63677. return growOp3(p, op, p1, p2, p3);
  63678. }
  63679. p->nOp++;
  63680. pOp = &p->aOp[i];
  63681. pOp->opcode = (u8)op;
  63682. pOp->p5 = 0;
  63683. pOp->p1 = p1;
  63684. pOp->p2 = p2;
  63685. pOp->p3 = p3;
  63686. pOp->p4.p = 0;
  63687. pOp->p4type = P4_NOTUSED;
  63688. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63689. pOp->zComment = 0;
  63690. #endif
  63691. #ifdef SQLITE_DEBUG
  63692. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  63693. int jj, kk;
  63694. Parse *pParse = p->pParse;
  63695. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  63696. struct yColCache *x = pParse->aColCache + jj;
  63697. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  63698. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  63699. kk++;
  63700. }
  63701. if( kk ) printf("\n");
  63702. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  63703. test_addop_breakpoint();
  63704. }
  63705. #endif
  63706. #ifdef VDBE_PROFILE
  63707. pOp->cycles = 0;
  63708. pOp->cnt = 0;
  63709. #endif
  63710. #ifdef SQLITE_VDBE_COVERAGE
  63711. pOp->iSrcLine = 0;
  63712. #endif
  63713. return i;
  63714. }
  63715. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  63716. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  63717. }
  63718. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  63719. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  63720. }
  63721. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  63722. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  63723. }
  63724. /* Generate code for an unconditional jump to instruction iDest
  63725. */
  63726. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  63727. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  63728. }
  63729. /* Generate code to cause the string zStr to be loaded into
  63730. ** register iDest
  63731. */
  63732. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  63733. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  63734. }
  63735. /*
  63736. ** Generate code that initializes multiple registers to string or integer
  63737. ** constants. The registers begin with iDest and increase consecutively.
  63738. ** One register is initialized for each characgter in zTypes[]. For each
  63739. ** "s" character in zTypes[], the register is a string if the argument is
  63740. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  63741. ** in zTypes[], the register is initialized to an integer.
  63742. */
  63743. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  63744. va_list ap;
  63745. int i;
  63746. char c;
  63747. va_start(ap, zTypes);
  63748. for(i=0; (c = zTypes[i])!=0; i++){
  63749. if( c=='s' ){
  63750. const char *z = va_arg(ap, const char*);
  63751. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
  63752. }else{
  63753. assert( c=='i' );
  63754. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
  63755. }
  63756. }
  63757. va_end(ap);
  63758. }
  63759. /*
  63760. ** Add an opcode that includes the p4 value as a pointer.
  63761. */
  63762. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  63763. Vdbe *p, /* Add the opcode to this VM */
  63764. int op, /* The new opcode */
  63765. int p1, /* The P1 operand */
  63766. int p2, /* The P2 operand */
  63767. int p3, /* The P3 operand */
  63768. const char *zP4, /* The P4 operand */
  63769. int p4type /* P4 operand type */
  63770. ){
  63771. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  63772. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  63773. return addr;
  63774. }
  63775. /*
  63776. ** Add an opcode that includes the p4 value with a P4_INT64 or
  63777. ** P4_REAL type.
  63778. */
  63779. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  63780. Vdbe *p, /* Add the opcode to this VM */
  63781. int op, /* The new opcode */
  63782. int p1, /* The P1 operand */
  63783. int p2, /* The P2 operand */
  63784. int p3, /* The P3 operand */
  63785. const u8 *zP4, /* The P4 operand */
  63786. int p4type /* P4 operand type */
  63787. ){
  63788. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  63789. if( p4copy ) memcpy(p4copy, zP4, 8);
  63790. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  63791. }
  63792. /*
  63793. ** Add an OP_ParseSchema opcode. This routine is broken out from
  63794. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  63795. ** as having been used.
  63796. **
  63797. ** The zWhere string must have been obtained from sqlite3_malloc().
  63798. ** This routine will take ownership of the allocated memory.
  63799. */
  63800. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  63801. int j;
  63802. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  63803. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  63804. }
  63805. /*
  63806. ** Add an opcode that includes the p4 value as an integer.
  63807. */
  63808. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  63809. Vdbe *p, /* Add the opcode to this VM */
  63810. int op, /* The new opcode */
  63811. int p1, /* The P1 operand */
  63812. int p2, /* The P2 operand */
  63813. int p3, /* The P3 operand */
  63814. int p4 /* The P4 operand as an integer */
  63815. ){
  63816. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  63817. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  63818. return addr;
  63819. }
  63820. /* Insert the end of a co-routine
  63821. */
  63822. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  63823. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  63824. /* Clear the temporary register cache, thereby ensuring that each
  63825. ** co-routine has its own independent set of registers, because co-routines
  63826. ** might expect their registers to be preserved across an OP_Yield, and
  63827. ** that could cause problems if two or more co-routines are using the same
  63828. ** temporary register.
  63829. */
  63830. v->pParse->nTempReg = 0;
  63831. v->pParse->nRangeReg = 0;
  63832. }
  63833. /*
  63834. ** Create a new symbolic label for an instruction that has yet to be
  63835. ** coded. The symbolic label is really just a negative number. The
  63836. ** label can be used as the P2 value of an operation. Later, when
  63837. ** the label is resolved to a specific address, the VDBE will scan
  63838. ** through its operation list and change all values of P2 which match
  63839. ** the label into the resolved address.
  63840. **
  63841. ** The VDBE knows that a P2 value is a label because labels are
  63842. ** always negative and P2 values are suppose to be non-negative.
  63843. ** Hence, a negative P2 value is a label that has yet to be resolved.
  63844. **
  63845. ** Zero is returned if a malloc() fails.
  63846. */
  63847. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  63848. Parse *p = v->pParse;
  63849. int i = p->nLabel++;
  63850. assert( v->magic==VDBE_MAGIC_INIT );
  63851. if( (i & (i-1))==0 ){
  63852. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  63853. (i*2+1)*sizeof(p->aLabel[0]));
  63854. }
  63855. if( p->aLabel ){
  63856. p->aLabel[i] = -1;
  63857. }
  63858. return ADDR(i);
  63859. }
  63860. /*
  63861. ** Resolve label "x" to be the address of the next instruction to
  63862. ** be inserted. The parameter "x" must have been obtained from
  63863. ** a prior call to sqlite3VdbeMakeLabel().
  63864. */
  63865. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  63866. Parse *p = v->pParse;
  63867. int j = ADDR(x);
  63868. assert( v->magic==VDBE_MAGIC_INIT );
  63869. assert( j<p->nLabel );
  63870. assert( j>=0 );
  63871. if( p->aLabel ){
  63872. p->aLabel[j] = v->nOp;
  63873. }
  63874. p->iFixedOp = v->nOp - 1;
  63875. }
  63876. /*
  63877. ** Mark the VDBE as one that can only be run one time.
  63878. */
  63879. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  63880. p->runOnlyOnce = 1;
  63881. }
  63882. /*
  63883. ** Mark the VDBE as one that can only be run multiple times.
  63884. */
  63885. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  63886. p->runOnlyOnce = 0;
  63887. }
  63888. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  63889. /*
  63890. ** The following type and function are used to iterate through all opcodes
  63891. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  63892. ** invoke directly or indirectly. It should be used as follows:
  63893. **
  63894. ** Op *pOp;
  63895. ** VdbeOpIter sIter;
  63896. **
  63897. ** memset(&sIter, 0, sizeof(sIter));
  63898. ** sIter.v = v; // v is of type Vdbe*
  63899. ** while( (pOp = opIterNext(&sIter)) ){
  63900. ** // Do something with pOp
  63901. ** }
  63902. ** sqlite3DbFree(v->db, sIter.apSub);
  63903. **
  63904. */
  63905. typedef struct VdbeOpIter VdbeOpIter;
  63906. struct VdbeOpIter {
  63907. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  63908. SubProgram **apSub; /* Array of subprograms */
  63909. int nSub; /* Number of entries in apSub */
  63910. int iAddr; /* Address of next instruction to return */
  63911. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  63912. };
  63913. static Op *opIterNext(VdbeOpIter *p){
  63914. Vdbe *v = p->v;
  63915. Op *pRet = 0;
  63916. Op *aOp;
  63917. int nOp;
  63918. if( p->iSub<=p->nSub ){
  63919. if( p->iSub==0 ){
  63920. aOp = v->aOp;
  63921. nOp = v->nOp;
  63922. }else{
  63923. aOp = p->apSub[p->iSub-1]->aOp;
  63924. nOp = p->apSub[p->iSub-1]->nOp;
  63925. }
  63926. assert( p->iAddr<nOp );
  63927. pRet = &aOp[p->iAddr];
  63928. p->iAddr++;
  63929. if( p->iAddr==nOp ){
  63930. p->iSub++;
  63931. p->iAddr = 0;
  63932. }
  63933. if( pRet->p4type==P4_SUBPROGRAM ){
  63934. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  63935. int j;
  63936. for(j=0; j<p->nSub; j++){
  63937. if( p->apSub[j]==pRet->p4.pProgram ) break;
  63938. }
  63939. if( j==p->nSub ){
  63940. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  63941. if( !p->apSub ){
  63942. pRet = 0;
  63943. }else{
  63944. p->apSub[p->nSub++] = pRet->p4.pProgram;
  63945. }
  63946. }
  63947. }
  63948. }
  63949. return pRet;
  63950. }
  63951. /*
  63952. ** Check if the program stored in the VM associated with pParse may
  63953. ** throw an ABORT exception (causing the statement, but not entire transaction
  63954. ** to be rolled back). This condition is true if the main program or any
  63955. ** sub-programs contains any of the following:
  63956. **
  63957. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  63958. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  63959. ** * OP_Destroy
  63960. ** * OP_VUpdate
  63961. ** * OP_VRename
  63962. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  63963. ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
  63964. **
  63965. ** Then check that the value of Parse.mayAbort is true if an
  63966. ** ABORT may be thrown, or false otherwise. Return true if it does
  63967. ** match, or false otherwise. This function is intended to be used as
  63968. ** part of an assert statement in the compiler. Similar to:
  63969. **
  63970. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  63971. */
  63972. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  63973. int hasAbort = 0;
  63974. int hasFkCounter = 0;
  63975. int hasCreateTable = 0;
  63976. int hasInitCoroutine = 0;
  63977. Op *pOp;
  63978. VdbeOpIter sIter;
  63979. memset(&sIter, 0, sizeof(sIter));
  63980. sIter.v = v;
  63981. while( (pOp = opIterNext(&sIter))!=0 ){
  63982. int opcode = pOp->opcode;
  63983. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  63984. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  63985. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  63986. ){
  63987. hasAbort = 1;
  63988. break;
  63989. }
  63990. if( opcode==OP_CreateTable ) hasCreateTable = 1;
  63991. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  63992. #ifndef SQLITE_OMIT_FOREIGN_KEY
  63993. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  63994. hasFkCounter = 1;
  63995. }
  63996. #endif
  63997. }
  63998. sqlite3DbFree(v->db, sIter.apSub);
  63999. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  64000. ** If malloc failed, then the while() loop above may not have iterated
  64001. ** through all opcodes and hasAbort may be set incorrectly. Return
  64002. ** true for this case to prevent the assert() in the callers frame
  64003. ** from failing. */
  64004. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  64005. || (hasCreateTable && hasInitCoroutine) );
  64006. }
  64007. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  64008. /*
  64009. ** This routine is called after all opcodes have been inserted. It loops
  64010. ** through all the opcodes and fixes up some details.
  64011. **
  64012. ** (1) For each jump instruction with a negative P2 value (a label)
  64013. ** resolve the P2 value to an actual address.
  64014. **
  64015. ** (2) Compute the maximum number of arguments used by any SQL function
  64016. ** and store that value in *pMaxFuncArgs.
  64017. **
  64018. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  64019. ** indicate what the prepared statement actually does.
  64020. **
  64021. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  64022. **
  64023. ** (5) Reclaim the memory allocated for storing labels.
  64024. */
  64025. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  64026. int i;
  64027. int nMaxArgs = *pMaxFuncArgs;
  64028. Op *pOp;
  64029. Parse *pParse = p->pParse;
  64030. int *aLabel = pParse->aLabel;
  64031. p->readOnly = 1;
  64032. p->bIsReader = 0;
  64033. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  64034. u8 opcode = pOp->opcode;
  64035. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  64036. ** cases from this switch! */
  64037. switch( opcode ){
  64038. case OP_Transaction: {
  64039. if( pOp->p2!=0 ) p->readOnly = 0;
  64040. /* fall thru */
  64041. }
  64042. case OP_AutoCommit:
  64043. case OP_Savepoint: {
  64044. p->bIsReader = 1;
  64045. break;
  64046. }
  64047. #ifndef SQLITE_OMIT_WAL
  64048. case OP_Checkpoint:
  64049. #endif
  64050. case OP_Vacuum:
  64051. case OP_JournalMode: {
  64052. p->readOnly = 0;
  64053. p->bIsReader = 1;
  64054. break;
  64055. }
  64056. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64057. case OP_VUpdate: {
  64058. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  64059. break;
  64060. }
  64061. case OP_VFilter: {
  64062. int n;
  64063. assert( p->nOp - i >= 3 );
  64064. assert( pOp[-1].opcode==OP_Integer );
  64065. n = pOp[-1].p1;
  64066. if( n>nMaxArgs ) nMaxArgs = n;
  64067. break;
  64068. }
  64069. #endif
  64070. case OP_Next:
  64071. case OP_NextIfOpen:
  64072. case OP_SorterNext: {
  64073. pOp->p4.xAdvance = sqlite3BtreeNext;
  64074. pOp->p4type = P4_ADVANCE;
  64075. break;
  64076. }
  64077. case OP_Prev:
  64078. case OP_PrevIfOpen: {
  64079. pOp->p4.xAdvance = sqlite3BtreePrevious;
  64080. pOp->p4type = P4_ADVANCE;
  64081. break;
  64082. }
  64083. }
  64084. pOp->opflags = sqlite3OpcodeProperty[opcode];
  64085. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  64086. assert( ADDR(pOp->p2)<pParse->nLabel );
  64087. pOp->p2 = aLabel[ADDR(pOp->p2)];
  64088. }
  64089. }
  64090. sqlite3DbFree(p->db, pParse->aLabel);
  64091. pParse->aLabel = 0;
  64092. pParse->nLabel = 0;
  64093. *pMaxFuncArgs = nMaxArgs;
  64094. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  64095. }
  64096. /*
  64097. ** Return the address of the next instruction to be inserted.
  64098. */
  64099. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  64100. assert( p->magic==VDBE_MAGIC_INIT );
  64101. return p->nOp;
  64102. }
  64103. /*
  64104. ** Verify that at least N opcode slots are available in p without
  64105. ** having to malloc for more space (except when compiled using
  64106. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  64107. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  64108. ** fail due to a OOM fault and hence that the return value from
  64109. ** sqlite3VdbeAddOpList() will always be non-NULL.
  64110. */
  64111. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  64112. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  64113. assert( p->nOp + N <= p->pParse->nOpAlloc );
  64114. }
  64115. #endif
  64116. /*
  64117. ** This function returns a pointer to the array of opcodes associated with
  64118. ** the Vdbe passed as the first argument. It is the callers responsibility
  64119. ** to arrange for the returned array to be eventually freed using the
  64120. ** vdbeFreeOpArray() function.
  64121. **
  64122. ** Before returning, *pnOp is set to the number of entries in the returned
  64123. ** array. Also, *pnMaxArg is set to the larger of its current value and
  64124. ** the number of entries in the Vdbe.apArg[] array required to execute the
  64125. ** returned program.
  64126. */
  64127. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  64128. VdbeOp *aOp = p->aOp;
  64129. assert( aOp && !p->db->mallocFailed );
  64130. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  64131. assert( DbMaskAllZero(p->btreeMask) );
  64132. resolveP2Values(p, pnMaxArg);
  64133. *pnOp = p->nOp;
  64134. p->aOp = 0;
  64135. return aOp;
  64136. }
  64137. /*
  64138. ** Add a whole list of operations to the operation stack. Return a
  64139. ** pointer to the first operation inserted.
  64140. **
  64141. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  64142. ** so that the jump target is relative to the first operation inserted.
  64143. */
  64144. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  64145. Vdbe *p, /* Add opcodes to the prepared statement */
  64146. int nOp, /* Number of opcodes to add */
  64147. VdbeOpList const *aOp, /* The opcodes to be added */
  64148. int iLineno /* Source-file line number of first opcode */
  64149. ){
  64150. int i;
  64151. VdbeOp *pOut, *pFirst;
  64152. assert( nOp>0 );
  64153. assert( p->magic==VDBE_MAGIC_INIT );
  64154. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  64155. return 0;
  64156. }
  64157. pFirst = pOut = &p->aOp[p->nOp];
  64158. for(i=0; i<nOp; i++, aOp++, pOut++){
  64159. pOut->opcode = aOp->opcode;
  64160. pOut->p1 = aOp->p1;
  64161. pOut->p2 = aOp->p2;
  64162. assert( aOp->p2>=0 );
  64163. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  64164. pOut->p2 += p->nOp;
  64165. }
  64166. pOut->p3 = aOp->p3;
  64167. pOut->p4type = P4_NOTUSED;
  64168. pOut->p4.p = 0;
  64169. pOut->p5 = 0;
  64170. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  64171. pOut->zComment = 0;
  64172. #endif
  64173. #ifdef SQLITE_VDBE_COVERAGE
  64174. pOut->iSrcLine = iLineno+i;
  64175. #else
  64176. (void)iLineno;
  64177. #endif
  64178. #ifdef SQLITE_DEBUG
  64179. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  64180. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  64181. }
  64182. #endif
  64183. }
  64184. p->nOp += nOp;
  64185. return pFirst;
  64186. }
  64187. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  64188. /*
  64189. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  64190. */
  64191. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  64192. Vdbe *p, /* VM to add scanstatus() to */
  64193. int addrExplain, /* Address of OP_Explain (or 0) */
  64194. int addrLoop, /* Address of loop counter */
  64195. int addrVisit, /* Address of rows visited counter */
  64196. LogEst nEst, /* Estimated number of output rows */
  64197. const char *zName /* Name of table or index being scanned */
  64198. ){
  64199. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  64200. ScanStatus *aNew;
  64201. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  64202. if( aNew ){
  64203. ScanStatus *pNew = &aNew[p->nScan++];
  64204. pNew->addrExplain = addrExplain;
  64205. pNew->addrLoop = addrLoop;
  64206. pNew->addrVisit = addrVisit;
  64207. pNew->nEst = nEst;
  64208. pNew->zName = sqlite3DbStrDup(p->db, zName);
  64209. p->aScan = aNew;
  64210. }
  64211. }
  64212. #endif
  64213. /*
  64214. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  64215. ** for a specific instruction.
  64216. */
  64217. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  64218. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  64219. }
  64220. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  64221. sqlite3VdbeGetOp(p,addr)->p1 = val;
  64222. }
  64223. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  64224. sqlite3VdbeGetOp(p,addr)->p2 = val;
  64225. }
  64226. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  64227. sqlite3VdbeGetOp(p,addr)->p3 = val;
  64228. }
  64229. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
  64230. if( !p->db->mallocFailed ) p->aOp[p->nOp-1].p5 = p5;
  64231. }
  64232. /*
  64233. ** Change the P2 operand of instruction addr so that it points to
  64234. ** the address of the next instruction to be coded.
  64235. */
  64236. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  64237. p->pParse->iFixedOp = p->nOp - 1;
  64238. sqlite3VdbeChangeP2(p, addr, p->nOp);
  64239. }
  64240. /*
  64241. ** If the input FuncDef structure is ephemeral, then free it. If
  64242. ** the FuncDef is not ephermal, then do nothing.
  64243. */
  64244. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  64245. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  64246. sqlite3DbFree(db, pDef);
  64247. }
  64248. }
  64249. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  64250. /*
  64251. ** Delete a P4 value if necessary.
  64252. */
  64253. static void freeP4(sqlite3 *db, int p4type, void *p4){
  64254. if( p4 ){
  64255. assert( db );
  64256. switch( p4type ){
  64257. case P4_FUNCCTX: {
  64258. freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
  64259. /* Fall through into the next case */
  64260. }
  64261. case P4_REAL:
  64262. case P4_INT64:
  64263. case P4_DYNAMIC:
  64264. case P4_INTARRAY: {
  64265. sqlite3DbFree(db, p4);
  64266. break;
  64267. }
  64268. case P4_KEYINFO: {
  64269. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  64270. break;
  64271. }
  64272. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  64273. case P4_EXPR: {
  64274. sqlite3ExprDelete(db, (Expr*)p4);
  64275. break;
  64276. }
  64277. #endif
  64278. case P4_MPRINTF: {
  64279. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  64280. break;
  64281. }
  64282. case P4_FUNCDEF: {
  64283. freeEphemeralFunction(db, (FuncDef*)p4);
  64284. break;
  64285. }
  64286. case P4_MEM: {
  64287. if( db->pnBytesFreed==0 ){
  64288. sqlite3ValueFree((sqlite3_value*)p4);
  64289. }else{
  64290. Mem *p = (Mem*)p4;
  64291. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  64292. sqlite3DbFree(db, p);
  64293. }
  64294. break;
  64295. }
  64296. case P4_VTAB : {
  64297. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  64298. break;
  64299. }
  64300. }
  64301. }
  64302. }
  64303. /*
  64304. ** Free the space allocated for aOp and any p4 values allocated for the
  64305. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  64306. ** nOp entries.
  64307. */
  64308. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  64309. if( aOp ){
  64310. Op *pOp;
  64311. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  64312. if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
  64313. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  64314. sqlite3DbFree(db, pOp->zComment);
  64315. #endif
  64316. }
  64317. }
  64318. sqlite3DbFree(db, aOp);
  64319. }
  64320. /*
  64321. ** Link the SubProgram object passed as the second argument into the linked
  64322. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  64323. ** objects when the VM is no longer required.
  64324. */
  64325. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  64326. p->pNext = pVdbe->pProgram;
  64327. pVdbe->pProgram = p;
  64328. }
  64329. /*
  64330. ** Change the opcode at addr into OP_Noop
  64331. */
  64332. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  64333. VdbeOp *pOp;
  64334. if( p->db->mallocFailed ) return 0;
  64335. assert( addr>=0 && addr<p->nOp );
  64336. pOp = &p->aOp[addr];
  64337. freeP4(p->db, pOp->p4type, pOp->p4.p);
  64338. pOp->p4type = P4_NOTUSED;
  64339. pOp->p4.z = 0;
  64340. pOp->opcode = OP_Noop;
  64341. return 1;
  64342. }
  64343. /*
  64344. ** If the last opcode is "op" and it is not a jump destination,
  64345. ** then remove it. Return true if and only if an opcode was removed.
  64346. */
  64347. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  64348. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  64349. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  64350. }else{
  64351. return 0;
  64352. }
  64353. }
  64354. /*
  64355. ** Change the value of the P4 operand for a specific instruction.
  64356. ** This routine is useful when a large program is loaded from a
  64357. ** static array using sqlite3VdbeAddOpList but we want to make a
  64358. ** few minor changes to the program.
  64359. **
  64360. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  64361. ** the string is made into memory obtained from sqlite3_malloc().
  64362. ** A value of n==0 means copy bytes of zP4 up to and including the
  64363. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  64364. **
  64365. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  64366. ** to a string or structure that is guaranteed to exist for the lifetime of
  64367. ** the Vdbe. In these cases we can just copy the pointer.
  64368. **
  64369. ** If addr<0 then change P4 on the most recently inserted instruction.
  64370. */
  64371. static void SQLITE_NOINLINE vdbeChangeP4Full(
  64372. Vdbe *p,
  64373. Op *pOp,
  64374. const char *zP4,
  64375. int n
  64376. ){
  64377. if( pOp->p4type ){
  64378. freeP4(p->db, pOp->p4type, pOp->p4.p);
  64379. pOp->p4type = 0;
  64380. pOp->p4.p = 0;
  64381. }
  64382. if( n<0 ){
  64383. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  64384. }else{
  64385. if( n==0 ) n = sqlite3Strlen30(zP4);
  64386. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  64387. pOp->p4type = P4_DYNAMIC;
  64388. }
  64389. }
  64390. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  64391. Op *pOp;
  64392. sqlite3 *db;
  64393. assert( p!=0 );
  64394. db = p->db;
  64395. assert( p->magic==VDBE_MAGIC_INIT );
  64396. assert( p->aOp!=0 || db->mallocFailed );
  64397. if( db->mallocFailed ){
  64398. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  64399. return;
  64400. }
  64401. assert( p->nOp>0 );
  64402. assert( addr<p->nOp );
  64403. if( addr<0 ){
  64404. addr = p->nOp - 1;
  64405. }
  64406. pOp = &p->aOp[addr];
  64407. if( n>=0 || pOp->p4type ){
  64408. vdbeChangeP4Full(p, pOp, zP4, n);
  64409. return;
  64410. }
  64411. if( n==P4_INT32 ){
  64412. /* Note: this cast is safe, because the origin data point was an int
  64413. ** that was cast to a (const char *). */
  64414. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  64415. pOp->p4type = P4_INT32;
  64416. }else if( zP4!=0 ){
  64417. assert( n<0 );
  64418. pOp->p4.p = (void*)zP4;
  64419. pOp->p4type = (signed char)n;
  64420. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  64421. }
  64422. }
  64423. /*
  64424. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  64425. ** index given.
  64426. */
  64427. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  64428. Vdbe *v = pParse->pVdbe;
  64429. assert( v!=0 );
  64430. assert( pIdx!=0 );
  64431. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  64432. P4_KEYINFO);
  64433. }
  64434. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  64435. /*
  64436. ** Change the comment on the most recently coded instruction. Or
  64437. ** insert a No-op and add the comment to that new instruction. This
  64438. ** makes the code easier to read during debugging. None of this happens
  64439. ** in a production build.
  64440. */
  64441. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  64442. assert( p->nOp>0 || p->aOp==0 );
  64443. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  64444. if( p->nOp ){
  64445. assert( p->aOp );
  64446. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  64447. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  64448. }
  64449. }
  64450. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  64451. va_list ap;
  64452. if( p ){
  64453. va_start(ap, zFormat);
  64454. vdbeVComment(p, zFormat, ap);
  64455. va_end(ap);
  64456. }
  64457. }
  64458. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  64459. va_list ap;
  64460. if( p ){
  64461. sqlite3VdbeAddOp0(p, OP_Noop);
  64462. va_start(ap, zFormat);
  64463. vdbeVComment(p, zFormat, ap);
  64464. va_end(ap);
  64465. }
  64466. }
  64467. #endif /* NDEBUG */
  64468. #ifdef SQLITE_VDBE_COVERAGE
  64469. /*
  64470. ** Set the value if the iSrcLine field for the previously coded instruction.
  64471. */
  64472. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  64473. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  64474. }
  64475. #endif /* SQLITE_VDBE_COVERAGE */
  64476. /*
  64477. ** Return the opcode for a given address. If the address is -1, then
  64478. ** return the most recently inserted opcode.
  64479. **
  64480. ** If a memory allocation error has occurred prior to the calling of this
  64481. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  64482. ** is readable but not writable, though it is cast to a writable value.
  64483. ** The return of a dummy opcode allows the call to continue functioning
  64484. ** after an OOM fault without having to check to see if the return from
  64485. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  64486. ** dummy will never be written to. This is verified by code inspection and
  64487. ** by running with Valgrind.
  64488. */
  64489. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  64490. /* C89 specifies that the constant "dummy" will be initialized to all
  64491. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  64492. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  64493. assert( p->magic==VDBE_MAGIC_INIT );
  64494. if( addr<0 ){
  64495. addr = p->nOp - 1;
  64496. }
  64497. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  64498. if( p->db->mallocFailed ){
  64499. return (VdbeOp*)&dummy;
  64500. }else{
  64501. return &p->aOp[addr];
  64502. }
  64503. }
  64504. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  64505. /*
  64506. ** Return an integer value for one of the parameters to the opcode pOp
  64507. ** determined by character c.
  64508. */
  64509. static int translateP(char c, const Op *pOp){
  64510. if( c=='1' ) return pOp->p1;
  64511. if( c=='2' ) return pOp->p2;
  64512. if( c=='3' ) return pOp->p3;
  64513. if( c=='4' ) return pOp->p4.i;
  64514. return pOp->p5;
  64515. }
  64516. /*
  64517. ** Compute a string for the "comment" field of a VDBE opcode listing.
  64518. **
  64519. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  64520. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  64521. ** absence of other comments, this synopsis becomes the comment on the opcode.
  64522. ** Some translation occurs:
  64523. **
  64524. ** "PX" -> "r[X]"
  64525. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  64526. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  64527. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  64528. */
  64529. static int displayComment(
  64530. const Op *pOp, /* The opcode to be commented */
  64531. const char *zP4, /* Previously obtained value for P4 */
  64532. char *zTemp, /* Write result here */
  64533. int nTemp /* Space available in zTemp[] */
  64534. ){
  64535. const char *zOpName;
  64536. const char *zSynopsis;
  64537. int nOpName;
  64538. int ii, jj;
  64539. zOpName = sqlite3OpcodeName(pOp->opcode);
  64540. nOpName = sqlite3Strlen30(zOpName);
  64541. if( zOpName[nOpName+1] ){
  64542. int seenCom = 0;
  64543. char c;
  64544. zSynopsis = zOpName += nOpName + 1;
  64545. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  64546. if( c=='P' ){
  64547. c = zSynopsis[++ii];
  64548. if( c=='4' ){
  64549. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  64550. }else if( c=='X' ){
  64551. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  64552. seenCom = 1;
  64553. }else{
  64554. int v1 = translateP(c, pOp);
  64555. int v2;
  64556. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  64557. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  64558. ii += 3;
  64559. jj += sqlite3Strlen30(zTemp+jj);
  64560. v2 = translateP(zSynopsis[ii], pOp);
  64561. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  64562. ii += 2;
  64563. v2++;
  64564. }
  64565. if( v2>1 ){
  64566. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  64567. }
  64568. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  64569. ii += 4;
  64570. }
  64571. }
  64572. jj += sqlite3Strlen30(zTemp+jj);
  64573. }else{
  64574. zTemp[jj++] = c;
  64575. }
  64576. }
  64577. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  64578. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  64579. jj += sqlite3Strlen30(zTemp+jj);
  64580. }
  64581. if( jj<nTemp ) zTemp[jj] = 0;
  64582. }else if( pOp->zComment ){
  64583. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  64584. jj = sqlite3Strlen30(zTemp);
  64585. }else{
  64586. zTemp[0] = 0;
  64587. jj = 0;
  64588. }
  64589. return jj;
  64590. }
  64591. #endif /* SQLITE_DEBUG */
  64592. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  64593. /*
  64594. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  64595. ** that can be displayed in the P4 column of EXPLAIN output.
  64596. */
  64597. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  64598. const char *zOp = 0;
  64599. switch( pExpr->op ){
  64600. case TK_STRING:
  64601. sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
  64602. break;
  64603. case TK_INTEGER:
  64604. sqlite3XPrintf(p, "%d", pExpr->u.iValue);
  64605. break;
  64606. case TK_NULL:
  64607. sqlite3XPrintf(p, "NULL");
  64608. break;
  64609. case TK_REGISTER: {
  64610. sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
  64611. break;
  64612. }
  64613. case TK_COLUMN: {
  64614. if( pExpr->iColumn<0 ){
  64615. sqlite3XPrintf(p, "rowid");
  64616. }else{
  64617. sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
  64618. }
  64619. break;
  64620. }
  64621. case TK_LT: zOp = "LT"; break;
  64622. case TK_LE: zOp = "LE"; break;
  64623. case TK_GT: zOp = "GT"; break;
  64624. case TK_GE: zOp = "GE"; break;
  64625. case TK_NE: zOp = "NE"; break;
  64626. case TK_EQ: zOp = "EQ"; break;
  64627. case TK_IS: zOp = "IS"; break;
  64628. case TK_ISNOT: zOp = "ISNOT"; break;
  64629. case TK_AND: zOp = "AND"; break;
  64630. case TK_OR: zOp = "OR"; break;
  64631. case TK_PLUS: zOp = "ADD"; break;
  64632. case TK_STAR: zOp = "MUL"; break;
  64633. case TK_MINUS: zOp = "SUB"; break;
  64634. case TK_REM: zOp = "REM"; break;
  64635. case TK_BITAND: zOp = "BITAND"; break;
  64636. case TK_BITOR: zOp = "BITOR"; break;
  64637. case TK_SLASH: zOp = "DIV"; break;
  64638. case TK_LSHIFT: zOp = "LSHIFT"; break;
  64639. case TK_RSHIFT: zOp = "RSHIFT"; break;
  64640. case TK_CONCAT: zOp = "CONCAT"; break;
  64641. case TK_UMINUS: zOp = "MINUS"; break;
  64642. case TK_UPLUS: zOp = "PLUS"; break;
  64643. case TK_BITNOT: zOp = "BITNOT"; break;
  64644. case TK_NOT: zOp = "NOT"; break;
  64645. case TK_ISNULL: zOp = "ISNULL"; break;
  64646. case TK_NOTNULL: zOp = "NOTNULL"; break;
  64647. default:
  64648. sqlite3XPrintf(p, "%s", "expr");
  64649. break;
  64650. }
  64651. if( zOp ){
  64652. sqlite3XPrintf(p, "%s(", zOp);
  64653. displayP4Expr(p, pExpr->pLeft);
  64654. if( pExpr->pRight ){
  64655. sqlite3StrAccumAppend(p, ",", 1);
  64656. displayP4Expr(p, pExpr->pRight);
  64657. }
  64658. sqlite3StrAccumAppend(p, ")", 1);
  64659. }
  64660. }
  64661. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  64662. #if VDBE_DISPLAY_P4
  64663. /*
  64664. ** Compute a string that describes the P4 parameter for an opcode.
  64665. ** Use zTemp for any required temporary buffer space.
  64666. */
  64667. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  64668. char *zP4 = zTemp;
  64669. StrAccum x;
  64670. assert( nTemp>=20 );
  64671. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  64672. switch( pOp->p4type ){
  64673. case P4_KEYINFO: {
  64674. int j;
  64675. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  64676. assert( pKeyInfo->aSortOrder!=0 );
  64677. sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
  64678. for(j=0; j<pKeyInfo->nField; j++){
  64679. CollSeq *pColl = pKeyInfo->aColl[j];
  64680. const char *zColl = pColl ? pColl->zName : "";
  64681. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  64682. sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  64683. }
  64684. sqlite3StrAccumAppend(&x, ")", 1);
  64685. break;
  64686. }
  64687. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  64688. case P4_EXPR: {
  64689. displayP4Expr(&x, pOp->p4.pExpr);
  64690. break;
  64691. }
  64692. #endif
  64693. case P4_COLLSEQ: {
  64694. CollSeq *pColl = pOp->p4.pColl;
  64695. sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
  64696. break;
  64697. }
  64698. case P4_FUNCDEF: {
  64699. FuncDef *pDef = pOp->p4.pFunc;
  64700. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  64701. break;
  64702. }
  64703. #ifdef SQLITE_DEBUG
  64704. case P4_FUNCCTX: {
  64705. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  64706. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  64707. break;
  64708. }
  64709. #endif
  64710. case P4_INT64: {
  64711. sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
  64712. break;
  64713. }
  64714. case P4_INT32: {
  64715. sqlite3XPrintf(&x, "%d", pOp->p4.i);
  64716. break;
  64717. }
  64718. case P4_REAL: {
  64719. sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
  64720. break;
  64721. }
  64722. case P4_MEM: {
  64723. Mem *pMem = pOp->p4.pMem;
  64724. if( pMem->flags & MEM_Str ){
  64725. zP4 = pMem->z;
  64726. }else if( pMem->flags & MEM_Int ){
  64727. sqlite3XPrintf(&x, "%lld", pMem->u.i);
  64728. }else if( pMem->flags & MEM_Real ){
  64729. sqlite3XPrintf(&x, "%.16g", pMem->u.r);
  64730. }else if( pMem->flags & MEM_Null ){
  64731. zP4 = "NULL";
  64732. }else{
  64733. assert( pMem->flags & MEM_Blob );
  64734. zP4 = "(blob)";
  64735. }
  64736. break;
  64737. }
  64738. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64739. case P4_VTAB: {
  64740. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  64741. sqlite3XPrintf(&x, "vtab:%p", pVtab);
  64742. break;
  64743. }
  64744. #endif
  64745. case P4_INTARRAY: {
  64746. int i;
  64747. int *ai = pOp->p4.ai;
  64748. int n = ai[0]; /* The first element of an INTARRAY is always the
  64749. ** count of the number of elements to follow */
  64750. for(i=1; i<n; i++){
  64751. sqlite3XPrintf(&x, ",%d", ai[i]);
  64752. }
  64753. zTemp[0] = '[';
  64754. sqlite3StrAccumAppend(&x, "]", 1);
  64755. break;
  64756. }
  64757. case P4_SUBPROGRAM: {
  64758. sqlite3XPrintf(&x, "program");
  64759. break;
  64760. }
  64761. case P4_ADVANCE: {
  64762. zTemp[0] = 0;
  64763. break;
  64764. }
  64765. default: {
  64766. zP4 = pOp->p4.z;
  64767. if( zP4==0 ){
  64768. zP4 = zTemp;
  64769. zTemp[0] = 0;
  64770. }
  64771. }
  64772. }
  64773. sqlite3StrAccumFinish(&x);
  64774. assert( zP4!=0 );
  64775. return zP4;
  64776. }
  64777. #endif /* VDBE_DISPLAY_P4 */
  64778. /*
  64779. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  64780. **
  64781. ** The prepared statements need to know in advance the complete set of
  64782. ** attached databases that will be use. A mask of these databases
  64783. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  64784. ** p->btreeMask of databases that will require a lock.
  64785. */
  64786. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  64787. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  64788. assert( i<(int)sizeof(p->btreeMask)*8 );
  64789. DbMaskSet(p->btreeMask, i);
  64790. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  64791. DbMaskSet(p->lockMask, i);
  64792. }
  64793. }
  64794. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  64795. /*
  64796. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  64797. ** this routine obtains the mutex associated with each BtShared structure
  64798. ** that may be accessed by the VM passed as an argument. In doing so it also
  64799. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  64800. ** that the correct busy-handler callback is invoked if required.
  64801. **
  64802. ** If SQLite is not threadsafe but does support shared-cache mode, then
  64803. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  64804. ** of all of BtShared structures accessible via the database handle
  64805. ** associated with the VM.
  64806. **
  64807. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  64808. ** function is a no-op.
  64809. **
  64810. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  64811. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  64812. ** corresponding to btrees that use shared cache. Then the runtime of
  64813. ** this routine is N*N. But as N is rarely more than 1, this should not
  64814. ** be a problem.
  64815. */
  64816. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  64817. int i;
  64818. sqlite3 *db;
  64819. Db *aDb;
  64820. int nDb;
  64821. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  64822. db = p->db;
  64823. aDb = db->aDb;
  64824. nDb = db->nDb;
  64825. for(i=0; i<nDb; i++){
  64826. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  64827. sqlite3BtreeEnter(aDb[i].pBt);
  64828. }
  64829. }
  64830. }
  64831. #endif
  64832. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  64833. /*
  64834. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  64835. */
  64836. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  64837. int i;
  64838. sqlite3 *db;
  64839. Db *aDb;
  64840. int nDb;
  64841. db = p->db;
  64842. aDb = db->aDb;
  64843. nDb = db->nDb;
  64844. for(i=0; i<nDb; i++){
  64845. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  64846. sqlite3BtreeLeave(aDb[i].pBt);
  64847. }
  64848. }
  64849. }
  64850. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  64851. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  64852. vdbeLeave(p);
  64853. }
  64854. #endif
  64855. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  64856. /*
  64857. ** Print a single opcode. This routine is used for debugging only.
  64858. */
  64859. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  64860. char *zP4;
  64861. char zPtr[50];
  64862. char zCom[100];
  64863. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  64864. if( pOut==0 ) pOut = stdout;
  64865. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  64866. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  64867. displayComment(pOp, zP4, zCom, sizeof(zCom));
  64868. #else
  64869. zCom[0] = 0;
  64870. #endif
  64871. /* NB: The sqlite3OpcodeName() function is implemented by code created
  64872. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  64873. ** information from the vdbe.c source text */
  64874. fprintf(pOut, zFormat1, pc,
  64875. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  64876. zCom
  64877. );
  64878. fflush(pOut);
  64879. }
  64880. #endif
  64881. /*
  64882. ** Release an array of N Mem elements
  64883. */
  64884. static void releaseMemArray(Mem *p, int N){
  64885. if( p && N ){
  64886. Mem *pEnd = &p[N];
  64887. sqlite3 *db = p->db;
  64888. if( db->pnBytesFreed ){
  64889. do{
  64890. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  64891. }while( (++p)<pEnd );
  64892. return;
  64893. }
  64894. do{
  64895. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  64896. assert( sqlite3VdbeCheckMemInvariants(p) );
  64897. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  64898. ** that takes advantage of the fact that the memory cell value is
  64899. ** being set to NULL after releasing any dynamic resources.
  64900. **
  64901. ** The justification for duplicating code is that according to
  64902. ** callgrind, this causes a certain test case to hit the CPU 4.7
  64903. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  64904. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  64905. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  64906. ** with no indexes using a single prepared INSERT statement, bind()
  64907. ** and reset(). Inserts are grouped into a transaction.
  64908. */
  64909. testcase( p->flags & MEM_Agg );
  64910. testcase( p->flags & MEM_Dyn );
  64911. testcase( p->flags & MEM_Frame );
  64912. testcase( p->flags & MEM_RowSet );
  64913. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  64914. sqlite3VdbeMemRelease(p);
  64915. }else if( p->szMalloc ){
  64916. sqlite3DbFree(db, p->zMalloc);
  64917. p->szMalloc = 0;
  64918. }
  64919. p->flags = MEM_Undefined;
  64920. }while( (++p)<pEnd );
  64921. }
  64922. }
  64923. /*
  64924. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  64925. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  64926. */
  64927. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  64928. int i;
  64929. Mem *aMem = VdbeFrameMem(p);
  64930. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  64931. for(i=0; i<p->nChildCsr; i++){
  64932. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  64933. }
  64934. releaseMemArray(aMem, p->nChildMem);
  64935. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  64936. sqlite3DbFree(p->v->db, p);
  64937. }
  64938. #ifndef SQLITE_OMIT_EXPLAIN
  64939. /*
  64940. ** Give a listing of the program in the virtual machine.
  64941. **
  64942. ** The interface is the same as sqlite3VdbeExec(). But instead of
  64943. ** running the code, it invokes the callback once for each instruction.
  64944. ** This feature is used to implement "EXPLAIN".
  64945. **
  64946. ** When p->explain==1, each instruction is listed. When
  64947. ** p->explain==2, only OP_Explain instructions are listed and these
  64948. ** are shown in a different format. p->explain==2 is used to implement
  64949. ** EXPLAIN QUERY PLAN.
  64950. **
  64951. ** When p->explain==1, first the main program is listed, then each of
  64952. ** the trigger subprograms are listed one by one.
  64953. */
  64954. SQLITE_PRIVATE int sqlite3VdbeList(
  64955. Vdbe *p /* The VDBE */
  64956. ){
  64957. int nRow; /* Stop when row count reaches this */
  64958. int nSub = 0; /* Number of sub-vdbes seen so far */
  64959. SubProgram **apSub = 0; /* Array of sub-vdbes */
  64960. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  64961. sqlite3 *db = p->db; /* The database connection */
  64962. int i; /* Loop counter */
  64963. int rc = SQLITE_OK; /* Return code */
  64964. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  64965. assert( p->explain );
  64966. assert( p->magic==VDBE_MAGIC_RUN );
  64967. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  64968. /* Even though this opcode does not use dynamic strings for
  64969. ** the result, result columns may become dynamic if the user calls
  64970. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  64971. */
  64972. releaseMemArray(pMem, 8);
  64973. p->pResultSet = 0;
  64974. if( p->rc==SQLITE_NOMEM_BKPT ){
  64975. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  64976. ** sqlite3_column_text16() failed. */
  64977. sqlite3OomFault(db);
  64978. return SQLITE_ERROR;
  64979. }
  64980. /* When the number of output rows reaches nRow, that means the
  64981. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  64982. ** nRow is the sum of the number of rows in the main program, plus
  64983. ** the sum of the number of rows in all trigger subprograms encountered
  64984. ** so far. The nRow value will increase as new trigger subprograms are
  64985. ** encountered, but p->pc will eventually catch up to nRow.
  64986. */
  64987. nRow = p->nOp;
  64988. if( p->explain==1 ){
  64989. /* The first 8 memory cells are used for the result set. So we will
  64990. ** commandeer the 9th cell to use as storage for an array of pointers
  64991. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  64992. ** cells. */
  64993. assert( p->nMem>9 );
  64994. pSub = &p->aMem[9];
  64995. if( pSub->flags&MEM_Blob ){
  64996. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  64997. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  64998. nSub = pSub->n/sizeof(Vdbe*);
  64999. apSub = (SubProgram **)pSub->z;
  65000. }
  65001. for(i=0; i<nSub; i++){
  65002. nRow += apSub[i]->nOp;
  65003. }
  65004. }
  65005. do{
  65006. i = p->pc++;
  65007. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  65008. if( i>=nRow ){
  65009. p->rc = SQLITE_OK;
  65010. rc = SQLITE_DONE;
  65011. }else if( db->u1.isInterrupted ){
  65012. p->rc = SQLITE_INTERRUPT;
  65013. rc = SQLITE_ERROR;
  65014. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  65015. }else{
  65016. char *zP4;
  65017. Op *pOp;
  65018. if( i<p->nOp ){
  65019. /* The output line number is small enough that we are still in the
  65020. ** main program. */
  65021. pOp = &p->aOp[i];
  65022. }else{
  65023. /* We are currently listing subprograms. Figure out which one and
  65024. ** pick up the appropriate opcode. */
  65025. int j;
  65026. i -= p->nOp;
  65027. for(j=0; i>=apSub[j]->nOp; j++){
  65028. i -= apSub[j]->nOp;
  65029. }
  65030. pOp = &apSub[j]->aOp[i];
  65031. }
  65032. if( p->explain==1 ){
  65033. pMem->flags = MEM_Int;
  65034. pMem->u.i = i; /* Program counter */
  65035. pMem++;
  65036. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  65037. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  65038. assert( pMem->z!=0 );
  65039. pMem->n = sqlite3Strlen30(pMem->z);
  65040. pMem->enc = SQLITE_UTF8;
  65041. pMem++;
  65042. /* When an OP_Program opcode is encounter (the only opcode that has
  65043. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  65044. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  65045. ** has not already been seen.
  65046. */
  65047. if( pOp->p4type==P4_SUBPROGRAM ){
  65048. int nByte = (nSub+1)*sizeof(SubProgram*);
  65049. int j;
  65050. for(j=0; j<nSub; j++){
  65051. if( apSub[j]==pOp->p4.pProgram ) break;
  65052. }
  65053. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  65054. apSub = (SubProgram **)pSub->z;
  65055. apSub[nSub++] = pOp->p4.pProgram;
  65056. pSub->flags |= MEM_Blob;
  65057. pSub->n = nSub*sizeof(SubProgram*);
  65058. }
  65059. }
  65060. }
  65061. pMem->flags = MEM_Int;
  65062. pMem->u.i = pOp->p1; /* P1 */
  65063. pMem++;
  65064. pMem->flags = MEM_Int;
  65065. pMem->u.i = pOp->p2; /* P2 */
  65066. pMem++;
  65067. pMem->flags = MEM_Int;
  65068. pMem->u.i = pOp->p3; /* P3 */
  65069. pMem++;
  65070. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  65071. assert( p->db->mallocFailed );
  65072. return SQLITE_ERROR;
  65073. }
  65074. pMem->flags = MEM_Str|MEM_Term;
  65075. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  65076. if( zP4!=pMem->z ){
  65077. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  65078. }else{
  65079. assert( pMem->z!=0 );
  65080. pMem->n = sqlite3Strlen30(pMem->z);
  65081. pMem->enc = SQLITE_UTF8;
  65082. }
  65083. pMem++;
  65084. if( p->explain==1 ){
  65085. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  65086. assert( p->db->mallocFailed );
  65087. return SQLITE_ERROR;
  65088. }
  65089. pMem->flags = MEM_Str|MEM_Term;
  65090. pMem->n = 2;
  65091. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  65092. pMem->enc = SQLITE_UTF8;
  65093. pMem++;
  65094. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  65095. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  65096. assert( p->db->mallocFailed );
  65097. return SQLITE_ERROR;
  65098. }
  65099. pMem->flags = MEM_Str|MEM_Term;
  65100. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  65101. pMem->enc = SQLITE_UTF8;
  65102. #else
  65103. pMem->flags = MEM_Null; /* Comment */
  65104. #endif
  65105. }
  65106. p->nResColumn = 8 - 4*(p->explain-1);
  65107. p->pResultSet = &p->aMem[1];
  65108. p->rc = SQLITE_OK;
  65109. rc = SQLITE_ROW;
  65110. }
  65111. return rc;
  65112. }
  65113. #endif /* SQLITE_OMIT_EXPLAIN */
  65114. #ifdef SQLITE_DEBUG
  65115. /*
  65116. ** Print the SQL that was used to generate a VDBE program.
  65117. */
  65118. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  65119. const char *z = 0;
  65120. if( p->zSql ){
  65121. z = p->zSql;
  65122. }else if( p->nOp>=1 ){
  65123. const VdbeOp *pOp = &p->aOp[0];
  65124. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  65125. z = pOp->p4.z;
  65126. while( sqlite3Isspace(*z) ) z++;
  65127. }
  65128. }
  65129. if( z ) printf("SQL: [%s]\n", z);
  65130. }
  65131. #endif
  65132. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  65133. /*
  65134. ** Print an IOTRACE message showing SQL content.
  65135. */
  65136. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  65137. int nOp = p->nOp;
  65138. VdbeOp *pOp;
  65139. if( sqlite3IoTrace==0 ) return;
  65140. if( nOp<1 ) return;
  65141. pOp = &p->aOp[0];
  65142. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  65143. int i, j;
  65144. char z[1000];
  65145. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  65146. for(i=0; sqlite3Isspace(z[i]); i++){}
  65147. for(j=0; z[i]; i++){
  65148. if( sqlite3Isspace(z[i]) ){
  65149. if( z[i-1]!=' ' ){
  65150. z[j++] = ' ';
  65151. }
  65152. }else{
  65153. z[j++] = z[i];
  65154. }
  65155. }
  65156. z[j] = 0;
  65157. sqlite3IoTrace("SQL %s\n", z);
  65158. }
  65159. }
  65160. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  65161. /* An instance of this object describes bulk memory available for use
  65162. ** by subcomponents of a prepared statement. Space is allocated out
  65163. ** of a ReusableSpace object by the allocSpace() routine below.
  65164. */
  65165. struct ReusableSpace {
  65166. u8 *pSpace; /* Available memory */
  65167. int nFree; /* Bytes of available memory */
  65168. int nNeeded; /* Total bytes that could not be allocated */
  65169. };
  65170. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  65171. ** from the ReusableSpace object. Return a pointer to the allocated
  65172. ** memory on success. If insufficient memory is available in the
  65173. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  65174. ** value by the amount needed and return NULL.
  65175. **
  65176. ** If pBuf is not initially NULL, that means that the memory has already
  65177. ** been allocated by a prior call to this routine, so just return a copy
  65178. ** of pBuf and leave ReusableSpace unchanged.
  65179. **
  65180. ** This allocator is employed to repurpose unused slots at the end of the
  65181. ** opcode array of prepared state for other memory needs of the prepared
  65182. ** statement.
  65183. */
  65184. static void *allocSpace(
  65185. struct ReusableSpace *p, /* Bulk memory available for allocation */
  65186. void *pBuf, /* Pointer to a prior allocation */
  65187. int nByte /* Bytes of memory needed */
  65188. ){
  65189. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  65190. if( pBuf==0 ){
  65191. nByte = ROUND8(nByte);
  65192. if( nByte <= p->nFree ){
  65193. p->nFree -= nByte;
  65194. pBuf = &p->pSpace[p->nFree];
  65195. }else{
  65196. p->nNeeded += nByte;
  65197. }
  65198. }
  65199. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  65200. return pBuf;
  65201. }
  65202. /*
  65203. ** Rewind the VDBE back to the beginning in preparation for
  65204. ** running it.
  65205. */
  65206. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  65207. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  65208. int i;
  65209. #endif
  65210. assert( p!=0 );
  65211. assert( p->magic==VDBE_MAGIC_INIT );
  65212. /* There should be at least one opcode.
  65213. */
  65214. assert( p->nOp>0 );
  65215. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  65216. p->magic = VDBE_MAGIC_RUN;
  65217. #ifdef SQLITE_DEBUG
  65218. for(i=0; i<p->nMem; i++){
  65219. assert( p->aMem[i].db==p->db );
  65220. }
  65221. #endif
  65222. p->pc = -1;
  65223. p->rc = SQLITE_OK;
  65224. p->errorAction = OE_Abort;
  65225. p->nChange = 0;
  65226. p->cacheCtr = 1;
  65227. p->minWriteFileFormat = 255;
  65228. p->iStatement = 0;
  65229. p->nFkConstraint = 0;
  65230. #ifdef VDBE_PROFILE
  65231. for(i=0; i<p->nOp; i++){
  65232. p->aOp[i].cnt = 0;
  65233. p->aOp[i].cycles = 0;
  65234. }
  65235. #endif
  65236. }
  65237. /*
  65238. ** Prepare a virtual machine for execution for the first time after
  65239. ** creating the virtual machine. This involves things such
  65240. ** as allocating registers and initializing the program counter.
  65241. ** After the VDBE has be prepped, it can be executed by one or more
  65242. ** calls to sqlite3VdbeExec().
  65243. **
  65244. ** This function may be called exactly once on each virtual machine.
  65245. ** After this routine is called the VM has been "packaged" and is ready
  65246. ** to run. After this routine is called, further calls to
  65247. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  65248. ** the Vdbe from the Parse object that helped generate it so that the
  65249. ** the Vdbe becomes an independent entity and the Parse object can be
  65250. ** destroyed.
  65251. **
  65252. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  65253. ** to its initial state after it has been run.
  65254. */
  65255. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  65256. Vdbe *p, /* The VDBE */
  65257. Parse *pParse /* Parsing context */
  65258. ){
  65259. sqlite3 *db; /* The database connection */
  65260. int nVar; /* Number of parameters */
  65261. int nMem; /* Number of VM memory registers */
  65262. int nCursor; /* Number of cursors required */
  65263. int nArg; /* Number of arguments in subprograms */
  65264. int nOnce; /* Number of OP_Once instructions */
  65265. int n; /* Loop counter */
  65266. struct ReusableSpace x; /* Reusable bulk memory */
  65267. assert( p!=0 );
  65268. assert( p->nOp>0 );
  65269. assert( pParse!=0 );
  65270. assert( p->magic==VDBE_MAGIC_INIT );
  65271. assert( pParse==p->pParse );
  65272. db = p->db;
  65273. assert( db->mallocFailed==0 );
  65274. nVar = pParse->nVar;
  65275. nMem = pParse->nMem;
  65276. nCursor = pParse->nTab;
  65277. nArg = pParse->nMaxArg;
  65278. nOnce = pParse->nOnce;
  65279. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  65280. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  65281. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  65282. ** space at the end of aMem[] for cursors 1 and greater.
  65283. ** See also: allocateCursor().
  65284. */
  65285. nMem += nCursor;
  65286. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  65287. /* Figure out how much reusable memory is available at the end of the
  65288. ** opcode array. This extra memory will be reallocated for other elements
  65289. ** of the prepared statement.
  65290. */
  65291. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  65292. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  65293. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  65294. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  65295. assert( x.nFree>=0 );
  65296. if( x.nFree>0 ){
  65297. memset(x.pSpace, 0, x.nFree);
  65298. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  65299. }
  65300. resolveP2Values(p, &nArg);
  65301. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  65302. if( pParse->explain && nMem<10 ){
  65303. nMem = 10;
  65304. }
  65305. p->expired = 0;
  65306. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  65307. ** passes. On the first pass, we try to reuse unused memory at the
  65308. ** end of the opcode array. If we are unable to satisfy all memory
  65309. ** requirements by reusing the opcode array tail, then the second
  65310. ** pass will fill in the remainder using a fresh memory allocation.
  65311. **
  65312. ** This two-pass approach that reuses as much memory as possible from
  65313. ** the leftover memory at the end of the opcode array. This can significantly
  65314. ** reduce the amount of memory held by a prepared statement.
  65315. */
  65316. do {
  65317. x.nNeeded = 0;
  65318. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  65319. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  65320. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  65321. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  65322. p->aOnceFlag = allocSpace(&x, p->aOnceFlag, nOnce);
  65323. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  65324. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  65325. #endif
  65326. if( x.nNeeded==0 ) break;
  65327. x.pSpace = p->pFree = sqlite3DbMallocZero(db, x.nNeeded);
  65328. x.nFree = x.nNeeded;
  65329. }while( !db->mallocFailed );
  65330. p->nCursor = nCursor;
  65331. p->nOnceFlag = nOnce;
  65332. if( p->aVar ){
  65333. p->nVar = (ynVar)nVar;
  65334. for(n=0; n<nVar; n++){
  65335. p->aVar[n].flags = MEM_Null;
  65336. p->aVar[n].db = db;
  65337. }
  65338. }
  65339. p->nzVar = pParse->nzVar;
  65340. p->azVar = pParse->azVar;
  65341. pParse->nzVar = 0;
  65342. pParse->azVar = 0;
  65343. if( p->aMem ){
  65344. p->nMem = nMem;
  65345. for(n=0; n<nMem; n++){
  65346. p->aMem[n].flags = MEM_Undefined;
  65347. p->aMem[n].db = db;
  65348. }
  65349. }
  65350. p->explain = pParse->explain;
  65351. sqlite3VdbeRewind(p);
  65352. }
  65353. /*
  65354. ** Close a VDBE cursor and release all the resources that cursor
  65355. ** happens to hold.
  65356. */
  65357. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  65358. if( pCx==0 ){
  65359. return;
  65360. }
  65361. assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
  65362. switch( pCx->eCurType ){
  65363. case CURTYPE_SORTER: {
  65364. sqlite3VdbeSorterClose(p->db, pCx);
  65365. break;
  65366. }
  65367. case CURTYPE_BTREE: {
  65368. if( pCx->pBt ){
  65369. sqlite3BtreeClose(pCx->pBt);
  65370. /* The pCx->pCursor will be close automatically, if it exists, by
  65371. ** the call above. */
  65372. }else{
  65373. assert( pCx->uc.pCursor!=0 );
  65374. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  65375. }
  65376. break;
  65377. }
  65378. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65379. case CURTYPE_VTAB: {
  65380. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  65381. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  65382. assert( pVCur->pVtab->nRef>0 );
  65383. pVCur->pVtab->nRef--;
  65384. pModule->xClose(pVCur);
  65385. break;
  65386. }
  65387. #endif
  65388. }
  65389. }
  65390. /*
  65391. ** Close all cursors in the current frame.
  65392. */
  65393. static void closeCursorsInFrame(Vdbe *p){
  65394. if( p->apCsr ){
  65395. int i;
  65396. for(i=0; i<p->nCursor; i++){
  65397. VdbeCursor *pC = p->apCsr[i];
  65398. if( pC ){
  65399. sqlite3VdbeFreeCursor(p, pC);
  65400. p->apCsr[i] = 0;
  65401. }
  65402. }
  65403. }
  65404. }
  65405. /*
  65406. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  65407. ** is used, for example, when a trigger sub-program is halted to restore
  65408. ** control to the main program.
  65409. */
  65410. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  65411. Vdbe *v = pFrame->v;
  65412. closeCursorsInFrame(v);
  65413. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  65414. v->anExec = pFrame->anExec;
  65415. #endif
  65416. v->aOnceFlag = pFrame->aOnceFlag;
  65417. v->nOnceFlag = pFrame->nOnceFlag;
  65418. v->aOp = pFrame->aOp;
  65419. v->nOp = pFrame->nOp;
  65420. v->aMem = pFrame->aMem;
  65421. v->nMem = pFrame->nMem;
  65422. v->apCsr = pFrame->apCsr;
  65423. v->nCursor = pFrame->nCursor;
  65424. v->db->lastRowid = pFrame->lastRowid;
  65425. v->nChange = pFrame->nChange;
  65426. v->db->nChange = pFrame->nDbChange;
  65427. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  65428. v->pAuxData = pFrame->pAuxData;
  65429. pFrame->pAuxData = 0;
  65430. return pFrame->pc;
  65431. }
  65432. /*
  65433. ** Close all cursors.
  65434. **
  65435. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  65436. ** cell array. This is necessary as the memory cell array may contain
  65437. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  65438. ** open cursors.
  65439. */
  65440. static void closeAllCursors(Vdbe *p){
  65441. if( p->pFrame ){
  65442. VdbeFrame *pFrame;
  65443. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  65444. sqlite3VdbeFrameRestore(pFrame);
  65445. p->pFrame = 0;
  65446. p->nFrame = 0;
  65447. }
  65448. assert( p->nFrame==0 );
  65449. closeCursorsInFrame(p);
  65450. if( p->aMem ){
  65451. releaseMemArray(p->aMem, p->nMem);
  65452. }
  65453. while( p->pDelFrame ){
  65454. VdbeFrame *pDel = p->pDelFrame;
  65455. p->pDelFrame = pDel->pParent;
  65456. sqlite3VdbeFrameDelete(pDel);
  65457. }
  65458. /* Delete any auxdata allocations made by the VM */
  65459. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  65460. assert( p->pAuxData==0 );
  65461. }
  65462. /*
  65463. ** Clean up the VM after a single run.
  65464. */
  65465. static void Cleanup(Vdbe *p){
  65466. sqlite3 *db = p->db;
  65467. #ifdef SQLITE_DEBUG
  65468. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  65469. ** Vdbe.aMem[] arrays have already been cleaned up. */
  65470. int i;
  65471. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  65472. if( p->aMem ){
  65473. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  65474. }
  65475. #endif
  65476. sqlite3DbFree(db, p->zErrMsg);
  65477. p->zErrMsg = 0;
  65478. p->pResultSet = 0;
  65479. }
  65480. /*
  65481. ** Set the number of result columns that will be returned by this SQL
  65482. ** statement. This is now set at compile time, rather than during
  65483. ** execution of the vdbe program so that sqlite3_column_count() can
  65484. ** be called on an SQL statement before sqlite3_step().
  65485. */
  65486. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  65487. Mem *pColName;
  65488. int n;
  65489. sqlite3 *db = p->db;
  65490. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  65491. sqlite3DbFree(db, p->aColName);
  65492. n = nResColumn*COLNAME_N;
  65493. p->nResColumn = (u16)nResColumn;
  65494. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  65495. if( p->aColName==0 ) return;
  65496. while( n-- > 0 ){
  65497. pColName->flags = MEM_Null;
  65498. pColName->db = p->db;
  65499. pColName++;
  65500. }
  65501. }
  65502. /*
  65503. ** Set the name of the idx'th column to be returned by the SQL statement.
  65504. ** zName must be a pointer to a nul terminated string.
  65505. **
  65506. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  65507. **
  65508. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  65509. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  65510. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  65511. */
  65512. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  65513. Vdbe *p, /* Vdbe being configured */
  65514. int idx, /* Index of column zName applies to */
  65515. int var, /* One of the COLNAME_* constants */
  65516. const char *zName, /* Pointer to buffer containing name */
  65517. void (*xDel)(void*) /* Memory management strategy for zName */
  65518. ){
  65519. int rc;
  65520. Mem *pColName;
  65521. assert( idx<p->nResColumn );
  65522. assert( var<COLNAME_N );
  65523. if( p->db->mallocFailed ){
  65524. assert( !zName || xDel!=SQLITE_DYNAMIC );
  65525. return SQLITE_NOMEM_BKPT;
  65526. }
  65527. assert( p->aColName!=0 );
  65528. pColName = &(p->aColName[idx+var*p->nResColumn]);
  65529. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  65530. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  65531. return rc;
  65532. }
  65533. /*
  65534. ** A read or write transaction may or may not be active on database handle
  65535. ** db. If a transaction is active, commit it. If there is a
  65536. ** write-transaction spanning more than one database file, this routine
  65537. ** takes care of the master journal trickery.
  65538. */
  65539. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  65540. int i;
  65541. int nTrans = 0; /* Number of databases with an active write-transaction
  65542. ** that are candidates for a two-phase commit using a
  65543. ** master-journal */
  65544. int rc = SQLITE_OK;
  65545. int needXcommit = 0;
  65546. #ifdef SQLITE_OMIT_VIRTUALTABLE
  65547. /* With this option, sqlite3VtabSync() is defined to be simply
  65548. ** SQLITE_OK so p is not used.
  65549. */
  65550. UNUSED_PARAMETER(p);
  65551. #endif
  65552. /* Before doing anything else, call the xSync() callback for any
  65553. ** virtual module tables written in this transaction. This has to
  65554. ** be done before determining whether a master journal file is
  65555. ** required, as an xSync() callback may add an attached database
  65556. ** to the transaction.
  65557. */
  65558. rc = sqlite3VtabSync(db, p);
  65559. /* This loop determines (a) if the commit hook should be invoked and
  65560. ** (b) how many database files have open write transactions, not
  65561. ** including the temp database. (b) is important because if more than
  65562. ** one database file has an open write transaction, a master journal
  65563. ** file is required for an atomic commit.
  65564. */
  65565. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  65566. Btree *pBt = db->aDb[i].pBt;
  65567. if( sqlite3BtreeIsInTrans(pBt) ){
  65568. /* Whether or not a database might need a master journal depends upon
  65569. ** its journal mode (among other things). This matrix determines which
  65570. ** journal modes use a master journal and which do not */
  65571. static const u8 aMJNeeded[] = {
  65572. /* DELETE */ 1,
  65573. /* PERSIST */ 1,
  65574. /* OFF */ 0,
  65575. /* TRUNCATE */ 1,
  65576. /* MEMORY */ 0,
  65577. /* WAL */ 0
  65578. };
  65579. Pager *pPager; /* Pager associated with pBt */
  65580. needXcommit = 1;
  65581. sqlite3BtreeEnter(pBt);
  65582. pPager = sqlite3BtreePager(pBt);
  65583. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  65584. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  65585. ){
  65586. assert( i!=1 );
  65587. nTrans++;
  65588. }
  65589. rc = sqlite3PagerExclusiveLock(pPager);
  65590. sqlite3BtreeLeave(pBt);
  65591. }
  65592. }
  65593. if( rc!=SQLITE_OK ){
  65594. return rc;
  65595. }
  65596. /* If there are any write-transactions at all, invoke the commit hook */
  65597. if( needXcommit && db->xCommitCallback ){
  65598. rc = db->xCommitCallback(db->pCommitArg);
  65599. if( rc ){
  65600. return SQLITE_CONSTRAINT_COMMITHOOK;
  65601. }
  65602. }
  65603. /* The simple case - no more than one database file (not counting the
  65604. ** TEMP database) has a transaction active. There is no need for the
  65605. ** master-journal.
  65606. **
  65607. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  65608. ** string, it means the main database is :memory: or a temp file. In
  65609. ** that case we do not support atomic multi-file commits, so use the
  65610. ** simple case then too.
  65611. */
  65612. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  65613. || nTrans<=1
  65614. ){
  65615. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  65616. Btree *pBt = db->aDb[i].pBt;
  65617. if( pBt ){
  65618. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  65619. }
  65620. }
  65621. /* Do the commit only if all databases successfully complete phase 1.
  65622. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  65623. ** IO error while deleting or truncating a journal file. It is unlikely,
  65624. ** but could happen. In this case abandon processing and return the error.
  65625. */
  65626. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  65627. Btree *pBt = db->aDb[i].pBt;
  65628. if( pBt ){
  65629. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  65630. }
  65631. }
  65632. if( rc==SQLITE_OK ){
  65633. sqlite3VtabCommit(db);
  65634. }
  65635. }
  65636. /* The complex case - There is a multi-file write-transaction active.
  65637. ** This requires a master journal file to ensure the transaction is
  65638. ** committed atomically.
  65639. */
  65640. #ifndef SQLITE_OMIT_DISKIO
  65641. else{
  65642. sqlite3_vfs *pVfs = db->pVfs;
  65643. char *zMaster = 0; /* File-name for the master journal */
  65644. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  65645. sqlite3_file *pMaster = 0;
  65646. i64 offset = 0;
  65647. int res;
  65648. int retryCount = 0;
  65649. int nMainFile;
  65650. /* Select a master journal file name */
  65651. nMainFile = sqlite3Strlen30(zMainFile);
  65652. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  65653. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  65654. do {
  65655. u32 iRandom;
  65656. if( retryCount ){
  65657. if( retryCount>100 ){
  65658. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  65659. sqlite3OsDelete(pVfs, zMaster, 0);
  65660. break;
  65661. }else if( retryCount==1 ){
  65662. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  65663. }
  65664. }
  65665. retryCount++;
  65666. sqlite3_randomness(sizeof(iRandom), &iRandom);
  65667. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  65668. (iRandom>>8)&0xffffff, iRandom&0xff);
  65669. /* The antipenultimate character of the master journal name must
  65670. ** be "9" to avoid name collisions when using 8+3 filenames. */
  65671. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  65672. sqlite3FileSuffix3(zMainFile, zMaster);
  65673. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  65674. }while( rc==SQLITE_OK && res );
  65675. if( rc==SQLITE_OK ){
  65676. /* Open the master journal. */
  65677. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  65678. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  65679. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  65680. );
  65681. }
  65682. if( rc!=SQLITE_OK ){
  65683. sqlite3DbFree(db, zMaster);
  65684. return rc;
  65685. }
  65686. /* Write the name of each database file in the transaction into the new
  65687. ** master journal file. If an error occurs at this point close
  65688. ** and delete the master journal file. All the individual journal files
  65689. ** still have 'null' as the master journal pointer, so they will roll
  65690. ** back independently if a failure occurs.
  65691. */
  65692. for(i=0; i<db->nDb; i++){
  65693. Btree *pBt = db->aDb[i].pBt;
  65694. if( sqlite3BtreeIsInTrans(pBt) ){
  65695. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  65696. if( zFile==0 ){
  65697. continue; /* Ignore TEMP and :memory: databases */
  65698. }
  65699. assert( zFile[0]!=0 );
  65700. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  65701. offset += sqlite3Strlen30(zFile)+1;
  65702. if( rc!=SQLITE_OK ){
  65703. sqlite3OsCloseFree(pMaster);
  65704. sqlite3OsDelete(pVfs, zMaster, 0);
  65705. sqlite3DbFree(db, zMaster);
  65706. return rc;
  65707. }
  65708. }
  65709. }
  65710. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  65711. ** flag is set this is not required.
  65712. */
  65713. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  65714. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  65715. ){
  65716. sqlite3OsCloseFree(pMaster);
  65717. sqlite3OsDelete(pVfs, zMaster, 0);
  65718. sqlite3DbFree(db, zMaster);
  65719. return rc;
  65720. }
  65721. /* Sync all the db files involved in the transaction. The same call
  65722. ** sets the master journal pointer in each individual journal. If
  65723. ** an error occurs here, do not delete the master journal file.
  65724. **
  65725. ** If the error occurs during the first call to
  65726. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  65727. ** master journal file will be orphaned. But we cannot delete it,
  65728. ** in case the master journal file name was written into the journal
  65729. ** file before the failure occurred.
  65730. */
  65731. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  65732. Btree *pBt = db->aDb[i].pBt;
  65733. if( pBt ){
  65734. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  65735. }
  65736. }
  65737. sqlite3OsCloseFree(pMaster);
  65738. assert( rc!=SQLITE_BUSY );
  65739. if( rc!=SQLITE_OK ){
  65740. sqlite3DbFree(db, zMaster);
  65741. return rc;
  65742. }
  65743. /* Delete the master journal file. This commits the transaction. After
  65744. ** doing this the directory is synced again before any individual
  65745. ** transaction files are deleted.
  65746. */
  65747. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  65748. sqlite3DbFree(db, zMaster);
  65749. zMaster = 0;
  65750. if( rc ){
  65751. return rc;
  65752. }
  65753. /* All files and directories have already been synced, so the following
  65754. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  65755. ** deleting or truncating journals. If something goes wrong while
  65756. ** this is happening we don't really care. The integrity of the
  65757. ** transaction is already guaranteed, but some stray 'cold' journals
  65758. ** may be lying around. Returning an error code won't help matters.
  65759. */
  65760. disable_simulated_io_errors();
  65761. sqlite3BeginBenignMalloc();
  65762. for(i=0; i<db->nDb; i++){
  65763. Btree *pBt = db->aDb[i].pBt;
  65764. if( pBt ){
  65765. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  65766. }
  65767. }
  65768. sqlite3EndBenignMalloc();
  65769. enable_simulated_io_errors();
  65770. sqlite3VtabCommit(db);
  65771. }
  65772. #endif
  65773. return rc;
  65774. }
  65775. /*
  65776. ** This routine checks that the sqlite3.nVdbeActive count variable
  65777. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  65778. ** currently active. An assertion fails if the two counts do not match.
  65779. ** This is an internal self-check only - it is not an essential processing
  65780. ** step.
  65781. **
  65782. ** This is a no-op if NDEBUG is defined.
  65783. */
  65784. #ifndef NDEBUG
  65785. static void checkActiveVdbeCnt(sqlite3 *db){
  65786. Vdbe *p;
  65787. int cnt = 0;
  65788. int nWrite = 0;
  65789. int nRead = 0;
  65790. p = db->pVdbe;
  65791. while( p ){
  65792. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  65793. cnt++;
  65794. if( p->readOnly==0 ) nWrite++;
  65795. if( p->bIsReader ) nRead++;
  65796. }
  65797. p = p->pNext;
  65798. }
  65799. assert( cnt==db->nVdbeActive );
  65800. assert( nWrite==db->nVdbeWrite );
  65801. assert( nRead==db->nVdbeRead );
  65802. }
  65803. #else
  65804. #define checkActiveVdbeCnt(x)
  65805. #endif
  65806. /*
  65807. ** If the Vdbe passed as the first argument opened a statement-transaction,
  65808. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  65809. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  65810. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  65811. ** statement transaction is committed.
  65812. **
  65813. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  65814. ** Otherwise SQLITE_OK.
  65815. */
  65816. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  65817. sqlite3 *const db = p->db;
  65818. int rc = SQLITE_OK;
  65819. /* If p->iStatement is greater than zero, then this Vdbe opened a
  65820. ** statement transaction that should be closed here. The only exception
  65821. ** is that an IO error may have occurred, causing an emergency rollback.
  65822. ** In this case (db->nStatement==0), and there is nothing to do.
  65823. */
  65824. if( db->nStatement && p->iStatement ){
  65825. int i;
  65826. const int iSavepoint = p->iStatement-1;
  65827. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  65828. assert( db->nStatement>0 );
  65829. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  65830. for(i=0; i<db->nDb; i++){
  65831. int rc2 = SQLITE_OK;
  65832. Btree *pBt = db->aDb[i].pBt;
  65833. if( pBt ){
  65834. if( eOp==SAVEPOINT_ROLLBACK ){
  65835. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  65836. }
  65837. if( rc2==SQLITE_OK ){
  65838. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  65839. }
  65840. if( rc==SQLITE_OK ){
  65841. rc = rc2;
  65842. }
  65843. }
  65844. }
  65845. db->nStatement--;
  65846. p->iStatement = 0;
  65847. if( rc==SQLITE_OK ){
  65848. if( eOp==SAVEPOINT_ROLLBACK ){
  65849. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  65850. }
  65851. if( rc==SQLITE_OK ){
  65852. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  65853. }
  65854. }
  65855. /* If the statement transaction is being rolled back, also restore the
  65856. ** database handles deferred constraint counter to the value it had when
  65857. ** the statement transaction was opened. */
  65858. if( eOp==SAVEPOINT_ROLLBACK ){
  65859. db->nDeferredCons = p->nStmtDefCons;
  65860. db->nDeferredImmCons = p->nStmtDefImmCons;
  65861. }
  65862. }
  65863. return rc;
  65864. }
  65865. /*
  65866. ** This function is called when a transaction opened by the database
  65867. ** handle associated with the VM passed as an argument is about to be
  65868. ** committed. If there are outstanding deferred foreign key constraint
  65869. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  65870. **
  65871. ** If there are outstanding FK violations and this function returns
  65872. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  65873. ** and write an error message to it. Then return SQLITE_ERROR.
  65874. */
  65875. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65876. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  65877. sqlite3 *db = p->db;
  65878. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  65879. || (!deferred && p->nFkConstraint>0)
  65880. ){
  65881. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  65882. p->errorAction = OE_Abort;
  65883. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  65884. return SQLITE_ERROR;
  65885. }
  65886. return SQLITE_OK;
  65887. }
  65888. #endif
  65889. /*
  65890. ** This routine is called the when a VDBE tries to halt. If the VDBE
  65891. ** has made changes and is in autocommit mode, then commit those
  65892. ** changes. If a rollback is needed, then do the rollback.
  65893. **
  65894. ** This routine is the only way to move the state of a VM from
  65895. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  65896. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  65897. **
  65898. ** Return an error code. If the commit could not complete because of
  65899. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  65900. ** means the close did not happen and needs to be repeated.
  65901. */
  65902. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  65903. int rc; /* Used to store transient return codes */
  65904. sqlite3 *db = p->db;
  65905. /* This function contains the logic that determines if a statement or
  65906. ** transaction will be committed or rolled back as a result of the
  65907. ** execution of this virtual machine.
  65908. **
  65909. ** If any of the following errors occur:
  65910. **
  65911. ** SQLITE_NOMEM
  65912. ** SQLITE_IOERR
  65913. ** SQLITE_FULL
  65914. ** SQLITE_INTERRUPT
  65915. **
  65916. ** Then the internal cache might have been left in an inconsistent
  65917. ** state. We need to rollback the statement transaction, if there is
  65918. ** one, or the complete transaction if there is no statement transaction.
  65919. */
  65920. if( db->mallocFailed ){
  65921. p->rc = SQLITE_NOMEM_BKPT;
  65922. }
  65923. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  65924. closeAllCursors(p);
  65925. if( p->magic!=VDBE_MAGIC_RUN ){
  65926. return SQLITE_OK;
  65927. }
  65928. checkActiveVdbeCnt(db);
  65929. /* No commit or rollback needed if the program never started or if the
  65930. ** SQL statement does not read or write a database file. */
  65931. if( p->pc>=0 && p->bIsReader ){
  65932. int mrc; /* Primary error code from p->rc */
  65933. int eStatementOp = 0;
  65934. int isSpecialError; /* Set to true if a 'special' error */
  65935. /* Lock all btrees used by the statement */
  65936. sqlite3VdbeEnter(p);
  65937. /* Check for one of the special errors */
  65938. mrc = p->rc & 0xff;
  65939. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  65940. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  65941. if( isSpecialError ){
  65942. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  65943. ** no rollback is necessary. Otherwise, at least a savepoint
  65944. ** transaction must be rolled back to restore the database to a
  65945. ** consistent state.
  65946. **
  65947. ** Even if the statement is read-only, it is important to perform
  65948. ** a statement or transaction rollback operation. If the error
  65949. ** occurred while writing to the journal, sub-journal or database
  65950. ** file as part of an effort to free up cache space (see function
  65951. ** pagerStress() in pager.c), the rollback is required to restore
  65952. ** the pager to a consistent state.
  65953. */
  65954. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  65955. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  65956. eStatementOp = SAVEPOINT_ROLLBACK;
  65957. }else{
  65958. /* We are forced to roll back the active transaction. Before doing
  65959. ** so, abort any other statements this handle currently has active.
  65960. */
  65961. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  65962. sqlite3CloseSavepoints(db);
  65963. db->autoCommit = 1;
  65964. p->nChange = 0;
  65965. }
  65966. }
  65967. }
  65968. /* Check for immediate foreign key violations. */
  65969. if( p->rc==SQLITE_OK ){
  65970. sqlite3VdbeCheckFk(p, 0);
  65971. }
  65972. /* If the auto-commit flag is set and this is the only active writer
  65973. ** VM, then we do either a commit or rollback of the current transaction.
  65974. **
  65975. ** Note: This block also runs if one of the special errors handled
  65976. ** above has occurred.
  65977. */
  65978. if( !sqlite3VtabInSync(db)
  65979. && db->autoCommit
  65980. && db->nVdbeWrite==(p->readOnly==0)
  65981. ){
  65982. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  65983. rc = sqlite3VdbeCheckFk(p, 1);
  65984. if( rc!=SQLITE_OK ){
  65985. if( NEVER(p->readOnly) ){
  65986. sqlite3VdbeLeave(p);
  65987. return SQLITE_ERROR;
  65988. }
  65989. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  65990. }else{
  65991. /* The auto-commit flag is true, the vdbe program was successful
  65992. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  65993. ** key constraints to hold up the transaction. This means a commit
  65994. ** is required. */
  65995. rc = vdbeCommit(db, p);
  65996. }
  65997. if( rc==SQLITE_BUSY && p->readOnly ){
  65998. sqlite3VdbeLeave(p);
  65999. return SQLITE_BUSY;
  66000. }else if( rc!=SQLITE_OK ){
  66001. p->rc = rc;
  66002. sqlite3RollbackAll(db, SQLITE_OK);
  66003. p->nChange = 0;
  66004. }else{
  66005. db->nDeferredCons = 0;
  66006. db->nDeferredImmCons = 0;
  66007. db->flags &= ~SQLITE_DeferFKs;
  66008. sqlite3CommitInternalChanges(db);
  66009. }
  66010. }else{
  66011. sqlite3RollbackAll(db, SQLITE_OK);
  66012. p->nChange = 0;
  66013. }
  66014. db->nStatement = 0;
  66015. }else if( eStatementOp==0 ){
  66016. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  66017. eStatementOp = SAVEPOINT_RELEASE;
  66018. }else if( p->errorAction==OE_Abort ){
  66019. eStatementOp = SAVEPOINT_ROLLBACK;
  66020. }else{
  66021. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  66022. sqlite3CloseSavepoints(db);
  66023. db->autoCommit = 1;
  66024. p->nChange = 0;
  66025. }
  66026. }
  66027. /* If eStatementOp is non-zero, then a statement transaction needs to
  66028. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  66029. ** do so. If this operation returns an error, and the current statement
  66030. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  66031. ** current statement error code.
  66032. */
  66033. if( eStatementOp ){
  66034. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  66035. if( rc ){
  66036. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  66037. p->rc = rc;
  66038. sqlite3DbFree(db, p->zErrMsg);
  66039. p->zErrMsg = 0;
  66040. }
  66041. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  66042. sqlite3CloseSavepoints(db);
  66043. db->autoCommit = 1;
  66044. p->nChange = 0;
  66045. }
  66046. }
  66047. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  66048. ** has been rolled back, update the database connection change-counter.
  66049. */
  66050. if( p->changeCntOn ){
  66051. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  66052. sqlite3VdbeSetChanges(db, p->nChange);
  66053. }else{
  66054. sqlite3VdbeSetChanges(db, 0);
  66055. }
  66056. p->nChange = 0;
  66057. }
  66058. /* Release the locks */
  66059. sqlite3VdbeLeave(p);
  66060. }
  66061. /* We have successfully halted and closed the VM. Record this fact. */
  66062. if( p->pc>=0 ){
  66063. db->nVdbeActive--;
  66064. if( !p->readOnly ) db->nVdbeWrite--;
  66065. if( p->bIsReader ) db->nVdbeRead--;
  66066. assert( db->nVdbeActive>=db->nVdbeRead );
  66067. assert( db->nVdbeRead>=db->nVdbeWrite );
  66068. assert( db->nVdbeWrite>=0 );
  66069. }
  66070. p->magic = VDBE_MAGIC_HALT;
  66071. checkActiveVdbeCnt(db);
  66072. if( db->mallocFailed ){
  66073. p->rc = SQLITE_NOMEM_BKPT;
  66074. }
  66075. /* If the auto-commit flag is set to true, then any locks that were held
  66076. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  66077. ** to invoke any required unlock-notify callbacks.
  66078. */
  66079. if( db->autoCommit ){
  66080. sqlite3ConnectionUnlocked(db);
  66081. }
  66082. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  66083. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  66084. }
  66085. /*
  66086. ** Each VDBE holds the result of the most recent sqlite3_step() call
  66087. ** in p->rc. This routine sets that result back to SQLITE_OK.
  66088. */
  66089. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  66090. p->rc = SQLITE_OK;
  66091. }
  66092. /*
  66093. ** Copy the error code and error message belonging to the VDBE passed
  66094. ** as the first argument to its database handle (so that they will be
  66095. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  66096. **
  66097. ** This function does not clear the VDBE error code or message, just
  66098. ** copies them to the database handle.
  66099. */
  66100. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  66101. sqlite3 *db = p->db;
  66102. int rc = p->rc;
  66103. if( p->zErrMsg ){
  66104. db->bBenignMalloc++;
  66105. sqlite3BeginBenignMalloc();
  66106. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  66107. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  66108. sqlite3EndBenignMalloc();
  66109. db->bBenignMalloc--;
  66110. db->errCode = rc;
  66111. }else{
  66112. sqlite3Error(db, rc);
  66113. }
  66114. return rc;
  66115. }
  66116. #ifdef SQLITE_ENABLE_SQLLOG
  66117. /*
  66118. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  66119. ** invoke it.
  66120. */
  66121. static void vdbeInvokeSqllog(Vdbe *v){
  66122. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  66123. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  66124. assert( v->db->init.busy==0 );
  66125. if( zExpanded ){
  66126. sqlite3GlobalConfig.xSqllog(
  66127. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  66128. );
  66129. sqlite3DbFree(v->db, zExpanded);
  66130. }
  66131. }
  66132. }
  66133. #else
  66134. # define vdbeInvokeSqllog(x)
  66135. #endif
  66136. /*
  66137. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  66138. ** Write any error messages into *pzErrMsg. Return the result code.
  66139. **
  66140. ** After this routine is run, the VDBE should be ready to be executed
  66141. ** again.
  66142. **
  66143. ** To look at it another way, this routine resets the state of the
  66144. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  66145. ** VDBE_MAGIC_INIT.
  66146. */
  66147. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  66148. sqlite3 *db;
  66149. db = p->db;
  66150. /* If the VM did not run to completion or if it encountered an
  66151. ** error, then it might not have been halted properly. So halt
  66152. ** it now.
  66153. */
  66154. sqlite3VdbeHalt(p);
  66155. /* If the VDBE has be run even partially, then transfer the error code
  66156. ** and error message from the VDBE into the main database structure. But
  66157. ** if the VDBE has just been set to run but has not actually executed any
  66158. ** instructions yet, leave the main database error information unchanged.
  66159. */
  66160. if( p->pc>=0 ){
  66161. vdbeInvokeSqllog(p);
  66162. sqlite3VdbeTransferError(p);
  66163. sqlite3DbFree(db, p->zErrMsg);
  66164. p->zErrMsg = 0;
  66165. if( p->runOnlyOnce ) p->expired = 1;
  66166. }else if( p->rc && p->expired ){
  66167. /* The expired flag was set on the VDBE before the first call
  66168. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  66169. ** called), set the database error in this case as well.
  66170. */
  66171. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  66172. sqlite3DbFree(db, p->zErrMsg);
  66173. p->zErrMsg = 0;
  66174. }
  66175. /* Reclaim all memory used by the VDBE
  66176. */
  66177. Cleanup(p);
  66178. /* Save profiling information from this VDBE run.
  66179. */
  66180. #ifdef VDBE_PROFILE
  66181. {
  66182. FILE *out = fopen("vdbe_profile.out", "a");
  66183. if( out ){
  66184. int i;
  66185. fprintf(out, "---- ");
  66186. for(i=0; i<p->nOp; i++){
  66187. fprintf(out, "%02x", p->aOp[i].opcode);
  66188. }
  66189. fprintf(out, "\n");
  66190. if( p->zSql ){
  66191. char c, pc = 0;
  66192. fprintf(out, "-- ");
  66193. for(i=0; (c = p->zSql[i])!=0; i++){
  66194. if( pc=='\n' ) fprintf(out, "-- ");
  66195. putc(c, out);
  66196. pc = c;
  66197. }
  66198. if( pc!='\n' ) fprintf(out, "\n");
  66199. }
  66200. for(i=0; i<p->nOp; i++){
  66201. char zHdr[100];
  66202. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  66203. p->aOp[i].cnt,
  66204. p->aOp[i].cycles,
  66205. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  66206. );
  66207. fprintf(out, "%s", zHdr);
  66208. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  66209. }
  66210. fclose(out);
  66211. }
  66212. }
  66213. #endif
  66214. p->iCurrentTime = 0;
  66215. p->magic = VDBE_MAGIC_INIT;
  66216. return p->rc & db->errMask;
  66217. }
  66218. /*
  66219. ** Clean up and delete a VDBE after execution. Return an integer which is
  66220. ** the result code. Write any error message text into *pzErrMsg.
  66221. */
  66222. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  66223. int rc = SQLITE_OK;
  66224. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  66225. rc = sqlite3VdbeReset(p);
  66226. assert( (rc & p->db->errMask)==rc );
  66227. }
  66228. sqlite3VdbeDelete(p);
  66229. return rc;
  66230. }
  66231. /*
  66232. ** If parameter iOp is less than zero, then invoke the destructor for
  66233. ** all auxiliary data pointers currently cached by the VM passed as
  66234. ** the first argument.
  66235. **
  66236. ** Or, if iOp is greater than or equal to zero, then the destructor is
  66237. ** only invoked for those auxiliary data pointers created by the user
  66238. ** function invoked by the OP_Function opcode at instruction iOp of
  66239. ** VM pVdbe, and only then if:
  66240. **
  66241. ** * the associated function parameter is the 32nd or later (counting
  66242. ** from left to right), or
  66243. **
  66244. ** * the corresponding bit in argument mask is clear (where the first
  66245. ** function parameter corresponds to bit 0 etc.).
  66246. */
  66247. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  66248. while( *pp ){
  66249. AuxData *pAux = *pp;
  66250. if( (iOp<0)
  66251. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  66252. ){
  66253. testcase( pAux->iArg==31 );
  66254. if( pAux->xDelete ){
  66255. pAux->xDelete(pAux->pAux);
  66256. }
  66257. *pp = pAux->pNext;
  66258. sqlite3DbFree(db, pAux);
  66259. }else{
  66260. pp= &pAux->pNext;
  66261. }
  66262. }
  66263. }
  66264. /*
  66265. ** Free all memory associated with the Vdbe passed as the second argument,
  66266. ** except for object itself, which is preserved.
  66267. **
  66268. ** The difference between this function and sqlite3VdbeDelete() is that
  66269. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  66270. ** the database connection and frees the object itself.
  66271. */
  66272. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  66273. SubProgram *pSub, *pNext;
  66274. int i;
  66275. assert( p->db==0 || p->db==db );
  66276. releaseMemArray(p->aVar, p->nVar);
  66277. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  66278. for(pSub=p->pProgram; pSub; pSub=pNext){
  66279. pNext = pSub->pNext;
  66280. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  66281. sqlite3DbFree(db, pSub);
  66282. }
  66283. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  66284. sqlite3DbFree(db, p->azVar);
  66285. vdbeFreeOpArray(db, p->aOp, p->nOp);
  66286. sqlite3DbFree(db, p->aColName);
  66287. sqlite3DbFree(db, p->zSql);
  66288. sqlite3DbFree(db, p->pFree);
  66289. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  66290. for(i=0; i<p->nScan; i++){
  66291. sqlite3DbFree(db, p->aScan[i].zName);
  66292. }
  66293. sqlite3DbFree(db, p->aScan);
  66294. #endif
  66295. }
  66296. /*
  66297. ** Delete an entire VDBE.
  66298. */
  66299. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  66300. sqlite3 *db;
  66301. if( NEVER(p==0) ) return;
  66302. db = p->db;
  66303. assert( sqlite3_mutex_held(db->mutex) );
  66304. sqlite3VdbeClearObject(db, p);
  66305. if( p->pPrev ){
  66306. p->pPrev->pNext = p->pNext;
  66307. }else{
  66308. assert( db->pVdbe==p );
  66309. db->pVdbe = p->pNext;
  66310. }
  66311. if( p->pNext ){
  66312. p->pNext->pPrev = p->pPrev;
  66313. }
  66314. p->magic = VDBE_MAGIC_DEAD;
  66315. p->db = 0;
  66316. sqlite3DbFree(db, p);
  66317. }
  66318. /*
  66319. ** The cursor "p" has a pending seek operation that has not yet been
  66320. ** carried out. Seek the cursor now. If an error occurs, return
  66321. ** the appropriate error code.
  66322. */
  66323. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  66324. int res, rc;
  66325. #ifdef SQLITE_TEST
  66326. extern int sqlite3_search_count;
  66327. #endif
  66328. assert( p->deferredMoveto );
  66329. assert( p->isTable );
  66330. assert( p->eCurType==CURTYPE_BTREE );
  66331. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  66332. if( rc ) return rc;
  66333. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  66334. #ifdef SQLITE_TEST
  66335. sqlite3_search_count++;
  66336. #endif
  66337. p->deferredMoveto = 0;
  66338. p->cacheStatus = CACHE_STALE;
  66339. return SQLITE_OK;
  66340. }
  66341. /*
  66342. ** Something has moved cursor "p" out of place. Maybe the row it was
  66343. ** pointed to was deleted out from under it. Or maybe the btree was
  66344. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  66345. ** is supposed to be pointing. If the row was deleted out from under the
  66346. ** cursor, set the cursor to point to a NULL row.
  66347. */
  66348. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  66349. int isDifferentRow, rc;
  66350. assert( p->eCurType==CURTYPE_BTREE );
  66351. assert( p->uc.pCursor!=0 );
  66352. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  66353. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  66354. p->cacheStatus = CACHE_STALE;
  66355. if( isDifferentRow ) p->nullRow = 1;
  66356. return rc;
  66357. }
  66358. /*
  66359. ** Check to ensure that the cursor is valid. Restore the cursor
  66360. ** if need be. Return any I/O error from the restore operation.
  66361. */
  66362. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  66363. assert( p->eCurType==CURTYPE_BTREE );
  66364. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  66365. return handleMovedCursor(p);
  66366. }
  66367. return SQLITE_OK;
  66368. }
  66369. /*
  66370. ** Make sure the cursor p is ready to read or write the row to which it
  66371. ** was last positioned. Return an error code if an OOM fault or I/O error
  66372. ** prevents us from positioning the cursor to its correct position.
  66373. **
  66374. ** If a MoveTo operation is pending on the given cursor, then do that
  66375. ** MoveTo now. If no move is pending, check to see if the row has been
  66376. ** deleted out from under the cursor and if it has, mark the row as
  66377. ** a NULL row.
  66378. **
  66379. ** If the cursor is already pointing to the correct row and that row has
  66380. ** not been deleted out from under the cursor, then this routine is a no-op.
  66381. */
  66382. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  66383. VdbeCursor *p = *pp;
  66384. if( p->eCurType==CURTYPE_BTREE ){
  66385. if( p->deferredMoveto ){
  66386. int iMap;
  66387. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  66388. *pp = p->pAltCursor;
  66389. *piCol = iMap - 1;
  66390. return SQLITE_OK;
  66391. }
  66392. return handleDeferredMoveto(p);
  66393. }
  66394. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  66395. return handleMovedCursor(p);
  66396. }
  66397. }
  66398. return SQLITE_OK;
  66399. }
  66400. /*
  66401. ** The following functions:
  66402. **
  66403. ** sqlite3VdbeSerialType()
  66404. ** sqlite3VdbeSerialTypeLen()
  66405. ** sqlite3VdbeSerialLen()
  66406. ** sqlite3VdbeSerialPut()
  66407. ** sqlite3VdbeSerialGet()
  66408. **
  66409. ** encapsulate the code that serializes values for storage in SQLite
  66410. ** data and index records. Each serialized value consists of a
  66411. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  66412. ** integer, stored as a varint.
  66413. **
  66414. ** In an SQLite index record, the serial type is stored directly before
  66415. ** the blob of data that it corresponds to. In a table record, all serial
  66416. ** types are stored at the start of the record, and the blobs of data at
  66417. ** the end. Hence these functions allow the caller to handle the
  66418. ** serial-type and data blob separately.
  66419. **
  66420. ** The following table describes the various storage classes for data:
  66421. **
  66422. ** serial type bytes of data type
  66423. ** -------------- --------------- ---------------
  66424. ** 0 0 NULL
  66425. ** 1 1 signed integer
  66426. ** 2 2 signed integer
  66427. ** 3 3 signed integer
  66428. ** 4 4 signed integer
  66429. ** 5 6 signed integer
  66430. ** 6 8 signed integer
  66431. ** 7 8 IEEE float
  66432. ** 8 0 Integer constant 0
  66433. ** 9 0 Integer constant 1
  66434. ** 10,11 reserved for expansion
  66435. ** N>=12 and even (N-12)/2 BLOB
  66436. ** N>=13 and odd (N-13)/2 text
  66437. **
  66438. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  66439. ** of SQLite will not understand those serial types.
  66440. */
  66441. /*
  66442. ** Return the serial-type for the value stored in pMem.
  66443. */
  66444. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  66445. int flags = pMem->flags;
  66446. u32 n;
  66447. assert( pLen!=0 );
  66448. if( flags&MEM_Null ){
  66449. *pLen = 0;
  66450. return 0;
  66451. }
  66452. if( flags&MEM_Int ){
  66453. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  66454. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  66455. i64 i = pMem->u.i;
  66456. u64 u;
  66457. if( i<0 ){
  66458. u = ~i;
  66459. }else{
  66460. u = i;
  66461. }
  66462. if( u<=127 ){
  66463. if( (i&1)==i && file_format>=4 ){
  66464. *pLen = 0;
  66465. return 8+(u32)u;
  66466. }else{
  66467. *pLen = 1;
  66468. return 1;
  66469. }
  66470. }
  66471. if( u<=32767 ){ *pLen = 2; return 2; }
  66472. if( u<=8388607 ){ *pLen = 3; return 3; }
  66473. if( u<=2147483647 ){ *pLen = 4; return 4; }
  66474. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  66475. *pLen = 8;
  66476. return 6;
  66477. }
  66478. if( flags&MEM_Real ){
  66479. *pLen = 8;
  66480. return 7;
  66481. }
  66482. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  66483. assert( pMem->n>=0 );
  66484. n = (u32)pMem->n;
  66485. if( flags & MEM_Zero ){
  66486. n += pMem->u.nZero;
  66487. }
  66488. *pLen = n;
  66489. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  66490. }
  66491. /*
  66492. ** The sizes for serial types less than 128
  66493. */
  66494. static const u8 sqlite3SmallTypeSizes[] = {
  66495. /* 0 1 2 3 4 5 6 7 8 9 */
  66496. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  66497. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  66498. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  66499. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  66500. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  66501. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  66502. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  66503. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  66504. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  66505. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  66506. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  66507. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  66508. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  66509. };
  66510. /*
  66511. ** Return the length of the data corresponding to the supplied serial-type.
  66512. */
  66513. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  66514. if( serial_type>=128 ){
  66515. return (serial_type-12)/2;
  66516. }else{
  66517. assert( serial_type<12
  66518. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  66519. return sqlite3SmallTypeSizes[serial_type];
  66520. }
  66521. }
  66522. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  66523. assert( serial_type<128 );
  66524. return sqlite3SmallTypeSizes[serial_type];
  66525. }
  66526. /*
  66527. ** If we are on an architecture with mixed-endian floating
  66528. ** points (ex: ARM7) then swap the lower 4 bytes with the
  66529. ** upper 4 bytes. Return the result.
  66530. **
  66531. ** For most architectures, this is a no-op.
  66532. **
  66533. ** (later): It is reported to me that the mixed-endian problem
  66534. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  66535. ** that early versions of GCC stored the two words of a 64-bit
  66536. ** float in the wrong order. And that error has been propagated
  66537. ** ever since. The blame is not necessarily with GCC, though.
  66538. ** GCC might have just copying the problem from a prior compiler.
  66539. ** I am also told that newer versions of GCC that follow a different
  66540. ** ABI get the byte order right.
  66541. **
  66542. ** Developers using SQLite on an ARM7 should compile and run their
  66543. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  66544. ** enabled, some asserts below will ensure that the byte order of
  66545. ** floating point values is correct.
  66546. **
  66547. ** (2007-08-30) Frank van Vugt has studied this problem closely
  66548. ** and has send his findings to the SQLite developers. Frank
  66549. ** writes that some Linux kernels offer floating point hardware
  66550. ** emulation that uses only 32-bit mantissas instead of a full
  66551. ** 48-bits as required by the IEEE standard. (This is the
  66552. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  66553. ** byte swapping becomes very complicated. To avoid problems,
  66554. ** the necessary byte swapping is carried out using a 64-bit integer
  66555. ** rather than a 64-bit float. Frank assures us that the code here
  66556. ** works for him. We, the developers, have no way to independently
  66557. ** verify this, but Frank seems to know what he is talking about
  66558. ** so we trust him.
  66559. */
  66560. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  66561. static u64 floatSwap(u64 in){
  66562. union {
  66563. u64 r;
  66564. u32 i[2];
  66565. } u;
  66566. u32 t;
  66567. u.r = in;
  66568. t = u.i[0];
  66569. u.i[0] = u.i[1];
  66570. u.i[1] = t;
  66571. return u.r;
  66572. }
  66573. # define swapMixedEndianFloat(X) X = floatSwap(X)
  66574. #else
  66575. # define swapMixedEndianFloat(X)
  66576. #endif
  66577. /*
  66578. ** Write the serialized data blob for the value stored in pMem into
  66579. ** buf. It is assumed that the caller has allocated sufficient space.
  66580. ** Return the number of bytes written.
  66581. **
  66582. ** nBuf is the amount of space left in buf[]. The caller is responsible
  66583. ** for allocating enough space to buf[] to hold the entire field, exclusive
  66584. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  66585. **
  66586. ** Return the number of bytes actually written into buf[]. The number
  66587. ** of bytes in the zero-filled tail is included in the return value only
  66588. ** if those bytes were zeroed in buf[].
  66589. */
  66590. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  66591. u32 len;
  66592. /* Integer and Real */
  66593. if( serial_type<=7 && serial_type>0 ){
  66594. u64 v;
  66595. u32 i;
  66596. if( serial_type==7 ){
  66597. assert( sizeof(v)==sizeof(pMem->u.r) );
  66598. memcpy(&v, &pMem->u.r, sizeof(v));
  66599. swapMixedEndianFloat(v);
  66600. }else{
  66601. v = pMem->u.i;
  66602. }
  66603. len = i = sqlite3SmallTypeSizes[serial_type];
  66604. assert( i>0 );
  66605. do{
  66606. buf[--i] = (u8)(v&0xFF);
  66607. v >>= 8;
  66608. }while( i );
  66609. return len;
  66610. }
  66611. /* String or blob */
  66612. if( serial_type>=12 ){
  66613. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  66614. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  66615. len = pMem->n;
  66616. if( len>0 ) memcpy(buf, pMem->z, len);
  66617. return len;
  66618. }
  66619. /* NULL or constants 0 or 1 */
  66620. return 0;
  66621. }
  66622. /* Input "x" is a sequence of unsigned characters that represent a
  66623. ** big-endian integer. Return the equivalent native integer
  66624. */
  66625. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  66626. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  66627. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  66628. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  66629. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  66630. /*
  66631. ** Deserialize the data blob pointed to by buf as serial type serial_type
  66632. ** and store the result in pMem. Return the number of bytes read.
  66633. **
  66634. ** This function is implemented as two separate routines for performance.
  66635. ** The few cases that require local variables are broken out into a separate
  66636. ** routine so that in most cases the overhead of moving the stack pointer
  66637. ** is avoided.
  66638. */
  66639. static u32 SQLITE_NOINLINE serialGet(
  66640. const unsigned char *buf, /* Buffer to deserialize from */
  66641. u32 serial_type, /* Serial type to deserialize */
  66642. Mem *pMem /* Memory cell to write value into */
  66643. ){
  66644. u64 x = FOUR_BYTE_UINT(buf);
  66645. u32 y = FOUR_BYTE_UINT(buf+4);
  66646. x = (x<<32) + y;
  66647. if( serial_type==6 ){
  66648. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  66649. ** twos-complement integer. */
  66650. pMem->u.i = *(i64*)&x;
  66651. pMem->flags = MEM_Int;
  66652. testcase( pMem->u.i<0 );
  66653. }else{
  66654. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  66655. ** floating point number. */
  66656. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  66657. /* Verify that integers and floating point values use the same
  66658. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  66659. ** defined that 64-bit floating point values really are mixed
  66660. ** endian.
  66661. */
  66662. static const u64 t1 = ((u64)0x3ff00000)<<32;
  66663. static const double r1 = 1.0;
  66664. u64 t2 = t1;
  66665. swapMixedEndianFloat(t2);
  66666. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  66667. #endif
  66668. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  66669. swapMixedEndianFloat(x);
  66670. memcpy(&pMem->u.r, &x, sizeof(x));
  66671. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  66672. }
  66673. return 8;
  66674. }
  66675. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  66676. const unsigned char *buf, /* Buffer to deserialize from */
  66677. u32 serial_type, /* Serial type to deserialize */
  66678. Mem *pMem /* Memory cell to write value into */
  66679. ){
  66680. switch( serial_type ){
  66681. case 10: /* Reserved for future use */
  66682. case 11: /* Reserved for future use */
  66683. case 0: { /* Null */
  66684. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  66685. pMem->flags = MEM_Null;
  66686. break;
  66687. }
  66688. case 1: {
  66689. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  66690. ** integer. */
  66691. pMem->u.i = ONE_BYTE_INT(buf);
  66692. pMem->flags = MEM_Int;
  66693. testcase( pMem->u.i<0 );
  66694. return 1;
  66695. }
  66696. case 2: { /* 2-byte signed integer */
  66697. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  66698. ** twos-complement integer. */
  66699. pMem->u.i = TWO_BYTE_INT(buf);
  66700. pMem->flags = MEM_Int;
  66701. testcase( pMem->u.i<0 );
  66702. return 2;
  66703. }
  66704. case 3: { /* 3-byte signed integer */
  66705. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  66706. ** twos-complement integer. */
  66707. pMem->u.i = THREE_BYTE_INT(buf);
  66708. pMem->flags = MEM_Int;
  66709. testcase( pMem->u.i<0 );
  66710. return 3;
  66711. }
  66712. case 4: { /* 4-byte signed integer */
  66713. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  66714. ** twos-complement integer. */
  66715. pMem->u.i = FOUR_BYTE_INT(buf);
  66716. #ifdef __HP_cc
  66717. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  66718. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  66719. #endif
  66720. pMem->flags = MEM_Int;
  66721. testcase( pMem->u.i<0 );
  66722. return 4;
  66723. }
  66724. case 5: { /* 6-byte signed integer */
  66725. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  66726. ** twos-complement integer. */
  66727. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  66728. pMem->flags = MEM_Int;
  66729. testcase( pMem->u.i<0 );
  66730. return 6;
  66731. }
  66732. case 6: /* 8-byte signed integer */
  66733. case 7: { /* IEEE floating point */
  66734. /* These use local variables, so do them in a separate routine
  66735. ** to avoid having to move the frame pointer in the common case */
  66736. return serialGet(buf,serial_type,pMem);
  66737. }
  66738. case 8: /* Integer 0 */
  66739. case 9: { /* Integer 1 */
  66740. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  66741. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  66742. pMem->u.i = serial_type-8;
  66743. pMem->flags = MEM_Int;
  66744. return 0;
  66745. }
  66746. default: {
  66747. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  66748. ** length.
  66749. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  66750. ** (N-13)/2 bytes in length. */
  66751. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  66752. pMem->z = (char *)buf;
  66753. pMem->n = (serial_type-12)/2;
  66754. pMem->flags = aFlag[serial_type&1];
  66755. return pMem->n;
  66756. }
  66757. }
  66758. return 0;
  66759. }
  66760. /*
  66761. ** This routine is used to allocate sufficient space for an UnpackedRecord
  66762. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  66763. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  66764. **
  66765. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  66766. ** the unaligned buffer passed via the second and third arguments (presumably
  66767. ** stack space). If the former, then *ppFree is set to a pointer that should
  66768. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  66769. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  66770. ** before returning.
  66771. **
  66772. ** If an OOM error occurs, NULL is returned.
  66773. */
  66774. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  66775. KeyInfo *pKeyInfo, /* Description of the record */
  66776. char *pSpace, /* Unaligned space available */
  66777. int szSpace, /* Size of pSpace[] in bytes */
  66778. char **ppFree /* OUT: Caller should free this pointer */
  66779. ){
  66780. UnpackedRecord *p; /* Unpacked record to return */
  66781. int nOff; /* Increment pSpace by nOff to align it */
  66782. int nByte; /* Number of bytes required for *p */
  66783. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  66784. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  66785. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  66786. */
  66787. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  66788. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  66789. if( nByte>szSpace+nOff ){
  66790. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  66791. *ppFree = (char *)p;
  66792. if( !p ) return 0;
  66793. }else{
  66794. p = (UnpackedRecord*)&pSpace[nOff];
  66795. *ppFree = 0;
  66796. }
  66797. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  66798. assert( pKeyInfo->aSortOrder!=0 );
  66799. p->pKeyInfo = pKeyInfo;
  66800. p->nField = pKeyInfo->nField + 1;
  66801. return p;
  66802. }
  66803. /*
  66804. ** Given the nKey-byte encoding of a record in pKey[], populate the
  66805. ** UnpackedRecord structure indicated by the fourth argument with the
  66806. ** contents of the decoded record.
  66807. */
  66808. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  66809. KeyInfo *pKeyInfo, /* Information about the record format */
  66810. int nKey, /* Size of the binary record */
  66811. const void *pKey, /* The binary record */
  66812. UnpackedRecord *p /* Populate this structure before returning. */
  66813. ){
  66814. const unsigned char *aKey = (const unsigned char *)pKey;
  66815. int d;
  66816. u32 idx; /* Offset in aKey[] to read from */
  66817. u16 u; /* Unsigned loop counter */
  66818. u32 szHdr;
  66819. Mem *pMem = p->aMem;
  66820. p->default_rc = 0;
  66821. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66822. idx = getVarint32(aKey, szHdr);
  66823. d = szHdr;
  66824. u = 0;
  66825. while( idx<szHdr && d<=nKey ){
  66826. u32 serial_type;
  66827. idx += getVarint32(&aKey[idx], serial_type);
  66828. pMem->enc = pKeyInfo->enc;
  66829. pMem->db = pKeyInfo->db;
  66830. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  66831. pMem->szMalloc = 0;
  66832. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  66833. pMem++;
  66834. if( (++u)>=p->nField ) break;
  66835. }
  66836. assert( u<=pKeyInfo->nField + 1 );
  66837. p->nField = u;
  66838. }
  66839. #if SQLITE_DEBUG
  66840. /*
  66841. ** This function compares two index or table record keys in the same way
  66842. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  66843. ** this function deserializes and compares values using the
  66844. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  66845. ** in assert() statements to ensure that the optimized code in
  66846. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  66847. **
  66848. ** Return true if the result of comparison is equivalent to desiredResult.
  66849. ** Return false if there is a disagreement.
  66850. */
  66851. static int vdbeRecordCompareDebug(
  66852. int nKey1, const void *pKey1, /* Left key */
  66853. const UnpackedRecord *pPKey2, /* Right key */
  66854. int desiredResult /* Correct answer */
  66855. ){
  66856. u32 d1; /* Offset into aKey[] of next data element */
  66857. u32 idx1; /* Offset into aKey[] of next header element */
  66858. u32 szHdr1; /* Number of bytes in header */
  66859. int i = 0;
  66860. int rc = 0;
  66861. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  66862. KeyInfo *pKeyInfo;
  66863. Mem mem1;
  66864. pKeyInfo = pPKey2->pKeyInfo;
  66865. if( pKeyInfo->db==0 ) return 1;
  66866. mem1.enc = pKeyInfo->enc;
  66867. mem1.db = pKeyInfo->db;
  66868. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  66869. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  66870. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  66871. ** We could initialize it, as shown here, to silence those complaints.
  66872. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  66873. ** the unnecessary initialization has a measurable negative performance
  66874. ** impact, since this routine is a very high runner. And so, we choose
  66875. ** to ignore the compiler warnings and leave this variable uninitialized.
  66876. */
  66877. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  66878. idx1 = getVarint32(aKey1, szHdr1);
  66879. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  66880. d1 = szHdr1;
  66881. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  66882. assert( pKeyInfo->aSortOrder!=0 );
  66883. assert( pKeyInfo->nField>0 );
  66884. assert( idx1<=szHdr1 || CORRUPT_DB );
  66885. do{
  66886. u32 serial_type1;
  66887. /* Read the serial types for the next element in each key. */
  66888. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  66889. /* Verify that there is enough key space remaining to avoid
  66890. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  66891. ** always be greater than or equal to the amount of required key space.
  66892. ** Use that approximation to avoid the more expensive call to
  66893. ** sqlite3VdbeSerialTypeLen() in the common case.
  66894. */
  66895. if( d1+serial_type1+2>(u32)nKey1
  66896. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  66897. ){
  66898. break;
  66899. }
  66900. /* Extract the values to be compared.
  66901. */
  66902. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  66903. /* Do the comparison
  66904. */
  66905. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  66906. if( rc!=0 ){
  66907. assert( mem1.szMalloc==0 ); /* See comment below */
  66908. if( pKeyInfo->aSortOrder[i] ){
  66909. rc = -rc; /* Invert the result for DESC sort order. */
  66910. }
  66911. goto debugCompareEnd;
  66912. }
  66913. i++;
  66914. }while( idx1<szHdr1 && i<pPKey2->nField );
  66915. /* No memory allocation is ever used on mem1. Prove this using
  66916. ** the following assert(). If the assert() fails, it indicates a
  66917. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  66918. */
  66919. assert( mem1.szMalloc==0 );
  66920. /* rc==0 here means that one of the keys ran out of fields and
  66921. ** all the fields up to that point were equal. Return the default_rc
  66922. ** value. */
  66923. rc = pPKey2->default_rc;
  66924. debugCompareEnd:
  66925. if( desiredResult==0 && rc==0 ) return 1;
  66926. if( desiredResult<0 && rc<0 ) return 1;
  66927. if( desiredResult>0 && rc>0 ) return 1;
  66928. if( CORRUPT_DB ) return 1;
  66929. if( pKeyInfo->db->mallocFailed ) return 1;
  66930. return 0;
  66931. }
  66932. #endif
  66933. #if SQLITE_DEBUG
  66934. /*
  66935. ** Count the number of fields (a.k.a. columns) in the record given by
  66936. ** pKey,nKey. The verify that this count is less than or equal to the
  66937. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  66938. **
  66939. ** If this constraint is not satisfied, it means that the high-speed
  66940. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  66941. ** not work correctly. If this assert() ever fires, it probably means
  66942. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  66943. ** incorrectly.
  66944. */
  66945. static void vdbeAssertFieldCountWithinLimits(
  66946. int nKey, const void *pKey, /* The record to verify */
  66947. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  66948. ){
  66949. int nField = 0;
  66950. u32 szHdr;
  66951. u32 idx;
  66952. u32 notUsed;
  66953. const unsigned char *aKey = (const unsigned char*)pKey;
  66954. if( CORRUPT_DB ) return;
  66955. idx = getVarint32(aKey, szHdr);
  66956. assert( nKey>=0 );
  66957. assert( szHdr<=(u32)nKey );
  66958. while( idx<szHdr ){
  66959. idx += getVarint32(aKey+idx, notUsed);
  66960. nField++;
  66961. }
  66962. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  66963. }
  66964. #else
  66965. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  66966. #endif
  66967. /*
  66968. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  66969. ** using the collation sequence pColl. As usual, return a negative , zero
  66970. ** or positive value if *pMem1 is less than, equal to or greater than
  66971. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  66972. */
  66973. static int vdbeCompareMemString(
  66974. const Mem *pMem1,
  66975. const Mem *pMem2,
  66976. const CollSeq *pColl,
  66977. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  66978. ){
  66979. if( pMem1->enc==pColl->enc ){
  66980. /* The strings are already in the correct encoding. Call the
  66981. ** comparison function directly */
  66982. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  66983. }else{
  66984. int rc;
  66985. const void *v1, *v2;
  66986. int n1, n2;
  66987. Mem c1;
  66988. Mem c2;
  66989. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  66990. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  66991. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  66992. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  66993. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  66994. n1 = v1==0 ? 0 : c1.n;
  66995. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  66996. n2 = v2==0 ? 0 : c2.n;
  66997. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  66998. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  66999. sqlite3VdbeMemRelease(&c1);
  67000. sqlite3VdbeMemRelease(&c2);
  67001. return rc;
  67002. }
  67003. }
  67004. /*
  67005. ** Compare two blobs. Return negative, zero, or positive if the first
  67006. ** is less than, equal to, or greater than the second, respectively.
  67007. ** If one blob is a prefix of the other, then the shorter is the lessor.
  67008. */
  67009. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  67010. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  67011. if( c ) return c;
  67012. return pB1->n - pB2->n;
  67013. }
  67014. /*
  67015. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  67016. ** number. Return negative, zero, or positive if the first (i64) is less than,
  67017. ** equal to, or greater than the second (double).
  67018. */
  67019. static int sqlite3IntFloatCompare(i64 i, double r){
  67020. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  67021. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  67022. if( x<r ) return -1;
  67023. if( x>r ) return +1;
  67024. return 0;
  67025. }else{
  67026. i64 y;
  67027. double s;
  67028. if( r<-9223372036854775808.0 ) return +1;
  67029. if( r>9223372036854775807.0 ) return -1;
  67030. y = (i64)r;
  67031. if( i<y ) return -1;
  67032. if( i>y ){
  67033. if( y==SMALLEST_INT64 && r>0.0 ) return -1;
  67034. return +1;
  67035. }
  67036. s = (double)i;
  67037. if( s<r ) return -1;
  67038. if( s>r ) return +1;
  67039. return 0;
  67040. }
  67041. }
  67042. /*
  67043. ** Compare the values contained by the two memory cells, returning
  67044. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  67045. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  67046. ** and reals) sorted numerically, followed by text ordered by the collating
  67047. ** sequence pColl and finally blob's ordered by memcmp().
  67048. **
  67049. ** Two NULL values are considered equal by this function.
  67050. */
  67051. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  67052. int f1, f2;
  67053. int combined_flags;
  67054. f1 = pMem1->flags;
  67055. f2 = pMem2->flags;
  67056. combined_flags = f1|f2;
  67057. assert( (combined_flags & MEM_RowSet)==0 );
  67058. /* If one value is NULL, it is less than the other. If both values
  67059. ** are NULL, return 0.
  67060. */
  67061. if( combined_flags&MEM_Null ){
  67062. return (f2&MEM_Null) - (f1&MEM_Null);
  67063. }
  67064. /* At least one of the two values is a number
  67065. */
  67066. if( combined_flags&(MEM_Int|MEM_Real) ){
  67067. if( (f1 & f2 & MEM_Int)!=0 ){
  67068. if( pMem1->u.i < pMem2->u.i ) return -1;
  67069. if( pMem1->u.i > pMem2->u.i ) return +1;
  67070. return 0;
  67071. }
  67072. if( (f1 & f2 & MEM_Real)!=0 ){
  67073. if( pMem1->u.r < pMem2->u.r ) return -1;
  67074. if( pMem1->u.r > pMem2->u.r ) return +1;
  67075. return 0;
  67076. }
  67077. if( (f1&MEM_Int)!=0 ){
  67078. if( (f2&MEM_Real)!=0 ){
  67079. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  67080. }else{
  67081. return -1;
  67082. }
  67083. }
  67084. if( (f1&MEM_Real)!=0 ){
  67085. if( (f2&MEM_Int)!=0 ){
  67086. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  67087. }else{
  67088. return -1;
  67089. }
  67090. }
  67091. return +1;
  67092. }
  67093. /* If one value is a string and the other is a blob, the string is less.
  67094. ** If both are strings, compare using the collating functions.
  67095. */
  67096. if( combined_flags&MEM_Str ){
  67097. if( (f1 & MEM_Str)==0 ){
  67098. return 1;
  67099. }
  67100. if( (f2 & MEM_Str)==0 ){
  67101. return -1;
  67102. }
  67103. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  67104. assert( pMem1->enc==SQLITE_UTF8 ||
  67105. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  67106. /* The collation sequence must be defined at this point, even if
  67107. ** the user deletes the collation sequence after the vdbe program is
  67108. ** compiled (this was not always the case).
  67109. */
  67110. assert( !pColl || pColl->xCmp );
  67111. if( pColl ){
  67112. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  67113. }
  67114. /* If a NULL pointer was passed as the collate function, fall through
  67115. ** to the blob case and use memcmp(). */
  67116. }
  67117. /* Both values must be blobs. Compare using memcmp(). */
  67118. return sqlite3BlobCompare(pMem1, pMem2);
  67119. }
  67120. /*
  67121. ** The first argument passed to this function is a serial-type that
  67122. ** corresponds to an integer - all values between 1 and 9 inclusive
  67123. ** except 7. The second points to a buffer containing an integer value
  67124. ** serialized according to serial_type. This function deserializes
  67125. ** and returns the value.
  67126. */
  67127. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  67128. u32 y;
  67129. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  67130. switch( serial_type ){
  67131. case 0:
  67132. case 1:
  67133. testcase( aKey[0]&0x80 );
  67134. return ONE_BYTE_INT(aKey);
  67135. case 2:
  67136. testcase( aKey[0]&0x80 );
  67137. return TWO_BYTE_INT(aKey);
  67138. case 3:
  67139. testcase( aKey[0]&0x80 );
  67140. return THREE_BYTE_INT(aKey);
  67141. case 4: {
  67142. testcase( aKey[0]&0x80 );
  67143. y = FOUR_BYTE_UINT(aKey);
  67144. return (i64)*(int*)&y;
  67145. }
  67146. case 5: {
  67147. testcase( aKey[0]&0x80 );
  67148. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  67149. }
  67150. case 6: {
  67151. u64 x = FOUR_BYTE_UINT(aKey);
  67152. testcase( aKey[0]&0x80 );
  67153. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  67154. return (i64)*(i64*)&x;
  67155. }
  67156. }
  67157. return (serial_type - 8);
  67158. }
  67159. /*
  67160. ** This function compares the two table rows or index records
  67161. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  67162. ** or positive integer if key1 is less than, equal to or
  67163. ** greater than key2. The {nKey1, pKey1} key must be a blob
  67164. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  67165. ** key must be a parsed key such as obtained from
  67166. ** sqlite3VdbeParseRecord.
  67167. **
  67168. ** If argument bSkip is non-zero, it is assumed that the caller has already
  67169. ** determined that the first fields of the keys are equal.
  67170. **
  67171. ** Key1 and Key2 do not have to contain the same number of fields. If all
  67172. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  67173. ** returned.
  67174. **
  67175. ** If database corruption is discovered, set pPKey2->errCode to
  67176. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  67177. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  67178. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  67179. */
  67180. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  67181. int nKey1, const void *pKey1, /* Left key */
  67182. UnpackedRecord *pPKey2, /* Right key */
  67183. int bSkip /* If true, skip the first field */
  67184. ){
  67185. u32 d1; /* Offset into aKey[] of next data element */
  67186. int i; /* Index of next field to compare */
  67187. u32 szHdr1; /* Size of record header in bytes */
  67188. u32 idx1; /* Offset of first type in header */
  67189. int rc = 0; /* Return value */
  67190. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  67191. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  67192. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  67193. Mem mem1;
  67194. /* If bSkip is true, then the caller has already determined that the first
  67195. ** two elements in the keys are equal. Fix the various stack variables so
  67196. ** that this routine begins comparing at the second field. */
  67197. if( bSkip ){
  67198. u32 s1;
  67199. idx1 = 1 + getVarint32(&aKey1[1], s1);
  67200. szHdr1 = aKey1[0];
  67201. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  67202. i = 1;
  67203. pRhs++;
  67204. }else{
  67205. idx1 = getVarint32(aKey1, szHdr1);
  67206. d1 = szHdr1;
  67207. if( d1>(unsigned)nKey1 ){
  67208. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  67209. return 0; /* Corruption */
  67210. }
  67211. i = 0;
  67212. }
  67213. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  67214. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  67215. || CORRUPT_DB );
  67216. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  67217. assert( pPKey2->pKeyInfo->nField>0 );
  67218. assert( idx1<=szHdr1 || CORRUPT_DB );
  67219. do{
  67220. u32 serial_type;
  67221. /* RHS is an integer */
  67222. if( pRhs->flags & MEM_Int ){
  67223. serial_type = aKey1[idx1];
  67224. testcase( serial_type==12 );
  67225. if( serial_type>=10 ){
  67226. rc = +1;
  67227. }else if( serial_type==0 ){
  67228. rc = -1;
  67229. }else if( serial_type==7 ){
  67230. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  67231. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  67232. }else{
  67233. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  67234. i64 rhs = pRhs->u.i;
  67235. if( lhs<rhs ){
  67236. rc = -1;
  67237. }else if( lhs>rhs ){
  67238. rc = +1;
  67239. }
  67240. }
  67241. }
  67242. /* RHS is real */
  67243. else if( pRhs->flags & MEM_Real ){
  67244. serial_type = aKey1[idx1];
  67245. if( serial_type>=10 ){
  67246. /* Serial types 12 or greater are strings and blobs (greater than
  67247. ** numbers). Types 10 and 11 are currently "reserved for future
  67248. ** use", so it doesn't really matter what the results of comparing
  67249. ** them to numberic values are. */
  67250. rc = +1;
  67251. }else if( serial_type==0 ){
  67252. rc = -1;
  67253. }else{
  67254. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  67255. if( serial_type==7 ){
  67256. if( mem1.u.r<pRhs->u.r ){
  67257. rc = -1;
  67258. }else if( mem1.u.r>pRhs->u.r ){
  67259. rc = +1;
  67260. }
  67261. }else{
  67262. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  67263. }
  67264. }
  67265. }
  67266. /* RHS is a string */
  67267. else if( pRhs->flags & MEM_Str ){
  67268. getVarint32(&aKey1[idx1], serial_type);
  67269. testcase( serial_type==12 );
  67270. if( serial_type<12 ){
  67271. rc = -1;
  67272. }else if( !(serial_type & 0x01) ){
  67273. rc = +1;
  67274. }else{
  67275. mem1.n = (serial_type - 12) / 2;
  67276. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  67277. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  67278. if( (d1+mem1.n) > (unsigned)nKey1 ){
  67279. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  67280. return 0; /* Corruption */
  67281. }else if( pKeyInfo->aColl[i] ){
  67282. mem1.enc = pKeyInfo->enc;
  67283. mem1.db = pKeyInfo->db;
  67284. mem1.flags = MEM_Str;
  67285. mem1.z = (char*)&aKey1[d1];
  67286. rc = vdbeCompareMemString(
  67287. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  67288. );
  67289. }else{
  67290. int nCmp = MIN(mem1.n, pRhs->n);
  67291. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  67292. if( rc==0 ) rc = mem1.n - pRhs->n;
  67293. }
  67294. }
  67295. }
  67296. /* RHS is a blob */
  67297. else if( pRhs->flags & MEM_Blob ){
  67298. getVarint32(&aKey1[idx1], serial_type);
  67299. testcase( serial_type==12 );
  67300. if( serial_type<12 || (serial_type & 0x01) ){
  67301. rc = -1;
  67302. }else{
  67303. int nStr = (serial_type - 12) / 2;
  67304. testcase( (d1+nStr)==(unsigned)nKey1 );
  67305. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  67306. if( (d1+nStr) > (unsigned)nKey1 ){
  67307. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  67308. return 0; /* Corruption */
  67309. }else{
  67310. int nCmp = MIN(nStr, pRhs->n);
  67311. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  67312. if( rc==0 ) rc = nStr - pRhs->n;
  67313. }
  67314. }
  67315. }
  67316. /* RHS is null */
  67317. else{
  67318. serial_type = aKey1[idx1];
  67319. rc = (serial_type!=0);
  67320. }
  67321. if( rc!=0 ){
  67322. if( pKeyInfo->aSortOrder[i] ){
  67323. rc = -rc;
  67324. }
  67325. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  67326. assert( mem1.szMalloc==0 ); /* See comment below */
  67327. return rc;
  67328. }
  67329. i++;
  67330. pRhs++;
  67331. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  67332. idx1 += sqlite3VarintLen(serial_type);
  67333. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  67334. /* No memory allocation is ever used on mem1. Prove this using
  67335. ** the following assert(). If the assert() fails, it indicates a
  67336. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  67337. assert( mem1.szMalloc==0 );
  67338. /* rc==0 here means that one or both of the keys ran out of fields and
  67339. ** all the fields up to that point were equal. Return the default_rc
  67340. ** value. */
  67341. assert( CORRUPT_DB
  67342. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  67343. || pKeyInfo->db->mallocFailed
  67344. );
  67345. pPKey2->eqSeen = 1;
  67346. return pPKey2->default_rc;
  67347. }
  67348. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  67349. int nKey1, const void *pKey1, /* Left key */
  67350. UnpackedRecord *pPKey2 /* Right key */
  67351. ){
  67352. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  67353. }
  67354. /*
  67355. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  67356. ** that (a) the first field of pPKey2 is an integer, and (b) the
  67357. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  67358. ** byte (i.e. is less than 128).
  67359. **
  67360. ** To avoid concerns about buffer overreads, this routine is only used
  67361. ** on schemas where the maximum valid header size is 63 bytes or less.
  67362. */
  67363. static int vdbeRecordCompareInt(
  67364. int nKey1, const void *pKey1, /* Left key */
  67365. UnpackedRecord *pPKey2 /* Right key */
  67366. ){
  67367. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  67368. int serial_type = ((const u8*)pKey1)[1];
  67369. int res;
  67370. u32 y;
  67371. u64 x;
  67372. i64 v = pPKey2->aMem[0].u.i;
  67373. i64 lhs;
  67374. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  67375. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  67376. switch( serial_type ){
  67377. case 1: { /* 1-byte signed integer */
  67378. lhs = ONE_BYTE_INT(aKey);
  67379. testcase( lhs<0 );
  67380. break;
  67381. }
  67382. case 2: { /* 2-byte signed integer */
  67383. lhs = TWO_BYTE_INT(aKey);
  67384. testcase( lhs<0 );
  67385. break;
  67386. }
  67387. case 3: { /* 3-byte signed integer */
  67388. lhs = THREE_BYTE_INT(aKey);
  67389. testcase( lhs<0 );
  67390. break;
  67391. }
  67392. case 4: { /* 4-byte signed integer */
  67393. y = FOUR_BYTE_UINT(aKey);
  67394. lhs = (i64)*(int*)&y;
  67395. testcase( lhs<0 );
  67396. break;
  67397. }
  67398. case 5: { /* 6-byte signed integer */
  67399. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  67400. testcase( lhs<0 );
  67401. break;
  67402. }
  67403. case 6: { /* 8-byte signed integer */
  67404. x = FOUR_BYTE_UINT(aKey);
  67405. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  67406. lhs = *(i64*)&x;
  67407. testcase( lhs<0 );
  67408. break;
  67409. }
  67410. case 8:
  67411. lhs = 0;
  67412. break;
  67413. case 9:
  67414. lhs = 1;
  67415. break;
  67416. /* This case could be removed without changing the results of running
  67417. ** this code. Including it causes gcc to generate a faster switch
  67418. ** statement (since the range of switch targets now starts at zero and
  67419. ** is contiguous) but does not cause any duplicate code to be generated
  67420. ** (as gcc is clever enough to combine the two like cases). Other
  67421. ** compilers might be similar. */
  67422. case 0: case 7:
  67423. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  67424. default:
  67425. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  67426. }
  67427. if( v>lhs ){
  67428. res = pPKey2->r1;
  67429. }else if( v<lhs ){
  67430. res = pPKey2->r2;
  67431. }else if( pPKey2->nField>1 ){
  67432. /* The first fields of the two keys are equal. Compare the trailing
  67433. ** fields. */
  67434. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  67435. }else{
  67436. /* The first fields of the two keys are equal and there are no trailing
  67437. ** fields. Return pPKey2->default_rc in this case. */
  67438. res = pPKey2->default_rc;
  67439. pPKey2->eqSeen = 1;
  67440. }
  67441. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  67442. return res;
  67443. }
  67444. /*
  67445. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  67446. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  67447. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  67448. ** at the start of (pKey1/nKey1) fits in a single byte.
  67449. */
  67450. static int vdbeRecordCompareString(
  67451. int nKey1, const void *pKey1, /* Left key */
  67452. UnpackedRecord *pPKey2 /* Right key */
  67453. ){
  67454. const u8 *aKey1 = (const u8*)pKey1;
  67455. int serial_type;
  67456. int res;
  67457. assert( pPKey2->aMem[0].flags & MEM_Str );
  67458. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  67459. getVarint32(&aKey1[1], serial_type);
  67460. if( serial_type<12 ){
  67461. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  67462. }else if( !(serial_type & 0x01) ){
  67463. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  67464. }else{
  67465. int nCmp;
  67466. int nStr;
  67467. int szHdr = aKey1[0];
  67468. nStr = (serial_type-12) / 2;
  67469. if( (szHdr + nStr) > nKey1 ){
  67470. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  67471. return 0; /* Corruption */
  67472. }
  67473. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  67474. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  67475. if( res==0 ){
  67476. res = nStr - pPKey2->aMem[0].n;
  67477. if( res==0 ){
  67478. if( pPKey2->nField>1 ){
  67479. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  67480. }else{
  67481. res = pPKey2->default_rc;
  67482. pPKey2->eqSeen = 1;
  67483. }
  67484. }else if( res>0 ){
  67485. res = pPKey2->r2;
  67486. }else{
  67487. res = pPKey2->r1;
  67488. }
  67489. }else if( res>0 ){
  67490. res = pPKey2->r2;
  67491. }else{
  67492. res = pPKey2->r1;
  67493. }
  67494. }
  67495. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  67496. || CORRUPT_DB
  67497. || pPKey2->pKeyInfo->db->mallocFailed
  67498. );
  67499. return res;
  67500. }
  67501. /*
  67502. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  67503. ** suitable for comparing serialized records to the unpacked record passed
  67504. ** as the only argument.
  67505. */
  67506. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  67507. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  67508. ** that the size-of-header varint that occurs at the start of each record
  67509. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  67510. ** also assumes that it is safe to overread a buffer by at least the
  67511. ** maximum possible legal header size plus 8 bytes. Because there is
  67512. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  67513. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  67514. ** limit the size of the header to 64 bytes in cases where the first field
  67515. ** is an integer.
  67516. **
  67517. ** The easiest way to enforce this limit is to consider only records with
  67518. ** 13 fields or less. If the first field is an integer, the maximum legal
  67519. ** header size is (12*5 + 1 + 1) bytes. */
  67520. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  67521. int flags = p->aMem[0].flags;
  67522. if( p->pKeyInfo->aSortOrder[0] ){
  67523. p->r1 = 1;
  67524. p->r2 = -1;
  67525. }else{
  67526. p->r1 = -1;
  67527. p->r2 = 1;
  67528. }
  67529. if( (flags & MEM_Int) ){
  67530. return vdbeRecordCompareInt;
  67531. }
  67532. testcase( flags & MEM_Real );
  67533. testcase( flags & MEM_Null );
  67534. testcase( flags & MEM_Blob );
  67535. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  67536. assert( flags & MEM_Str );
  67537. return vdbeRecordCompareString;
  67538. }
  67539. }
  67540. return sqlite3VdbeRecordCompare;
  67541. }
  67542. /*
  67543. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  67544. ** Read the rowid (the last field in the record) and store it in *rowid.
  67545. ** Return SQLITE_OK if everything works, or an error code otherwise.
  67546. **
  67547. ** pCur might be pointing to text obtained from a corrupt database file.
  67548. ** So the content cannot be trusted. Do appropriate checks on the content.
  67549. */
  67550. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  67551. i64 nCellKey = 0;
  67552. int rc;
  67553. u32 szHdr; /* Size of the header */
  67554. u32 typeRowid; /* Serial type of the rowid */
  67555. u32 lenRowid; /* Size of the rowid */
  67556. Mem m, v;
  67557. /* Get the size of the index entry. Only indices entries of less
  67558. ** than 2GiB are support - anything large must be database corruption.
  67559. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  67560. ** this code can safely assume that nCellKey is 32-bits
  67561. */
  67562. assert( sqlite3BtreeCursorIsValid(pCur) );
  67563. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  67564. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  67565. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  67566. /* Read in the complete content of the index entry */
  67567. sqlite3VdbeMemInit(&m, db, 0);
  67568. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  67569. if( rc ){
  67570. return rc;
  67571. }
  67572. /* The index entry must begin with a header size */
  67573. (void)getVarint32((u8*)m.z, szHdr);
  67574. testcase( szHdr==3 );
  67575. testcase( szHdr==m.n );
  67576. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  67577. goto idx_rowid_corruption;
  67578. }
  67579. /* The last field of the index should be an integer - the ROWID.
  67580. ** Verify that the last entry really is an integer. */
  67581. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  67582. testcase( typeRowid==1 );
  67583. testcase( typeRowid==2 );
  67584. testcase( typeRowid==3 );
  67585. testcase( typeRowid==4 );
  67586. testcase( typeRowid==5 );
  67587. testcase( typeRowid==6 );
  67588. testcase( typeRowid==8 );
  67589. testcase( typeRowid==9 );
  67590. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  67591. goto idx_rowid_corruption;
  67592. }
  67593. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  67594. testcase( (u32)m.n==szHdr+lenRowid );
  67595. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  67596. goto idx_rowid_corruption;
  67597. }
  67598. /* Fetch the integer off the end of the index record */
  67599. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  67600. *rowid = v.u.i;
  67601. sqlite3VdbeMemRelease(&m);
  67602. return SQLITE_OK;
  67603. /* Jump here if database corruption is detected after m has been
  67604. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  67605. idx_rowid_corruption:
  67606. testcase( m.szMalloc!=0 );
  67607. sqlite3VdbeMemRelease(&m);
  67608. return SQLITE_CORRUPT_BKPT;
  67609. }
  67610. /*
  67611. ** Compare the key of the index entry that cursor pC is pointing to against
  67612. ** the key string in pUnpacked. Write into *pRes a number
  67613. ** that is negative, zero, or positive if pC is less than, equal to,
  67614. ** or greater than pUnpacked. Return SQLITE_OK on success.
  67615. **
  67616. ** pUnpacked is either created without a rowid or is truncated so that it
  67617. ** omits the rowid at the end. The rowid at the end of the index entry
  67618. ** is ignored as well. Hence, this routine only compares the prefixes
  67619. ** of the keys prior to the final rowid, not the entire key.
  67620. */
  67621. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  67622. sqlite3 *db, /* Database connection */
  67623. VdbeCursor *pC, /* The cursor to compare against */
  67624. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  67625. int *res /* Write the comparison result here */
  67626. ){
  67627. i64 nCellKey = 0;
  67628. int rc;
  67629. BtCursor *pCur;
  67630. Mem m;
  67631. assert( pC->eCurType==CURTYPE_BTREE );
  67632. pCur = pC->uc.pCursor;
  67633. assert( sqlite3BtreeCursorIsValid(pCur) );
  67634. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  67635. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  67636. /* nCellKey will always be between 0 and 0xffffffff because of the way
  67637. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  67638. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  67639. *res = 0;
  67640. return SQLITE_CORRUPT_BKPT;
  67641. }
  67642. sqlite3VdbeMemInit(&m, db, 0);
  67643. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  67644. if( rc ){
  67645. return rc;
  67646. }
  67647. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  67648. sqlite3VdbeMemRelease(&m);
  67649. return SQLITE_OK;
  67650. }
  67651. /*
  67652. ** This routine sets the value to be returned by subsequent calls to
  67653. ** sqlite3_changes() on the database handle 'db'.
  67654. */
  67655. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  67656. assert( sqlite3_mutex_held(db->mutex) );
  67657. db->nChange = nChange;
  67658. db->nTotalChange += nChange;
  67659. }
  67660. /*
  67661. ** Set a flag in the vdbe to update the change counter when it is finalised
  67662. ** or reset.
  67663. */
  67664. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  67665. v->changeCntOn = 1;
  67666. }
  67667. /*
  67668. ** Mark every prepared statement associated with a database connection
  67669. ** as expired.
  67670. **
  67671. ** An expired statement means that recompilation of the statement is
  67672. ** recommend. Statements expire when things happen that make their
  67673. ** programs obsolete. Removing user-defined functions or collating
  67674. ** sequences, or changing an authorization function are the types of
  67675. ** things that make prepared statements obsolete.
  67676. */
  67677. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  67678. Vdbe *p;
  67679. for(p = db->pVdbe; p; p=p->pNext){
  67680. p->expired = 1;
  67681. }
  67682. }
  67683. /*
  67684. ** Return the database associated with the Vdbe.
  67685. */
  67686. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  67687. return v->db;
  67688. }
  67689. /*
  67690. ** Return a pointer to an sqlite3_value structure containing the value bound
  67691. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  67692. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  67693. ** constants) to the value before returning it.
  67694. **
  67695. ** The returned value must be freed by the caller using sqlite3ValueFree().
  67696. */
  67697. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  67698. assert( iVar>0 );
  67699. if( v ){
  67700. Mem *pMem = &v->aVar[iVar-1];
  67701. if( 0==(pMem->flags & MEM_Null) ){
  67702. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  67703. if( pRet ){
  67704. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  67705. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  67706. }
  67707. return pRet;
  67708. }
  67709. }
  67710. return 0;
  67711. }
  67712. /*
  67713. ** Configure SQL variable iVar so that binding a new value to it signals
  67714. ** to sqlite3_reoptimize() that re-preparing the statement may result
  67715. ** in a better query plan.
  67716. */
  67717. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  67718. assert( iVar>0 );
  67719. if( iVar>32 ){
  67720. v->expmask = 0xffffffff;
  67721. }else{
  67722. v->expmask |= ((u32)1 << (iVar-1));
  67723. }
  67724. }
  67725. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67726. /*
  67727. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  67728. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  67729. ** in memory obtained from sqlite3DbMalloc).
  67730. */
  67731. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  67732. if( pVtab->zErrMsg ){
  67733. sqlite3 *db = p->db;
  67734. sqlite3DbFree(db, p->zErrMsg);
  67735. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  67736. sqlite3_free(pVtab->zErrMsg);
  67737. pVtab->zErrMsg = 0;
  67738. }
  67739. }
  67740. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67741. /************** End of vdbeaux.c *********************************************/
  67742. /************** Begin file vdbeapi.c *****************************************/
  67743. /*
  67744. ** 2004 May 26
  67745. **
  67746. ** The author disclaims copyright to this source code. In place of
  67747. ** a legal notice, here is a blessing:
  67748. **
  67749. ** May you do good and not evil.
  67750. ** May you find forgiveness for yourself and forgive others.
  67751. ** May you share freely, never taking more than you give.
  67752. **
  67753. *************************************************************************
  67754. **
  67755. ** This file contains code use to implement APIs that are part of the
  67756. ** VDBE.
  67757. */
  67758. /* #include "sqliteInt.h" */
  67759. /* #include "vdbeInt.h" */
  67760. #ifndef SQLITE_OMIT_DEPRECATED
  67761. /*
  67762. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  67763. ** to be recompiled. A statement needs to be recompiled whenever the
  67764. ** execution environment changes in a way that would alter the program
  67765. ** that sqlite3_prepare() generates. For example, if new functions or
  67766. ** collating sequences are registered or if an authorizer function is
  67767. ** added or changed.
  67768. */
  67769. SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
  67770. Vdbe *p = (Vdbe*)pStmt;
  67771. return p==0 || p->expired;
  67772. }
  67773. #endif
  67774. /*
  67775. ** Check on a Vdbe to make sure it has not been finalized. Log
  67776. ** an error and return true if it has been finalized (or is otherwise
  67777. ** invalid). Return false if it is ok.
  67778. */
  67779. static int vdbeSafety(Vdbe *p){
  67780. if( p->db==0 ){
  67781. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  67782. return 1;
  67783. }else{
  67784. return 0;
  67785. }
  67786. }
  67787. static int vdbeSafetyNotNull(Vdbe *p){
  67788. if( p==0 ){
  67789. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  67790. return 1;
  67791. }else{
  67792. return vdbeSafety(p);
  67793. }
  67794. }
  67795. #ifndef SQLITE_OMIT_TRACE
  67796. /*
  67797. ** Invoke the profile callback. This routine is only called if we already
  67798. ** know that the profile callback is defined and needs to be invoked.
  67799. */
  67800. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  67801. sqlite3_int64 iNow;
  67802. assert( p->startTime>0 );
  67803. assert( db->xProfile!=0 );
  67804. assert( db->init.busy==0 );
  67805. assert( p->zSql!=0 );
  67806. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  67807. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  67808. p->startTime = 0;
  67809. }
  67810. /*
  67811. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  67812. ** is needed, and it invokes the callback if it is needed.
  67813. */
  67814. # define checkProfileCallback(DB,P) \
  67815. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  67816. #else
  67817. # define checkProfileCallback(DB,P) /*no-op*/
  67818. #endif
  67819. /*
  67820. ** The following routine destroys a virtual machine that is created by
  67821. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  67822. ** success/failure code that describes the result of executing the virtual
  67823. ** machine.
  67824. **
  67825. ** This routine sets the error code and string returned by
  67826. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  67827. */
  67828. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
  67829. int rc;
  67830. if( pStmt==0 ){
  67831. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  67832. ** pointer is a harmless no-op. */
  67833. rc = SQLITE_OK;
  67834. }else{
  67835. Vdbe *v = (Vdbe*)pStmt;
  67836. sqlite3 *db = v->db;
  67837. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  67838. sqlite3_mutex_enter(db->mutex);
  67839. checkProfileCallback(db, v);
  67840. rc = sqlite3VdbeFinalize(v);
  67841. rc = sqlite3ApiExit(db, rc);
  67842. sqlite3LeaveMutexAndCloseZombie(db);
  67843. }
  67844. return rc;
  67845. }
  67846. /*
  67847. ** Terminate the current execution of an SQL statement and reset it
  67848. ** back to its starting state so that it can be reused. A success code from
  67849. ** the prior execution is returned.
  67850. **
  67851. ** This routine sets the error code and string returned by
  67852. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  67853. */
  67854. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
  67855. int rc;
  67856. if( pStmt==0 ){
  67857. rc = SQLITE_OK;
  67858. }else{
  67859. Vdbe *v = (Vdbe*)pStmt;
  67860. sqlite3 *db = v->db;
  67861. sqlite3_mutex_enter(db->mutex);
  67862. checkProfileCallback(db, v);
  67863. rc = sqlite3VdbeReset(v);
  67864. sqlite3VdbeRewind(v);
  67865. assert( (rc & (db->errMask))==rc );
  67866. rc = sqlite3ApiExit(db, rc);
  67867. sqlite3_mutex_leave(db->mutex);
  67868. }
  67869. return rc;
  67870. }
  67871. /*
  67872. ** Set all the parameters in the compiled SQL statement to NULL.
  67873. */
  67874. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  67875. int i;
  67876. int rc = SQLITE_OK;
  67877. Vdbe *p = (Vdbe*)pStmt;
  67878. #if SQLITE_THREADSAFE
  67879. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  67880. #endif
  67881. sqlite3_mutex_enter(mutex);
  67882. for(i=0; i<p->nVar; i++){
  67883. sqlite3VdbeMemRelease(&p->aVar[i]);
  67884. p->aVar[i].flags = MEM_Null;
  67885. }
  67886. if( p->isPrepareV2 && p->expmask ){
  67887. p->expired = 1;
  67888. }
  67889. sqlite3_mutex_leave(mutex);
  67890. return rc;
  67891. }
  67892. /**************************** sqlite3_value_ *******************************
  67893. ** The following routines extract information from a Mem or sqlite3_value
  67894. ** structure.
  67895. */
  67896. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
  67897. Mem *p = (Mem*)pVal;
  67898. if( p->flags & (MEM_Blob|MEM_Str) ){
  67899. if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
  67900. assert( p->flags==MEM_Null && p->z==0 );
  67901. return 0;
  67902. }
  67903. p->flags |= MEM_Blob;
  67904. return p->n ? p->z : 0;
  67905. }else{
  67906. return sqlite3_value_text(pVal);
  67907. }
  67908. }
  67909. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
  67910. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  67911. }
  67912. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
  67913. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  67914. }
  67915. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
  67916. return sqlite3VdbeRealValue((Mem*)pVal);
  67917. }
  67918. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
  67919. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  67920. }
  67921. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
  67922. return sqlite3VdbeIntValue((Mem*)pVal);
  67923. }
  67924. SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
  67925. Mem *pMem = (Mem*)pVal;
  67926. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  67927. }
  67928. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
  67929. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  67930. }
  67931. #ifndef SQLITE_OMIT_UTF16
  67932. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
  67933. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  67934. }
  67935. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
  67936. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  67937. }
  67938. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
  67939. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  67940. }
  67941. #endif /* SQLITE_OMIT_UTF16 */
  67942. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  67943. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  67944. ** point number string BLOB NULL
  67945. */
  67946. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
  67947. static const u8 aType[] = {
  67948. SQLITE_BLOB, /* 0x00 */
  67949. SQLITE_NULL, /* 0x01 */
  67950. SQLITE_TEXT, /* 0x02 */
  67951. SQLITE_NULL, /* 0x03 */
  67952. SQLITE_INTEGER, /* 0x04 */
  67953. SQLITE_NULL, /* 0x05 */
  67954. SQLITE_INTEGER, /* 0x06 */
  67955. SQLITE_NULL, /* 0x07 */
  67956. SQLITE_FLOAT, /* 0x08 */
  67957. SQLITE_NULL, /* 0x09 */
  67958. SQLITE_FLOAT, /* 0x0a */
  67959. SQLITE_NULL, /* 0x0b */
  67960. SQLITE_INTEGER, /* 0x0c */
  67961. SQLITE_NULL, /* 0x0d */
  67962. SQLITE_INTEGER, /* 0x0e */
  67963. SQLITE_NULL, /* 0x0f */
  67964. SQLITE_BLOB, /* 0x10 */
  67965. SQLITE_NULL, /* 0x11 */
  67966. SQLITE_TEXT, /* 0x12 */
  67967. SQLITE_NULL, /* 0x13 */
  67968. SQLITE_INTEGER, /* 0x14 */
  67969. SQLITE_NULL, /* 0x15 */
  67970. SQLITE_INTEGER, /* 0x16 */
  67971. SQLITE_NULL, /* 0x17 */
  67972. SQLITE_FLOAT, /* 0x18 */
  67973. SQLITE_NULL, /* 0x19 */
  67974. SQLITE_FLOAT, /* 0x1a */
  67975. SQLITE_NULL, /* 0x1b */
  67976. SQLITE_INTEGER, /* 0x1c */
  67977. SQLITE_NULL, /* 0x1d */
  67978. SQLITE_INTEGER, /* 0x1e */
  67979. SQLITE_NULL, /* 0x1f */
  67980. };
  67981. return aType[pVal->flags&MEM_AffMask];
  67982. }
  67983. /* Make a copy of an sqlite3_value object
  67984. */
  67985. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
  67986. sqlite3_value *pNew;
  67987. if( pOrig==0 ) return 0;
  67988. pNew = sqlite3_malloc( sizeof(*pNew) );
  67989. if( pNew==0 ) return 0;
  67990. memset(pNew, 0, sizeof(*pNew));
  67991. memcpy(pNew, pOrig, MEMCELLSIZE);
  67992. pNew->flags &= ~MEM_Dyn;
  67993. pNew->db = 0;
  67994. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  67995. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  67996. pNew->flags |= MEM_Ephem;
  67997. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  67998. sqlite3ValueFree(pNew);
  67999. pNew = 0;
  68000. }
  68001. }
  68002. return pNew;
  68003. }
  68004. /* Destroy an sqlite3_value object previously obtained from
  68005. ** sqlite3_value_dup().
  68006. */
  68007. SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
  68008. sqlite3ValueFree(pOld);
  68009. }
  68010. /**************************** sqlite3_result_ *******************************
  68011. ** The following routines are used by user-defined functions to specify
  68012. ** the function result.
  68013. **
  68014. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  68015. ** result as a string or blob but if the string or blob is too large, it
  68016. ** then sets the error code to SQLITE_TOOBIG
  68017. **
  68018. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  68019. ** on value P is not going to be used and need to be destroyed.
  68020. */
  68021. static void setResultStrOrError(
  68022. sqlite3_context *pCtx, /* Function context */
  68023. const char *z, /* String pointer */
  68024. int n, /* Bytes in string, or negative */
  68025. u8 enc, /* Encoding of z. 0 for BLOBs */
  68026. void (*xDel)(void*) /* Destructor function */
  68027. ){
  68028. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  68029. sqlite3_result_error_toobig(pCtx);
  68030. }
  68031. }
  68032. static int invokeValueDestructor(
  68033. const void *p, /* Value to destroy */
  68034. void (*xDel)(void*), /* The destructor */
  68035. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  68036. ){
  68037. assert( xDel!=SQLITE_DYNAMIC );
  68038. if( xDel==0 ){
  68039. /* noop */
  68040. }else if( xDel==SQLITE_TRANSIENT ){
  68041. /* noop */
  68042. }else{
  68043. xDel((void*)p);
  68044. }
  68045. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  68046. return SQLITE_TOOBIG;
  68047. }
  68048. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
  68049. sqlite3_context *pCtx,
  68050. const void *z,
  68051. int n,
  68052. void (*xDel)(void *)
  68053. ){
  68054. assert( n>=0 );
  68055. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68056. setResultStrOrError(pCtx, z, n, 0, xDel);
  68057. }
  68058. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
  68059. sqlite3_context *pCtx,
  68060. const void *z,
  68061. sqlite3_uint64 n,
  68062. void (*xDel)(void *)
  68063. ){
  68064. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68065. assert( xDel!=SQLITE_DYNAMIC );
  68066. if( n>0x7fffffff ){
  68067. (void)invokeValueDestructor(z, xDel, pCtx);
  68068. }else{
  68069. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  68070. }
  68071. }
  68072. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  68073. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68074. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  68075. }
  68076. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  68077. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68078. pCtx->isError = SQLITE_ERROR;
  68079. pCtx->fErrorOrAux = 1;
  68080. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  68081. }
  68082. #ifndef SQLITE_OMIT_UTF16
  68083. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  68084. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68085. pCtx->isError = SQLITE_ERROR;
  68086. pCtx->fErrorOrAux = 1;
  68087. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  68088. }
  68089. #endif
  68090. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  68091. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68092. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  68093. }
  68094. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  68095. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68096. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  68097. }
  68098. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
  68099. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68100. sqlite3VdbeMemSetNull(pCtx->pOut);
  68101. }
  68102. SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  68103. Mem *pOut = pCtx->pOut;
  68104. assert( sqlite3_mutex_held(pOut->db->mutex) );
  68105. pOut->eSubtype = eSubtype & 0xff;
  68106. pOut->flags |= MEM_Subtype;
  68107. }
  68108. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
  68109. sqlite3_context *pCtx,
  68110. const char *z,
  68111. int n,
  68112. void (*xDel)(void *)
  68113. ){
  68114. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68115. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  68116. }
  68117. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
  68118. sqlite3_context *pCtx,
  68119. const char *z,
  68120. sqlite3_uint64 n,
  68121. void (*xDel)(void *),
  68122. unsigned char enc
  68123. ){
  68124. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68125. assert( xDel!=SQLITE_DYNAMIC );
  68126. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  68127. if( n>0x7fffffff ){
  68128. (void)invokeValueDestructor(z, xDel, pCtx);
  68129. }else{
  68130. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  68131. }
  68132. }
  68133. #ifndef SQLITE_OMIT_UTF16
  68134. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
  68135. sqlite3_context *pCtx,
  68136. const void *z,
  68137. int n,
  68138. void (*xDel)(void *)
  68139. ){
  68140. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68141. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  68142. }
  68143. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
  68144. sqlite3_context *pCtx,
  68145. const void *z,
  68146. int n,
  68147. void (*xDel)(void *)
  68148. ){
  68149. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68150. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  68151. }
  68152. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
  68153. sqlite3_context *pCtx,
  68154. const void *z,
  68155. int n,
  68156. void (*xDel)(void *)
  68157. ){
  68158. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68159. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  68160. }
  68161. #endif /* SQLITE_OMIT_UTF16 */
  68162. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  68163. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68164. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  68165. }
  68166. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  68167. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68168. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  68169. }
  68170. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  68171. Mem *pOut = pCtx->pOut;
  68172. assert( sqlite3_mutex_held(pOut->db->mutex) );
  68173. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68174. return SQLITE_TOOBIG;
  68175. }
  68176. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  68177. return SQLITE_OK;
  68178. }
  68179. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  68180. pCtx->isError = errCode;
  68181. pCtx->fErrorOrAux = 1;
  68182. #ifdef SQLITE_DEBUG
  68183. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  68184. #endif
  68185. if( pCtx->pOut->flags & MEM_Null ){
  68186. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  68187. SQLITE_UTF8, SQLITE_STATIC);
  68188. }
  68189. }
  68190. /* Force an SQLITE_TOOBIG error. */
  68191. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
  68192. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68193. pCtx->isError = SQLITE_TOOBIG;
  68194. pCtx->fErrorOrAux = 1;
  68195. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  68196. SQLITE_UTF8, SQLITE_STATIC);
  68197. }
  68198. /* An SQLITE_NOMEM error. */
  68199. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
  68200. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68201. sqlite3VdbeMemSetNull(pCtx->pOut);
  68202. pCtx->isError = SQLITE_NOMEM_BKPT;
  68203. pCtx->fErrorOrAux = 1;
  68204. sqlite3OomFault(pCtx->pOut->db);
  68205. }
  68206. /*
  68207. ** This function is called after a transaction has been committed. It
  68208. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  68209. */
  68210. static int doWalCallbacks(sqlite3 *db){
  68211. int rc = SQLITE_OK;
  68212. #ifndef SQLITE_OMIT_WAL
  68213. int i;
  68214. for(i=0; i<db->nDb; i++){
  68215. Btree *pBt = db->aDb[i].pBt;
  68216. if( pBt ){
  68217. int nEntry;
  68218. sqlite3BtreeEnter(pBt);
  68219. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  68220. sqlite3BtreeLeave(pBt);
  68221. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  68222. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  68223. }
  68224. }
  68225. }
  68226. #endif
  68227. return rc;
  68228. }
  68229. /*
  68230. ** Execute the statement pStmt, either until a row of data is ready, the
  68231. ** statement is completely executed or an error occurs.
  68232. **
  68233. ** This routine implements the bulk of the logic behind the sqlite_step()
  68234. ** API. The only thing omitted is the automatic recompile if a
  68235. ** schema change has occurred. That detail is handled by the
  68236. ** outer sqlite3_step() wrapper procedure.
  68237. */
  68238. static int sqlite3Step(Vdbe *p){
  68239. sqlite3 *db;
  68240. int rc;
  68241. assert(p);
  68242. if( p->magic!=VDBE_MAGIC_RUN ){
  68243. /* We used to require that sqlite3_reset() be called before retrying
  68244. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  68245. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  68246. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  68247. ** This "automatic-reset" change is not technically an incompatibility,
  68248. ** since any application that receives an SQLITE_MISUSE is broken by
  68249. ** definition.
  68250. **
  68251. ** Nevertheless, some published applications that were originally written
  68252. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  68253. ** returns, and those were broken by the automatic-reset change. As a
  68254. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  68255. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  68256. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  68257. ** or SQLITE_BUSY error.
  68258. */
  68259. #ifdef SQLITE_OMIT_AUTORESET
  68260. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  68261. sqlite3_reset((sqlite3_stmt*)p);
  68262. }else{
  68263. return SQLITE_MISUSE_BKPT;
  68264. }
  68265. #else
  68266. sqlite3_reset((sqlite3_stmt*)p);
  68267. #endif
  68268. }
  68269. /* Check that malloc() has not failed. If it has, return early. */
  68270. db = p->db;
  68271. if( db->mallocFailed ){
  68272. p->rc = SQLITE_NOMEM;
  68273. return SQLITE_NOMEM_BKPT;
  68274. }
  68275. if( p->pc<=0 && p->expired ){
  68276. p->rc = SQLITE_SCHEMA;
  68277. rc = SQLITE_ERROR;
  68278. goto end_of_step;
  68279. }
  68280. if( p->pc<0 ){
  68281. /* If there are no other statements currently running, then
  68282. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  68283. ** from interrupting a statement that has not yet started.
  68284. */
  68285. if( db->nVdbeActive==0 ){
  68286. db->u1.isInterrupted = 0;
  68287. }
  68288. assert( db->nVdbeWrite>0 || db->autoCommit==0
  68289. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  68290. );
  68291. #ifndef SQLITE_OMIT_TRACE
  68292. if( db->xProfile && !db->init.busy && p->zSql ){
  68293. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  68294. }else{
  68295. assert( p->startTime==0 );
  68296. }
  68297. #endif
  68298. db->nVdbeActive++;
  68299. if( p->readOnly==0 ) db->nVdbeWrite++;
  68300. if( p->bIsReader ) db->nVdbeRead++;
  68301. p->pc = 0;
  68302. }
  68303. #ifdef SQLITE_DEBUG
  68304. p->rcApp = SQLITE_OK;
  68305. #endif
  68306. #ifndef SQLITE_OMIT_EXPLAIN
  68307. if( p->explain ){
  68308. rc = sqlite3VdbeList(p);
  68309. }else
  68310. #endif /* SQLITE_OMIT_EXPLAIN */
  68311. {
  68312. db->nVdbeExec++;
  68313. rc = sqlite3VdbeExec(p);
  68314. db->nVdbeExec--;
  68315. }
  68316. #ifndef SQLITE_OMIT_TRACE
  68317. /* If the statement completed successfully, invoke the profile callback */
  68318. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  68319. #endif
  68320. if( rc==SQLITE_DONE ){
  68321. assert( p->rc==SQLITE_OK );
  68322. p->rc = doWalCallbacks(db);
  68323. if( p->rc!=SQLITE_OK ){
  68324. rc = SQLITE_ERROR;
  68325. }
  68326. }
  68327. db->errCode = rc;
  68328. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  68329. p->rc = SQLITE_NOMEM_BKPT;
  68330. }
  68331. end_of_step:
  68332. /* At this point local variable rc holds the value that should be
  68333. ** returned if this statement was compiled using the legacy
  68334. ** sqlite3_prepare() interface. According to the docs, this can only
  68335. ** be one of the values in the first assert() below. Variable p->rc
  68336. ** contains the value that would be returned if sqlite3_finalize()
  68337. ** were called on statement p.
  68338. */
  68339. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  68340. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  68341. );
  68342. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  68343. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  68344. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  68345. ** error has occurred, then return the error code in p->rc to the
  68346. ** caller. Set the error code in the database handle to the same value.
  68347. */
  68348. rc = sqlite3VdbeTransferError(p);
  68349. }
  68350. return (rc&db->errMask);
  68351. }
  68352. /*
  68353. ** This is the top-level implementation of sqlite3_step(). Call
  68354. ** sqlite3Step() to do most of the work. If a schema error occurs,
  68355. ** call sqlite3Reprepare() and try again.
  68356. */
  68357. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
  68358. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  68359. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  68360. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  68361. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  68362. sqlite3 *db; /* The database connection */
  68363. if( vdbeSafetyNotNull(v) ){
  68364. return SQLITE_MISUSE_BKPT;
  68365. }
  68366. db = v->db;
  68367. sqlite3_mutex_enter(db->mutex);
  68368. v->doingRerun = 0;
  68369. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  68370. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  68371. int savedPc = v->pc;
  68372. rc2 = rc = sqlite3Reprepare(v);
  68373. if( rc!=SQLITE_OK) break;
  68374. sqlite3_reset(pStmt);
  68375. if( savedPc>=0 ) v->doingRerun = 1;
  68376. assert( v->expired==0 );
  68377. }
  68378. if( rc2!=SQLITE_OK ){
  68379. /* This case occurs after failing to recompile an sql statement.
  68380. ** The error message from the SQL compiler has already been loaded
  68381. ** into the database handle. This block copies the error message
  68382. ** from the database handle into the statement and sets the statement
  68383. ** program counter to 0 to ensure that when the statement is
  68384. ** finalized or reset the parser error message is available via
  68385. ** sqlite3_errmsg() and sqlite3_errcode().
  68386. */
  68387. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  68388. sqlite3DbFree(db, v->zErrMsg);
  68389. if( !db->mallocFailed ){
  68390. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  68391. v->rc = rc2;
  68392. } else {
  68393. v->zErrMsg = 0;
  68394. v->rc = rc = SQLITE_NOMEM_BKPT;
  68395. }
  68396. }
  68397. rc = sqlite3ApiExit(db, rc);
  68398. sqlite3_mutex_leave(db->mutex);
  68399. return rc;
  68400. }
  68401. /*
  68402. ** Extract the user data from a sqlite3_context structure and return a
  68403. ** pointer to it.
  68404. */
  68405. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
  68406. assert( p && p->pFunc );
  68407. return p->pFunc->pUserData;
  68408. }
  68409. /*
  68410. ** Extract the user data from a sqlite3_context structure and return a
  68411. ** pointer to it.
  68412. **
  68413. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  68414. ** returns a copy of the pointer to the database connection (the 1st
  68415. ** parameter) of the sqlite3_create_function() and
  68416. ** sqlite3_create_function16() routines that originally registered the
  68417. ** application defined function.
  68418. */
  68419. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
  68420. assert( p && p->pOut );
  68421. return p->pOut->db;
  68422. }
  68423. /*
  68424. ** Return the current time for a statement. If the current time
  68425. ** is requested more than once within the same run of a single prepared
  68426. ** statement, the exact same time is returned for each invocation regardless
  68427. ** of the amount of time that elapses between invocations. In other words,
  68428. ** the time returned is always the time of the first call.
  68429. */
  68430. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  68431. int rc;
  68432. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  68433. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  68434. assert( p->pVdbe!=0 );
  68435. #else
  68436. sqlite3_int64 iTime = 0;
  68437. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  68438. #endif
  68439. if( *piTime==0 ){
  68440. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  68441. if( rc ) *piTime = 0;
  68442. }
  68443. return *piTime;
  68444. }
  68445. /*
  68446. ** The following is the implementation of an SQL function that always
  68447. ** fails with an error message stating that the function is used in the
  68448. ** wrong context. The sqlite3_overload_function() API might construct
  68449. ** SQL function that use this routine so that the functions will exist
  68450. ** for name resolution but are actually overloaded by the xFindFunction
  68451. ** method of virtual tables.
  68452. */
  68453. SQLITE_PRIVATE void sqlite3InvalidFunction(
  68454. sqlite3_context *context, /* The function calling context */
  68455. int NotUsed, /* Number of arguments to the function */
  68456. sqlite3_value **NotUsed2 /* Value of each argument */
  68457. ){
  68458. const char *zName = context->pFunc->zName;
  68459. char *zErr;
  68460. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  68461. zErr = sqlite3_mprintf(
  68462. "unable to use function %s in the requested context", zName);
  68463. sqlite3_result_error(context, zErr, -1);
  68464. sqlite3_free(zErr);
  68465. }
  68466. /*
  68467. ** Create a new aggregate context for p and return a pointer to
  68468. ** its pMem->z element.
  68469. */
  68470. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  68471. Mem *pMem = p->pMem;
  68472. assert( (pMem->flags & MEM_Agg)==0 );
  68473. if( nByte<=0 ){
  68474. sqlite3VdbeMemSetNull(pMem);
  68475. pMem->z = 0;
  68476. }else{
  68477. sqlite3VdbeMemClearAndResize(pMem, nByte);
  68478. pMem->flags = MEM_Agg;
  68479. pMem->u.pDef = p->pFunc;
  68480. if( pMem->z ){
  68481. memset(pMem->z, 0, nByte);
  68482. }
  68483. }
  68484. return (void*)pMem->z;
  68485. }
  68486. /*
  68487. ** Allocate or return the aggregate context for a user function. A new
  68488. ** context is allocated on the first call. Subsequent calls return the
  68489. ** same context that was returned on prior calls.
  68490. */
  68491. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  68492. assert( p && p->pFunc && p->pFunc->xFinalize );
  68493. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  68494. testcase( nByte<0 );
  68495. if( (p->pMem->flags & MEM_Agg)==0 ){
  68496. return createAggContext(p, nByte);
  68497. }else{
  68498. return (void*)p->pMem->z;
  68499. }
  68500. }
  68501. /*
  68502. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  68503. ** the user-function defined by pCtx.
  68504. */
  68505. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  68506. AuxData *pAuxData;
  68507. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68508. #if SQLITE_ENABLE_STAT3_OR_STAT4
  68509. if( pCtx->pVdbe==0 ) return 0;
  68510. #else
  68511. assert( pCtx->pVdbe!=0 );
  68512. #endif
  68513. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  68514. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  68515. }
  68516. return (pAuxData ? pAuxData->pAux : 0);
  68517. }
  68518. /*
  68519. ** Set the auxiliary data pointer and delete function, for the iArg'th
  68520. ** argument to the user-function defined by pCtx. Any previous value is
  68521. ** deleted by calling the delete function specified when it was set.
  68522. */
  68523. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
  68524. sqlite3_context *pCtx,
  68525. int iArg,
  68526. void *pAux,
  68527. void (*xDelete)(void*)
  68528. ){
  68529. AuxData *pAuxData;
  68530. Vdbe *pVdbe = pCtx->pVdbe;
  68531. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  68532. if( iArg<0 ) goto failed;
  68533. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  68534. if( pVdbe==0 ) goto failed;
  68535. #else
  68536. assert( pVdbe!=0 );
  68537. #endif
  68538. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  68539. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  68540. }
  68541. if( pAuxData==0 ){
  68542. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  68543. if( !pAuxData ) goto failed;
  68544. pAuxData->iOp = pCtx->iOp;
  68545. pAuxData->iArg = iArg;
  68546. pAuxData->pNext = pVdbe->pAuxData;
  68547. pVdbe->pAuxData = pAuxData;
  68548. if( pCtx->fErrorOrAux==0 ){
  68549. pCtx->isError = 0;
  68550. pCtx->fErrorOrAux = 1;
  68551. }
  68552. }else if( pAuxData->xDelete ){
  68553. pAuxData->xDelete(pAuxData->pAux);
  68554. }
  68555. pAuxData->pAux = pAux;
  68556. pAuxData->xDelete = xDelete;
  68557. return;
  68558. failed:
  68559. if( xDelete ){
  68560. xDelete(pAux);
  68561. }
  68562. }
  68563. #ifndef SQLITE_OMIT_DEPRECATED
  68564. /*
  68565. ** Return the number of times the Step function of an aggregate has been
  68566. ** called.
  68567. **
  68568. ** This function is deprecated. Do not use it for new code. It is
  68569. ** provide only to avoid breaking legacy code. New aggregate function
  68570. ** implementations should keep their own counts within their aggregate
  68571. ** context.
  68572. */
  68573. SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
  68574. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  68575. return p->pMem->n;
  68576. }
  68577. #endif
  68578. /*
  68579. ** Return the number of columns in the result set for the statement pStmt.
  68580. */
  68581. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
  68582. Vdbe *pVm = (Vdbe *)pStmt;
  68583. return pVm ? pVm->nResColumn : 0;
  68584. }
  68585. /*
  68586. ** Return the number of values available from the current row of the
  68587. ** currently executing statement pStmt.
  68588. */
  68589. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
  68590. Vdbe *pVm = (Vdbe *)pStmt;
  68591. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  68592. return pVm->nResColumn;
  68593. }
  68594. /*
  68595. ** Return a pointer to static memory containing an SQL NULL value.
  68596. */
  68597. static const Mem *columnNullValue(void){
  68598. /* Even though the Mem structure contains an element
  68599. ** of type i64, on certain architectures (x86) with certain compiler
  68600. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  68601. ** instead of an 8-byte one. This all works fine, except that when
  68602. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  68603. ** that a Mem structure is located on an 8-byte boundary. To prevent
  68604. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  68605. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  68606. ** __attribute__((aligned(8))) macro. */
  68607. static const Mem nullMem
  68608. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  68609. __attribute__((aligned(8)))
  68610. #endif
  68611. = {
  68612. /* .u = */ {0},
  68613. /* .flags = */ (u16)MEM_Null,
  68614. /* .enc = */ (u8)0,
  68615. /* .eSubtype = */ (u8)0,
  68616. /* .n = */ (int)0,
  68617. /* .z = */ (char*)0,
  68618. /* .zMalloc = */ (char*)0,
  68619. /* .szMalloc = */ (int)0,
  68620. /* .uTemp = */ (u32)0,
  68621. /* .db = */ (sqlite3*)0,
  68622. /* .xDel = */ (void(*)(void*))0,
  68623. #ifdef SQLITE_DEBUG
  68624. /* .pScopyFrom = */ (Mem*)0,
  68625. /* .pFiller = */ (void*)0,
  68626. #endif
  68627. };
  68628. return &nullMem;
  68629. }
  68630. /*
  68631. ** Check to see if column iCol of the given statement is valid. If
  68632. ** it is, return a pointer to the Mem for the value of that column.
  68633. ** If iCol is not valid, return a pointer to a Mem which has a value
  68634. ** of NULL.
  68635. */
  68636. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  68637. Vdbe *pVm;
  68638. Mem *pOut;
  68639. pVm = (Vdbe *)pStmt;
  68640. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  68641. sqlite3_mutex_enter(pVm->db->mutex);
  68642. pOut = &pVm->pResultSet[i];
  68643. }else{
  68644. if( pVm && ALWAYS(pVm->db) ){
  68645. sqlite3_mutex_enter(pVm->db->mutex);
  68646. sqlite3Error(pVm->db, SQLITE_RANGE);
  68647. }
  68648. pOut = (Mem*)columnNullValue();
  68649. }
  68650. return pOut;
  68651. }
  68652. /*
  68653. ** This function is called after invoking an sqlite3_value_XXX function on a
  68654. ** column value (i.e. a value returned by evaluating an SQL expression in the
  68655. ** select list of a SELECT statement) that may cause a malloc() failure. If
  68656. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  68657. ** code of statement pStmt set to SQLITE_NOMEM.
  68658. **
  68659. ** Specifically, this is called from within:
  68660. **
  68661. ** sqlite3_column_int()
  68662. ** sqlite3_column_int64()
  68663. ** sqlite3_column_text()
  68664. ** sqlite3_column_text16()
  68665. ** sqlite3_column_real()
  68666. ** sqlite3_column_bytes()
  68667. ** sqlite3_column_bytes16()
  68668. ** sqiite3_column_blob()
  68669. */
  68670. static void columnMallocFailure(sqlite3_stmt *pStmt)
  68671. {
  68672. /* If malloc() failed during an encoding conversion within an
  68673. ** sqlite3_column_XXX API, then set the return code of the statement to
  68674. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  68675. ** and _finalize() will return NOMEM.
  68676. */
  68677. Vdbe *p = (Vdbe *)pStmt;
  68678. if( p ){
  68679. p->rc = sqlite3ApiExit(p->db, p->rc);
  68680. sqlite3_mutex_leave(p->db->mutex);
  68681. }
  68682. }
  68683. /**************************** sqlite3_column_ *******************************
  68684. ** The following routines are used to access elements of the current row
  68685. ** in the result set.
  68686. */
  68687. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  68688. const void *val;
  68689. val = sqlite3_value_blob( columnMem(pStmt,i) );
  68690. /* Even though there is no encoding conversion, value_blob() might
  68691. ** need to call malloc() to expand the result of a zeroblob()
  68692. ** expression.
  68693. */
  68694. columnMallocFailure(pStmt);
  68695. return val;
  68696. }
  68697. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  68698. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  68699. columnMallocFailure(pStmt);
  68700. return val;
  68701. }
  68702. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  68703. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  68704. columnMallocFailure(pStmt);
  68705. return val;
  68706. }
  68707. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  68708. double val = sqlite3_value_double( columnMem(pStmt,i) );
  68709. columnMallocFailure(pStmt);
  68710. return val;
  68711. }
  68712. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  68713. int val = sqlite3_value_int( columnMem(pStmt,i) );
  68714. columnMallocFailure(pStmt);
  68715. return val;
  68716. }
  68717. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  68718. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  68719. columnMallocFailure(pStmt);
  68720. return val;
  68721. }
  68722. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  68723. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  68724. columnMallocFailure(pStmt);
  68725. return val;
  68726. }
  68727. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  68728. Mem *pOut = columnMem(pStmt, i);
  68729. if( pOut->flags&MEM_Static ){
  68730. pOut->flags &= ~MEM_Static;
  68731. pOut->flags |= MEM_Ephem;
  68732. }
  68733. columnMallocFailure(pStmt);
  68734. return (sqlite3_value *)pOut;
  68735. }
  68736. #ifndef SQLITE_OMIT_UTF16
  68737. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  68738. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  68739. columnMallocFailure(pStmt);
  68740. return val;
  68741. }
  68742. #endif /* SQLITE_OMIT_UTF16 */
  68743. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  68744. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  68745. columnMallocFailure(pStmt);
  68746. return iType;
  68747. }
  68748. /*
  68749. ** Convert the N-th element of pStmt->pColName[] into a string using
  68750. ** xFunc() then return that string. If N is out of range, return 0.
  68751. **
  68752. ** There are up to 5 names for each column. useType determines which
  68753. ** name is returned. Here are the names:
  68754. **
  68755. ** 0 The column name as it should be displayed for output
  68756. ** 1 The datatype name for the column
  68757. ** 2 The name of the database that the column derives from
  68758. ** 3 The name of the table that the column derives from
  68759. ** 4 The name of the table column that the result column derives from
  68760. **
  68761. ** If the result is not a simple column reference (if it is an expression
  68762. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  68763. */
  68764. static const void *columnName(
  68765. sqlite3_stmt *pStmt,
  68766. int N,
  68767. const void *(*xFunc)(Mem*),
  68768. int useType
  68769. ){
  68770. const void *ret;
  68771. Vdbe *p;
  68772. int n;
  68773. sqlite3 *db;
  68774. #ifdef SQLITE_ENABLE_API_ARMOR
  68775. if( pStmt==0 ){
  68776. (void)SQLITE_MISUSE_BKPT;
  68777. return 0;
  68778. }
  68779. #endif
  68780. ret = 0;
  68781. p = (Vdbe *)pStmt;
  68782. db = p->db;
  68783. assert( db!=0 );
  68784. n = sqlite3_column_count(pStmt);
  68785. if( N<n && N>=0 ){
  68786. N += useType*n;
  68787. sqlite3_mutex_enter(db->mutex);
  68788. assert( db->mallocFailed==0 );
  68789. ret = xFunc(&p->aColName[N]);
  68790. /* A malloc may have failed inside of the xFunc() call. If this
  68791. ** is the case, clear the mallocFailed flag and return NULL.
  68792. */
  68793. if( db->mallocFailed ){
  68794. sqlite3OomClear(db);
  68795. ret = 0;
  68796. }
  68797. sqlite3_mutex_leave(db->mutex);
  68798. }
  68799. return ret;
  68800. }
  68801. /*
  68802. ** Return the name of the Nth column of the result set returned by SQL
  68803. ** statement pStmt.
  68804. */
  68805. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  68806. return columnName(
  68807. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  68808. }
  68809. #ifndef SQLITE_OMIT_UTF16
  68810. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  68811. return columnName(
  68812. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  68813. }
  68814. #endif
  68815. /*
  68816. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  68817. ** not define OMIT_DECLTYPE.
  68818. */
  68819. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  68820. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  68821. and SQLITE_ENABLE_COLUMN_METADATA"
  68822. #endif
  68823. #ifndef SQLITE_OMIT_DECLTYPE
  68824. /*
  68825. ** Return the column declaration type (if applicable) of the 'i'th column
  68826. ** of the result set of SQL statement pStmt.
  68827. */
  68828. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  68829. return columnName(
  68830. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  68831. }
  68832. #ifndef SQLITE_OMIT_UTF16
  68833. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  68834. return columnName(
  68835. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  68836. }
  68837. #endif /* SQLITE_OMIT_UTF16 */
  68838. #endif /* SQLITE_OMIT_DECLTYPE */
  68839. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  68840. /*
  68841. ** Return the name of the database from which a result column derives.
  68842. ** NULL is returned if the result column is an expression or constant or
  68843. ** anything else which is not an unambiguous reference to a database column.
  68844. */
  68845. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  68846. return columnName(
  68847. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  68848. }
  68849. #ifndef SQLITE_OMIT_UTF16
  68850. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  68851. return columnName(
  68852. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  68853. }
  68854. #endif /* SQLITE_OMIT_UTF16 */
  68855. /*
  68856. ** Return the name of the table from which a result column derives.
  68857. ** NULL is returned if the result column is an expression or constant or
  68858. ** anything else which is not an unambiguous reference to a database column.
  68859. */
  68860. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  68861. return columnName(
  68862. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  68863. }
  68864. #ifndef SQLITE_OMIT_UTF16
  68865. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  68866. return columnName(
  68867. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  68868. }
  68869. #endif /* SQLITE_OMIT_UTF16 */
  68870. /*
  68871. ** Return the name of the table column from which a result column derives.
  68872. ** NULL is returned if the result column is an expression or constant or
  68873. ** anything else which is not an unambiguous reference to a database column.
  68874. */
  68875. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  68876. return columnName(
  68877. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  68878. }
  68879. #ifndef SQLITE_OMIT_UTF16
  68880. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  68881. return columnName(
  68882. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  68883. }
  68884. #endif /* SQLITE_OMIT_UTF16 */
  68885. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  68886. /******************************* sqlite3_bind_ ***************************
  68887. **
  68888. ** Routines used to attach values to wildcards in a compiled SQL statement.
  68889. */
  68890. /*
  68891. ** Unbind the value bound to variable i in virtual machine p. This is the
  68892. ** the same as binding a NULL value to the column. If the "i" parameter is
  68893. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  68894. **
  68895. ** A successful evaluation of this routine acquires the mutex on p.
  68896. ** the mutex is released if any kind of error occurs.
  68897. **
  68898. ** The error code stored in database p->db is overwritten with the return
  68899. ** value in any case.
  68900. */
  68901. static int vdbeUnbind(Vdbe *p, int i){
  68902. Mem *pVar;
  68903. if( vdbeSafetyNotNull(p) ){
  68904. return SQLITE_MISUSE_BKPT;
  68905. }
  68906. sqlite3_mutex_enter(p->db->mutex);
  68907. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  68908. sqlite3Error(p->db, SQLITE_MISUSE);
  68909. sqlite3_mutex_leave(p->db->mutex);
  68910. sqlite3_log(SQLITE_MISUSE,
  68911. "bind on a busy prepared statement: [%s]", p->zSql);
  68912. return SQLITE_MISUSE_BKPT;
  68913. }
  68914. if( i<1 || i>p->nVar ){
  68915. sqlite3Error(p->db, SQLITE_RANGE);
  68916. sqlite3_mutex_leave(p->db->mutex);
  68917. return SQLITE_RANGE;
  68918. }
  68919. i--;
  68920. pVar = &p->aVar[i];
  68921. sqlite3VdbeMemRelease(pVar);
  68922. pVar->flags = MEM_Null;
  68923. sqlite3Error(p->db, SQLITE_OK);
  68924. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  68925. ** binding a new value to this variable invalidates the current query plan.
  68926. **
  68927. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  68928. ** parameter in the WHERE clause might influence the choice of query plan
  68929. ** for a statement, then the statement will be automatically recompiled,
  68930. ** as if there had been a schema change, on the first sqlite3_step() call
  68931. ** following any change to the bindings of that parameter.
  68932. */
  68933. if( p->isPrepareV2 &&
  68934. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  68935. ){
  68936. p->expired = 1;
  68937. }
  68938. return SQLITE_OK;
  68939. }
  68940. /*
  68941. ** Bind a text or BLOB value.
  68942. */
  68943. static int bindText(
  68944. sqlite3_stmt *pStmt, /* The statement to bind against */
  68945. int i, /* Index of the parameter to bind */
  68946. const void *zData, /* Pointer to the data to be bound */
  68947. int nData, /* Number of bytes of data to be bound */
  68948. void (*xDel)(void*), /* Destructor for the data */
  68949. u8 encoding /* Encoding for the data */
  68950. ){
  68951. Vdbe *p = (Vdbe *)pStmt;
  68952. Mem *pVar;
  68953. int rc;
  68954. rc = vdbeUnbind(p, i);
  68955. if( rc==SQLITE_OK ){
  68956. if( zData!=0 ){
  68957. pVar = &p->aVar[i-1];
  68958. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  68959. if( rc==SQLITE_OK && encoding!=0 ){
  68960. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  68961. }
  68962. sqlite3Error(p->db, rc);
  68963. rc = sqlite3ApiExit(p->db, rc);
  68964. }
  68965. sqlite3_mutex_leave(p->db->mutex);
  68966. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  68967. xDel((void*)zData);
  68968. }
  68969. return rc;
  68970. }
  68971. /*
  68972. ** Bind a blob value to an SQL statement variable.
  68973. */
  68974. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
  68975. sqlite3_stmt *pStmt,
  68976. int i,
  68977. const void *zData,
  68978. int nData,
  68979. void (*xDel)(void*)
  68980. ){
  68981. #ifdef SQLITE_ENABLE_API_ARMOR
  68982. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  68983. #endif
  68984. return bindText(pStmt, i, zData, nData, xDel, 0);
  68985. }
  68986. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
  68987. sqlite3_stmt *pStmt,
  68988. int i,
  68989. const void *zData,
  68990. sqlite3_uint64 nData,
  68991. void (*xDel)(void*)
  68992. ){
  68993. assert( xDel!=SQLITE_DYNAMIC );
  68994. if( nData>0x7fffffff ){
  68995. return invokeValueDestructor(zData, xDel, 0);
  68996. }else{
  68997. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  68998. }
  68999. }
  69000. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  69001. int rc;
  69002. Vdbe *p = (Vdbe *)pStmt;
  69003. rc = vdbeUnbind(p, i);
  69004. if( rc==SQLITE_OK ){
  69005. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  69006. sqlite3_mutex_leave(p->db->mutex);
  69007. }
  69008. return rc;
  69009. }
  69010. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  69011. return sqlite3_bind_int64(p, i, (i64)iValue);
  69012. }
  69013. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  69014. int rc;
  69015. Vdbe *p = (Vdbe *)pStmt;
  69016. rc = vdbeUnbind(p, i);
  69017. if( rc==SQLITE_OK ){
  69018. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  69019. sqlite3_mutex_leave(p->db->mutex);
  69020. }
  69021. return rc;
  69022. }
  69023. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  69024. int rc;
  69025. Vdbe *p = (Vdbe*)pStmt;
  69026. rc = vdbeUnbind(p, i);
  69027. if( rc==SQLITE_OK ){
  69028. sqlite3_mutex_leave(p->db->mutex);
  69029. }
  69030. return rc;
  69031. }
  69032. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
  69033. sqlite3_stmt *pStmt,
  69034. int i,
  69035. const char *zData,
  69036. int nData,
  69037. void (*xDel)(void*)
  69038. ){
  69039. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  69040. }
  69041. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
  69042. sqlite3_stmt *pStmt,
  69043. int i,
  69044. const char *zData,
  69045. sqlite3_uint64 nData,
  69046. void (*xDel)(void*),
  69047. unsigned char enc
  69048. ){
  69049. assert( xDel!=SQLITE_DYNAMIC );
  69050. if( nData>0x7fffffff ){
  69051. return invokeValueDestructor(zData, xDel, 0);
  69052. }else{
  69053. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  69054. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  69055. }
  69056. }
  69057. #ifndef SQLITE_OMIT_UTF16
  69058. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
  69059. sqlite3_stmt *pStmt,
  69060. int i,
  69061. const void *zData,
  69062. int nData,
  69063. void (*xDel)(void*)
  69064. ){
  69065. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  69066. }
  69067. #endif /* SQLITE_OMIT_UTF16 */
  69068. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  69069. int rc;
  69070. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  69071. case SQLITE_INTEGER: {
  69072. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  69073. break;
  69074. }
  69075. case SQLITE_FLOAT: {
  69076. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  69077. break;
  69078. }
  69079. case SQLITE_BLOB: {
  69080. if( pValue->flags & MEM_Zero ){
  69081. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  69082. }else{
  69083. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  69084. }
  69085. break;
  69086. }
  69087. case SQLITE_TEXT: {
  69088. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  69089. pValue->enc);
  69090. break;
  69091. }
  69092. default: {
  69093. rc = sqlite3_bind_null(pStmt, i);
  69094. break;
  69095. }
  69096. }
  69097. return rc;
  69098. }
  69099. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  69100. int rc;
  69101. Vdbe *p = (Vdbe *)pStmt;
  69102. rc = vdbeUnbind(p, i);
  69103. if( rc==SQLITE_OK ){
  69104. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  69105. sqlite3_mutex_leave(p->db->mutex);
  69106. }
  69107. return rc;
  69108. }
  69109. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  69110. int rc;
  69111. Vdbe *p = (Vdbe *)pStmt;
  69112. sqlite3_mutex_enter(p->db->mutex);
  69113. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  69114. rc = SQLITE_TOOBIG;
  69115. }else{
  69116. assert( (n & 0x7FFFFFFF)==n );
  69117. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  69118. }
  69119. rc = sqlite3ApiExit(p->db, rc);
  69120. sqlite3_mutex_leave(p->db->mutex);
  69121. return rc;
  69122. }
  69123. /*
  69124. ** Return the number of wildcards that can be potentially bound to.
  69125. ** This routine is added to support DBD::SQLite.
  69126. */
  69127. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  69128. Vdbe *p = (Vdbe*)pStmt;
  69129. return p ? p->nVar : 0;
  69130. }
  69131. /*
  69132. ** Return the name of a wildcard parameter. Return NULL if the index
  69133. ** is out of range or if the wildcard is unnamed.
  69134. **
  69135. ** The result is always UTF-8.
  69136. */
  69137. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  69138. Vdbe *p = (Vdbe*)pStmt;
  69139. if( p==0 || i<1 || i>p->nzVar ){
  69140. return 0;
  69141. }
  69142. return p->azVar[i-1];
  69143. }
  69144. /*
  69145. ** Given a wildcard parameter name, return the index of the variable
  69146. ** with that name. If there is no variable with the given name,
  69147. ** return 0.
  69148. */
  69149. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  69150. int i;
  69151. if( p==0 ){
  69152. return 0;
  69153. }
  69154. if( zName ){
  69155. for(i=0; i<p->nzVar; i++){
  69156. const char *z = p->azVar[i];
  69157. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  69158. return i+1;
  69159. }
  69160. }
  69161. }
  69162. return 0;
  69163. }
  69164. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  69165. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  69166. }
  69167. /*
  69168. ** Transfer all bindings from the first statement over to the second.
  69169. */
  69170. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  69171. Vdbe *pFrom = (Vdbe*)pFromStmt;
  69172. Vdbe *pTo = (Vdbe*)pToStmt;
  69173. int i;
  69174. assert( pTo->db==pFrom->db );
  69175. assert( pTo->nVar==pFrom->nVar );
  69176. sqlite3_mutex_enter(pTo->db->mutex);
  69177. for(i=0; i<pFrom->nVar; i++){
  69178. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  69179. }
  69180. sqlite3_mutex_leave(pTo->db->mutex);
  69181. return SQLITE_OK;
  69182. }
  69183. #ifndef SQLITE_OMIT_DEPRECATED
  69184. /*
  69185. ** Deprecated external interface. Internal/core SQLite code
  69186. ** should call sqlite3TransferBindings.
  69187. **
  69188. ** It is misuse to call this routine with statements from different
  69189. ** database connections. But as this is a deprecated interface, we
  69190. ** will not bother to check for that condition.
  69191. **
  69192. ** If the two statements contain a different number of bindings, then
  69193. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  69194. ** SQLITE_OK is returned.
  69195. */
  69196. SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  69197. Vdbe *pFrom = (Vdbe*)pFromStmt;
  69198. Vdbe *pTo = (Vdbe*)pToStmt;
  69199. if( pFrom->nVar!=pTo->nVar ){
  69200. return SQLITE_ERROR;
  69201. }
  69202. if( pTo->isPrepareV2 && pTo->expmask ){
  69203. pTo->expired = 1;
  69204. }
  69205. if( pFrom->isPrepareV2 && pFrom->expmask ){
  69206. pFrom->expired = 1;
  69207. }
  69208. return sqlite3TransferBindings(pFromStmt, pToStmt);
  69209. }
  69210. #endif
  69211. /*
  69212. ** Return the sqlite3* database handle to which the prepared statement given
  69213. ** in the argument belongs. This is the same database handle that was
  69214. ** the first argument to the sqlite3_prepare() that was used to create
  69215. ** the statement in the first place.
  69216. */
  69217. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
  69218. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  69219. }
  69220. /*
  69221. ** Return true if the prepared statement is guaranteed to not modify the
  69222. ** database.
  69223. */
  69224. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  69225. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  69226. }
  69227. /*
  69228. ** Return true if the prepared statement is in need of being reset.
  69229. */
  69230. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  69231. Vdbe *v = (Vdbe*)pStmt;
  69232. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  69233. }
  69234. /*
  69235. ** Return a pointer to the next prepared statement after pStmt associated
  69236. ** with database connection pDb. If pStmt is NULL, return the first
  69237. ** prepared statement for the database connection. Return NULL if there
  69238. ** are no more.
  69239. */
  69240. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  69241. sqlite3_stmt *pNext;
  69242. #ifdef SQLITE_ENABLE_API_ARMOR
  69243. if( !sqlite3SafetyCheckOk(pDb) ){
  69244. (void)SQLITE_MISUSE_BKPT;
  69245. return 0;
  69246. }
  69247. #endif
  69248. sqlite3_mutex_enter(pDb->mutex);
  69249. if( pStmt==0 ){
  69250. pNext = (sqlite3_stmt*)pDb->pVdbe;
  69251. }else{
  69252. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  69253. }
  69254. sqlite3_mutex_leave(pDb->mutex);
  69255. return pNext;
  69256. }
  69257. /*
  69258. ** Return the value of a status counter for a prepared statement
  69259. */
  69260. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  69261. Vdbe *pVdbe = (Vdbe*)pStmt;
  69262. u32 v;
  69263. #ifdef SQLITE_ENABLE_API_ARMOR
  69264. if( !pStmt ){
  69265. (void)SQLITE_MISUSE_BKPT;
  69266. return 0;
  69267. }
  69268. #endif
  69269. v = pVdbe->aCounter[op];
  69270. if( resetFlag ) pVdbe->aCounter[op] = 0;
  69271. return (int)v;
  69272. }
  69273. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69274. /*
  69275. ** Return status data for a single loop within query pStmt.
  69276. */
  69277. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  69278. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  69279. int idx, /* Index of loop to report on */
  69280. int iScanStatusOp, /* Which metric to return */
  69281. void *pOut /* OUT: Write the answer here */
  69282. ){
  69283. Vdbe *p = (Vdbe*)pStmt;
  69284. ScanStatus *pScan;
  69285. if( idx<0 || idx>=p->nScan ) return 1;
  69286. pScan = &p->aScan[idx];
  69287. switch( iScanStatusOp ){
  69288. case SQLITE_SCANSTAT_NLOOP: {
  69289. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  69290. break;
  69291. }
  69292. case SQLITE_SCANSTAT_NVISIT: {
  69293. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  69294. break;
  69295. }
  69296. case SQLITE_SCANSTAT_EST: {
  69297. double r = 1.0;
  69298. LogEst x = pScan->nEst;
  69299. while( x<100 ){
  69300. x += 10;
  69301. r *= 0.5;
  69302. }
  69303. *(double*)pOut = r*sqlite3LogEstToInt(x);
  69304. break;
  69305. }
  69306. case SQLITE_SCANSTAT_NAME: {
  69307. *(const char**)pOut = pScan->zName;
  69308. break;
  69309. }
  69310. case SQLITE_SCANSTAT_EXPLAIN: {
  69311. if( pScan->addrExplain ){
  69312. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  69313. }else{
  69314. *(const char**)pOut = 0;
  69315. }
  69316. break;
  69317. }
  69318. case SQLITE_SCANSTAT_SELECTID: {
  69319. if( pScan->addrExplain ){
  69320. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  69321. }else{
  69322. *(int*)pOut = -1;
  69323. }
  69324. break;
  69325. }
  69326. default: {
  69327. return 1;
  69328. }
  69329. }
  69330. return 0;
  69331. }
  69332. /*
  69333. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  69334. */
  69335. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  69336. Vdbe *p = (Vdbe*)pStmt;
  69337. memset(p->anExec, 0, p->nOp * sizeof(i64));
  69338. }
  69339. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  69340. /************** End of vdbeapi.c *********************************************/
  69341. /************** Begin file vdbetrace.c ***************************************/
  69342. /*
  69343. ** 2009 November 25
  69344. **
  69345. ** The author disclaims copyright to this source code. In place of
  69346. ** a legal notice, here is a blessing:
  69347. **
  69348. ** May you do good and not evil.
  69349. ** May you find forgiveness for yourself and forgive others.
  69350. ** May you share freely, never taking more than you give.
  69351. **
  69352. *************************************************************************
  69353. **
  69354. ** This file contains code used to insert the values of host parameters
  69355. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  69356. **
  69357. ** The Vdbe parse-tree explainer is also found here.
  69358. */
  69359. /* #include "sqliteInt.h" */
  69360. /* #include "vdbeInt.h" */
  69361. #ifndef SQLITE_OMIT_TRACE
  69362. /*
  69363. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  69364. ** bytes in this text up to but excluding the first character in
  69365. ** a host parameter. If the text contains no host parameters, return
  69366. ** the total number of bytes in the text.
  69367. */
  69368. static int findNextHostParameter(const char *zSql, int *pnToken){
  69369. int tokenType;
  69370. int nTotal = 0;
  69371. int n;
  69372. *pnToken = 0;
  69373. while( zSql[0] ){
  69374. n = sqlite3GetToken((u8*)zSql, &tokenType);
  69375. assert( n>0 && tokenType!=TK_ILLEGAL );
  69376. if( tokenType==TK_VARIABLE ){
  69377. *pnToken = n;
  69378. break;
  69379. }
  69380. nTotal += n;
  69381. zSql += n;
  69382. }
  69383. return nTotal;
  69384. }
  69385. /*
  69386. ** This function returns a pointer to a nul-terminated string in memory
  69387. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  69388. ** string contains a copy of zRawSql but with host parameters expanded to
  69389. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  69390. ** then the returned string holds a copy of zRawSql with "-- " prepended
  69391. ** to each line of text.
  69392. **
  69393. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  69394. ** then long strings and blobs are truncated to that many bytes. This
  69395. ** can be used to prevent unreasonably large trace strings when dealing
  69396. ** with large (multi-megabyte) strings and blobs.
  69397. **
  69398. ** The calling function is responsible for making sure the memory returned
  69399. ** is eventually freed.
  69400. **
  69401. ** ALGORITHM: Scan the input string looking for host parameters in any of
  69402. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  69403. ** string literals, quoted identifier names, and comments. For text forms,
  69404. ** the host parameter index is found by scanning the prepared
  69405. ** statement for the corresponding OP_Variable opcode. Once the host
  69406. ** parameter index is known, locate the value in p->aVar[]. Then render
  69407. ** the value as a literal in place of the host parameter name.
  69408. */
  69409. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  69410. Vdbe *p, /* The prepared statement being evaluated */
  69411. const char *zRawSql /* Raw text of the SQL statement */
  69412. ){
  69413. sqlite3 *db; /* The database connection */
  69414. int idx = 0; /* Index of a host parameter */
  69415. int nextIndex = 1; /* Index of next ? host parameter */
  69416. int n; /* Length of a token prefix */
  69417. int nToken; /* Length of the parameter token */
  69418. int i; /* Loop counter */
  69419. Mem *pVar; /* Value of a host parameter */
  69420. StrAccum out; /* Accumulate the output here */
  69421. char zBase[100]; /* Initial working space */
  69422. db = p->db;
  69423. sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
  69424. db->aLimit[SQLITE_LIMIT_LENGTH]);
  69425. if( db->nVdbeExec>1 ){
  69426. while( *zRawSql ){
  69427. const char *zStart = zRawSql;
  69428. while( *(zRawSql++)!='\n' && *zRawSql );
  69429. sqlite3StrAccumAppend(&out, "-- ", 3);
  69430. assert( (zRawSql - zStart) > 0 );
  69431. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  69432. }
  69433. }else if( p->nVar==0 ){
  69434. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  69435. }else{
  69436. while( zRawSql[0] ){
  69437. n = findNextHostParameter(zRawSql, &nToken);
  69438. assert( n>0 );
  69439. sqlite3StrAccumAppend(&out, zRawSql, n);
  69440. zRawSql += n;
  69441. assert( zRawSql[0] || nToken==0 );
  69442. if( nToken==0 ) break;
  69443. if( zRawSql[0]=='?' ){
  69444. if( nToken>1 ){
  69445. assert( sqlite3Isdigit(zRawSql[1]) );
  69446. sqlite3GetInt32(&zRawSql[1], &idx);
  69447. }else{
  69448. idx = nextIndex;
  69449. }
  69450. }else{
  69451. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  69452. zRawSql[0]=='@' || zRawSql[0]=='#' );
  69453. testcase( zRawSql[0]==':' );
  69454. testcase( zRawSql[0]=='$' );
  69455. testcase( zRawSql[0]=='@' );
  69456. testcase( zRawSql[0]=='#' );
  69457. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  69458. assert( idx>0 );
  69459. }
  69460. zRawSql += nToken;
  69461. nextIndex = idx + 1;
  69462. assert( idx>0 && idx<=p->nVar );
  69463. pVar = &p->aVar[idx-1];
  69464. if( pVar->flags & MEM_Null ){
  69465. sqlite3StrAccumAppend(&out, "NULL", 4);
  69466. }else if( pVar->flags & MEM_Int ){
  69467. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  69468. }else if( pVar->flags & MEM_Real ){
  69469. sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
  69470. }else if( pVar->flags & MEM_Str ){
  69471. int nOut; /* Number of bytes of the string text to include in output */
  69472. #ifndef SQLITE_OMIT_UTF16
  69473. u8 enc = ENC(db);
  69474. Mem utf8;
  69475. if( enc!=SQLITE_UTF8 ){
  69476. memset(&utf8, 0, sizeof(utf8));
  69477. utf8.db = db;
  69478. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  69479. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  69480. pVar = &utf8;
  69481. }
  69482. #endif
  69483. nOut = pVar->n;
  69484. #ifdef SQLITE_TRACE_SIZE_LIMIT
  69485. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  69486. nOut = SQLITE_TRACE_SIZE_LIMIT;
  69487. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  69488. }
  69489. #endif
  69490. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  69491. #ifdef SQLITE_TRACE_SIZE_LIMIT
  69492. if( nOut<pVar->n ){
  69493. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  69494. }
  69495. #endif
  69496. #ifndef SQLITE_OMIT_UTF16
  69497. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  69498. #endif
  69499. }else if( pVar->flags & MEM_Zero ){
  69500. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  69501. }else{
  69502. int nOut; /* Number of bytes of the blob to include in output */
  69503. assert( pVar->flags & MEM_Blob );
  69504. sqlite3StrAccumAppend(&out, "x'", 2);
  69505. nOut = pVar->n;
  69506. #ifdef SQLITE_TRACE_SIZE_LIMIT
  69507. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  69508. #endif
  69509. for(i=0; i<nOut; i++){
  69510. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  69511. }
  69512. sqlite3StrAccumAppend(&out, "'", 1);
  69513. #ifdef SQLITE_TRACE_SIZE_LIMIT
  69514. if( nOut<pVar->n ){
  69515. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  69516. }
  69517. #endif
  69518. }
  69519. }
  69520. }
  69521. return sqlite3StrAccumFinish(&out);
  69522. }
  69523. #endif /* #ifndef SQLITE_OMIT_TRACE */
  69524. /************** End of vdbetrace.c *******************************************/
  69525. /************** Begin file vdbe.c ********************************************/
  69526. /*
  69527. ** 2001 September 15
  69528. **
  69529. ** The author disclaims copyright to this source code. In place of
  69530. ** a legal notice, here is a blessing:
  69531. **
  69532. ** May you do good and not evil.
  69533. ** May you find forgiveness for yourself and forgive others.
  69534. ** May you share freely, never taking more than you give.
  69535. **
  69536. *************************************************************************
  69537. ** The code in this file implements the function that runs the
  69538. ** bytecode of a prepared statement.
  69539. **
  69540. ** Various scripts scan this source file in order to generate HTML
  69541. ** documentation, headers files, or other derived files. The formatting
  69542. ** of the code in this file is, therefore, important. See other comments
  69543. ** in this file for details. If in doubt, do not deviate from existing
  69544. ** commenting and indentation practices when changing or adding code.
  69545. */
  69546. /* #include "sqliteInt.h" */
  69547. /* #include "vdbeInt.h" */
  69548. /*
  69549. ** Invoke this macro on memory cells just prior to changing the
  69550. ** value of the cell. This macro verifies that shallow copies are
  69551. ** not misused. A shallow copy of a string or blob just copies a
  69552. ** pointer to the string or blob, not the content. If the original
  69553. ** is changed while the copy is still in use, the string or blob might
  69554. ** be changed out from under the copy. This macro verifies that nothing
  69555. ** like that ever happens.
  69556. */
  69557. #ifdef SQLITE_DEBUG
  69558. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  69559. #else
  69560. # define memAboutToChange(P,M)
  69561. #endif
  69562. /*
  69563. ** The following global variable is incremented every time a cursor
  69564. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  69565. ** procedures use this information to make sure that indices are
  69566. ** working correctly. This variable has no function other than to
  69567. ** help verify the correct operation of the library.
  69568. */
  69569. #ifdef SQLITE_TEST
  69570. SQLITE_API int sqlite3_search_count = 0;
  69571. #endif
  69572. /*
  69573. ** When this global variable is positive, it gets decremented once before
  69574. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  69575. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  69576. **
  69577. ** This facility is used for testing purposes only. It does not function
  69578. ** in an ordinary build.
  69579. */
  69580. #ifdef SQLITE_TEST
  69581. SQLITE_API int sqlite3_interrupt_count = 0;
  69582. #endif
  69583. /*
  69584. ** The next global variable is incremented each type the OP_Sort opcode
  69585. ** is executed. The test procedures use this information to make sure that
  69586. ** sorting is occurring or not occurring at appropriate times. This variable
  69587. ** has no function other than to help verify the correct operation of the
  69588. ** library.
  69589. */
  69590. #ifdef SQLITE_TEST
  69591. SQLITE_API int sqlite3_sort_count = 0;
  69592. #endif
  69593. /*
  69594. ** The next global variable records the size of the largest MEM_Blob
  69595. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  69596. ** use this information to make sure that the zero-blob functionality
  69597. ** is working correctly. This variable has no function other than to
  69598. ** help verify the correct operation of the library.
  69599. */
  69600. #ifdef SQLITE_TEST
  69601. SQLITE_API int sqlite3_max_blobsize = 0;
  69602. static void updateMaxBlobsize(Mem *p){
  69603. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  69604. sqlite3_max_blobsize = p->n;
  69605. }
  69606. }
  69607. #endif
  69608. /*
  69609. ** The next global variable is incremented each time the OP_Found opcode
  69610. ** is executed. This is used to test whether or not the foreign key
  69611. ** operation implemented using OP_FkIsZero is working. This variable
  69612. ** has no function other than to help verify the correct operation of the
  69613. ** library.
  69614. */
  69615. #ifdef SQLITE_TEST
  69616. SQLITE_API int sqlite3_found_count = 0;
  69617. #endif
  69618. /*
  69619. ** Test a register to see if it exceeds the current maximum blob size.
  69620. ** If it does, record the new maximum blob size.
  69621. */
  69622. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  69623. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  69624. #else
  69625. # define UPDATE_MAX_BLOBSIZE(P)
  69626. #endif
  69627. /*
  69628. ** Invoke the VDBE coverage callback, if that callback is defined. This
  69629. ** feature is used for test suite validation only and does not appear an
  69630. ** production builds.
  69631. **
  69632. ** M is an integer, 2 or 3, that indices how many different ways the
  69633. ** branch can go. It is usually 2. "I" is the direction the branch
  69634. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  69635. ** second alternative branch is taken.
  69636. **
  69637. ** iSrcLine is the source code line (from the __LINE__ macro) that
  69638. ** generated the VDBE instruction. This instrumentation assumes that all
  69639. ** source code is in a single file (the amalgamation). Special values 1
  69640. ** and 2 for the iSrcLine parameter mean that this particular branch is
  69641. ** always taken or never taken, respectively.
  69642. */
  69643. #if !defined(SQLITE_VDBE_COVERAGE)
  69644. # define VdbeBranchTaken(I,M)
  69645. #else
  69646. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  69647. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  69648. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  69649. M = iSrcLine;
  69650. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  69651. ** VdbeCoverageNeverTaken() */
  69652. assert( (M & I)==I );
  69653. }else{
  69654. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  69655. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  69656. iSrcLine,I,M);
  69657. }
  69658. }
  69659. #endif
  69660. /*
  69661. ** Convert the given register into a string if it isn't one
  69662. ** already. Return non-zero if a malloc() fails.
  69663. */
  69664. #define Stringify(P, enc) \
  69665. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  69666. { goto no_mem; }
  69667. /*
  69668. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  69669. ** a pointer to a dynamically allocated string where some other entity
  69670. ** is responsible for deallocating that string. Because the register
  69671. ** does not control the string, it might be deleted without the register
  69672. ** knowing it.
  69673. **
  69674. ** This routine converts an ephemeral string into a dynamically allocated
  69675. ** string that the register itself controls. In other words, it
  69676. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  69677. */
  69678. #define Deephemeralize(P) \
  69679. if( ((P)->flags&MEM_Ephem)!=0 \
  69680. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  69681. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  69682. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  69683. /*
  69684. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  69685. ** if we run out of memory.
  69686. */
  69687. static VdbeCursor *allocateCursor(
  69688. Vdbe *p, /* The virtual machine */
  69689. int iCur, /* Index of the new VdbeCursor */
  69690. int nField, /* Number of fields in the table or index */
  69691. int iDb, /* Database the cursor belongs to, or -1 */
  69692. u8 eCurType /* Type of the new cursor */
  69693. ){
  69694. /* Find the memory cell that will be used to store the blob of memory
  69695. ** required for this VdbeCursor structure. It is convenient to use a
  69696. ** vdbe memory cell to manage the memory allocation required for a
  69697. ** VdbeCursor structure for the following reasons:
  69698. **
  69699. ** * Sometimes cursor numbers are used for a couple of different
  69700. ** purposes in a vdbe program. The different uses might require
  69701. ** different sized allocations. Memory cells provide growable
  69702. ** allocations.
  69703. **
  69704. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  69705. ** be freed lazily via the sqlite3_release_memory() API. This
  69706. ** minimizes the number of malloc calls made by the system.
  69707. **
  69708. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  69709. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  69710. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  69711. */
  69712. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  69713. int nByte;
  69714. VdbeCursor *pCx = 0;
  69715. nByte =
  69716. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  69717. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  69718. assert( iCur>=0 && iCur<p->nCursor );
  69719. if( p->apCsr[iCur] ){
  69720. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  69721. p->apCsr[iCur] = 0;
  69722. }
  69723. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  69724. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  69725. memset(pCx, 0, sizeof(VdbeCursor));
  69726. pCx->eCurType = eCurType;
  69727. pCx->iDb = iDb;
  69728. pCx->nField = nField;
  69729. pCx->aOffset = &pCx->aType[nField];
  69730. if( eCurType==CURTYPE_BTREE ){
  69731. pCx->uc.pCursor = (BtCursor*)
  69732. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  69733. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  69734. }
  69735. }
  69736. return pCx;
  69737. }
  69738. /*
  69739. ** Try to convert a value into a numeric representation if we can
  69740. ** do so without loss of information. In other words, if the string
  69741. ** looks like a number, convert it into a number. If it does not
  69742. ** look like a number, leave it alone.
  69743. **
  69744. ** If the bTryForInt flag is true, then extra effort is made to give
  69745. ** an integer representation. Strings that look like floating point
  69746. ** values but which have no fractional component (example: '48.00')
  69747. ** will have a MEM_Int representation when bTryForInt is true.
  69748. **
  69749. ** If bTryForInt is false, then if the input string contains a decimal
  69750. ** point or exponential notation, the result is only MEM_Real, even
  69751. ** if there is an exact integer representation of the quantity.
  69752. */
  69753. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  69754. double rValue;
  69755. i64 iValue;
  69756. u8 enc = pRec->enc;
  69757. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  69758. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  69759. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  69760. pRec->u.i = iValue;
  69761. pRec->flags |= MEM_Int;
  69762. }else{
  69763. pRec->u.r = rValue;
  69764. pRec->flags |= MEM_Real;
  69765. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  69766. }
  69767. }
  69768. /*
  69769. ** Processing is determine by the affinity parameter:
  69770. **
  69771. ** SQLITE_AFF_INTEGER:
  69772. ** SQLITE_AFF_REAL:
  69773. ** SQLITE_AFF_NUMERIC:
  69774. ** Try to convert pRec to an integer representation or a
  69775. ** floating-point representation if an integer representation
  69776. ** is not possible. Note that the integer representation is
  69777. ** always preferred, even if the affinity is REAL, because
  69778. ** an integer representation is more space efficient on disk.
  69779. **
  69780. ** SQLITE_AFF_TEXT:
  69781. ** Convert pRec to a text representation.
  69782. **
  69783. ** SQLITE_AFF_BLOB:
  69784. ** No-op. pRec is unchanged.
  69785. */
  69786. static void applyAffinity(
  69787. Mem *pRec, /* The value to apply affinity to */
  69788. char affinity, /* The affinity to be applied */
  69789. u8 enc /* Use this text encoding */
  69790. ){
  69791. if( affinity>=SQLITE_AFF_NUMERIC ){
  69792. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  69793. || affinity==SQLITE_AFF_NUMERIC );
  69794. if( (pRec->flags & MEM_Int)==0 ){
  69795. if( (pRec->flags & MEM_Real)==0 ){
  69796. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  69797. }else{
  69798. sqlite3VdbeIntegerAffinity(pRec);
  69799. }
  69800. }
  69801. }else if( affinity==SQLITE_AFF_TEXT ){
  69802. /* Only attempt the conversion to TEXT if there is an integer or real
  69803. ** representation (blob and NULL do not get converted) but no string
  69804. ** representation.
  69805. */
  69806. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  69807. sqlite3VdbeMemStringify(pRec, enc, 1);
  69808. }
  69809. pRec->flags &= ~(MEM_Real|MEM_Int);
  69810. }
  69811. }
  69812. /*
  69813. ** Try to convert the type of a function argument or a result column
  69814. ** into a numeric representation. Use either INTEGER or REAL whichever
  69815. ** is appropriate. But only do the conversion if it is possible without
  69816. ** loss of information and return the revised type of the argument.
  69817. */
  69818. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
  69819. int eType = sqlite3_value_type(pVal);
  69820. if( eType==SQLITE_TEXT ){
  69821. Mem *pMem = (Mem*)pVal;
  69822. applyNumericAffinity(pMem, 0);
  69823. eType = sqlite3_value_type(pVal);
  69824. }
  69825. return eType;
  69826. }
  69827. /*
  69828. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  69829. ** not the internal Mem* type.
  69830. */
  69831. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  69832. sqlite3_value *pVal,
  69833. u8 affinity,
  69834. u8 enc
  69835. ){
  69836. applyAffinity((Mem *)pVal, affinity, enc);
  69837. }
  69838. /*
  69839. ** pMem currently only holds a string type (or maybe a BLOB that we can
  69840. ** interpret as a string if we want to). Compute its corresponding
  69841. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  69842. ** accordingly.
  69843. */
  69844. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  69845. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  69846. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  69847. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  69848. return 0;
  69849. }
  69850. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  69851. return MEM_Int;
  69852. }
  69853. return MEM_Real;
  69854. }
  69855. /*
  69856. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  69857. ** none.
  69858. **
  69859. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  69860. ** But it does set pMem->u.r and pMem->u.i appropriately.
  69861. */
  69862. static u16 numericType(Mem *pMem){
  69863. if( pMem->flags & (MEM_Int|MEM_Real) ){
  69864. return pMem->flags & (MEM_Int|MEM_Real);
  69865. }
  69866. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  69867. return computeNumericType(pMem);
  69868. }
  69869. return 0;
  69870. }
  69871. #ifdef SQLITE_DEBUG
  69872. /*
  69873. ** Write a nice string representation of the contents of cell pMem
  69874. ** into buffer zBuf, length nBuf.
  69875. */
  69876. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  69877. char *zCsr = zBuf;
  69878. int f = pMem->flags;
  69879. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  69880. if( f&MEM_Blob ){
  69881. int i;
  69882. char c;
  69883. if( f & MEM_Dyn ){
  69884. c = 'z';
  69885. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  69886. }else if( f & MEM_Static ){
  69887. c = 't';
  69888. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  69889. }else if( f & MEM_Ephem ){
  69890. c = 'e';
  69891. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  69892. }else{
  69893. c = 's';
  69894. }
  69895. sqlite3_snprintf(100, zCsr, "%c", c);
  69896. zCsr += sqlite3Strlen30(zCsr);
  69897. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  69898. zCsr += sqlite3Strlen30(zCsr);
  69899. for(i=0; i<16 && i<pMem->n; i++){
  69900. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  69901. zCsr += sqlite3Strlen30(zCsr);
  69902. }
  69903. for(i=0; i<16 && i<pMem->n; i++){
  69904. char z = pMem->z[i];
  69905. if( z<32 || z>126 ) *zCsr++ = '.';
  69906. else *zCsr++ = z;
  69907. }
  69908. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  69909. zCsr += sqlite3Strlen30(zCsr);
  69910. if( f & MEM_Zero ){
  69911. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  69912. zCsr += sqlite3Strlen30(zCsr);
  69913. }
  69914. *zCsr = '\0';
  69915. }else if( f & MEM_Str ){
  69916. int j, k;
  69917. zBuf[0] = ' ';
  69918. if( f & MEM_Dyn ){
  69919. zBuf[1] = 'z';
  69920. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  69921. }else if( f & MEM_Static ){
  69922. zBuf[1] = 't';
  69923. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  69924. }else if( f & MEM_Ephem ){
  69925. zBuf[1] = 'e';
  69926. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  69927. }else{
  69928. zBuf[1] = 's';
  69929. }
  69930. k = 2;
  69931. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  69932. k += sqlite3Strlen30(&zBuf[k]);
  69933. zBuf[k++] = '[';
  69934. for(j=0; j<15 && j<pMem->n; j++){
  69935. u8 c = pMem->z[j];
  69936. if( c>=0x20 && c<0x7f ){
  69937. zBuf[k++] = c;
  69938. }else{
  69939. zBuf[k++] = '.';
  69940. }
  69941. }
  69942. zBuf[k++] = ']';
  69943. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  69944. k += sqlite3Strlen30(&zBuf[k]);
  69945. zBuf[k++] = 0;
  69946. }
  69947. }
  69948. #endif
  69949. #ifdef SQLITE_DEBUG
  69950. /*
  69951. ** Print the value of a register for tracing purposes:
  69952. */
  69953. static void memTracePrint(Mem *p){
  69954. if( p->flags & MEM_Undefined ){
  69955. printf(" undefined");
  69956. }else if( p->flags & MEM_Null ){
  69957. printf(" NULL");
  69958. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  69959. printf(" si:%lld", p->u.i);
  69960. }else if( p->flags & MEM_Int ){
  69961. printf(" i:%lld", p->u.i);
  69962. #ifndef SQLITE_OMIT_FLOATING_POINT
  69963. }else if( p->flags & MEM_Real ){
  69964. printf(" r:%g", p->u.r);
  69965. #endif
  69966. }else if( p->flags & MEM_RowSet ){
  69967. printf(" (rowset)");
  69968. }else{
  69969. char zBuf[200];
  69970. sqlite3VdbeMemPrettyPrint(p, zBuf);
  69971. printf(" %s", zBuf);
  69972. }
  69973. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  69974. }
  69975. static void registerTrace(int iReg, Mem *p){
  69976. printf("REG[%d] = ", iReg);
  69977. memTracePrint(p);
  69978. printf("\n");
  69979. }
  69980. #endif
  69981. #ifdef SQLITE_DEBUG
  69982. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  69983. #else
  69984. # define REGISTER_TRACE(R,M)
  69985. #endif
  69986. #ifdef VDBE_PROFILE
  69987. /*
  69988. ** hwtime.h contains inline assembler code for implementing
  69989. ** high-performance timing routines.
  69990. */
  69991. /************** Include hwtime.h in the middle of vdbe.c *********************/
  69992. /************** Begin file hwtime.h ******************************************/
  69993. /*
  69994. ** 2008 May 27
  69995. **
  69996. ** The author disclaims copyright to this source code. In place of
  69997. ** a legal notice, here is a blessing:
  69998. **
  69999. ** May you do good and not evil.
  70000. ** May you find forgiveness for yourself and forgive others.
  70001. ** May you share freely, never taking more than you give.
  70002. **
  70003. ******************************************************************************
  70004. **
  70005. ** This file contains inline asm code for retrieving "high-performance"
  70006. ** counters for x86 class CPUs.
  70007. */
  70008. #ifndef _HWTIME_H_
  70009. #define _HWTIME_H_
  70010. /*
  70011. ** The following routine only works on pentium-class (or newer) processors.
  70012. ** It uses the RDTSC opcode to read the cycle count value out of the
  70013. ** processor and returns that value. This can be used for high-res
  70014. ** profiling.
  70015. */
  70016. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  70017. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  70018. #if defined(__GNUC__)
  70019. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  70020. unsigned int lo, hi;
  70021. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  70022. return (sqlite_uint64)hi << 32 | lo;
  70023. }
  70024. #elif defined(_MSC_VER)
  70025. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  70026. __asm {
  70027. rdtsc
  70028. ret ; return value at EDX:EAX
  70029. }
  70030. }
  70031. #endif
  70032. #elif (defined(__GNUC__) && defined(__x86_64__))
  70033. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  70034. unsigned long val;
  70035. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  70036. return val;
  70037. }
  70038. #elif (defined(__GNUC__) && defined(__ppc__))
  70039. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  70040. unsigned long long retval;
  70041. unsigned long junk;
  70042. __asm__ __volatile__ ("\n\
  70043. 1: mftbu %1\n\
  70044. mftb %L0\n\
  70045. mftbu %0\n\
  70046. cmpw %0,%1\n\
  70047. bne 1b"
  70048. : "=r" (retval), "=r" (junk));
  70049. return retval;
  70050. }
  70051. #else
  70052. #error Need implementation of sqlite3Hwtime() for your platform.
  70053. /*
  70054. ** To compile without implementing sqlite3Hwtime() for your platform,
  70055. ** you can remove the above #error and use the following
  70056. ** stub function. You will lose timing support for many
  70057. ** of the debugging and testing utilities, but it should at
  70058. ** least compile and run.
  70059. */
  70060. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  70061. #endif
  70062. #endif /* !defined(_HWTIME_H_) */
  70063. /************** End of hwtime.h **********************************************/
  70064. /************** Continuing where we left off in vdbe.c ***********************/
  70065. #endif
  70066. #ifndef NDEBUG
  70067. /*
  70068. ** This function is only called from within an assert() expression. It
  70069. ** checks that the sqlite3.nTransaction variable is correctly set to
  70070. ** the number of non-transaction savepoints currently in the
  70071. ** linked list starting at sqlite3.pSavepoint.
  70072. **
  70073. ** Usage:
  70074. **
  70075. ** assert( checkSavepointCount(db) );
  70076. */
  70077. static int checkSavepointCount(sqlite3 *db){
  70078. int n = 0;
  70079. Savepoint *p;
  70080. for(p=db->pSavepoint; p; p=p->pNext) n++;
  70081. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  70082. return 1;
  70083. }
  70084. #endif
  70085. /*
  70086. ** Return the register of pOp->p2 after first preparing it to be
  70087. ** overwritten with an integer value.
  70088. */
  70089. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  70090. sqlite3VdbeMemSetNull(pOut);
  70091. pOut->flags = MEM_Int;
  70092. return pOut;
  70093. }
  70094. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  70095. Mem *pOut;
  70096. assert( pOp->p2>0 );
  70097. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  70098. pOut = &p->aMem[pOp->p2];
  70099. memAboutToChange(p, pOut);
  70100. if( VdbeMemDynamic(pOut) ){
  70101. return out2PrereleaseWithClear(pOut);
  70102. }else{
  70103. pOut->flags = MEM_Int;
  70104. return pOut;
  70105. }
  70106. }
  70107. /*
  70108. ** Execute as much of a VDBE program as we can.
  70109. ** This is the core of sqlite3_step().
  70110. */
  70111. SQLITE_PRIVATE int sqlite3VdbeExec(
  70112. Vdbe *p /* The VDBE */
  70113. ){
  70114. Op *aOp = p->aOp; /* Copy of p->aOp */
  70115. Op *pOp = aOp; /* Current operation */
  70116. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  70117. Op *pOrigOp; /* Value of pOp at the top of the loop */
  70118. #endif
  70119. #ifdef SQLITE_DEBUG
  70120. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  70121. #endif
  70122. int rc = SQLITE_OK; /* Value to return */
  70123. sqlite3 *db = p->db; /* The database */
  70124. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  70125. u8 encoding = ENC(db); /* The database encoding */
  70126. int iCompare = 0; /* Result of last OP_Compare operation */
  70127. unsigned nVmStep = 0; /* Number of virtual machine steps */
  70128. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  70129. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  70130. #endif
  70131. Mem *aMem = p->aMem; /* Copy of p->aMem */
  70132. Mem *pIn1 = 0; /* 1st input operand */
  70133. Mem *pIn2 = 0; /* 2nd input operand */
  70134. Mem *pIn3 = 0; /* 3rd input operand */
  70135. Mem *pOut = 0; /* Output operand */
  70136. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  70137. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  70138. #ifdef VDBE_PROFILE
  70139. u64 start; /* CPU clock count at start of opcode */
  70140. #endif
  70141. /*** INSERT STACK UNION HERE ***/
  70142. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  70143. sqlite3VdbeEnter(p);
  70144. if( p->rc==SQLITE_NOMEM ){
  70145. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  70146. ** sqlite3_column_text16() failed. */
  70147. goto no_mem;
  70148. }
  70149. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  70150. assert( p->bIsReader || p->readOnly!=0 );
  70151. p->rc = SQLITE_OK;
  70152. p->iCurrentTime = 0;
  70153. assert( p->explain==0 );
  70154. p->pResultSet = 0;
  70155. db->busyHandler.nBusy = 0;
  70156. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  70157. sqlite3VdbeIOTraceSql(p);
  70158. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  70159. if( db->xProgress ){
  70160. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  70161. assert( 0 < db->nProgressOps );
  70162. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  70163. }
  70164. #endif
  70165. #ifdef SQLITE_DEBUG
  70166. sqlite3BeginBenignMalloc();
  70167. if( p->pc==0
  70168. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  70169. ){
  70170. int i;
  70171. int once = 1;
  70172. sqlite3VdbePrintSql(p);
  70173. if( p->db->flags & SQLITE_VdbeListing ){
  70174. printf("VDBE Program Listing:\n");
  70175. for(i=0; i<p->nOp; i++){
  70176. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  70177. }
  70178. }
  70179. if( p->db->flags & SQLITE_VdbeEQP ){
  70180. for(i=0; i<p->nOp; i++){
  70181. if( aOp[i].opcode==OP_Explain ){
  70182. if( once ) printf("VDBE Query Plan:\n");
  70183. printf("%s\n", aOp[i].p4.z);
  70184. once = 0;
  70185. }
  70186. }
  70187. }
  70188. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  70189. }
  70190. sqlite3EndBenignMalloc();
  70191. #endif
  70192. for(pOp=&aOp[p->pc]; 1; pOp++){
  70193. /* Errors are detected by individual opcodes, with an immediate
  70194. ** jumps to abort_due_to_error. */
  70195. assert( rc==SQLITE_OK );
  70196. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  70197. #ifdef VDBE_PROFILE
  70198. start = sqlite3Hwtime();
  70199. #endif
  70200. nVmStep++;
  70201. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  70202. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  70203. #endif
  70204. /* Only allow tracing if SQLITE_DEBUG is defined.
  70205. */
  70206. #ifdef SQLITE_DEBUG
  70207. if( db->flags & SQLITE_VdbeTrace ){
  70208. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  70209. }
  70210. #endif
  70211. /* Check to see if we need to simulate an interrupt. This only happens
  70212. ** if we have a special test build.
  70213. */
  70214. #ifdef SQLITE_TEST
  70215. if( sqlite3_interrupt_count>0 ){
  70216. sqlite3_interrupt_count--;
  70217. if( sqlite3_interrupt_count==0 ){
  70218. sqlite3_interrupt(db);
  70219. }
  70220. }
  70221. #endif
  70222. /* Sanity checking on other operands */
  70223. #ifdef SQLITE_DEBUG
  70224. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  70225. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  70226. assert( pOp->p1>0 );
  70227. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  70228. assert( memIsValid(&aMem[pOp->p1]) );
  70229. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  70230. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  70231. }
  70232. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  70233. assert( pOp->p2>0 );
  70234. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  70235. assert( memIsValid(&aMem[pOp->p2]) );
  70236. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  70237. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  70238. }
  70239. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  70240. assert( pOp->p3>0 );
  70241. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  70242. assert( memIsValid(&aMem[pOp->p3]) );
  70243. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  70244. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  70245. }
  70246. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  70247. assert( pOp->p2>0 );
  70248. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  70249. memAboutToChange(p, &aMem[pOp->p2]);
  70250. }
  70251. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  70252. assert( pOp->p3>0 );
  70253. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  70254. memAboutToChange(p, &aMem[pOp->p3]);
  70255. }
  70256. #endif
  70257. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  70258. pOrigOp = pOp;
  70259. #endif
  70260. switch( pOp->opcode ){
  70261. /*****************************************************************************
  70262. ** What follows is a massive switch statement where each case implements a
  70263. ** separate instruction in the virtual machine. If we follow the usual
  70264. ** indentation conventions, each case should be indented by 6 spaces. But
  70265. ** that is a lot of wasted space on the left margin. So the code within
  70266. ** the switch statement will break with convention and be flush-left. Another
  70267. ** big comment (similar to this one) will mark the point in the code where
  70268. ** we transition back to normal indentation.
  70269. **
  70270. ** The formatting of each case is important. The makefile for SQLite
  70271. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  70272. ** file looking for lines that begin with "case OP_". The opcodes.h files
  70273. ** will be filled with #defines that give unique integer values to each
  70274. ** opcode and the opcodes.c file is filled with an array of strings where
  70275. ** each string is the symbolic name for the corresponding opcode. If the
  70276. ** case statement is followed by a comment of the form "/# same as ... #/"
  70277. ** that comment is used to determine the particular value of the opcode.
  70278. **
  70279. ** Other keywords in the comment that follows each case are used to
  70280. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  70281. ** Keywords include: in1, in2, in3, out2, out3. See
  70282. ** the mkopcodeh.awk script for additional information.
  70283. **
  70284. ** Documentation about VDBE opcodes is generated by scanning this file
  70285. ** for lines of that contain "Opcode:". That line and all subsequent
  70286. ** comment lines are used in the generation of the opcode.html documentation
  70287. ** file.
  70288. **
  70289. ** SUMMARY:
  70290. **
  70291. ** Formatting is important to scripts that scan this file.
  70292. ** Do not deviate from the formatting style currently in use.
  70293. **
  70294. *****************************************************************************/
  70295. /* Opcode: Goto * P2 * * *
  70296. **
  70297. ** An unconditional jump to address P2.
  70298. ** The next instruction executed will be
  70299. ** the one at index P2 from the beginning of
  70300. ** the program.
  70301. **
  70302. ** The P1 parameter is not actually used by this opcode. However, it
  70303. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  70304. ** that this Goto is the bottom of a loop and that the lines from P2 down
  70305. ** to the current line should be indented for EXPLAIN output.
  70306. */
  70307. case OP_Goto: { /* jump */
  70308. jump_to_p2_and_check_for_interrupt:
  70309. pOp = &aOp[pOp->p2 - 1];
  70310. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  70311. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  70312. ** completion. Check to see if sqlite3_interrupt() has been called
  70313. ** or if the progress callback needs to be invoked.
  70314. **
  70315. ** This code uses unstructured "goto" statements and does not look clean.
  70316. ** But that is not due to sloppy coding habits. The code is written this
  70317. ** way for performance, to avoid having to run the interrupt and progress
  70318. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  70319. ** faster according to "valgrind --tool=cachegrind" */
  70320. check_for_interrupt:
  70321. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  70322. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  70323. /* Call the progress callback if it is configured and the required number
  70324. ** of VDBE ops have been executed (either since this invocation of
  70325. ** sqlite3VdbeExec() or since last time the progress callback was called).
  70326. ** If the progress callback returns non-zero, exit the virtual machine with
  70327. ** a return code SQLITE_ABORT.
  70328. */
  70329. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  70330. assert( db->nProgressOps!=0 );
  70331. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  70332. if( db->xProgress(db->pProgressArg) ){
  70333. rc = SQLITE_INTERRUPT;
  70334. goto abort_due_to_error;
  70335. }
  70336. }
  70337. #endif
  70338. break;
  70339. }
  70340. /* Opcode: Gosub P1 P2 * * *
  70341. **
  70342. ** Write the current address onto register P1
  70343. ** and then jump to address P2.
  70344. */
  70345. case OP_Gosub: { /* jump */
  70346. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  70347. pIn1 = &aMem[pOp->p1];
  70348. assert( VdbeMemDynamic(pIn1)==0 );
  70349. memAboutToChange(p, pIn1);
  70350. pIn1->flags = MEM_Int;
  70351. pIn1->u.i = (int)(pOp-aOp);
  70352. REGISTER_TRACE(pOp->p1, pIn1);
  70353. /* Most jump operations do a goto to this spot in order to update
  70354. ** the pOp pointer. */
  70355. jump_to_p2:
  70356. pOp = &aOp[pOp->p2 - 1];
  70357. break;
  70358. }
  70359. /* Opcode: Return P1 * * * *
  70360. **
  70361. ** Jump to the next instruction after the address in register P1. After
  70362. ** the jump, register P1 becomes undefined.
  70363. */
  70364. case OP_Return: { /* in1 */
  70365. pIn1 = &aMem[pOp->p1];
  70366. assert( pIn1->flags==MEM_Int );
  70367. pOp = &aOp[pIn1->u.i];
  70368. pIn1->flags = MEM_Undefined;
  70369. break;
  70370. }
  70371. /* Opcode: InitCoroutine P1 P2 P3 * *
  70372. **
  70373. ** Set up register P1 so that it will Yield to the coroutine
  70374. ** located at address P3.
  70375. **
  70376. ** If P2!=0 then the coroutine implementation immediately follows
  70377. ** this opcode. So jump over the coroutine implementation to
  70378. ** address P2.
  70379. **
  70380. ** See also: EndCoroutine
  70381. */
  70382. case OP_InitCoroutine: { /* jump */
  70383. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  70384. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  70385. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  70386. pOut = &aMem[pOp->p1];
  70387. assert( !VdbeMemDynamic(pOut) );
  70388. pOut->u.i = pOp->p3 - 1;
  70389. pOut->flags = MEM_Int;
  70390. if( pOp->p2 ) goto jump_to_p2;
  70391. break;
  70392. }
  70393. /* Opcode: EndCoroutine P1 * * * *
  70394. **
  70395. ** The instruction at the address in register P1 is a Yield.
  70396. ** Jump to the P2 parameter of that Yield.
  70397. ** After the jump, register P1 becomes undefined.
  70398. **
  70399. ** See also: InitCoroutine
  70400. */
  70401. case OP_EndCoroutine: { /* in1 */
  70402. VdbeOp *pCaller;
  70403. pIn1 = &aMem[pOp->p1];
  70404. assert( pIn1->flags==MEM_Int );
  70405. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  70406. pCaller = &aOp[pIn1->u.i];
  70407. assert( pCaller->opcode==OP_Yield );
  70408. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  70409. pOp = &aOp[pCaller->p2 - 1];
  70410. pIn1->flags = MEM_Undefined;
  70411. break;
  70412. }
  70413. /* Opcode: Yield P1 P2 * * *
  70414. **
  70415. ** Swap the program counter with the value in register P1. This
  70416. ** has the effect of yielding to a coroutine.
  70417. **
  70418. ** If the coroutine that is launched by this instruction ends with
  70419. ** Yield or Return then continue to the next instruction. But if
  70420. ** the coroutine launched by this instruction ends with
  70421. ** EndCoroutine, then jump to P2 rather than continuing with the
  70422. ** next instruction.
  70423. **
  70424. ** See also: InitCoroutine
  70425. */
  70426. case OP_Yield: { /* in1, jump */
  70427. int pcDest;
  70428. pIn1 = &aMem[pOp->p1];
  70429. assert( VdbeMemDynamic(pIn1)==0 );
  70430. pIn1->flags = MEM_Int;
  70431. pcDest = (int)pIn1->u.i;
  70432. pIn1->u.i = (int)(pOp - aOp);
  70433. REGISTER_TRACE(pOp->p1, pIn1);
  70434. pOp = &aOp[pcDest];
  70435. break;
  70436. }
  70437. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  70438. ** Synopsis: if r[P3]=null halt
  70439. **
  70440. ** Check the value in register P3. If it is NULL then Halt using
  70441. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  70442. ** value in register P3 is not NULL, then this routine is a no-op.
  70443. ** The P5 parameter should be 1.
  70444. */
  70445. case OP_HaltIfNull: { /* in3 */
  70446. pIn3 = &aMem[pOp->p3];
  70447. if( (pIn3->flags & MEM_Null)==0 ) break;
  70448. /* Fall through into OP_Halt */
  70449. }
  70450. /* Opcode: Halt P1 P2 * P4 P5
  70451. **
  70452. ** Exit immediately. All open cursors, etc are closed
  70453. ** automatically.
  70454. **
  70455. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  70456. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  70457. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  70458. ** whether or not to rollback the current transaction. Do not rollback
  70459. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  70460. ** then back out all changes that have occurred during this execution of the
  70461. ** VDBE, but do not rollback the transaction.
  70462. **
  70463. ** If P4 is not null then it is an error message string.
  70464. **
  70465. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  70466. **
  70467. ** 0: (no change)
  70468. ** 1: NOT NULL contraint failed: P4
  70469. ** 2: UNIQUE constraint failed: P4
  70470. ** 3: CHECK constraint failed: P4
  70471. ** 4: FOREIGN KEY constraint failed: P4
  70472. **
  70473. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  70474. ** omitted.
  70475. **
  70476. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  70477. ** every program. So a jump past the last instruction of the program
  70478. ** is the same as executing Halt.
  70479. */
  70480. case OP_Halt: {
  70481. const char *zType;
  70482. const char *zLogFmt;
  70483. VdbeFrame *pFrame;
  70484. int pcx;
  70485. pcx = (int)(pOp - aOp);
  70486. if( pOp->p1==SQLITE_OK && p->pFrame ){
  70487. /* Halt the sub-program. Return control to the parent frame. */
  70488. pFrame = p->pFrame;
  70489. p->pFrame = pFrame->pParent;
  70490. p->nFrame--;
  70491. sqlite3VdbeSetChanges(db, p->nChange);
  70492. pcx = sqlite3VdbeFrameRestore(pFrame);
  70493. lastRowid = db->lastRowid;
  70494. if( pOp->p2==OE_Ignore ){
  70495. /* Instruction pcx is the OP_Program that invoked the sub-program
  70496. ** currently being halted. If the p2 instruction of this OP_Halt
  70497. ** instruction is set to OE_Ignore, then the sub-program is throwing
  70498. ** an IGNORE exception. In this case jump to the address specified
  70499. ** as the p2 of the calling OP_Program. */
  70500. pcx = p->aOp[pcx].p2-1;
  70501. }
  70502. aOp = p->aOp;
  70503. aMem = p->aMem;
  70504. pOp = &aOp[pcx];
  70505. break;
  70506. }
  70507. p->rc = pOp->p1;
  70508. p->errorAction = (u8)pOp->p2;
  70509. p->pc = pcx;
  70510. if( p->rc ){
  70511. if( pOp->p5 ){
  70512. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  70513. "FOREIGN KEY" };
  70514. assert( pOp->p5>=1 && pOp->p5<=4 );
  70515. testcase( pOp->p5==1 );
  70516. testcase( pOp->p5==2 );
  70517. testcase( pOp->p5==3 );
  70518. testcase( pOp->p5==4 );
  70519. zType = azType[pOp->p5-1];
  70520. }else{
  70521. zType = 0;
  70522. }
  70523. assert( zType!=0 || pOp->p4.z!=0 );
  70524. zLogFmt = "abort at %d in [%s]: %s";
  70525. if( zType && pOp->p4.z ){
  70526. sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
  70527. }else if( pOp->p4.z ){
  70528. sqlite3VdbeError(p, "%s", pOp->p4.z);
  70529. }else{
  70530. sqlite3VdbeError(p, "%s constraint failed", zType);
  70531. }
  70532. sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
  70533. }
  70534. rc = sqlite3VdbeHalt(p);
  70535. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  70536. if( rc==SQLITE_BUSY ){
  70537. p->rc = rc = SQLITE_BUSY;
  70538. }else{
  70539. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  70540. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  70541. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  70542. }
  70543. goto vdbe_return;
  70544. }
  70545. /* Opcode: Integer P1 P2 * * *
  70546. ** Synopsis: r[P2]=P1
  70547. **
  70548. ** The 32-bit integer value P1 is written into register P2.
  70549. */
  70550. case OP_Integer: { /* out2 */
  70551. pOut = out2Prerelease(p, pOp);
  70552. pOut->u.i = pOp->p1;
  70553. break;
  70554. }
  70555. /* Opcode: Int64 * P2 * P4 *
  70556. ** Synopsis: r[P2]=P4
  70557. **
  70558. ** P4 is a pointer to a 64-bit integer value.
  70559. ** Write that value into register P2.
  70560. */
  70561. case OP_Int64: { /* out2 */
  70562. pOut = out2Prerelease(p, pOp);
  70563. assert( pOp->p4.pI64!=0 );
  70564. pOut->u.i = *pOp->p4.pI64;
  70565. break;
  70566. }
  70567. #ifndef SQLITE_OMIT_FLOATING_POINT
  70568. /* Opcode: Real * P2 * P4 *
  70569. ** Synopsis: r[P2]=P4
  70570. **
  70571. ** P4 is a pointer to a 64-bit floating point value.
  70572. ** Write that value into register P2.
  70573. */
  70574. case OP_Real: { /* same as TK_FLOAT, out2 */
  70575. pOut = out2Prerelease(p, pOp);
  70576. pOut->flags = MEM_Real;
  70577. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  70578. pOut->u.r = *pOp->p4.pReal;
  70579. break;
  70580. }
  70581. #endif
  70582. /* Opcode: String8 * P2 * P4 *
  70583. ** Synopsis: r[P2]='P4'
  70584. **
  70585. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  70586. ** into a String opcode before it is executed for the first time. During
  70587. ** this transformation, the length of string P4 is computed and stored
  70588. ** as the P1 parameter.
  70589. */
  70590. case OP_String8: { /* same as TK_STRING, out2 */
  70591. assert( pOp->p4.z!=0 );
  70592. pOut = out2Prerelease(p, pOp);
  70593. pOp->opcode = OP_String;
  70594. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  70595. #ifndef SQLITE_OMIT_UTF16
  70596. if( encoding!=SQLITE_UTF8 ){
  70597. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  70598. if( rc ){
  70599. assert( rc==SQLITE_TOOBIG ); /* This is the only possible error here */
  70600. goto too_big;
  70601. }
  70602. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  70603. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  70604. assert( VdbeMemDynamic(pOut)==0 );
  70605. pOut->szMalloc = 0;
  70606. pOut->flags |= MEM_Static;
  70607. if( pOp->p4type==P4_DYNAMIC ){
  70608. sqlite3DbFree(db, pOp->p4.z);
  70609. }
  70610. pOp->p4type = P4_DYNAMIC;
  70611. pOp->p4.z = pOut->z;
  70612. pOp->p1 = pOut->n;
  70613. }
  70614. #endif
  70615. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70616. goto too_big;
  70617. }
  70618. /* Fall through to the next case, OP_String */
  70619. }
  70620. /* Opcode: String P1 P2 P3 P4 P5
  70621. ** Synopsis: r[P2]='P4' (len=P1)
  70622. **
  70623. ** The string value P4 of length P1 (bytes) is stored in register P2.
  70624. **
  70625. ** If P5!=0 and the content of register P3 is greater than zero, then
  70626. ** the datatype of the register P2 is converted to BLOB. The content is
  70627. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  70628. ** of a string, as if it had been CAST.
  70629. */
  70630. case OP_String: { /* out2 */
  70631. assert( pOp->p4.z!=0 );
  70632. pOut = out2Prerelease(p, pOp);
  70633. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  70634. pOut->z = pOp->p4.z;
  70635. pOut->n = pOp->p1;
  70636. pOut->enc = encoding;
  70637. UPDATE_MAX_BLOBSIZE(pOut);
  70638. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  70639. if( pOp->p5 ){
  70640. assert( pOp->p3>0 );
  70641. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  70642. pIn3 = &aMem[pOp->p3];
  70643. assert( pIn3->flags & MEM_Int );
  70644. if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  70645. }
  70646. #endif
  70647. break;
  70648. }
  70649. /* Opcode: Null P1 P2 P3 * *
  70650. ** Synopsis: r[P2..P3]=NULL
  70651. **
  70652. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  70653. ** NULL into register P3 and every register in between P2 and P3. If P3
  70654. ** is less than P2 (typically P3 is zero) then only register P2 is
  70655. ** set to NULL.
  70656. **
  70657. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  70658. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  70659. ** OP_Ne or OP_Eq.
  70660. */
  70661. case OP_Null: { /* out2 */
  70662. int cnt;
  70663. u16 nullFlag;
  70664. pOut = out2Prerelease(p, pOp);
  70665. cnt = pOp->p3-pOp->p2;
  70666. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  70667. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  70668. while( cnt>0 ){
  70669. pOut++;
  70670. memAboutToChange(p, pOut);
  70671. sqlite3VdbeMemSetNull(pOut);
  70672. pOut->flags = nullFlag;
  70673. cnt--;
  70674. }
  70675. break;
  70676. }
  70677. /* Opcode: SoftNull P1 * * * *
  70678. ** Synopsis: r[P1]=NULL
  70679. **
  70680. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  70681. ** instruction, but do not free any string or blob memory associated with
  70682. ** the register, so that if the value was a string or blob that was
  70683. ** previously copied using OP_SCopy, the copies will continue to be valid.
  70684. */
  70685. case OP_SoftNull: {
  70686. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  70687. pOut = &aMem[pOp->p1];
  70688. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  70689. break;
  70690. }
  70691. /* Opcode: Blob P1 P2 * P4 *
  70692. ** Synopsis: r[P2]=P4 (len=P1)
  70693. **
  70694. ** P4 points to a blob of data P1 bytes long. Store this
  70695. ** blob in register P2.
  70696. */
  70697. case OP_Blob: { /* out2 */
  70698. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  70699. pOut = out2Prerelease(p, pOp);
  70700. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  70701. pOut->enc = encoding;
  70702. UPDATE_MAX_BLOBSIZE(pOut);
  70703. break;
  70704. }
  70705. /* Opcode: Variable P1 P2 * P4 *
  70706. ** Synopsis: r[P2]=parameter(P1,P4)
  70707. **
  70708. ** Transfer the values of bound parameter P1 into register P2
  70709. **
  70710. ** If the parameter is named, then its name appears in P4.
  70711. ** The P4 value is used by sqlite3_bind_parameter_name().
  70712. */
  70713. case OP_Variable: { /* out2 */
  70714. Mem *pVar; /* Value being transferred */
  70715. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  70716. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  70717. pVar = &p->aVar[pOp->p1 - 1];
  70718. if( sqlite3VdbeMemTooBig(pVar) ){
  70719. goto too_big;
  70720. }
  70721. pOut = out2Prerelease(p, pOp);
  70722. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  70723. UPDATE_MAX_BLOBSIZE(pOut);
  70724. break;
  70725. }
  70726. /* Opcode: Move P1 P2 P3 * *
  70727. ** Synopsis: r[P2@P3]=r[P1@P3]
  70728. **
  70729. ** Move the P3 values in register P1..P1+P3-1 over into
  70730. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  70731. ** left holding a NULL. It is an error for register ranges
  70732. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  70733. ** for P3 to be less than 1.
  70734. */
  70735. case OP_Move: {
  70736. int n; /* Number of registers left to copy */
  70737. int p1; /* Register to copy from */
  70738. int p2; /* Register to copy to */
  70739. n = pOp->p3;
  70740. p1 = pOp->p1;
  70741. p2 = pOp->p2;
  70742. assert( n>0 && p1>0 && p2>0 );
  70743. assert( p1+n<=p2 || p2+n<=p1 );
  70744. pIn1 = &aMem[p1];
  70745. pOut = &aMem[p2];
  70746. do{
  70747. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  70748. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  70749. assert( memIsValid(pIn1) );
  70750. memAboutToChange(p, pOut);
  70751. sqlite3VdbeMemMove(pOut, pIn1);
  70752. #ifdef SQLITE_DEBUG
  70753. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  70754. pOut->pScopyFrom += pOp->p2 - p1;
  70755. }
  70756. #endif
  70757. Deephemeralize(pOut);
  70758. REGISTER_TRACE(p2++, pOut);
  70759. pIn1++;
  70760. pOut++;
  70761. }while( --n );
  70762. break;
  70763. }
  70764. /* Opcode: Copy P1 P2 P3 * *
  70765. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  70766. **
  70767. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  70768. **
  70769. ** This instruction makes a deep copy of the value. A duplicate
  70770. ** is made of any string or blob constant. See also OP_SCopy.
  70771. */
  70772. case OP_Copy: {
  70773. int n;
  70774. n = pOp->p3;
  70775. pIn1 = &aMem[pOp->p1];
  70776. pOut = &aMem[pOp->p2];
  70777. assert( pOut!=pIn1 );
  70778. while( 1 ){
  70779. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  70780. Deephemeralize(pOut);
  70781. #ifdef SQLITE_DEBUG
  70782. pOut->pScopyFrom = 0;
  70783. #endif
  70784. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  70785. if( (n--)==0 ) break;
  70786. pOut++;
  70787. pIn1++;
  70788. }
  70789. break;
  70790. }
  70791. /* Opcode: SCopy P1 P2 * * *
  70792. ** Synopsis: r[P2]=r[P1]
  70793. **
  70794. ** Make a shallow copy of register P1 into register P2.
  70795. **
  70796. ** This instruction makes a shallow copy of the value. If the value
  70797. ** is a string or blob, then the copy is only a pointer to the
  70798. ** original and hence if the original changes so will the copy.
  70799. ** Worse, if the original is deallocated, the copy becomes invalid.
  70800. ** Thus the program must guarantee that the original will not change
  70801. ** during the lifetime of the copy. Use OP_Copy to make a complete
  70802. ** copy.
  70803. */
  70804. case OP_SCopy: { /* out2 */
  70805. pIn1 = &aMem[pOp->p1];
  70806. pOut = &aMem[pOp->p2];
  70807. assert( pOut!=pIn1 );
  70808. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  70809. #ifdef SQLITE_DEBUG
  70810. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  70811. #endif
  70812. break;
  70813. }
  70814. /* Opcode: IntCopy P1 P2 * * *
  70815. ** Synopsis: r[P2]=r[P1]
  70816. **
  70817. ** Transfer the integer value held in register P1 into register P2.
  70818. **
  70819. ** This is an optimized version of SCopy that works only for integer
  70820. ** values.
  70821. */
  70822. case OP_IntCopy: { /* out2 */
  70823. pIn1 = &aMem[pOp->p1];
  70824. assert( (pIn1->flags & MEM_Int)!=0 );
  70825. pOut = &aMem[pOp->p2];
  70826. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  70827. break;
  70828. }
  70829. /* Opcode: ResultRow P1 P2 * * *
  70830. ** Synopsis: output=r[P1@P2]
  70831. **
  70832. ** The registers P1 through P1+P2-1 contain a single row of
  70833. ** results. This opcode causes the sqlite3_step() call to terminate
  70834. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  70835. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  70836. ** the result row.
  70837. */
  70838. case OP_ResultRow: {
  70839. Mem *pMem;
  70840. int i;
  70841. assert( p->nResColumn==pOp->p2 );
  70842. assert( pOp->p1>0 );
  70843. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  70844. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  70845. /* Run the progress counter just before returning.
  70846. */
  70847. if( db->xProgress!=0
  70848. && nVmStep>=nProgressLimit
  70849. && db->xProgress(db->pProgressArg)!=0
  70850. ){
  70851. rc = SQLITE_INTERRUPT;
  70852. goto abort_due_to_error;
  70853. }
  70854. #endif
  70855. /* If this statement has violated immediate foreign key constraints, do
  70856. ** not return the number of rows modified. And do not RELEASE the statement
  70857. ** transaction. It needs to be rolled back. */
  70858. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  70859. assert( db->flags&SQLITE_CountRows );
  70860. assert( p->usesStmtJournal );
  70861. goto abort_due_to_error;
  70862. }
  70863. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  70864. ** DML statements invoke this opcode to return the number of rows
  70865. ** modified to the user. This is the only way that a VM that
  70866. ** opens a statement transaction may invoke this opcode.
  70867. **
  70868. ** In case this is such a statement, close any statement transaction
  70869. ** opened by this VM before returning control to the user. This is to
  70870. ** ensure that statement-transactions are always nested, not overlapping.
  70871. ** If the open statement-transaction is not closed here, then the user
  70872. ** may step another VM that opens its own statement transaction. This
  70873. ** may lead to overlapping statement transactions.
  70874. **
  70875. ** The statement transaction is never a top-level transaction. Hence
  70876. ** the RELEASE call below can never fail.
  70877. */
  70878. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  70879. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  70880. assert( rc==SQLITE_OK );
  70881. /* Invalidate all ephemeral cursor row caches */
  70882. p->cacheCtr = (p->cacheCtr + 2)|1;
  70883. /* Make sure the results of the current row are \000 terminated
  70884. ** and have an assigned type. The results are de-ephemeralized as
  70885. ** a side effect.
  70886. */
  70887. pMem = p->pResultSet = &aMem[pOp->p1];
  70888. for(i=0; i<pOp->p2; i++){
  70889. assert( memIsValid(&pMem[i]) );
  70890. Deephemeralize(&pMem[i]);
  70891. assert( (pMem[i].flags & MEM_Ephem)==0
  70892. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  70893. sqlite3VdbeMemNulTerminate(&pMem[i]);
  70894. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  70895. }
  70896. if( db->mallocFailed ) goto no_mem;
  70897. /* Return SQLITE_ROW
  70898. */
  70899. p->pc = (int)(pOp - aOp) + 1;
  70900. rc = SQLITE_ROW;
  70901. goto vdbe_return;
  70902. }
  70903. /* Opcode: Concat P1 P2 P3 * *
  70904. ** Synopsis: r[P3]=r[P2]+r[P1]
  70905. **
  70906. ** Add the text in register P1 onto the end of the text in
  70907. ** register P2 and store the result in register P3.
  70908. ** If either the P1 or P2 text are NULL then store NULL in P3.
  70909. **
  70910. ** P3 = P2 || P1
  70911. **
  70912. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  70913. ** if P3 is the same register as P2, the implementation is able
  70914. ** to avoid a memcpy().
  70915. */
  70916. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  70917. i64 nByte;
  70918. pIn1 = &aMem[pOp->p1];
  70919. pIn2 = &aMem[pOp->p2];
  70920. pOut = &aMem[pOp->p3];
  70921. assert( pIn1!=pOut );
  70922. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  70923. sqlite3VdbeMemSetNull(pOut);
  70924. break;
  70925. }
  70926. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  70927. Stringify(pIn1, encoding);
  70928. Stringify(pIn2, encoding);
  70929. nByte = pIn1->n + pIn2->n;
  70930. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70931. goto too_big;
  70932. }
  70933. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  70934. goto no_mem;
  70935. }
  70936. MemSetTypeFlag(pOut, MEM_Str);
  70937. if( pOut!=pIn2 ){
  70938. memcpy(pOut->z, pIn2->z, pIn2->n);
  70939. }
  70940. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  70941. pOut->z[nByte]=0;
  70942. pOut->z[nByte+1] = 0;
  70943. pOut->flags |= MEM_Term;
  70944. pOut->n = (int)nByte;
  70945. pOut->enc = encoding;
  70946. UPDATE_MAX_BLOBSIZE(pOut);
  70947. break;
  70948. }
  70949. /* Opcode: Add P1 P2 P3 * *
  70950. ** Synopsis: r[P3]=r[P1]+r[P2]
  70951. **
  70952. ** Add the value in register P1 to the value in register P2
  70953. ** and store the result in register P3.
  70954. ** If either input is NULL, the result is NULL.
  70955. */
  70956. /* Opcode: Multiply P1 P2 P3 * *
  70957. ** Synopsis: r[P3]=r[P1]*r[P2]
  70958. **
  70959. **
  70960. ** Multiply the value in register P1 by the value in register P2
  70961. ** and store the result in register P3.
  70962. ** If either input is NULL, the result is NULL.
  70963. */
  70964. /* Opcode: Subtract P1 P2 P3 * *
  70965. ** Synopsis: r[P3]=r[P2]-r[P1]
  70966. **
  70967. ** Subtract the value in register P1 from the value in register P2
  70968. ** and store the result in register P3.
  70969. ** If either input is NULL, the result is NULL.
  70970. */
  70971. /* Opcode: Divide P1 P2 P3 * *
  70972. ** Synopsis: r[P3]=r[P2]/r[P1]
  70973. **
  70974. ** Divide the value in register P1 by the value in register P2
  70975. ** and store the result in register P3 (P3=P2/P1). If the value in
  70976. ** register P1 is zero, then the result is NULL. If either input is
  70977. ** NULL, the result is NULL.
  70978. */
  70979. /* Opcode: Remainder P1 P2 P3 * *
  70980. ** Synopsis: r[P3]=r[P2]%r[P1]
  70981. **
  70982. ** Compute the remainder after integer register P2 is divided by
  70983. ** register P1 and store the result in register P3.
  70984. ** If the value in register P1 is zero the result is NULL.
  70985. ** If either operand is NULL, the result is NULL.
  70986. */
  70987. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  70988. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  70989. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  70990. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  70991. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  70992. char bIntint; /* Started out as two integer operands */
  70993. u16 flags; /* Combined MEM_* flags from both inputs */
  70994. u16 type1; /* Numeric type of left operand */
  70995. u16 type2; /* Numeric type of right operand */
  70996. i64 iA; /* Integer value of left operand */
  70997. i64 iB; /* Integer value of right operand */
  70998. double rA; /* Real value of left operand */
  70999. double rB; /* Real value of right operand */
  71000. pIn1 = &aMem[pOp->p1];
  71001. type1 = numericType(pIn1);
  71002. pIn2 = &aMem[pOp->p2];
  71003. type2 = numericType(pIn2);
  71004. pOut = &aMem[pOp->p3];
  71005. flags = pIn1->flags | pIn2->flags;
  71006. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  71007. if( (type1 & type2 & MEM_Int)!=0 ){
  71008. iA = pIn1->u.i;
  71009. iB = pIn2->u.i;
  71010. bIntint = 1;
  71011. switch( pOp->opcode ){
  71012. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  71013. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  71014. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  71015. case OP_Divide: {
  71016. if( iA==0 ) goto arithmetic_result_is_null;
  71017. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  71018. iB /= iA;
  71019. break;
  71020. }
  71021. default: {
  71022. if( iA==0 ) goto arithmetic_result_is_null;
  71023. if( iA==-1 ) iA = 1;
  71024. iB %= iA;
  71025. break;
  71026. }
  71027. }
  71028. pOut->u.i = iB;
  71029. MemSetTypeFlag(pOut, MEM_Int);
  71030. }else{
  71031. bIntint = 0;
  71032. fp_math:
  71033. rA = sqlite3VdbeRealValue(pIn1);
  71034. rB = sqlite3VdbeRealValue(pIn2);
  71035. switch( pOp->opcode ){
  71036. case OP_Add: rB += rA; break;
  71037. case OP_Subtract: rB -= rA; break;
  71038. case OP_Multiply: rB *= rA; break;
  71039. case OP_Divide: {
  71040. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  71041. if( rA==(double)0 ) goto arithmetic_result_is_null;
  71042. rB /= rA;
  71043. break;
  71044. }
  71045. default: {
  71046. iA = (i64)rA;
  71047. iB = (i64)rB;
  71048. if( iA==0 ) goto arithmetic_result_is_null;
  71049. if( iA==-1 ) iA = 1;
  71050. rB = (double)(iB % iA);
  71051. break;
  71052. }
  71053. }
  71054. #ifdef SQLITE_OMIT_FLOATING_POINT
  71055. pOut->u.i = rB;
  71056. MemSetTypeFlag(pOut, MEM_Int);
  71057. #else
  71058. if( sqlite3IsNaN(rB) ){
  71059. goto arithmetic_result_is_null;
  71060. }
  71061. pOut->u.r = rB;
  71062. MemSetTypeFlag(pOut, MEM_Real);
  71063. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  71064. sqlite3VdbeIntegerAffinity(pOut);
  71065. }
  71066. #endif
  71067. }
  71068. break;
  71069. arithmetic_result_is_null:
  71070. sqlite3VdbeMemSetNull(pOut);
  71071. break;
  71072. }
  71073. /* Opcode: CollSeq P1 * * P4
  71074. **
  71075. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  71076. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  71077. ** be returned. This is used by the built-in min(), max() and nullif()
  71078. ** functions.
  71079. **
  71080. ** If P1 is not zero, then it is a register that a subsequent min() or
  71081. ** max() aggregate will set to 1 if the current row is not the minimum or
  71082. ** maximum. The P1 register is initialized to 0 by this instruction.
  71083. **
  71084. ** The interface used by the implementation of the aforementioned functions
  71085. ** to retrieve the collation sequence set by this opcode is not available
  71086. ** publicly. Only built-in functions have access to this feature.
  71087. */
  71088. case OP_CollSeq: {
  71089. assert( pOp->p4type==P4_COLLSEQ );
  71090. if( pOp->p1 ){
  71091. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  71092. }
  71093. break;
  71094. }
  71095. /* Opcode: Function0 P1 P2 P3 P4 P5
  71096. ** Synopsis: r[P3]=func(r[P2@P5])
  71097. **
  71098. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  71099. ** defines the function) with P5 arguments taken from register P2 and
  71100. ** successors. The result of the function is stored in register P3.
  71101. ** Register P3 must not be one of the function inputs.
  71102. **
  71103. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  71104. ** function was determined to be constant at compile time. If the first
  71105. ** argument was constant then bit 0 of P1 is set. This is used to determine
  71106. ** whether meta data associated with a user function argument using the
  71107. ** sqlite3_set_auxdata() API may be safely retained until the next
  71108. ** invocation of this opcode.
  71109. **
  71110. ** See also: Function, AggStep, AggFinal
  71111. */
  71112. /* Opcode: Function P1 P2 P3 P4 P5
  71113. ** Synopsis: r[P3]=func(r[P2@P5])
  71114. **
  71115. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  71116. ** contains a pointer to the function to be run) with P5 arguments taken
  71117. ** from register P2 and successors. The result of the function is stored
  71118. ** in register P3. Register P3 must not be one of the function inputs.
  71119. **
  71120. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  71121. ** function was determined to be constant at compile time. If the first
  71122. ** argument was constant then bit 0 of P1 is set. This is used to determine
  71123. ** whether meta data associated with a user function argument using the
  71124. ** sqlite3_set_auxdata() API may be safely retained until the next
  71125. ** invocation of this opcode.
  71126. **
  71127. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  71128. ** to a FuncDef object. But on first evaluation, the P4 operand is
  71129. ** automatically converted into an sqlite3_context object and the operation
  71130. ** changed to this OP_Function opcode. In this way, the initialization of
  71131. ** the sqlite3_context object occurs only once, rather than once for each
  71132. ** evaluation of the function.
  71133. **
  71134. ** See also: Function0, AggStep, AggFinal
  71135. */
  71136. case OP_Function0: {
  71137. int n;
  71138. sqlite3_context *pCtx;
  71139. assert( pOp->p4type==P4_FUNCDEF );
  71140. n = pOp->p5;
  71141. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  71142. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  71143. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  71144. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  71145. if( pCtx==0 ) goto no_mem;
  71146. pCtx->pOut = 0;
  71147. pCtx->pFunc = pOp->p4.pFunc;
  71148. pCtx->iOp = (int)(pOp - aOp);
  71149. pCtx->pVdbe = p;
  71150. pCtx->argc = n;
  71151. pOp->p4type = P4_FUNCCTX;
  71152. pOp->p4.pCtx = pCtx;
  71153. pOp->opcode = OP_Function;
  71154. /* Fall through into OP_Function */
  71155. }
  71156. case OP_Function: {
  71157. int i;
  71158. sqlite3_context *pCtx;
  71159. assert( pOp->p4type==P4_FUNCCTX );
  71160. pCtx = pOp->p4.pCtx;
  71161. /* If this function is inside of a trigger, the register array in aMem[]
  71162. ** might change from one evaluation to the next. The next block of code
  71163. ** checks to see if the register array has changed, and if so it
  71164. ** reinitializes the relavant parts of the sqlite3_context object */
  71165. pOut = &aMem[pOp->p3];
  71166. if( pCtx->pOut != pOut ){
  71167. pCtx->pOut = pOut;
  71168. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  71169. }
  71170. memAboutToChange(p, pCtx->pOut);
  71171. #ifdef SQLITE_DEBUG
  71172. for(i=0; i<pCtx->argc; i++){
  71173. assert( memIsValid(pCtx->argv[i]) );
  71174. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  71175. }
  71176. #endif
  71177. MemSetTypeFlag(pCtx->pOut, MEM_Null);
  71178. pCtx->fErrorOrAux = 0;
  71179. db->lastRowid = lastRowid;
  71180. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  71181. lastRowid = db->lastRowid; /* Remember rowid changes made by xSFunc */
  71182. /* If the function returned an error, throw an exception */
  71183. if( pCtx->fErrorOrAux ){
  71184. if( pCtx->isError ){
  71185. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  71186. rc = pCtx->isError;
  71187. }
  71188. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  71189. if( rc ) goto abort_due_to_error;
  71190. }
  71191. /* Copy the result of the function into register P3 */
  71192. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  71193. sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
  71194. if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
  71195. }
  71196. REGISTER_TRACE(pOp->p3, pCtx->pOut);
  71197. UPDATE_MAX_BLOBSIZE(pCtx->pOut);
  71198. break;
  71199. }
  71200. /* Opcode: BitAnd P1 P2 P3 * *
  71201. ** Synopsis: r[P3]=r[P1]&r[P2]
  71202. **
  71203. ** Take the bit-wise AND of the values in register P1 and P2 and
  71204. ** store the result in register P3.
  71205. ** If either input is NULL, the result is NULL.
  71206. */
  71207. /* Opcode: BitOr P1 P2 P3 * *
  71208. ** Synopsis: r[P3]=r[P1]|r[P2]
  71209. **
  71210. ** Take the bit-wise OR of the values in register P1 and P2 and
  71211. ** store the result in register P3.
  71212. ** If either input is NULL, the result is NULL.
  71213. */
  71214. /* Opcode: ShiftLeft P1 P2 P3 * *
  71215. ** Synopsis: r[P3]=r[P2]<<r[P1]
  71216. **
  71217. ** Shift the integer value in register P2 to the left by the
  71218. ** number of bits specified by the integer in register P1.
  71219. ** Store the result in register P3.
  71220. ** If either input is NULL, the result is NULL.
  71221. */
  71222. /* Opcode: ShiftRight P1 P2 P3 * *
  71223. ** Synopsis: r[P3]=r[P2]>>r[P1]
  71224. **
  71225. ** Shift the integer value in register P2 to the right by the
  71226. ** number of bits specified by the integer in register P1.
  71227. ** Store the result in register P3.
  71228. ** If either input is NULL, the result is NULL.
  71229. */
  71230. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  71231. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  71232. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  71233. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  71234. i64 iA;
  71235. u64 uA;
  71236. i64 iB;
  71237. u8 op;
  71238. pIn1 = &aMem[pOp->p1];
  71239. pIn2 = &aMem[pOp->p2];
  71240. pOut = &aMem[pOp->p3];
  71241. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  71242. sqlite3VdbeMemSetNull(pOut);
  71243. break;
  71244. }
  71245. iA = sqlite3VdbeIntValue(pIn2);
  71246. iB = sqlite3VdbeIntValue(pIn1);
  71247. op = pOp->opcode;
  71248. if( op==OP_BitAnd ){
  71249. iA &= iB;
  71250. }else if( op==OP_BitOr ){
  71251. iA |= iB;
  71252. }else if( iB!=0 ){
  71253. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  71254. /* If shifting by a negative amount, shift in the other direction */
  71255. if( iB<0 ){
  71256. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  71257. op = 2*OP_ShiftLeft + 1 - op;
  71258. iB = iB>(-64) ? -iB : 64;
  71259. }
  71260. if( iB>=64 ){
  71261. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  71262. }else{
  71263. memcpy(&uA, &iA, sizeof(uA));
  71264. if( op==OP_ShiftLeft ){
  71265. uA <<= iB;
  71266. }else{
  71267. uA >>= iB;
  71268. /* Sign-extend on a right shift of a negative number */
  71269. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  71270. }
  71271. memcpy(&iA, &uA, sizeof(iA));
  71272. }
  71273. }
  71274. pOut->u.i = iA;
  71275. MemSetTypeFlag(pOut, MEM_Int);
  71276. break;
  71277. }
  71278. /* Opcode: AddImm P1 P2 * * *
  71279. ** Synopsis: r[P1]=r[P1]+P2
  71280. **
  71281. ** Add the constant P2 to the value in register P1.
  71282. ** The result is always an integer.
  71283. **
  71284. ** To force any register to be an integer, just add 0.
  71285. */
  71286. case OP_AddImm: { /* in1 */
  71287. pIn1 = &aMem[pOp->p1];
  71288. memAboutToChange(p, pIn1);
  71289. sqlite3VdbeMemIntegerify(pIn1);
  71290. pIn1->u.i += pOp->p2;
  71291. break;
  71292. }
  71293. /* Opcode: MustBeInt P1 P2 * * *
  71294. **
  71295. ** Force the value in register P1 to be an integer. If the value
  71296. ** in P1 is not an integer and cannot be converted into an integer
  71297. ** without data loss, then jump immediately to P2, or if P2==0
  71298. ** raise an SQLITE_MISMATCH exception.
  71299. */
  71300. case OP_MustBeInt: { /* jump, in1 */
  71301. pIn1 = &aMem[pOp->p1];
  71302. if( (pIn1->flags & MEM_Int)==0 ){
  71303. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  71304. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  71305. if( (pIn1->flags & MEM_Int)==0 ){
  71306. if( pOp->p2==0 ){
  71307. rc = SQLITE_MISMATCH;
  71308. goto abort_due_to_error;
  71309. }else{
  71310. goto jump_to_p2;
  71311. }
  71312. }
  71313. }
  71314. MemSetTypeFlag(pIn1, MEM_Int);
  71315. break;
  71316. }
  71317. #ifndef SQLITE_OMIT_FLOATING_POINT
  71318. /* Opcode: RealAffinity P1 * * * *
  71319. **
  71320. ** If register P1 holds an integer convert it to a real value.
  71321. **
  71322. ** This opcode is used when extracting information from a column that
  71323. ** has REAL affinity. Such column values may still be stored as
  71324. ** integers, for space efficiency, but after extraction we want them
  71325. ** to have only a real value.
  71326. */
  71327. case OP_RealAffinity: { /* in1 */
  71328. pIn1 = &aMem[pOp->p1];
  71329. if( pIn1->flags & MEM_Int ){
  71330. sqlite3VdbeMemRealify(pIn1);
  71331. }
  71332. break;
  71333. }
  71334. #endif
  71335. #ifndef SQLITE_OMIT_CAST
  71336. /* Opcode: Cast P1 P2 * * *
  71337. ** Synopsis: affinity(r[P1])
  71338. **
  71339. ** Force the value in register P1 to be the type defined by P2.
  71340. **
  71341. ** <ul>
  71342. ** <li value="97"> TEXT
  71343. ** <li value="98"> BLOB
  71344. ** <li value="99"> NUMERIC
  71345. ** <li value="100"> INTEGER
  71346. ** <li value="101"> REAL
  71347. ** </ul>
  71348. **
  71349. ** A NULL value is not changed by this routine. It remains NULL.
  71350. */
  71351. case OP_Cast: { /* in1 */
  71352. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  71353. testcase( pOp->p2==SQLITE_AFF_TEXT );
  71354. testcase( pOp->p2==SQLITE_AFF_BLOB );
  71355. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  71356. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  71357. testcase( pOp->p2==SQLITE_AFF_REAL );
  71358. pIn1 = &aMem[pOp->p1];
  71359. memAboutToChange(p, pIn1);
  71360. rc = ExpandBlob(pIn1);
  71361. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  71362. UPDATE_MAX_BLOBSIZE(pIn1);
  71363. if( rc ) goto abort_due_to_error;
  71364. break;
  71365. }
  71366. #endif /* SQLITE_OMIT_CAST */
  71367. /* Opcode: Lt P1 P2 P3 P4 P5
  71368. ** Synopsis: if r[P1]<r[P3] goto P2
  71369. **
  71370. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  71371. ** jump to address P2.
  71372. **
  71373. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  71374. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  71375. ** bit is clear then fall through if either operand is NULL.
  71376. **
  71377. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  71378. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  71379. ** to coerce both inputs according to this affinity before the
  71380. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  71381. ** affinity is used. Note that the affinity conversions are stored
  71382. ** back into the input registers P1 and P3. So this opcode can cause
  71383. ** persistent changes to registers P1 and P3.
  71384. **
  71385. ** Once any conversions have taken place, and neither value is NULL,
  71386. ** the values are compared. If both values are blobs then memcmp() is
  71387. ** used to determine the results of the comparison. If both values
  71388. ** are text, then the appropriate collating function specified in
  71389. ** P4 is used to do the comparison. If P4 is not specified then
  71390. ** memcmp() is used to compare text string. If both values are
  71391. ** numeric, then a numeric comparison is used. If the two values
  71392. ** are of different types, then numbers are considered less than
  71393. ** strings and strings are considered less than blobs.
  71394. **
  71395. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  71396. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  71397. **
  71398. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  71399. ** equal to one another, provided that they do not have their MEM_Cleared
  71400. ** bit set.
  71401. */
  71402. /* Opcode: Ne P1 P2 P3 P4 P5
  71403. ** Synopsis: if r[P1]!=r[P3] goto P2
  71404. **
  71405. ** This works just like the Lt opcode except that the jump is taken if
  71406. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  71407. ** additional information.
  71408. **
  71409. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  71410. ** true or false and is never NULL. If both operands are NULL then the result
  71411. ** of comparison is false. If either operand is NULL then the result is true.
  71412. ** If neither operand is NULL the result is the same as it would be if
  71413. ** the SQLITE_NULLEQ flag were omitted from P5.
  71414. */
  71415. /* Opcode: Eq P1 P2 P3 P4 P5
  71416. ** Synopsis: if r[P1]==r[P3] goto P2
  71417. **
  71418. ** This works just like the Lt opcode except that the jump is taken if
  71419. ** the operands in registers P1 and P3 are equal.
  71420. ** See the Lt opcode for additional information.
  71421. **
  71422. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  71423. ** true or false and is never NULL. If both operands are NULL then the result
  71424. ** of comparison is true. If either operand is NULL then the result is false.
  71425. ** If neither operand is NULL the result is the same as it would be if
  71426. ** the SQLITE_NULLEQ flag were omitted from P5.
  71427. */
  71428. /* Opcode: Le P1 P2 P3 P4 P5
  71429. ** Synopsis: if r[P1]<=r[P3] goto P2
  71430. **
  71431. ** This works just like the Lt opcode except that the jump is taken if
  71432. ** the content of register P3 is less than or equal to the content of
  71433. ** register P1. See the Lt opcode for additional information.
  71434. */
  71435. /* Opcode: Gt P1 P2 P3 P4 P5
  71436. ** Synopsis: if r[P1]>r[P3] goto P2
  71437. **
  71438. ** This works just like the Lt opcode except that the jump is taken if
  71439. ** the content of register P3 is greater than the content of
  71440. ** register P1. See the Lt opcode for additional information.
  71441. */
  71442. /* Opcode: Ge P1 P2 P3 P4 P5
  71443. ** Synopsis: if r[P1]>=r[P3] goto P2
  71444. **
  71445. ** This works just like the Lt opcode except that the jump is taken if
  71446. ** the content of register P3 is greater than or equal to the content of
  71447. ** register P1. See the Lt opcode for additional information.
  71448. */
  71449. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  71450. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  71451. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  71452. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  71453. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  71454. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  71455. int res; /* Result of the comparison of pIn1 against pIn3 */
  71456. char affinity; /* Affinity to use for comparison */
  71457. u16 flags1; /* Copy of initial value of pIn1->flags */
  71458. u16 flags3; /* Copy of initial value of pIn3->flags */
  71459. pIn1 = &aMem[pOp->p1];
  71460. pIn3 = &aMem[pOp->p3];
  71461. flags1 = pIn1->flags;
  71462. flags3 = pIn3->flags;
  71463. if( (flags1 | flags3)&MEM_Null ){
  71464. /* One or both operands are NULL */
  71465. if( pOp->p5 & SQLITE_NULLEQ ){
  71466. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  71467. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  71468. ** or not both operands are null.
  71469. */
  71470. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  71471. assert( (flags1 & MEM_Cleared)==0 );
  71472. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  71473. if( (flags1&MEM_Null)!=0
  71474. && (flags3&MEM_Null)!=0
  71475. && (flags3&MEM_Cleared)==0
  71476. ){
  71477. res = 0; /* Results are equal */
  71478. }else{
  71479. res = 1; /* Results are not equal */
  71480. }
  71481. }else{
  71482. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  71483. ** then the result is always NULL.
  71484. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  71485. */
  71486. if( pOp->p5 & SQLITE_STOREP2 ){
  71487. pOut = &aMem[pOp->p2];
  71488. memAboutToChange(p, pOut);
  71489. MemSetTypeFlag(pOut, MEM_Null);
  71490. REGISTER_TRACE(pOp->p2, pOut);
  71491. }else{
  71492. VdbeBranchTaken(2,3);
  71493. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  71494. goto jump_to_p2;
  71495. }
  71496. }
  71497. break;
  71498. }
  71499. }else{
  71500. /* Neither operand is NULL. Do a comparison. */
  71501. affinity = pOp->p5 & SQLITE_AFF_MASK;
  71502. if( affinity>=SQLITE_AFF_NUMERIC ){
  71503. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  71504. applyNumericAffinity(pIn1,0);
  71505. }
  71506. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  71507. applyNumericAffinity(pIn3,0);
  71508. }
  71509. }else if( affinity==SQLITE_AFF_TEXT ){
  71510. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  71511. testcase( pIn1->flags & MEM_Int );
  71512. testcase( pIn1->flags & MEM_Real );
  71513. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  71514. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  71515. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  71516. }
  71517. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  71518. testcase( pIn3->flags & MEM_Int );
  71519. testcase( pIn3->flags & MEM_Real );
  71520. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  71521. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  71522. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  71523. }
  71524. }
  71525. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  71526. if( flags1 & MEM_Zero ){
  71527. sqlite3VdbeMemExpandBlob(pIn1);
  71528. flags1 &= ~MEM_Zero;
  71529. }
  71530. if( flags3 & MEM_Zero ){
  71531. sqlite3VdbeMemExpandBlob(pIn3);
  71532. flags3 &= ~MEM_Zero;
  71533. }
  71534. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  71535. }
  71536. switch( pOp->opcode ){
  71537. case OP_Eq: res = res==0; break;
  71538. case OP_Ne: res = res!=0; break;
  71539. case OP_Lt: res = res<0; break;
  71540. case OP_Le: res = res<=0; break;
  71541. case OP_Gt: res = res>0; break;
  71542. default: res = res>=0; break;
  71543. }
  71544. /* Undo any changes made by applyAffinity() to the input registers. */
  71545. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  71546. pIn1->flags = flags1;
  71547. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  71548. pIn3->flags = flags3;
  71549. if( pOp->p5 & SQLITE_STOREP2 ){
  71550. pOut = &aMem[pOp->p2];
  71551. memAboutToChange(p, pOut);
  71552. MemSetTypeFlag(pOut, MEM_Int);
  71553. pOut->u.i = res;
  71554. REGISTER_TRACE(pOp->p2, pOut);
  71555. }else{
  71556. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  71557. if( res ){
  71558. goto jump_to_p2;
  71559. }
  71560. }
  71561. break;
  71562. }
  71563. /* Opcode: Permutation * * * P4 *
  71564. **
  71565. ** Set the permutation used by the OP_Compare operator to be the array
  71566. ** of integers in P4.
  71567. **
  71568. ** The permutation is only valid until the next OP_Compare that has
  71569. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  71570. ** occur immediately prior to the OP_Compare.
  71571. **
  71572. ** The first integer in the P4 integer array is the length of the array
  71573. ** and does not become part of the permutation.
  71574. */
  71575. case OP_Permutation: {
  71576. assert( pOp->p4type==P4_INTARRAY );
  71577. assert( pOp->p4.ai );
  71578. aPermute = pOp->p4.ai + 1;
  71579. break;
  71580. }
  71581. /* Opcode: Compare P1 P2 P3 P4 P5
  71582. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  71583. **
  71584. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  71585. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  71586. ** the comparison for use by the next OP_Jump instruct.
  71587. **
  71588. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  71589. ** determined by the most recent OP_Permutation operator. If the
  71590. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  71591. ** order.
  71592. **
  71593. ** P4 is a KeyInfo structure that defines collating sequences and sort
  71594. ** orders for the comparison. The permutation applies to registers
  71595. ** only. The KeyInfo elements are used sequentially.
  71596. **
  71597. ** The comparison is a sort comparison, so NULLs compare equal,
  71598. ** NULLs are less than numbers, numbers are less than strings,
  71599. ** and strings are less than blobs.
  71600. */
  71601. case OP_Compare: {
  71602. int n;
  71603. int i;
  71604. int p1;
  71605. int p2;
  71606. const KeyInfo *pKeyInfo;
  71607. int idx;
  71608. CollSeq *pColl; /* Collating sequence to use on this term */
  71609. int bRev; /* True for DESCENDING sort order */
  71610. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  71611. n = pOp->p3;
  71612. pKeyInfo = pOp->p4.pKeyInfo;
  71613. assert( n>0 );
  71614. assert( pKeyInfo!=0 );
  71615. p1 = pOp->p1;
  71616. p2 = pOp->p2;
  71617. #if SQLITE_DEBUG
  71618. if( aPermute ){
  71619. int k, mx = 0;
  71620. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  71621. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  71622. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  71623. }else{
  71624. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  71625. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  71626. }
  71627. #endif /* SQLITE_DEBUG */
  71628. for(i=0; i<n; i++){
  71629. idx = aPermute ? aPermute[i] : i;
  71630. assert( memIsValid(&aMem[p1+idx]) );
  71631. assert( memIsValid(&aMem[p2+idx]) );
  71632. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  71633. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  71634. assert( i<pKeyInfo->nField );
  71635. pColl = pKeyInfo->aColl[i];
  71636. bRev = pKeyInfo->aSortOrder[i];
  71637. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  71638. if( iCompare ){
  71639. if( bRev ) iCompare = -iCompare;
  71640. break;
  71641. }
  71642. }
  71643. aPermute = 0;
  71644. break;
  71645. }
  71646. /* Opcode: Jump P1 P2 P3 * *
  71647. **
  71648. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  71649. ** in the most recent OP_Compare instruction the P1 vector was less than
  71650. ** equal to, or greater than the P2 vector, respectively.
  71651. */
  71652. case OP_Jump: { /* jump */
  71653. if( iCompare<0 ){
  71654. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  71655. }else if( iCompare==0 ){
  71656. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  71657. }else{
  71658. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  71659. }
  71660. break;
  71661. }
  71662. /* Opcode: And P1 P2 P3 * *
  71663. ** Synopsis: r[P3]=(r[P1] && r[P2])
  71664. **
  71665. ** Take the logical AND of the values in registers P1 and P2 and
  71666. ** write the result into register P3.
  71667. **
  71668. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  71669. ** the other input is NULL. A NULL and true or two NULLs give
  71670. ** a NULL output.
  71671. */
  71672. /* Opcode: Or P1 P2 P3 * *
  71673. ** Synopsis: r[P3]=(r[P1] || r[P2])
  71674. **
  71675. ** Take the logical OR of the values in register P1 and P2 and
  71676. ** store the answer in register P3.
  71677. **
  71678. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  71679. ** even if the other input is NULL. A NULL and false or two NULLs
  71680. ** give a NULL output.
  71681. */
  71682. case OP_And: /* same as TK_AND, in1, in2, out3 */
  71683. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  71684. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  71685. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  71686. pIn1 = &aMem[pOp->p1];
  71687. if( pIn1->flags & MEM_Null ){
  71688. v1 = 2;
  71689. }else{
  71690. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  71691. }
  71692. pIn2 = &aMem[pOp->p2];
  71693. if( pIn2->flags & MEM_Null ){
  71694. v2 = 2;
  71695. }else{
  71696. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  71697. }
  71698. if( pOp->opcode==OP_And ){
  71699. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  71700. v1 = and_logic[v1*3+v2];
  71701. }else{
  71702. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  71703. v1 = or_logic[v1*3+v2];
  71704. }
  71705. pOut = &aMem[pOp->p3];
  71706. if( v1==2 ){
  71707. MemSetTypeFlag(pOut, MEM_Null);
  71708. }else{
  71709. pOut->u.i = v1;
  71710. MemSetTypeFlag(pOut, MEM_Int);
  71711. }
  71712. break;
  71713. }
  71714. /* Opcode: Not P1 P2 * * *
  71715. ** Synopsis: r[P2]= !r[P1]
  71716. **
  71717. ** Interpret the value in register P1 as a boolean value. Store the
  71718. ** boolean complement in register P2. If the value in register P1 is
  71719. ** NULL, then a NULL is stored in P2.
  71720. */
  71721. case OP_Not: { /* same as TK_NOT, in1, out2 */
  71722. pIn1 = &aMem[pOp->p1];
  71723. pOut = &aMem[pOp->p2];
  71724. sqlite3VdbeMemSetNull(pOut);
  71725. if( (pIn1->flags & MEM_Null)==0 ){
  71726. pOut->flags = MEM_Int;
  71727. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  71728. }
  71729. break;
  71730. }
  71731. /* Opcode: BitNot P1 P2 * * *
  71732. ** Synopsis: r[P1]= ~r[P1]
  71733. **
  71734. ** Interpret the content of register P1 as an integer. Store the
  71735. ** ones-complement of the P1 value into register P2. If P1 holds
  71736. ** a NULL then store a NULL in P2.
  71737. */
  71738. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  71739. pIn1 = &aMem[pOp->p1];
  71740. pOut = &aMem[pOp->p2];
  71741. sqlite3VdbeMemSetNull(pOut);
  71742. if( (pIn1->flags & MEM_Null)==0 ){
  71743. pOut->flags = MEM_Int;
  71744. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  71745. }
  71746. break;
  71747. }
  71748. /* Opcode: Once P1 P2 * * *
  71749. **
  71750. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  71751. ** Otherwise, set the flag and fall through to the next instruction.
  71752. ** In other words, this opcode causes all following opcodes up through P2
  71753. ** (but not including P2) to run just once and to be skipped on subsequent
  71754. ** times through the loop.
  71755. **
  71756. ** All "once" flags are initially cleared whenever a prepared statement
  71757. ** first begins to run.
  71758. */
  71759. case OP_Once: { /* jump */
  71760. assert( pOp->p1<p->nOnceFlag );
  71761. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  71762. if( p->aOnceFlag[pOp->p1] ){
  71763. goto jump_to_p2;
  71764. }else{
  71765. p->aOnceFlag[pOp->p1] = 1;
  71766. }
  71767. break;
  71768. }
  71769. /* Opcode: If P1 P2 P3 * *
  71770. **
  71771. ** Jump to P2 if the value in register P1 is true. The value
  71772. ** is considered true if it is numeric and non-zero. If the value
  71773. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  71774. */
  71775. /* Opcode: IfNot P1 P2 P3 * *
  71776. **
  71777. ** Jump to P2 if the value in register P1 is False. The value
  71778. ** is considered false if it has a numeric value of zero. If the value
  71779. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  71780. */
  71781. case OP_If: /* jump, in1 */
  71782. case OP_IfNot: { /* jump, in1 */
  71783. int c;
  71784. pIn1 = &aMem[pOp->p1];
  71785. if( pIn1->flags & MEM_Null ){
  71786. c = pOp->p3;
  71787. }else{
  71788. #ifdef SQLITE_OMIT_FLOATING_POINT
  71789. c = sqlite3VdbeIntValue(pIn1)!=0;
  71790. #else
  71791. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  71792. #endif
  71793. if( pOp->opcode==OP_IfNot ) c = !c;
  71794. }
  71795. VdbeBranchTaken(c!=0, 2);
  71796. if( c ){
  71797. goto jump_to_p2;
  71798. }
  71799. break;
  71800. }
  71801. /* Opcode: IsNull P1 P2 * * *
  71802. ** Synopsis: if r[P1]==NULL goto P2
  71803. **
  71804. ** Jump to P2 if the value in register P1 is NULL.
  71805. */
  71806. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  71807. pIn1 = &aMem[pOp->p1];
  71808. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  71809. if( (pIn1->flags & MEM_Null)!=0 ){
  71810. goto jump_to_p2;
  71811. }
  71812. break;
  71813. }
  71814. /* Opcode: NotNull P1 P2 * * *
  71815. ** Synopsis: if r[P1]!=NULL goto P2
  71816. **
  71817. ** Jump to P2 if the value in register P1 is not NULL.
  71818. */
  71819. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  71820. pIn1 = &aMem[pOp->p1];
  71821. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  71822. if( (pIn1->flags & MEM_Null)==0 ){
  71823. goto jump_to_p2;
  71824. }
  71825. break;
  71826. }
  71827. /* Opcode: Column P1 P2 P3 P4 P5
  71828. ** Synopsis: r[P3]=PX
  71829. **
  71830. ** Interpret the data that cursor P1 points to as a structure built using
  71831. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  71832. ** information about the format of the data.) Extract the P2-th column
  71833. ** from this record. If there are less that (P2+1)
  71834. ** values in the record, extract a NULL.
  71835. **
  71836. ** The value extracted is stored in register P3.
  71837. **
  71838. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  71839. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  71840. ** the result.
  71841. **
  71842. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  71843. ** then the cache of the cursor is reset prior to extracting the column.
  71844. ** The first OP_Column against a pseudo-table after the value of the content
  71845. ** register has changed should have this bit set.
  71846. **
  71847. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  71848. ** the result is guaranteed to only be used as the argument of a length()
  71849. ** or typeof() function, respectively. The loading of large blobs can be
  71850. ** skipped for length() and all content loading can be skipped for typeof().
  71851. */
  71852. case OP_Column: {
  71853. i64 payloadSize64; /* Number of bytes in the record */
  71854. int p2; /* column number to retrieve */
  71855. VdbeCursor *pC; /* The VDBE cursor */
  71856. BtCursor *pCrsr; /* The BTree cursor */
  71857. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  71858. int len; /* The length of the serialized data for the column */
  71859. int i; /* Loop counter */
  71860. Mem *pDest; /* Where to write the extracted value */
  71861. Mem sMem; /* For storing the record being decoded */
  71862. const u8 *zData; /* Part of the record being decoded */
  71863. const u8 *zHdr; /* Next unparsed byte of the header */
  71864. const u8 *zEndHdr; /* Pointer to first byte after the header */
  71865. u32 offset; /* Offset into the data */
  71866. u64 offset64; /* 64-bit offset */
  71867. u32 avail; /* Number of bytes of available data */
  71868. u32 t; /* A type code from the record header */
  71869. Mem *pReg; /* PseudoTable input register */
  71870. pC = p->apCsr[pOp->p1];
  71871. p2 = pOp->p2;
  71872. /* If the cursor cache is stale, bring it up-to-date */
  71873. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  71874. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  71875. pDest = &aMem[pOp->p3];
  71876. memAboutToChange(p, pDest);
  71877. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71878. assert( pC!=0 );
  71879. assert( p2<pC->nField );
  71880. aOffset = pC->aOffset;
  71881. assert( pC->eCurType!=CURTYPE_VTAB );
  71882. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  71883. assert( pC->eCurType!=CURTYPE_SORTER );
  71884. pCrsr = pC->uc.pCursor;
  71885. if( rc ) goto abort_due_to_error;
  71886. if( pC->cacheStatus!=p->cacheCtr ){
  71887. if( pC->nullRow ){
  71888. if( pC->eCurType==CURTYPE_PSEUDO ){
  71889. assert( pC->uc.pseudoTableReg>0 );
  71890. pReg = &aMem[pC->uc.pseudoTableReg];
  71891. assert( pReg->flags & MEM_Blob );
  71892. assert( memIsValid(pReg) );
  71893. pC->payloadSize = pC->szRow = avail = pReg->n;
  71894. pC->aRow = (u8*)pReg->z;
  71895. }else{
  71896. sqlite3VdbeMemSetNull(pDest);
  71897. goto op_column_out;
  71898. }
  71899. }else{
  71900. assert( pC->eCurType==CURTYPE_BTREE );
  71901. assert( pCrsr );
  71902. if( pC->isTable==0 ){
  71903. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  71904. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  71905. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  71906. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  71907. ** payload size, so it is impossible for payloadSize64 to be
  71908. ** larger than 32 bits. */
  71909. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  71910. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  71911. pC->payloadSize = (u32)payloadSize64;
  71912. }else{
  71913. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  71914. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  71915. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  71916. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  71917. }
  71918. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  71919. if( pC->payloadSize <= (u32)avail ){
  71920. pC->szRow = pC->payloadSize;
  71921. }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71922. goto too_big;
  71923. }else{
  71924. pC->szRow = avail;
  71925. }
  71926. }
  71927. pC->cacheStatus = p->cacheCtr;
  71928. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  71929. pC->nHdrParsed = 0;
  71930. aOffset[0] = offset;
  71931. if( avail<offset ){
  71932. /* pC->aRow does not have to hold the entire row, but it does at least
  71933. ** need to cover the header of the record. If pC->aRow does not contain
  71934. ** the complete header, then set it to zero, forcing the header to be
  71935. ** dynamically allocated. */
  71936. pC->aRow = 0;
  71937. pC->szRow = 0;
  71938. /* Make sure a corrupt database has not given us an oversize header.
  71939. ** Do this now to avoid an oversize memory allocation.
  71940. **
  71941. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  71942. ** types use so much data space that there can only be 4096 and 32 of
  71943. ** them, respectively. So the maximum header length results from a
  71944. ** 3-byte type for each of the maximum of 32768 columns plus three
  71945. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  71946. */
  71947. if( offset > 98307 || offset > pC->payloadSize ){
  71948. rc = SQLITE_CORRUPT_BKPT;
  71949. goto abort_due_to_error;
  71950. }
  71951. }
  71952. /* The following goto is an optimization. It can be omitted and
  71953. ** everything will still work. But OP_Column is measurably faster
  71954. ** by skipping the subsequent conditional, which is always true.
  71955. */
  71956. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  71957. goto op_column_read_header;
  71958. }
  71959. /* Make sure at least the first p2+1 entries of the header have been
  71960. ** parsed and valid information is in aOffset[] and pC->aType[].
  71961. */
  71962. if( pC->nHdrParsed<=p2 ){
  71963. /* If there is more header available for parsing in the record, try
  71964. ** to extract additional fields up through the p2+1-th field
  71965. */
  71966. op_column_read_header:
  71967. if( pC->iHdrOffset<aOffset[0] ){
  71968. /* Make sure zData points to enough of the record to cover the header. */
  71969. if( pC->aRow==0 ){
  71970. memset(&sMem, 0, sizeof(sMem));
  71971. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
  71972. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71973. zData = (u8*)sMem.z;
  71974. }else{
  71975. zData = pC->aRow;
  71976. }
  71977. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  71978. i = pC->nHdrParsed;
  71979. offset64 = aOffset[i];
  71980. zHdr = zData + pC->iHdrOffset;
  71981. zEndHdr = zData + aOffset[0];
  71982. assert( i<=p2 && zHdr<zEndHdr );
  71983. do{
  71984. if( (t = zHdr[0])<0x80 ){
  71985. zHdr++;
  71986. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  71987. }else{
  71988. zHdr += sqlite3GetVarint32(zHdr, &t);
  71989. offset64 += sqlite3VdbeSerialTypeLen(t);
  71990. }
  71991. pC->aType[i++] = t;
  71992. aOffset[i] = (u32)(offset64 & 0xffffffff);
  71993. }while( i<=p2 && zHdr<zEndHdr );
  71994. pC->nHdrParsed = i;
  71995. pC->iHdrOffset = (u32)(zHdr - zData);
  71996. /* The record is corrupt if any of the following are true:
  71997. ** (1) the bytes of the header extend past the declared header size
  71998. ** (2) the entire header was used but not all data was used
  71999. ** (3) the end of the data extends beyond the end of the record.
  72000. */
  72001. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  72002. || (offset64 > pC->payloadSize)
  72003. ){
  72004. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  72005. rc = SQLITE_CORRUPT_BKPT;
  72006. goto abort_due_to_error;
  72007. }
  72008. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  72009. }else{
  72010. t = 0;
  72011. }
  72012. /* If after trying to extract new entries from the header, nHdrParsed is
  72013. ** still not up to p2, that means that the record has fewer than p2
  72014. ** columns. So the result will be either the default value or a NULL.
  72015. */
  72016. if( pC->nHdrParsed<=p2 ){
  72017. if( pOp->p4type==P4_MEM ){
  72018. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  72019. }else{
  72020. sqlite3VdbeMemSetNull(pDest);
  72021. }
  72022. goto op_column_out;
  72023. }
  72024. }else{
  72025. t = pC->aType[p2];
  72026. }
  72027. /* Extract the content for the p2+1-th column. Control can only
  72028. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  72029. ** all valid.
  72030. */
  72031. assert( p2<pC->nHdrParsed );
  72032. assert( rc==SQLITE_OK );
  72033. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  72034. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  72035. assert( t==pC->aType[p2] );
  72036. pDest->enc = encoding;
  72037. if( pC->szRow>=aOffset[p2+1] ){
  72038. /* This is the common case where the desired content fits on the original
  72039. ** page - where the content is not on an overflow page */
  72040. zData = pC->aRow + aOffset[p2];
  72041. if( t<12 ){
  72042. sqlite3VdbeSerialGet(zData, t, pDest);
  72043. }else{
  72044. /* If the column value is a string, we need a persistent value, not
  72045. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  72046. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  72047. */
  72048. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  72049. pDest->n = len = (t-12)/2;
  72050. if( pDest->szMalloc < len+2 ){
  72051. pDest->flags = MEM_Null;
  72052. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  72053. }else{
  72054. pDest->z = pDest->zMalloc;
  72055. }
  72056. memcpy(pDest->z, zData, len);
  72057. pDest->z[len] = 0;
  72058. pDest->z[len+1] = 0;
  72059. pDest->flags = aFlag[t&1];
  72060. }
  72061. }else{
  72062. /* This branch happens only when content is on overflow pages */
  72063. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  72064. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  72065. || (len = sqlite3VdbeSerialTypeLen(t))==0
  72066. ){
  72067. /* Content is irrelevant for
  72068. ** 1. the typeof() function,
  72069. ** 2. the length(X) function if X is a blob, and
  72070. ** 3. if the content length is zero.
  72071. ** So we might as well use bogus content rather than reading
  72072. ** content from disk. */
  72073. static u8 aZero[8]; /* This is the bogus content */
  72074. sqlite3VdbeSerialGet(aZero, t, pDest);
  72075. }else{
  72076. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  72077. pDest);
  72078. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72079. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  72080. pDest->flags &= ~MEM_Ephem;
  72081. }
  72082. }
  72083. op_column_out:
  72084. UPDATE_MAX_BLOBSIZE(pDest);
  72085. REGISTER_TRACE(pOp->p3, pDest);
  72086. break;
  72087. }
  72088. /* Opcode: Affinity P1 P2 * P4 *
  72089. ** Synopsis: affinity(r[P1@P2])
  72090. **
  72091. ** Apply affinities to a range of P2 registers starting with P1.
  72092. **
  72093. ** P4 is a string that is P2 characters long. The nth character of the
  72094. ** string indicates the column affinity that should be used for the nth
  72095. ** memory cell in the range.
  72096. */
  72097. case OP_Affinity: {
  72098. const char *zAffinity; /* The affinity to be applied */
  72099. char cAff; /* A single character of affinity */
  72100. zAffinity = pOp->p4.z;
  72101. assert( zAffinity!=0 );
  72102. assert( zAffinity[pOp->p2]==0 );
  72103. pIn1 = &aMem[pOp->p1];
  72104. while( (cAff = *(zAffinity++))!=0 ){
  72105. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  72106. assert( memIsValid(pIn1) );
  72107. applyAffinity(pIn1, cAff, encoding);
  72108. pIn1++;
  72109. }
  72110. break;
  72111. }
  72112. /* Opcode: MakeRecord P1 P2 P3 P4 *
  72113. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  72114. **
  72115. ** Convert P2 registers beginning with P1 into the [record format]
  72116. ** use as a data record in a database table or as a key
  72117. ** in an index. The OP_Column opcode can decode the record later.
  72118. **
  72119. ** P4 may be a string that is P2 characters long. The nth character of the
  72120. ** string indicates the column affinity that should be used for the nth
  72121. ** field of the index key.
  72122. **
  72123. ** The mapping from character to affinity is given by the SQLITE_AFF_
  72124. ** macros defined in sqliteInt.h.
  72125. **
  72126. ** If P4 is NULL then all index fields have the affinity BLOB.
  72127. */
  72128. case OP_MakeRecord: {
  72129. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  72130. Mem *pRec; /* The new record */
  72131. u64 nData; /* Number of bytes of data space */
  72132. int nHdr; /* Number of bytes of header space */
  72133. i64 nByte; /* Data space required for this record */
  72134. i64 nZero; /* Number of zero bytes at the end of the record */
  72135. int nVarint; /* Number of bytes in a varint */
  72136. u32 serial_type; /* Type field */
  72137. Mem *pData0; /* First field to be combined into the record */
  72138. Mem *pLast; /* Last field of the record */
  72139. int nField; /* Number of fields in the record */
  72140. char *zAffinity; /* The affinity string for the record */
  72141. int file_format; /* File format to use for encoding */
  72142. int i; /* Space used in zNewRecord[] header */
  72143. int j; /* Space used in zNewRecord[] content */
  72144. u32 len; /* Length of a field */
  72145. /* Assuming the record contains N fields, the record format looks
  72146. ** like this:
  72147. **
  72148. ** ------------------------------------------------------------------------
  72149. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  72150. ** ------------------------------------------------------------------------
  72151. **
  72152. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  72153. ** and so forth.
  72154. **
  72155. ** Each type field is a varint representing the serial type of the
  72156. ** corresponding data element (see sqlite3VdbeSerialType()). The
  72157. ** hdr-size field is also a varint which is the offset from the beginning
  72158. ** of the record to data0.
  72159. */
  72160. nData = 0; /* Number of bytes of data space */
  72161. nHdr = 0; /* Number of bytes of header space */
  72162. nZero = 0; /* Number of zero bytes at the end of the record */
  72163. nField = pOp->p1;
  72164. zAffinity = pOp->p4.z;
  72165. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  72166. pData0 = &aMem[nField];
  72167. nField = pOp->p2;
  72168. pLast = &pData0[nField-1];
  72169. file_format = p->minWriteFileFormat;
  72170. /* Identify the output register */
  72171. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  72172. pOut = &aMem[pOp->p3];
  72173. memAboutToChange(p, pOut);
  72174. /* Apply the requested affinity to all inputs
  72175. */
  72176. assert( pData0<=pLast );
  72177. if( zAffinity ){
  72178. pRec = pData0;
  72179. do{
  72180. applyAffinity(pRec++, *(zAffinity++), encoding);
  72181. assert( zAffinity[0]==0 || pRec<=pLast );
  72182. }while( zAffinity[0] );
  72183. }
  72184. /* Loop through the elements that will make up the record to figure
  72185. ** out how much space is required for the new record.
  72186. */
  72187. pRec = pLast;
  72188. do{
  72189. assert( memIsValid(pRec) );
  72190. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  72191. if( pRec->flags & MEM_Zero ){
  72192. if( nData ){
  72193. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  72194. }else{
  72195. nZero += pRec->u.nZero;
  72196. len -= pRec->u.nZero;
  72197. }
  72198. }
  72199. nData += len;
  72200. testcase( serial_type==127 );
  72201. testcase( serial_type==128 );
  72202. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  72203. }while( (--pRec)>=pData0 );
  72204. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  72205. ** which determines the total number of bytes in the header. The varint
  72206. ** value is the size of the header in bytes including the size varint
  72207. ** itself. */
  72208. testcase( nHdr==126 );
  72209. testcase( nHdr==127 );
  72210. if( nHdr<=126 ){
  72211. /* The common case */
  72212. nHdr += 1;
  72213. }else{
  72214. /* Rare case of a really large header */
  72215. nVarint = sqlite3VarintLen(nHdr);
  72216. nHdr += nVarint;
  72217. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  72218. }
  72219. nByte = nHdr+nData;
  72220. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  72221. goto too_big;
  72222. }
  72223. /* Make sure the output register has a buffer large enough to store
  72224. ** the new record. The output register (pOp->p3) is not allowed to
  72225. ** be one of the input registers (because the following call to
  72226. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  72227. */
  72228. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  72229. goto no_mem;
  72230. }
  72231. zNewRecord = (u8 *)pOut->z;
  72232. /* Write the record */
  72233. i = putVarint32(zNewRecord, nHdr);
  72234. j = nHdr;
  72235. assert( pData0<=pLast );
  72236. pRec = pData0;
  72237. do{
  72238. serial_type = pRec->uTemp;
  72239. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  72240. ** additional varints, one per column. */
  72241. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  72242. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  72243. ** immediately follow the header. */
  72244. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  72245. }while( (++pRec)<=pLast );
  72246. assert( i==nHdr );
  72247. assert( j==nByte );
  72248. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  72249. pOut->n = (int)nByte;
  72250. pOut->flags = MEM_Blob;
  72251. if( nZero ){
  72252. pOut->u.nZero = nZero;
  72253. pOut->flags |= MEM_Zero;
  72254. }
  72255. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  72256. REGISTER_TRACE(pOp->p3, pOut);
  72257. UPDATE_MAX_BLOBSIZE(pOut);
  72258. break;
  72259. }
  72260. /* Opcode: Count P1 P2 * * *
  72261. ** Synopsis: r[P2]=count()
  72262. **
  72263. ** Store the number of entries (an integer value) in the table or index
  72264. ** opened by cursor P1 in register P2
  72265. */
  72266. #ifndef SQLITE_OMIT_BTREECOUNT
  72267. case OP_Count: { /* out2 */
  72268. i64 nEntry;
  72269. BtCursor *pCrsr;
  72270. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  72271. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  72272. assert( pCrsr );
  72273. nEntry = 0; /* Not needed. Only used to silence a warning. */
  72274. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  72275. if( rc ) goto abort_due_to_error;
  72276. pOut = out2Prerelease(p, pOp);
  72277. pOut->u.i = nEntry;
  72278. break;
  72279. }
  72280. #endif
  72281. /* Opcode: Savepoint P1 * * P4 *
  72282. **
  72283. ** Open, release or rollback the savepoint named by parameter P4, depending
  72284. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  72285. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  72286. */
  72287. case OP_Savepoint: {
  72288. int p1; /* Value of P1 operand */
  72289. char *zName; /* Name of savepoint */
  72290. int nName;
  72291. Savepoint *pNew;
  72292. Savepoint *pSavepoint;
  72293. Savepoint *pTmp;
  72294. int iSavepoint;
  72295. int ii;
  72296. p1 = pOp->p1;
  72297. zName = pOp->p4.z;
  72298. /* Assert that the p1 parameter is valid. Also that if there is no open
  72299. ** transaction, then there cannot be any savepoints.
  72300. */
  72301. assert( db->pSavepoint==0 || db->autoCommit==0 );
  72302. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  72303. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  72304. assert( checkSavepointCount(db) );
  72305. assert( p->bIsReader );
  72306. if( p1==SAVEPOINT_BEGIN ){
  72307. if( db->nVdbeWrite>0 ){
  72308. /* A new savepoint cannot be created if there are active write
  72309. ** statements (i.e. open read/write incremental blob handles).
  72310. */
  72311. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  72312. rc = SQLITE_BUSY;
  72313. }else{
  72314. nName = sqlite3Strlen30(zName);
  72315. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72316. /* This call is Ok even if this savepoint is actually a transaction
  72317. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  72318. ** If this is a transaction savepoint being opened, it is guaranteed
  72319. ** that the db->aVTrans[] array is empty. */
  72320. assert( db->autoCommit==0 || db->nVTrans==0 );
  72321. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  72322. db->nStatement+db->nSavepoint);
  72323. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72324. #endif
  72325. /* Create a new savepoint structure. */
  72326. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  72327. if( pNew ){
  72328. pNew->zName = (char *)&pNew[1];
  72329. memcpy(pNew->zName, zName, nName+1);
  72330. /* If there is no open transaction, then mark this as a special
  72331. ** "transaction savepoint". */
  72332. if( db->autoCommit ){
  72333. db->autoCommit = 0;
  72334. db->isTransactionSavepoint = 1;
  72335. }else{
  72336. db->nSavepoint++;
  72337. }
  72338. /* Link the new savepoint into the database handle's list. */
  72339. pNew->pNext = db->pSavepoint;
  72340. db->pSavepoint = pNew;
  72341. pNew->nDeferredCons = db->nDeferredCons;
  72342. pNew->nDeferredImmCons = db->nDeferredImmCons;
  72343. }
  72344. }
  72345. }else{
  72346. iSavepoint = 0;
  72347. /* Find the named savepoint. If there is no such savepoint, then an
  72348. ** an error is returned to the user. */
  72349. for(
  72350. pSavepoint = db->pSavepoint;
  72351. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  72352. pSavepoint = pSavepoint->pNext
  72353. ){
  72354. iSavepoint++;
  72355. }
  72356. if( !pSavepoint ){
  72357. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  72358. rc = SQLITE_ERROR;
  72359. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  72360. /* It is not possible to release (commit) a savepoint if there are
  72361. ** active write statements.
  72362. */
  72363. sqlite3VdbeError(p, "cannot release savepoint - "
  72364. "SQL statements in progress");
  72365. rc = SQLITE_BUSY;
  72366. }else{
  72367. /* Determine whether or not this is a transaction savepoint. If so,
  72368. ** and this is a RELEASE command, then the current transaction
  72369. ** is committed.
  72370. */
  72371. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  72372. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  72373. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  72374. goto vdbe_return;
  72375. }
  72376. db->autoCommit = 1;
  72377. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  72378. p->pc = (int)(pOp - aOp);
  72379. db->autoCommit = 0;
  72380. p->rc = rc = SQLITE_BUSY;
  72381. goto vdbe_return;
  72382. }
  72383. db->isTransactionSavepoint = 0;
  72384. rc = p->rc;
  72385. }else{
  72386. int isSchemaChange;
  72387. iSavepoint = db->nSavepoint - iSavepoint - 1;
  72388. if( p1==SAVEPOINT_ROLLBACK ){
  72389. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  72390. for(ii=0; ii<db->nDb; ii++){
  72391. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  72392. SQLITE_ABORT_ROLLBACK,
  72393. isSchemaChange==0);
  72394. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72395. }
  72396. }else{
  72397. isSchemaChange = 0;
  72398. }
  72399. for(ii=0; ii<db->nDb; ii++){
  72400. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  72401. if( rc!=SQLITE_OK ){
  72402. goto abort_due_to_error;
  72403. }
  72404. }
  72405. if( isSchemaChange ){
  72406. sqlite3ExpirePreparedStatements(db);
  72407. sqlite3ResetAllSchemasOfConnection(db);
  72408. db->flags = (db->flags | SQLITE_InternChanges);
  72409. }
  72410. }
  72411. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  72412. ** savepoints nested inside of the savepoint being operated on. */
  72413. while( db->pSavepoint!=pSavepoint ){
  72414. pTmp = db->pSavepoint;
  72415. db->pSavepoint = pTmp->pNext;
  72416. sqlite3DbFree(db, pTmp);
  72417. db->nSavepoint--;
  72418. }
  72419. /* If it is a RELEASE, then destroy the savepoint being operated on
  72420. ** too. If it is a ROLLBACK TO, then set the number of deferred
  72421. ** constraint violations present in the database to the value stored
  72422. ** when the savepoint was created. */
  72423. if( p1==SAVEPOINT_RELEASE ){
  72424. assert( pSavepoint==db->pSavepoint );
  72425. db->pSavepoint = pSavepoint->pNext;
  72426. sqlite3DbFree(db, pSavepoint);
  72427. if( !isTransaction ){
  72428. db->nSavepoint--;
  72429. }
  72430. }else{
  72431. db->nDeferredCons = pSavepoint->nDeferredCons;
  72432. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  72433. }
  72434. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  72435. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  72436. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72437. }
  72438. }
  72439. }
  72440. if( rc ) goto abort_due_to_error;
  72441. break;
  72442. }
  72443. /* Opcode: AutoCommit P1 P2 * * *
  72444. **
  72445. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  72446. ** back any currently active btree transactions. If there are any active
  72447. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  72448. ** there are active writing VMs or active VMs that use shared cache.
  72449. **
  72450. ** This instruction causes the VM to halt.
  72451. */
  72452. case OP_AutoCommit: {
  72453. int desiredAutoCommit;
  72454. int iRollback;
  72455. desiredAutoCommit = pOp->p1;
  72456. iRollback = pOp->p2;
  72457. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  72458. assert( desiredAutoCommit==1 || iRollback==0 );
  72459. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  72460. assert( p->bIsReader );
  72461. if( desiredAutoCommit!=db->autoCommit ){
  72462. if( iRollback ){
  72463. assert( desiredAutoCommit==1 );
  72464. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72465. db->autoCommit = 1;
  72466. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  72467. /* If this instruction implements a COMMIT and other VMs are writing
  72468. ** return an error indicating that the other VMs must complete first.
  72469. */
  72470. sqlite3VdbeError(p, "cannot commit transaction - "
  72471. "SQL statements in progress");
  72472. rc = SQLITE_BUSY;
  72473. goto abort_due_to_error;
  72474. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  72475. goto vdbe_return;
  72476. }else{
  72477. db->autoCommit = (u8)desiredAutoCommit;
  72478. }
  72479. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  72480. p->pc = (int)(pOp - aOp);
  72481. db->autoCommit = (u8)(1-desiredAutoCommit);
  72482. p->rc = rc = SQLITE_BUSY;
  72483. goto vdbe_return;
  72484. }
  72485. assert( db->nStatement==0 );
  72486. sqlite3CloseSavepoints(db);
  72487. if( p->rc==SQLITE_OK ){
  72488. rc = SQLITE_DONE;
  72489. }else{
  72490. rc = SQLITE_ERROR;
  72491. }
  72492. goto vdbe_return;
  72493. }else{
  72494. sqlite3VdbeError(p,
  72495. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  72496. (iRollback)?"cannot rollback - no transaction is active":
  72497. "cannot commit - no transaction is active"));
  72498. rc = SQLITE_ERROR;
  72499. goto abort_due_to_error;
  72500. }
  72501. break;
  72502. }
  72503. /* Opcode: Transaction P1 P2 P3 P4 P5
  72504. **
  72505. ** Begin a transaction on database P1 if a transaction is not already
  72506. ** active.
  72507. ** If P2 is non-zero, then a write-transaction is started, or if a
  72508. ** read-transaction is already active, it is upgraded to a write-transaction.
  72509. ** If P2 is zero, then a read-transaction is started.
  72510. **
  72511. ** P1 is the index of the database file on which the transaction is
  72512. ** started. Index 0 is the main database file and index 1 is the
  72513. ** file used for temporary tables. Indices of 2 or more are used for
  72514. ** attached databases.
  72515. **
  72516. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  72517. ** true (this flag is set if the Vdbe may modify more than one row and may
  72518. ** throw an ABORT exception), a statement transaction may also be opened.
  72519. ** More specifically, a statement transaction is opened iff the database
  72520. ** connection is currently not in autocommit mode, or if there are other
  72521. ** active statements. A statement transaction allows the changes made by this
  72522. ** VDBE to be rolled back after an error without having to roll back the
  72523. ** entire transaction. If no error is encountered, the statement transaction
  72524. ** will automatically commit when the VDBE halts.
  72525. **
  72526. ** If P5!=0 then this opcode also checks the schema cookie against P3
  72527. ** and the schema generation counter against P4.
  72528. ** The cookie changes its value whenever the database schema changes.
  72529. ** This operation is used to detect when that the cookie has changed
  72530. ** and that the current process needs to reread the schema. If the schema
  72531. ** cookie in P3 differs from the schema cookie in the database header or
  72532. ** if the schema generation counter in P4 differs from the current
  72533. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  72534. ** halts. The sqlite3_step() wrapper function might then reprepare the
  72535. ** statement and rerun it from the beginning.
  72536. */
  72537. case OP_Transaction: {
  72538. Btree *pBt;
  72539. int iMeta;
  72540. int iGen;
  72541. assert( p->bIsReader );
  72542. assert( p->readOnly==0 || pOp->p2==0 );
  72543. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  72544. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  72545. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  72546. rc = SQLITE_READONLY;
  72547. goto abort_due_to_error;
  72548. }
  72549. pBt = db->aDb[pOp->p1].pBt;
  72550. if( pBt ){
  72551. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  72552. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  72553. testcase( rc==SQLITE_BUSY_RECOVERY );
  72554. if( (rc&0xff)==SQLITE_BUSY ){
  72555. p->pc = (int)(pOp - aOp);
  72556. p->rc = rc;
  72557. goto vdbe_return;
  72558. }
  72559. if( rc!=SQLITE_OK ){
  72560. goto abort_due_to_error;
  72561. }
  72562. if( pOp->p2 && p->usesStmtJournal
  72563. && (db->autoCommit==0 || db->nVdbeRead>1)
  72564. ){
  72565. assert( sqlite3BtreeIsInTrans(pBt) );
  72566. if( p->iStatement==0 ){
  72567. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  72568. db->nStatement++;
  72569. p->iStatement = db->nSavepoint + db->nStatement;
  72570. }
  72571. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  72572. if( rc==SQLITE_OK ){
  72573. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  72574. }
  72575. /* Store the current value of the database handles deferred constraint
  72576. ** counter. If the statement transaction needs to be rolled back,
  72577. ** the value of this counter needs to be restored too. */
  72578. p->nStmtDefCons = db->nDeferredCons;
  72579. p->nStmtDefImmCons = db->nDeferredImmCons;
  72580. }
  72581. /* Gather the schema version number for checking:
  72582. ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
  72583. ** each time a query is executed to ensure that the internal cache of the
  72584. ** schema used when compiling the SQL query matches the schema of the
  72585. ** database against which the compiled query is actually executed.
  72586. */
  72587. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  72588. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  72589. }else{
  72590. iGen = iMeta = 0;
  72591. }
  72592. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  72593. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  72594. sqlite3DbFree(db, p->zErrMsg);
  72595. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  72596. /* If the schema-cookie from the database file matches the cookie
  72597. ** stored with the in-memory representation of the schema, do
  72598. ** not reload the schema from the database file.
  72599. **
  72600. ** If virtual-tables are in use, this is not just an optimization.
  72601. ** Often, v-tables store their data in other SQLite tables, which
  72602. ** are queried from within xNext() and other v-table methods using
  72603. ** prepared queries. If such a query is out-of-date, we do not want to
  72604. ** discard the database schema, as the user code implementing the
  72605. ** v-table would have to be ready for the sqlite3_vtab structure itself
  72606. ** to be invalidated whenever sqlite3_step() is called from within
  72607. ** a v-table method.
  72608. */
  72609. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  72610. sqlite3ResetOneSchema(db, pOp->p1);
  72611. }
  72612. p->expired = 1;
  72613. rc = SQLITE_SCHEMA;
  72614. }
  72615. if( rc ) goto abort_due_to_error;
  72616. break;
  72617. }
  72618. /* Opcode: ReadCookie P1 P2 P3 * *
  72619. **
  72620. ** Read cookie number P3 from database P1 and write it into register P2.
  72621. ** P3==1 is the schema version. P3==2 is the database format.
  72622. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  72623. ** the main database file and P1==1 is the database file used to store
  72624. ** temporary tables.
  72625. **
  72626. ** There must be a read-lock on the database (either a transaction
  72627. ** must be started or there must be an open cursor) before
  72628. ** executing this instruction.
  72629. */
  72630. case OP_ReadCookie: { /* out2 */
  72631. int iMeta;
  72632. int iDb;
  72633. int iCookie;
  72634. assert( p->bIsReader );
  72635. iDb = pOp->p1;
  72636. iCookie = pOp->p3;
  72637. assert( pOp->p3<SQLITE_N_BTREE_META );
  72638. assert( iDb>=0 && iDb<db->nDb );
  72639. assert( db->aDb[iDb].pBt!=0 );
  72640. assert( DbMaskTest(p->btreeMask, iDb) );
  72641. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  72642. pOut = out2Prerelease(p, pOp);
  72643. pOut->u.i = iMeta;
  72644. break;
  72645. }
  72646. /* Opcode: SetCookie P1 P2 P3 * *
  72647. **
  72648. ** Write the integer value P3 into cookie number P2 of database P1.
  72649. ** P2==1 is the schema version. P2==2 is the database format.
  72650. ** P2==3 is the recommended pager cache
  72651. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  72652. ** database file used to store temporary tables.
  72653. **
  72654. ** A transaction must be started before executing this opcode.
  72655. */
  72656. case OP_SetCookie: {
  72657. Db *pDb;
  72658. assert( pOp->p2<SQLITE_N_BTREE_META );
  72659. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  72660. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  72661. assert( p->readOnly==0 );
  72662. pDb = &db->aDb[pOp->p1];
  72663. assert( pDb->pBt!=0 );
  72664. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  72665. /* See note about index shifting on OP_ReadCookie */
  72666. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  72667. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  72668. /* When the schema cookie changes, record the new cookie internally */
  72669. pDb->pSchema->schema_cookie = pOp->p3;
  72670. db->flags |= SQLITE_InternChanges;
  72671. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  72672. /* Record changes in the file format */
  72673. pDb->pSchema->file_format = pOp->p3;
  72674. }
  72675. if( pOp->p1==1 ){
  72676. /* Invalidate all prepared statements whenever the TEMP database
  72677. ** schema is changed. Ticket #1644 */
  72678. sqlite3ExpirePreparedStatements(db);
  72679. p->expired = 0;
  72680. }
  72681. if( rc ) goto abort_due_to_error;
  72682. break;
  72683. }
  72684. /* Opcode: OpenRead P1 P2 P3 P4 P5
  72685. ** Synopsis: root=P2 iDb=P3
  72686. **
  72687. ** Open a read-only cursor for the database table whose root page is
  72688. ** P2 in a database file. The database file is determined by P3.
  72689. ** P3==0 means the main database, P3==1 means the database used for
  72690. ** temporary tables, and P3>1 means used the corresponding attached
  72691. ** database. Give the new cursor an identifier of P1. The P1
  72692. ** values need not be contiguous but all P1 values should be small integers.
  72693. ** It is an error for P1 to be negative.
  72694. **
  72695. ** If P5!=0 then use the content of register P2 as the root page, not
  72696. ** the value of P2 itself.
  72697. **
  72698. ** There will be a read lock on the database whenever there is an
  72699. ** open cursor. If the database was unlocked prior to this instruction
  72700. ** then a read lock is acquired as part of this instruction. A read
  72701. ** lock allows other processes to read the database but prohibits
  72702. ** any other process from modifying the database. The read lock is
  72703. ** released when all cursors are closed. If this instruction attempts
  72704. ** to get a read lock but fails, the script terminates with an
  72705. ** SQLITE_BUSY error code.
  72706. **
  72707. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  72708. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  72709. ** structure, then said structure defines the content and collating
  72710. ** sequence of the index being opened. Otherwise, if P4 is an integer
  72711. ** value, it is set to the number of columns in the table.
  72712. **
  72713. ** See also: OpenWrite, ReopenIdx
  72714. */
  72715. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  72716. ** Synopsis: root=P2 iDb=P3
  72717. **
  72718. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  72719. ** checks to see if the cursor on P1 is already open with a root page
  72720. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  72721. ** if the cursor is already open, do not reopen it.
  72722. **
  72723. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  72724. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  72725. ** every other ReopenIdx or OpenRead for the same cursor number.
  72726. **
  72727. ** See the OpenRead opcode documentation for additional information.
  72728. */
  72729. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  72730. ** Synopsis: root=P2 iDb=P3
  72731. **
  72732. ** Open a read/write cursor named P1 on the table or index whose root
  72733. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  72734. ** root page.
  72735. **
  72736. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  72737. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  72738. ** structure, then said structure defines the content and collating
  72739. ** sequence of the index being opened. Otherwise, if P4 is an integer
  72740. ** value, it is set to the number of columns in the table, or to the
  72741. ** largest index of any column of the table that is actually used.
  72742. **
  72743. ** This instruction works just like OpenRead except that it opens the cursor
  72744. ** in read/write mode. For a given table, there can be one or more read-only
  72745. ** cursors or a single read/write cursor but not both.
  72746. **
  72747. ** See also OpenRead.
  72748. */
  72749. case OP_ReopenIdx: {
  72750. int nField;
  72751. KeyInfo *pKeyInfo;
  72752. int p2;
  72753. int iDb;
  72754. int wrFlag;
  72755. Btree *pX;
  72756. VdbeCursor *pCur;
  72757. Db *pDb;
  72758. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  72759. assert( pOp->p4type==P4_KEYINFO );
  72760. pCur = p->apCsr[pOp->p1];
  72761. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  72762. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  72763. goto open_cursor_set_hints;
  72764. }
  72765. /* If the cursor is not currently open or is open on a different
  72766. ** index, then fall through into OP_OpenRead to force a reopen */
  72767. case OP_OpenRead:
  72768. case OP_OpenWrite:
  72769. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  72770. assert( p->bIsReader );
  72771. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  72772. || p->readOnly==0 );
  72773. if( p->expired ){
  72774. rc = SQLITE_ABORT_ROLLBACK;
  72775. goto abort_due_to_error;
  72776. }
  72777. nField = 0;
  72778. pKeyInfo = 0;
  72779. p2 = pOp->p2;
  72780. iDb = pOp->p3;
  72781. assert( iDb>=0 && iDb<db->nDb );
  72782. assert( DbMaskTest(p->btreeMask, iDb) );
  72783. pDb = &db->aDb[iDb];
  72784. pX = pDb->pBt;
  72785. assert( pX!=0 );
  72786. if( pOp->opcode==OP_OpenWrite ){
  72787. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  72788. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  72789. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72790. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  72791. p->minWriteFileFormat = pDb->pSchema->file_format;
  72792. }
  72793. }else{
  72794. wrFlag = 0;
  72795. }
  72796. if( pOp->p5 & OPFLAG_P2ISREG ){
  72797. assert( p2>0 );
  72798. assert( p2<=(p->nMem+1 - p->nCursor) );
  72799. pIn2 = &aMem[p2];
  72800. assert( memIsValid(pIn2) );
  72801. assert( (pIn2->flags & MEM_Int)!=0 );
  72802. sqlite3VdbeMemIntegerify(pIn2);
  72803. p2 = (int)pIn2->u.i;
  72804. /* The p2 value always comes from a prior OP_CreateTable opcode and
  72805. ** that opcode will always set the p2 value to 2 or more or else fail.
  72806. ** If there were a failure, the prepared statement would have halted
  72807. ** before reaching this instruction. */
  72808. assert( p2>=2 );
  72809. }
  72810. if( pOp->p4type==P4_KEYINFO ){
  72811. pKeyInfo = pOp->p4.pKeyInfo;
  72812. assert( pKeyInfo->enc==ENC(db) );
  72813. assert( pKeyInfo->db==db );
  72814. nField = pKeyInfo->nField+pKeyInfo->nXField;
  72815. }else if( pOp->p4type==P4_INT32 ){
  72816. nField = pOp->p4.i;
  72817. }
  72818. assert( pOp->p1>=0 );
  72819. assert( nField>=0 );
  72820. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  72821. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  72822. if( pCur==0 ) goto no_mem;
  72823. pCur->nullRow = 1;
  72824. pCur->isOrdered = 1;
  72825. pCur->pgnoRoot = p2;
  72826. #ifdef SQLITE_DEBUG
  72827. pCur->wrFlag = wrFlag;
  72828. #endif
  72829. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  72830. pCur->pKeyInfo = pKeyInfo;
  72831. /* Set the VdbeCursor.isTable variable. Previous versions of
  72832. ** SQLite used to check if the root-page flags were sane at this point
  72833. ** and report database corruption if they were not, but this check has
  72834. ** since moved into the btree layer. */
  72835. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  72836. open_cursor_set_hints:
  72837. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  72838. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  72839. testcase( pOp->p5 & OPFLAG_BULKCSR );
  72840. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  72841. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  72842. #endif
  72843. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  72844. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  72845. if( rc ) goto abort_due_to_error;
  72846. break;
  72847. }
  72848. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  72849. ** Synopsis: nColumn=P2
  72850. **
  72851. ** Open a new cursor P1 to a transient table.
  72852. ** The cursor is always opened read/write even if
  72853. ** the main database is read-only. The ephemeral
  72854. ** table is deleted automatically when the cursor is closed.
  72855. **
  72856. ** P2 is the number of columns in the ephemeral table.
  72857. ** The cursor points to a BTree table if P4==0 and to a BTree index
  72858. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  72859. ** that defines the format of keys in the index.
  72860. **
  72861. ** The P5 parameter can be a mask of the BTREE_* flags defined
  72862. ** in btree.h. These flags control aspects of the operation of
  72863. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  72864. ** added automatically.
  72865. */
  72866. /* Opcode: OpenAutoindex P1 P2 * P4 *
  72867. ** Synopsis: nColumn=P2
  72868. **
  72869. ** This opcode works the same as OP_OpenEphemeral. It has a
  72870. ** different name to distinguish its use. Tables created using
  72871. ** by this opcode will be used for automatically created transient
  72872. ** indices in joins.
  72873. */
  72874. case OP_OpenAutoindex:
  72875. case OP_OpenEphemeral: {
  72876. VdbeCursor *pCx;
  72877. KeyInfo *pKeyInfo;
  72878. static const int vfsFlags =
  72879. SQLITE_OPEN_READWRITE |
  72880. SQLITE_OPEN_CREATE |
  72881. SQLITE_OPEN_EXCLUSIVE |
  72882. SQLITE_OPEN_DELETEONCLOSE |
  72883. SQLITE_OPEN_TRANSIENT_DB;
  72884. assert( pOp->p1>=0 );
  72885. assert( pOp->p2>=0 );
  72886. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  72887. if( pCx==0 ) goto no_mem;
  72888. pCx->nullRow = 1;
  72889. pCx->isEphemeral = 1;
  72890. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  72891. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  72892. if( rc==SQLITE_OK ){
  72893. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  72894. }
  72895. if( rc==SQLITE_OK ){
  72896. /* If a transient index is required, create it by calling
  72897. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  72898. ** opening it. If a transient table is required, just use the
  72899. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  72900. */
  72901. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  72902. int pgno;
  72903. assert( pOp->p4type==P4_KEYINFO );
  72904. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  72905. if( rc==SQLITE_OK ){
  72906. assert( pgno==MASTER_ROOT+1 );
  72907. assert( pKeyInfo->db==db );
  72908. assert( pKeyInfo->enc==ENC(db) );
  72909. pCx->pKeyInfo = pKeyInfo;
  72910. rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
  72911. pKeyInfo, pCx->uc.pCursor);
  72912. }
  72913. pCx->isTable = 0;
  72914. }else{
  72915. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
  72916. 0, pCx->uc.pCursor);
  72917. pCx->isTable = 1;
  72918. }
  72919. }
  72920. if( rc ) goto abort_due_to_error;
  72921. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  72922. break;
  72923. }
  72924. /* Opcode: SorterOpen P1 P2 P3 P4 *
  72925. **
  72926. ** This opcode works like OP_OpenEphemeral except that it opens
  72927. ** a transient index that is specifically designed to sort large
  72928. ** tables using an external merge-sort algorithm.
  72929. **
  72930. ** If argument P3 is non-zero, then it indicates that the sorter may
  72931. ** assume that a stable sort considering the first P3 fields of each
  72932. ** key is sufficient to produce the required results.
  72933. */
  72934. case OP_SorterOpen: {
  72935. VdbeCursor *pCx;
  72936. assert( pOp->p1>=0 );
  72937. assert( pOp->p2>=0 );
  72938. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  72939. if( pCx==0 ) goto no_mem;
  72940. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  72941. assert( pCx->pKeyInfo->db==db );
  72942. assert( pCx->pKeyInfo->enc==ENC(db) );
  72943. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  72944. if( rc ) goto abort_due_to_error;
  72945. break;
  72946. }
  72947. /* Opcode: SequenceTest P1 P2 * * *
  72948. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  72949. **
  72950. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  72951. ** to P2. Regardless of whether or not the jump is taken, increment the
  72952. ** the sequence value.
  72953. */
  72954. case OP_SequenceTest: {
  72955. VdbeCursor *pC;
  72956. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72957. pC = p->apCsr[pOp->p1];
  72958. assert( isSorter(pC) );
  72959. if( (pC->seqCount++)==0 ){
  72960. goto jump_to_p2;
  72961. }
  72962. break;
  72963. }
  72964. /* Opcode: OpenPseudo P1 P2 P3 * *
  72965. ** Synopsis: P3 columns in r[P2]
  72966. **
  72967. ** Open a new cursor that points to a fake table that contains a single
  72968. ** row of data. The content of that one row is the content of memory
  72969. ** register P2. In other words, cursor P1 becomes an alias for the
  72970. ** MEM_Blob content contained in register P2.
  72971. **
  72972. ** A pseudo-table created by this opcode is used to hold a single
  72973. ** row output from the sorter so that the row can be decomposed into
  72974. ** individual columns using the OP_Column opcode. The OP_Column opcode
  72975. ** is the only cursor opcode that works with a pseudo-table.
  72976. **
  72977. ** P3 is the number of fields in the records that will be stored by
  72978. ** the pseudo-table.
  72979. */
  72980. case OP_OpenPseudo: {
  72981. VdbeCursor *pCx;
  72982. assert( pOp->p1>=0 );
  72983. assert( pOp->p3>=0 );
  72984. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  72985. if( pCx==0 ) goto no_mem;
  72986. pCx->nullRow = 1;
  72987. pCx->uc.pseudoTableReg = pOp->p2;
  72988. pCx->isTable = 1;
  72989. assert( pOp->p5==0 );
  72990. break;
  72991. }
  72992. /* Opcode: Close P1 * * * *
  72993. **
  72994. ** Close a cursor previously opened as P1. If P1 is not
  72995. ** currently open, this instruction is a no-op.
  72996. */
  72997. case OP_Close: {
  72998. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72999. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  73000. p->apCsr[pOp->p1] = 0;
  73001. break;
  73002. }
  73003. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  73004. /* Opcode: ColumnsUsed P1 * * P4 *
  73005. **
  73006. ** This opcode (which only exists if SQLite was compiled with
  73007. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  73008. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  73009. ** (P4_INT64) in which the first 63 bits are one for each of the
  73010. ** first 63 columns of the table or index that are actually used
  73011. ** by the cursor. The high-order bit is set if any column after
  73012. ** the 64th is used.
  73013. */
  73014. case OP_ColumnsUsed: {
  73015. VdbeCursor *pC;
  73016. pC = p->apCsr[pOp->p1];
  73017. assert( pC->eCurType==CURTYPE_BTREE );
  73018. pC->maskUsed = *(u64*)pOp->p4.pI64;
  73019. break;
  73020. }
  73021. #endif
  73022. /* Opcode: SeekGE P1 P2 P3 P4 *
  73023. ** Synopsis: key=r[P3@P4]
  73024. **
  73025. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  73026. ** use the value in register P3 as the key. If cursor P1 refers
  73027. ** to an SQL index, then P3 is the first in an array of P4 registers
  73028. ** that are used as an unpacked index key.
  73029. **
  73030. ** Reposition cursor P1 so that it points to the smallest entry that
  73031. ** is greater than or equal to the key value. If there are no records
  73032. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  73033. **
  73034. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  73035. ** opcode will always land on a record that equally equals the key, or
  73036. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  73037. ** opcode must be followed by an IdxLE opcode with the same arguments.
  73038. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  73039. ** IdxLE opcode will be used on subsequent loop iterations.
  73040. **
  73041. ** This opcode leaves the cursor configured to move in forward order,
  73042. ** from the beginning toward the end. In other words, the cursor is
  73043. ** configured to use Next, not Prev.
  73044. **
  73045. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  73046. */
  73047. /* Opcode: SeekGT P1 P2 P3 P4 *
  73048. ** Synopsis: key=r[P3@P4]
  73049. **
  73050. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  73051. ** use the value in register P3 as a key. If cursor P1 refers
  73052. ** to an SQL index, then P3 is the first in an array of P4 registers
  73053. ** that are used as an unpacked index key.
  73054. **
  73055. ** Reposition cursor P1 so that it points to the smallest entry that
  73056. ** is greater than the key value. If there are no records greater than
  73057. ** the key and P2 is not zero, then jump to P2.
  73058. **
  73059. ** This opcode leaves the cursor configured to move in forward order,
  73060. ** from the beginning toward the end. In other words, the cursor is
  73061. ** configured to use Next, not Prev.
  73062. **
  73063. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  73064. */
  73065. /* Opcode: SeekLT P1 P2 P3 P4 *
  73066. ** Synopsis: key=r[P3@P4]
  73067. **
  73068. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  73069. ** use the value in register P3 as a key. If cursor P1 refers
  73070. ** to an SQL index, then P3 is the first in an array of P4 registers
  73071. ** that are used as an unpacked index key.
  73072. **
  73073. ** Reposition cursor P1 so that it points to the largest entry that
  73074. ** is less than the key value. If there are no records less than
  73075. ** the key and P2 is not zero, then jump to P2.
  73076. **
  73077. ** This opcode leaves the cursor configured to move in reverse order,
  73078. ** from the end toward the beginning. In other words, the cursor is
  73079. ** configured to use Prev, not Next.
  73080. **
  73081. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  73082. */
  73083. /* Opcode: SeekLE P1 P2 P3 P4 *
  73084. ** Synopsis: key=r[P3@P4]
  73085. **
  73086. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  73087. ** use the value in register P3 as a key. If cursor P1 refers
  73088. ** to an SQL index, then P3 is the first in an array of P4 registers
  73089. ** that are used as an unpacked index key.
  73090. **
  73091. ** Reposition cursor P1 so that it points to the largest entry that
  73092. ** is less than or equal to the key value. If there are no records
  73093. ** less than or equal to the key and P2 is not zero, then jump to P2.
  73094. **
  73095. ** This opcode leaves the cursor configured to move in reverse order,
  73096. ** from the end toward the beginning. In other words, the cursor is
  73097. ** configured to use Prev, not Next.
  73098. **
  73099. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  73100. ** opcode will always land on a record that equally equals the key, or
  73101. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  73102. ** opcode must be followed by an IdxGE opcode with the same arguments.
  73103. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  73104. ** IdxGE opcode will be used on subsequent loop iterations.
  73105. **
  73106. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  73107. */
  73108. case OP_SeekLT: /* jump, in3 */
  73109. case OP_SeekLE: /* jump, in3 */
  73110. case OP_SeekGE: /* jump, in3 */
  73111. case OP_SeekGT: { /* jump, in3 */
  73112. int res; /* Comparison result */
  73113. int oc; /* Opcode */
  73114. VdbeCursor *pC; /* The cursor to seek */
  73115. UnpackedRecord r; /* The key to seek for */
  73116. int nField; /* Number of columns or fields in the key */
  73117. i64 iKey; /* The rowid we are to seek to */
  73118. int eqOnly; /* Only interested in == results */
  73119. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73120. assert( pOp->p2!=0 );
  73121. pC = p->apCsr[pOp->p1];
  73122. assert( pC!=0 );
  73123. assert( pC->eCurType==CURTYPE_BTREE );
  73124. assert( OP_SeekLE == OP_SeekLT+1 );
  73125. assert( OP_SeekGE == OP_SeekLT+2 );
  73126. assert( OP_SeekGT == OP_SeekLT+3 );
  73127. assert( pC->isOrdered );
  73128. assert( pC->uc.pCursor!=0 );
  73129. oc = pOp->opcode;
  73130. eqOnly = 0;
  73131. pC->nullRow = 0;
  73132. #ifdef SQLITE_DEBUG
  73133. pC->seekOp = pOp->opcode;
  73134. #endif
  73135. if( pC->isTable ){
  73136. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  73137. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 );
  73138. /* The input value in P3 might be of any type: integer, real, string,
  73139. ** blob, or NULL. But it needs to be an integer before we can do
  73140. ** the seek, so convert it. */
  73141. pIn3 = &aMem[pOp->p3];
  73142. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  73143. applyNumericAffinity(pIn3, 0);
  73144. }
  73145. iKey = sqlite3VdbeIntValue(pIn3);
  73146. /* If the P3 value could not be converted into an integer without
  73147. ** loss of information, then special processing is required... */
  73148. if( (pIn3->flags & MEM_Int)==0 ){
  73149. if( (pIn3->flags & MEM_Real)==0 ){
  73150. /* If the P3 value cannot be converted into any kind of a number,
  73151. ** then the seek is not possible, so jump to P2 */
  73152. VdbeBranchTaken(1,2); goto jump_to_p2;
  73153. break;
  73154. }
  73155. /* If the approximation iKey is larger than the actual real search
  73156. ** term, substitute >= for > and < for <=. e.g. if the search term
  73157. ** is 4.9 and the integer approximation 5:
  73158. **
  73159. ** (x > 4.9) -> (x >= 5)
  73160. ** (x <= 4.9) -> (x < 5)
  73161. */
  73162. if( pIn3->u.r<(double)iKey ){
  73163. assert( OP_SeekGE==(OP_SeekGT-1) );
  73164. assert( OP_SeekLT==(OP_SeekLE-1) );
  73165. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  73166. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  73167. }
  73168. /* If the approximation iKey is smaller than the actual real search
  73169. ** term, substitute <= for < and > for >=. */
  73170. else if( pIn3->u.r>(double)iKey ){
  73171. assert( OP_SeekLE==(OP_SeekLT+1) );
  73172. assert( OP_SeekGT==(OP_SeekGE+1) );
  73173. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  73174. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  73175. }
  73176. }
  73177. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  73178. pC->movetoTarget = iKey; /* Used by OP_Delete */
  73179. if( rc!=SQLITE_OK ){
  73180. goto abort_due_to_error;
  73181. }
  73182. }else{
  73183. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  73184. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  73185. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  73186. */
  73187. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  73188. eqOnly = 1;
  73189. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  73190. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  73191. assert( pOp[1].p1==pOp[0].p1 );
  73192. assert( pOp[1].p2==pOp[0].p2 );
  73193. assert( pOp[1].p3==pOp[0].p3 );
  73194. assert( pOp[1].p4.i==pOp[0].p4.i );
  73195. }
  73196. nField = pOp->p4.i;
  73197. assert( pOp->p4type==P4_INT32 );
  73198. assert( nField>0 );
  73199. r.pKeyInfo = pC->pKeyInfo;
  73200. r.nField = (u16)nField;
  73201. /* The next line of code computes as follows, only faster:
  73202. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  73203. ** r.default_rc = -1;
  73204. ** }else{
  73205. ** r.default_rc = +1;
  73206. ** }
  73207. */
  73208. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  73209. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  73210. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  73211. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  73212. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  73213. r.aMem = &aMem[pOp->p3];
  73214. #ifdef SQLITE_DEBUG
  73215. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  73216. #endif
  73217. ExpandBlob(r.aMem);
  73218. r.eqSeen = 0;
  73219. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  73220. if( rc!=SQLITE_OK ){
  73221. goto abort_due_to_error;
  73222. }
  73223. if( eqOnly && r.eqSeen==0 ){
  73224. assert( res!=0 );
  73225. goto seek_not_found;
  73226. }
  73227. }
  73228. pC->deferredMoveto = 0;
  73229. pC->cacheStatus = CACHE_STALE;
  73230. #ifdef SQLITE_TEST
  73231. sqlite3_search_count++;
  73232. #endif
  73233. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  73234. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  73235. res = 0;
  73236. rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
  73237. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  73238. }else{
  73239. res = 0;
  73240. }
  73241. }else{
  73242. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  73243. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  73244. res = 0;
  73245. rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
  73246. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  73247. }else{
  73248. /* res might be negative because the table is empty. Check to
  73249. ** see if this is the case.
  73250. */
  73251. res = sqlite3BtreeEof(pC->uc.pCursor);
  73252. }
  73253. }
  73254. seek_not_found:
  73255. assert( pOp->p2>0 );
  73256. VdbeBranchTaken(res!=0,2);
  73257. if( res ){
  73258. goto jump_to_p2;
  73259. }else if( eqOnly ){
  73260. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  73261. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  73262. }
  73263. break;
  73264. }
  73265. /* Opcode: Found P1 P2 P3 P4 *
  73266. ** Synopsis: key=r[P3@P4]
  73267. **
  73268. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  73269. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  73270. ** record.
  73271. **
  73272. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  73273. ** is a prefix of any entry in P1 then a jump is made to P2 and
  73274. ** P1 is left pointing at the matching entry.
  73275. **
  73276. ** This operation leaves the cursor in a state where it can be
  73277. ** advanced in the forward direction. The Next instruction will work,
  73278. ** but not the Prev instruction.
  73279. **
  73280. ** See also: NotFound, NoConflict, NotExists. SeekGe
  73281. */
  73282. /* Opcode: NotFound P1 P2 P3 P4 *
  73283. ** Synopsis: key=r[P3@P4]
  73284. **
  73285. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  73286. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  73287. ** record.
  73288. **
  73289. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  73290. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  73291. ** does contain an entry whose prefix matches the P3/P4 record then control
  73292. ** falls through to the next instruction and P1 is left pointing at the
  73293. ** matching entry.
  73294. **
  73295. ** This operation leaves the cursor in a state where it cannot be
  73296. ** advanced in either direction. In other words, the Next and Prev
  73297. ** opcodes do not work after this operation.
  73298. **
  73299. ** See also: Found, NotExists, NoConflict
  73300. */
  73301. /* Opcode: NoConflict P1 P2 P3 P4 *
  73302. ** Synopsis: key=r[P3@P4]
  73303. **
  73304. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  73305. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  73306. ** record.
  73307. **
  73308. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  73309. ** contains any NULL value, jump immediately to P2. If all terms of the
  73310. ** record are not-NULL then a check is done to determine if any row in the
  73311. ** P1 index btree has a matching key prefix. If there are no matches, jump
  73312. ** immediately to P2. If there is a match, fall through and leave the P1
  73313. ** cursor pointing to the matching row.
  73314. **
  73315. ** This opcode is similar to OP_NotFound with the exceptions that the
  73316. ** branch is always taken if any part of the search key input is NULL.
  73317. **
  73318. ** This operation leaves the cursor in a state where it cannot be
  73319. ** advanced in either direction. In other words, the Next and Prev
  73320. ** opcodes do not work after this operation.
  73321. **
  73322. ** See also: NotFound, Found, NotExists
  73323. */
  73324. case OP_NoConflict: /* jump, in3 */
  73325. case OP_NotFound: /* jump, in3 */
  73326. case OP_Found: { /* jump, in3 */
  73327. int alreadyExists;
  73328. int takeJump;
  73329. int ii;
  73330. VdbeCursor *pC;
  73331. int res;
  73332. char *pFree;
  73333. UnpackedRecord *pIdxKey;
  73334. UnpackedRecord r;
  73335. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  73336. #ifdef SQLITE_TEST
  73337. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  73338. #endif
  73339. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73340. assert( pOp->p4type==P4_INT32 );
  73341. pC = p->apCsr[pOp->p1];
  73342. assert( pC!=0 );
  73343. #ifdef SQLITE_DEBUG
  73344. pC->seekOp = pOp->opcode;
  73345. #endif
  73346. pIn3 = &aMem[pOp->p3];
  73347. assert( pC->eCurType==CURTYPE_BTREE );
  73348. assert( pC->uc.pCursor!=0 );
  73349. assert( pC->isTable==0 );
  73350. pFree = 0;
  73351. if( pOp->p4.i>0 ){
  73352. r.pKeyInfo = pC->pKeyInfo;
  73353. r.nField = (u16)pOp->p4.i;
  73354. r.aMem = pIn3;
  73355. for(ii=0; ii<r.nField; ii++){
  73356. assert( memIsValid(&r.aMem[ii]) );
  73357. ExpandBlob(&r.aMem[ii]);
  73358. #ifdef SQLITE_DEBUG
  73359. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  73360. #endif
  73361. }
  73362. pIdxKey = &r;
  73363. }else{
  73364. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  73365. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  73366. );
  73367. if( pIdxKey==0 ) goto no_mem;
  73368. assert( pIn3->flags & MEM_Blob );
  73369. ExpandBlob(pIn3);
  73370. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  73371. }
  73372. pIdxKey->default_rc = 0;
  73373. takeJump = 0;
  73374. if( pOp->opcode==OP_NoConflict ){
  73375. /* For the OP_NoConflict opcode, take the jump if any of the
  73376. ** input fields are NULL, since any key with a NULL will not
  73377. ** conflict */
  73378. for(ii=0; ii<pIdxKey->nField; ii++){
  73379. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  73380. takeJump = 1;
  73381. break;
  73382. }
  73383. }
  73384. }
  73385. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  73386. sqlite3DbFree(db, pFree);
  73387. if( rc!=SQLITE_OK ){
  73388. goto abort_due_to_error;
  73389. }
  73390. pC->seekResult = res;
  73391. alreadyExists = (res==0);
  73392. pC->nullRow = 1-alreadyExists;
  73393. pC->deferredMoveto = 0;
  73394. pC->cacheStatus = CACHE_STALE;
  73395. if( pOp->opcode==OP_Found ){
  73396. VdbeBranchTaken(alreadyExists!=0,2);
  73397. if( alreadyExists ) goto jump_to_p2;
  73398. }else{
  73399. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  73400. if( takeJump || !alreadyExists ) goto jump_to_p2;
  73401. }
  73402. break;
  73403. }
  73404. /* Opcode: NotExists P1 P2 P3 * *
  73405. ** Synopsis: intkey=r[P3]
  73406. **
  73407. ** P1 is the index of a cursor open on an SQL table btree (with integer
  73408. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  73409. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  73410. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  73411. ** leave the cursor pointing at that record and fall through to the next
  73412. ** instruction.
  73413. **
  73414. ** The OP_NotFound opcode performs the same operation on index btrees
  73415. ** (with arbitrary multi-value keys).
  73416. **
  73417. ** This opcode leaves the cursor in a state where it cannot be advanced
  73418. ** in either direction. In other words, the Next and Prev opcodes will
  73419. ** not work following this opcode.
  73420. **
  73421. ** See also: Found, NotFound, NoConflict
  73422. */
  73423. case OP_NotExists: { /* jump, in3 */
  73424. VdbeCursor *pC;
  73425. BtCursor *pCrsr;
  73426. int res;
  73427. u64 iKey;
  73428. pIn3 = &aMem[pOp->p3];
  73429. assert( pIn3->flags & MEM_Int );
  73430. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73431. pC = p->apCsr[pOp->p1];
  73432. assert( pC!=0 );
  73433. #ifdef SQLITE_DEBUG
  73434. pC->seekOp = 0;
  73435. #endif
  73436. assert( pC->isTable );
  73437. assert( pC->eCurType==CURTYPE_BTREE );
  73438. pCrsr = pC->uc.pCursor;
  73439. assert( pCrsr!=0 );
  73440. res = 0;
  73441. iKey = pIn3->u.i;
  73442. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  73443. assert( rc==SQLITE_OK || res==0 );
  73444. pC->movetoTarget = iKey; /* Used by OP_Delete */
  73445. pC->nullRow = 0;
  73446. pC->cacheStatus = CACHE_STALE;
  73447. pC->deferredMoveto = 0;
  73448. VdbeBranchTaken(res!=0,2);
  73449. pC->seekResult = res;
  73450. if( res!=0 ){
  73451. assert( rc==SQLITE_OK );
  73452. if( pOp->p2==0 ){
  73453. rc = SQLITE_CORRUPT_BKPT;
  73454. }else{
  73455. goto jump_to_p2;
  73456. }
  73457. }
  73458. if( rc ) goto abort_due_to_error;
  73459. break;
  73460. }
  73461. /* Opcode: Sequence P1 P2 * * *
  73462. ** Synopsis: r[P2]=cursor[P1].ctr++
  73463. **
  73464. ** Find the next available sequence number for cursor P1.
  73465. ** Write the sequence number into register P2.
  73466. ** The sequence number on the cursor is incremented after this
  73467. ** instruction.
  73468. */
  73469. case OP_Sequence: { /* out2 */
  73470. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73471. assert( p->apCsr[pOp->p1]!=0 );
  73472. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  73473. pOut = out2Prerelease(p, pOp);
  73474. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  73475. break;
  73476. }
  73477. /* Opcode: NewRowid P1 P2 P3 * *
  73478. ** Synopsis: r[P2]=rowid
  73479. **
  73480. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  73481. ** The record number is not previously used as a key in the database
  73482. ** table that cursor P1 points to. The new record number is written
  73483. ** written to register P2.
  73484. **
  73485. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  73486. ** the largest previously generated record number. No new record numbers are
  73487. ** allowed to be less than this value. When this value reaches its maximum,
  73488. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  73489. ** generated record number. This P3 mechanism is used to help implement the
  73490. ** AUTOINCREMENT feature.
  73491. */
  73492. case OP_NewRowid: { /* out2 */
  73493. i64 v; /* The new rowid */
  73494. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  73495. int res; /* Result of an sqlite3BtreeLast() */
  73496. int cnt; /* Counter to limit the number of searches */
  73497. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  73498. VdbeFrame *pFrame; /* Root frame of VDBE */
  73499. v = 0;
  73500. res = 0;
  73501. pOut = out2Prerelease(p, pOp);
  73502. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73503. pC = p->apCsr[pOp->p1];
  73504. assert( pC!=0 );
  73505. assert( pC->eCurType==CURTYPE_BTREE );
  73506. assert( pC->uc.pCursor!=0 );
  73507. {
  73508. /* The next rowid or record number (different terms for the same
  73509. ** thing) is obtained in a two-step algorithm.
  73510. **
  73511. ** First we attempt to find the largest existing rowid and add one
  73512. ** to that. But if the largest existing rowid is already the maximum
  73513. ** positive integer, we have to fall through to the second
  73514. ** probabilistic algorithm
  73515. **
  73516. ** The second algorithm is to select a rowid at random and see if
  73517. ** it already exists in the table. If it does not exist, we have
  73518. ** succeeded. If the random rowid does exist, we select a new one
  73519. ** and try again, up to 100 times.
  73520. */
  73521. assert( pC->isTable );
  73522. #ifdef SQLITE_32BIT_ROWID
  73523. # define MAX_ROWID 0x7fffffff
  73524. #else
  73525. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  73526. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  73527. ** to provide the constant while making all compilers happy.
  73528. */
  73529. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  73530. #endif
  73531. if( !pC->useRandomRowid ){
  73532. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  73533. if( rc!=SQLITE_OK ){
  73534. goto abort_due_to_error;
  73535. }
  73536. if( res ){
  73537. v = 1; /* IMP: R-61914-48074 */
  73538. }else{
  73539. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  73540. rc = sqlite3BtreeKeySize(pC->uc.pCursor, &v);
  73541. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  73542. if( v>=MAX_ROWID ){
  73543. pC->useRandomRowid = 1;
  73544. }else{
  73545. v++; /* IMP: R-29538-34987 */
  73546. }
  73547. }
  73548. }
  73549. #ifndef SQLITE_OMIT_AUTOINCREMENT
  73550. if( pOp->p3 ){
  73551. /* Assert that P3 is a valid memory cell. */
  73552. assert( pOp->p3>0 );
  73553. if( p->pFrame ){
  73554. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  73555. /* Assert that P3 is a valid memory cell. */
  73556. assert( pOp->p3<=pFrame->nMem );
  73557. pMem = &pFrame->aMem[pOp->p3];
  73558. }else{
  73559. /* Assert that P3 is a valid memory cell. */
  73560. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  73561. pMem = &aMem[pOp->p3];
  73562. memAboutToChange(p, pMem);
  73563. }
  73564. assert( memIsValid(pMem) );
  73565. REGISTER_TRACE(pOp->p3, pMem);
  73566. sqlite3VdbeMemIntegerify(pMem);
  73567. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  73568. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  73569. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  73570. goto abort_due_to_error;
  73571. }
  73572. if( v<pMem->u.i+1 ){
  73573. v = pMem->u.i + 1;
  73574. }
  73575. pMem->u.i = v;
  73576. }
  73577. #endif
  73578. if( pC->useRandomRowid ){
  73579. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  73580. ** largest possible integer (9223372036854775807) then the database
  73581. ** engine starts picking positive candidate ROWIDs at random until
  73582. ** it finds one that is not previously used. */
  73583. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  73584. ** an AUTOINCREMENT table. */
  73585. cnt = 0;
  73586. do{
  73587. sqlite3_randomness(sizeof(v), &v);
  73588. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  73589. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  73590. 0, &res))==SQLITE_OK)
  73591. && (res==0)
  73592. && (++cnt<100));
  73593. if( rc ) goto abort_due_to_error;
  73594. if( res==0 ){
  73595. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  73596. goto abort_due_to_error;
  73597. }
  73598. assert( v>0 ); /* EV: R-40812-03570 */
  73599. }
  73600. pC->deferredMoveto = 0;
  73601. pC->cacheStatus = CACHE_STALE;
  73602. }
  73603. pOut->u.i = v;
  73604. break;
  73605. }
  73606. /* Opcode: Insert P1 P2 P3 P4 P5
  73607. ** Synopsis: intkey=r[P3] data=r[P2]
  73608. **
  73609. ** Write an entry into the table of cursor P1. A new entry is
  73610. ** created if it doesn't already exist or the data for an existing
  73611. ** entry is overwritten. The data is the value MEM_Blob stored in register
  73612. ** number P2. The key is stored in register P3. The key must
  73613. ** be a MEM_Int.
  73614. **
  73615. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  73616. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  73617. ** then rowid is stored for subsequent return by the
  73618. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  73619. **
  73620. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  73621. ** the last seek operation (OP_NotExists) was a success, then this
  73622. ** operation will not attempt to find the appropriate row before doing
  73623. ** the insert but will instead overwrite the row that the cursor is
  73624. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  73625. ** has already positioned the cursor correctly. This is an optimization
  73626. ** that boosts performance by avoiding redundant seeks.
  73627. **
  73628. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  73629. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  73630. ** is part of an INSERT operation. The difference is only important to
  73631. ** the update hook.
  73632. **
  73633. ** Parameter P4 may point to a string containing the table-name, or
  73634. ** may be NULL. If it is not NULL, then the update-hook
  73635. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  73636. **
  73637. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  73638. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  73639. ** and register P2 becomes ephemeral. If the cursor is changed, the
  73640. ** value of register P2 will then change. Make sure this does not
  73641. ** cause any problems.)
  73642. **
  73643. ** This instruction only works on tables. The equivalent instruction
  73644. ** for indices is OP_IdxInsert.
  73645. */
  73646. /* Opcode: InsertInt P1 P2 P3 P4 P5
  73647. ** Synopsis: intkey=P3 data=r[P2]
  73648. **
  73649. ** This works exactly like OP_Insert except that the key is the
  73650. ** integer value P3, not the value of the integer stored in register P3.
  73651. */
  73652. case OP_Insert:
  73653. case OP_InsertInt: {
  73654. Mem *pData; /* MEM cell holding data for the record to be inserted */
  73655. Mem *pKey; /* MEM cell holding key for the record */
  73656. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  73657. VdbeCursor *pC; /* Cursor to table into which insert is written */
  73658. int nZero; /* Number of zero-bytes to append */
  73659. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  73660. const char *zDb; /* database name - used by the update hook */
  73661. const char *zTbl; /* Table name - used by the opdate hook */
  73662. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  73663. pData = &aMem[pOp->p2];
  73664. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73665. assert( memIsValid(pData) );
  73666. pC = p->apCsr[pOp->p1];
  73667. assert( pC!=0 );
  73668. assert( pC->eCurType==CURTYPE_BTREE );
  73669. assert( pC->uc.pCursor!=0 );
  73670. assert( pC->isTable );
  73671. REGISTER_TRACE(pOp->p2, pData);
  73672. if( pOp->opcode==OP_Insert ){
  73673. pKey = &aMem[pOp->p3];
  73674. assert( pKey->flags & MEM_Int );
  73675. assert( memIsValid(pKey) );
  73676. REGISTER_TRACE(pOp->p3, pKey);
  73677. iKey = pKey->u.i;
  73678. }else{
  73679. assert( pOp->opcode==OP_InsertInt );
  73680. iKey = pOp->p3;
  73681. }
  73682. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  73683. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  73684. if( pData->flags & MEM_Null ){
  73685. pData->z = 0;
  73686. pData->n = 0;
  73687. }else{
  73688. assert( pData->flags & (MEM_Blob|MEM_Str) );
  73689. }
  73690. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  73691. if( pData->flags & MEM_Zero ){
  73692. nZero = pData->u.nZero;
  73693. }else{
  73694. nZero = 0;
  73695. }
  73696. rc = sqlite3BtreeInsert(pC->uc.pCursor, 0, iKey,
  73697. pData->z, pData->n, nZero,
  73698. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  73699. );
  73700. pC->deferredMoveto = 0;
  73701. pC->cacheStatus = CACHE_STALE;
  73702. /* Invoke the update-hook if required. */
  73703. if( rc ) goto abort_due_to_error;
  73704. if( db->xUpdateCallback && pOp->p4.z ){
  73705. zDb = db->aDb[pC->iDb].zName;
  73706. zTbl = pOp->p4.z;
  73707. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  73708. assert( pC->isTable );
  73709. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  73710. assert( pC->iDb>=0 );
  73711. }
  73712. break;
  73713. }
  73714. /* Opcode: Delete P1 P2 * P4 P5
  73715. **
  73716. ** Delete the record at which the P1 cursor is currently pointing.
  73717. **
  73718. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  73719. ** the cursor will be left pointing at either the next or the previous
  73720. ** record in the table. If it is left pointing at the next record, then
  73721. ** the next Next instruction will be a no-op. As a result, in this case
  73722. ** it is ok to delete a record from within a Next loop. If
  73723. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  73724. ** left in an undefined state.
  73725. **
  73726. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  73727. ** delete one of several associated with deleting a table row and all its
  73728. ** associated index entries. Exactly one of those deletes is the "primary"
  73729. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  73730. ** marked with the AUXDELETE flag.
  73731. **
  73732. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  73733. ** change count is incremented (otherwise not).
  73734. **
  73735. ** P1 must not be pseudo-table. It has to be a real table with
  73736. ** multiple rows.
  73737. **
  73738. ** If P4 is not NULL, then it is the name of the table that P1 is
  73739. ** pointing to. The update hook will be invoked, if it exists.
  73740. ** If P4 is not NULL then the P1 cursor must have been positioned
  73741. ** using OP_NotFound prior to invoking this opcode.
  73742. */
  73743. case OP_Delete: {
  73744. VdbeCursor *pC;
  73745. u8 hasUpdateCallback;
  73746. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73747. pC = p->apCsr[pOp->p1];
  73748. assert( pC!=0 );
  73749. assert( pC->eCurType==CURTYPE_BTREE );
  73750. assert( pC->uc.pCursor!=0 );
  73751. assert( pC->deferredMoveto==0 );
  73752. hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
  73753. if( pOp->p5 && hasUpdateCallback ){
  73754. sqlite3BtreeKeySize(pC->uc.pCursor, &pC->movetoTarget);
  73755. }
  73756. #ifdef SQLITE_DEBUG
  73757. /* The seek operation that positioned the cursor prior to OP_Delete will
  73758. ** have also set the pC->movetoTarget field to the rowid of the row that
  73759. ** is being deleted */
  73760. if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
  73761. i64 iKey = 0;
  73762. sqlite3BtreeKeySize(pC->uc.pCursor, &iKey);
  73763. assert( pC->movetoTarget==iKey );
  73764. }
  73765. #endif
  73766. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  73767. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  73768. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  73769. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  73770. #ifdef SQLITE_DEBUG
  73771. if( p->pFrame==0 ){
  73772. if( pC->isEphemeral==0
  73773. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  73774. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  73775. ){
  73776. nExtraDelete++;
  73777. }
  73778. if( pOp->p2 & OPFLAG_NCHANGE ){
  73779. nExtraDelete--;
  73780. }
  73781. }
  73782. #endif
  73783. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  73784. pC->cacheStatus = CACHE_STALE;
  73785. /* Invoke the update-hook if required. */
  73786. if( rc ) goto abort_due_to_error;
  73787. if( hasUpdateCallback ){
  73788. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  73789. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  73790. assert( pC->iDb>=0 );
  73791. }
  73792. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  73793. break;
  73794. }
  73795. /* Opcode: ResetCount * * * * *
  73796. **
  73797. ** The value of the change counter is copied to the database handle
  73798. ** change counter (returned by subsequent calls to sqlite3_changes()).
  73799. ** Then the VMs internal change counter resets to 0.
  73800. ** This is used by trigger programs.
  73801. */
  73802. case OP_ResetCount: {
  73803. sqlite3VdbeSetChanges(db, p->nChange);
  73804. p->nChange = 0;
  73805. break;
  73806. }
  73807. /* Opcode: SorterCompare P1 P2 P3 P4
  73808. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  73809. **
  73810. ** P1 is a sorter cursor. This instruction compares a prefix of the
  73811. ** record blob in register P3 against a prefix of the entry that
  73812. ** the sorter cursor currently points to. Only the first P4 fields
  73813. ** of r[P3] and the sorter record are compared.
  73814. **
  73815. ** If either P3 or the sorter contains a NULL in one of their significant
  73816. ** fields (not counting the P4 fields at the end which are ignored) then
  73817. ** the comparison is assumed to be equal.
  73818. **
  73819. ** Fall through to next instruction if the two records compare equal to
  73820. ** each other. Jump to P2 if they are different.
  73821. */
  73822. case OP_SorterCompare: {
  73823. VdbeCursor *pC;
  73824. int res;
  73825. int nKeyCol;
  73826. pC = p->apCsr[pOp->p1];
  73827. assert( isSorter(pC) );
  73828. assert( pOp->p4type==P4_INT32 );
  73829. pIn3 = &aMem[pOp->p3];
  73830. nKeyCol = pOp->p4.i;
  73831. res = 0;
  73832. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  73833. VdbeBranchTaken(res!=0,2);
  73834. if( rc ) goto abort_due_to_error;
  73835. if( res ) goto jump_to_p2;
  73836. break;
  73837. };
  73838. /* Opcode: SorterData P1 P2 P3 * *
  73839. ** Synopsis: r[P2]=data
  73840. **
  73841. ** Write into register P2 the current sorter data for sorter cursor P1.
  73842. ** Then clear the column header cache on cursor P3.
  73843. **
  73844. ** This opcode is normally use to move a record out of the sorter and into
  73845. ** a register that is the source for a pseudo-table cursor created using
  73846. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  73847. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  73848. ** us from having to issue a separate NullRow instruction to clear that cache.
  73849. */
  73850. case OP_SorterData: {
  73851. VdbeCursor *pC;
  73852. pOut = &aMem[pOp->p2];
  73853. pC = p->apCsr[pOp->p1];
  73854. assert( isSorter(pC) );
  73855. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  73856. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  73857. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73858. if( rc ) goto abort_due_to_error;
  73859. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  73860. break;
  73861. }
  73862. /* Opcode: RowData P1 P2 * * *
  73863. ** Synopsis: r[P2]=data
  73864. **
  73865. ** Write into register P2 the complete row data for cursor P1.
  73866. ** There is no interpretation of the data.
  73867. ** It is just copied onto the P2 register exactly as
  73868. ** it is found in the database file.
  73869. **
  73870. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  73871. ** of a real table, not a pseudo-table.
  73872. */
  73873. /* Opcode: RowKey P1 P2 * * *
  73874. ** Synopsis: r[P2]=key
  73875. **
  73876. ** Write into register P2 the complete row key for cursor P1.
  73877. ** There is no interpretation of the data.
  73878. ** The key is copied onto the P2 register exactly as
  73879. ** it is found in the database file.
  73880. **
  73881. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  73882. ** of a real table, not a pseudo-table.
  73883. */
  73884. case OP_RowKey:
  73885. case OP_RowData: {
  73886. VdbeCursor *pC;
  73887. BtCursor *pCrsr;
  73888. u32 n;
  73889. i64 n64;
  73890. pOut = &aMem[pOp->p2];
  73891. memAboutToChange(p, pOut);
  73892. /* Note that RowKey and RowData are really exactly the same instruction */
  73893. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73894. pC = p->apCsr[pOp->p1];
  73895. assert( pC!=0 );
  73896. assert( pC->eCurType==CURTYPE_BTREE );
  73897. assert( isSorter(pC)==0 );
  73898. assert( pC->isTable || pOp->opcode!=OP_RowData );
  73899. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  73900. assert( pC->nullRow==0 );
  73901. assert( pC->uc.pCursor!=0 );
  73902. pCrsr = pC->uc.pCursor;
  73903. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  73904. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  73905. ** the cursor. If this where not the case, on of the following assert()s
  73906. ** would fail. Should this ever change (because of changes in the code
  73907. ** generator) then the fix would be to insert a call to
  73908. ** sqlite3VdbeCursorMoveto().
  73909. */
  73910. assert( pC->deferredMoveto==0 );
  73911. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  73912. #if 0 /* Not required due to the previous to assert() statements */
  73913. rc = sqlite3VdbeCursorMoveto(pC);
  73914. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  73915. #endif
  73916. if( pC->isTable==0 ){
  73917. assert( !pC->isTable );
  73918. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  73919. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  73920. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73921. goto too_big;
  73922. }
  73923. n = (u32)n64;
  73924. }else{
  73925. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  73926. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  73927. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73928. goto too_big;
  73929. }
  73930. }
  73931. testcase( n==0 );
  73932. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  73933. goto no_mem;
  73934. }
  73935. pOut->n = n;
  73936. MemSetTypeFlag(pOut, MEM_Blob);
  73937. if( pC->isTable==0 ){
  73938. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  73939. }else{
  73940. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  73941. }
  73942. if( rc ) goto abort_due_to_error;
  73943. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  73944. UPDATE_MAX_BLOBSIZE(pOut);
  73945. REGISTER_TRACE(pOp->p2, pOut);
  73946. break;
  73947. }
  73948. /* Opcode: Rowid P1 P2 * * *
  73949. ** Synopsis: r[P2]=rowid
  73950. **
  73951. ** Store in register P2 an integer which is the key of the table entry that
  73952. ** P1 is currently point to.
  73953. **
  73954. ** P1 can be either an ordinary table or a virtual table. There used to
  73955. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  73956. ** one opcode now works for both table types.
  73957. */
  73958. case OP_Rowid: { /* out2 */
  73959. VdbeCursor *pC;
  73960. i64 v;
  73961. sqlite3_vtab *pVtab;
  73962. const sqlite3_module *pModule;
  73963. pOut = out2Prerelease(p, pOp);
  73964. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73965. pC = p->apCsr[pOp->p1];
  73966. assert( pC!=0 );
  73967. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  73968. if( pC->nullRow ){
  73969. pOut->flags = MEM_Null;
  73970. break;
  73971. }else if( pC->deferredMoveto ){
  73972. v = pC->movetoTarget;
  73973. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73974. }else if( pC->eCurType==CURTYPE_VTAB ){
  73975. assert( pC->uc.pVCur!=0 );
  73976. pVtab = pC->uc.pVCur->pVtab;
  73977. pModule = pVtab->pModule;
  73978. assert( pModule->xRowid );
  73979. rc = pModule->xRowid(pC->uc.pVCur, &v);
  73980. sqlite3VtabImportErrmsg(p, pVtab);
  73981. if( rc ) goto abort_due_to_error;
  73982. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73983. }else{
  73984. assert( pC->eCurType==CURTYPE_BTREE );
  73985. assert( pC->uc.pCursor!=0 );
  73986. rc = sqlite3VdbeCursorRestore(pC);
  73987. if( rc ) goto abort_due_to_error;
  73988. if( pC->nullRow ){
  73989. pOut->flags = MEM_Null;
  73990. break;
  73991. }
  73992. rc = sqlite3BtreeKeySize(pC->uc.pCursor, &v);
  73993. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  73994. }
  73995. pOut->u.i = v;
  73996. break;
  73997. }
  73998. /* Opcode: NullRow P1 * * * *
  73999. **
  74000. ** Move the cursor P1 to a null row. Any OP_Column operations
  74001. ** that occur while the cursor is on the null row will always
  74002. ** write a NULL.
  74003. */
  74004. case OP_NullRow: {
  74005. VdbeCursor *pC;
  74006. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74007. pC = p->apCsr[pOp->p1];
  74008. assert( pC!=0 );
  74009. pC->nullRow = 1;
  74010. pC->cacheStatus = CACHE_STALE;
  74011. if( pC->eCurType==CURTYPE_BTREE ){
  74012. assert( pC->uc.pCursor!=0 );
  74013. sqlite3BtreeClearCursor(pC->uc.pCursor);
  74014. }
  74015. break;
  74016. }
  74017. /* Opcode: Last P1 P2 P3 * *
  74018. **
  74019. ** The next use of the Rowid or Column or Prev instruction for P1
  74020. ** will refer to the last entry in the database table or index.
  74021. ** If the table or index is empty and P2>0, then jump immediately to P2.
  74022. ** If P2 is 0 or if the table or index is not empty, fall through
  74023. ** to the following instruction.
  74024. **
  74025. ** This opcode leaves the cursor configured to move in reverse order,
  74026. ** from the end toward the beginning. In other words, the cursor is
  74027. ** configured to use Prev, not Next.
  74028. */
  74029. case OP_Last: { /* jump */
  74030. VdbeCursor *pC;
  74031. BtCursor *pCrsr;
  74032. int res;
  74033. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74034. pC = p->apCsr[pOp->p1];
  74035. assert( pC!=0 );
  74036. assert( pC->eCurType==CURTYPE_BTREE );
  74037. pCrsr = pC->uc.pCursor;
  74038. res = 0;
  74039. assert( pCrsr!=0 );
  74040. rc = sqlite3BtreeLast(pCrsr, &res);
  74041. pC->nullRow = (u8)res;
  74042. pC->deferredMoveto = 0;
  74043. pC->cacheStatus = CACHE_STALE;
  74044. pC->seekResult = pOp->p3;
  74045. #ifdef SQLITE_DEBUG
  74046. pC->seekOp = OP_Last;
  74047. #endif
  74048. if( rc ) goto abort_due_to_error;
  74049. if( pOp->p2>0 ){
  74050. VdbeBranchTaken(res!=0,2);
  74051. if( res ) goto jump_to_p2;
  74052. }
  74053. break;
  74054. }
  74055. /* Opcode: Sort P1 P2 * * *
  74056. **
  74057. ** This opcode does exactly the same thing as OP_Rewind except that
  74058. ** it increments an undocumented global variable used for testing.
  74059. **
  74060. ** Sorting is accomplished by writing records into a sorting index,
  74061. ** then rewinding that index and playing it back from beginning to
  74062. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  74063. ** rewinding so that the global variable will be incremented and
  74064. ** regression tests can determine whether or not the optimizer is
  74065. ** correctly optimizing out sorts.
  74066. */
  74067. case OP_SorterSort: /* jump */
  74068. case OP_Sort: { /* jump */
  74069. #ifdef SQLITE_TEST
  74070. sqlite3_sort_count++;
  74071. sqlite3_search_count--;
  74072. #endif
  74073. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  74074. /* Fall through into OP_Rewind */
  74075. }
  74076. /* Opcode: Rewind P1 P2 * * *
  74077. **
  74078. ** The next use of the Rowid or Column or Next instruction for P1
  74079. ** will refer to the first entry in the database table or index.
  74080. ** If the table or index is empty, jump immediately to P2.
  74081. ** If the table or index is not empty, fall through to the following
  74082. ** instruction.
  74083. **
  74084. ** This opcode leaves the cursor configured to move in forward order,
  74085. ** from the beginning toward the end. In other words, the cursor is
  74086. ** configured to use Next, not Prev.
  74087. */
  74088. case OP_Rewind: { /* jump */
  74089. VdbeCursor *pC;
  74090. BtCursor *pCrsr;
  74091. int res;
  74092. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74093. pC = p->apCsr[pOp->p1];
  74094. assert( pC!=0 );
  74095. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  74096. res = 1;
  74097. #ifdef SQLITE_DEBUG
  74098. pC->seekOp = OP_Rewind;
  74099. #endif
  74100. if( isSorter(pC) ){
  74101. rc = sqlite3VdbeSorterRewind(pC, &res);
  74102. }else{
  74103. assert( pC->eCurType==CURTYPE_BTREE );
  74104. pCrsr = pC->uc.pCursor;
  74105. assert( pCrsr );
  74106. rc = sqlite3BtreeFirst(pCrsr, &res);
  74107. pC->deferredMoveto = 0;
  74108. pC->cacheStatus = CACHE_STALE;
  74109. }
  74110. if( rc ) goto abort_due_to_error;
  74111. pC->nullRow = (u8)res;
  74112. assert( pOp->p2>0 && pOp->p2<p->nOp );
  74113. VdbeBranchTaken(res!=0,2);
  74114. if( res ) goto jump_to_p2;
  74115. break;
  74116. }
  74117. /* Opcode: Next P1 P2 P3 P4 P5
  74118. **
  74119. ** Advance cursor P1 so that it points to the next key/data pair in its
  74120. ** table or index. If there are no more key/value pairs then fall through
  74121. ** to the following instruction. But if the cursor advance was successful,
  74122. ** jump immediately to P2.
  74123. **
  74124. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  74125. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  74126. ** to follow SeekLT, SeekLE, or OP_Last.
  74127. **
  74128. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  74129. ** been opened prior to this opcode or the program will segfault.
  74130. **
  74131. ** The P3 value is a hint to the btree implementation. If P3==1, that
  74132. ** means P1 is an SQL index and that this instruction could have been
  74133. ** omitted if that index had been unique. P3 is usually 0. P3 is
  74134. ** always either 0 or 1.
  74135. **
  74136. ** P4 is always of type P4_ADVANCE. The function pointer points to
  74137. ** sqlite3BtreeNext().
  74138. **
  74139. ** If P5 is positive and the jump is taken, then event counter
  74140. ** number P5-1 in the prepared statement is incremented.
  74141. **
  74142. ** See also: Prev, NextIfOpen
  74143. */
  74144. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  74145. **
  74146. ** This opcode works just like Next except that if cursor P1 is not
  74147. ** open it behaves a no-op.
  74148. */
  74149. /* Opcode: Prev P1 P2 P3 P4 P5
  74150. **
  74151. ** Back up cursor P1 so that it points to the previous key/data pair in its
  74152. ** table or index. If there is no previous key/value pairs then fall through
  74153. ** to the following instruction. But if the cursor backup was successful,
  74154. ** jump immediately to P2.
  74155. **
  74156. **
  74157. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  74158. ** OP_Last opcode used to position the cursor. Prev is not allowed
  74159. ** to follow SeekGT, SeekGE, or OP_Rewind.
  74160. **
  74161. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  74162. ** not open then the behavior is undefined.
  74163. **
  74164. ** The P3 value is a hint to the btree implementation. If P3==1, that
  74165. ** means P1 is an SQL index and that this instruction could have been
  74166. ** omitted if that index had been unique. P3 is usually 0. P3 is
  74167. ** always either 0 or 1.
  74168. **
  74169. ** P4 is always of type P4_ADVANCE. The function pointer points to
  74170. ** sqlite3BtreePrevious().
  74171. **
  74172. ** If P5 is positive and the jump is taken, then event counter
  74173. ** number P5-1 in the prepared statement is incremented.
  74174. */
  74175. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  74176. **
  74177. ** This opcode works just like Prev except that if cursor P1 is not
  74178. ** open it behaves a no-op.
  74179. */
  74180. case OP_SorterNext: { /* jump */
  74181. VdbeCursor *pC;
  74182. int res;
  74183. pC = p->apCsr[pOp->p1];
  74184. assert( isSorter(pC) );
  74185. res = 0;
  74186. rc = sqlite3VdbeSorterNext(db, pC, &res);
  74187. goto next_tail;
  74188. case OP_PrevIfOpen: /* jump */
  74189. case OP_NextIfOpen: /* jump */
  74190. if( p->apCsr[pOp->p1]==0 ) break;
  74191. /* Fall through */
  74192. case OP_Prev: /* jump */
  74193. case OP_Next: /* jump */
  74194. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74195. assert( pOp->p5<ArraySize(p->aCounter) );
  74196. pC = p->apCsr[pOp->p1];
  74197. res = pOp->p3;
  74198. assert( pC!=0 );
  74199. assert( pC->deferredMoveto==0 );
  74200. assert( pC->eCurType==CURTYPE_BTREE );
  74201. assert( res==0 || (res==1 && pC->isTable==0) );
  74202. testcase( res==1 );
  74203. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  74204. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  74205. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  74206. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  74207. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  74208. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  74209. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  74210. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  74211. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  74212. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  74213. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  74214. || pC->seekOp==OP_Last );
  74215. rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
  74216. next_tail:
  74217. pC->cacheStatus = CACHE_STALE;
  74218. VdbeBranchTaken(res==0,2);
  74219. if( rc ) goto abort_due_to_error;
  74220. if( res==0 ){
  74221. pC->nullRow = 0;
  74222. p->aCounter[pOp->p5]++;
  74223. #ifdef SQLITE_TEST
  74224. sqlite3_search_count++;
  74225. #endif
  74226. goto jump_to_p2_and_check_for_interrupt;
  74227. }else{
  74228. pC->nullRow = 1;
  74229. }
  74230. goto check_for_interrupt;
  74231. }
  74232. /* Opcode: IdxInsert P1 P2 P3 * P5
  74233. ** Synopsis: key=r[P2]
  74234. **
  74235. ** Register P2 holds an SQL index key made using the
  74236. ** MakeRecord instructions. This opcode writes that key
  74237. ** into the index P1. Data for the entry is nil.
  74238. **
  74239. ** P3 is a flag that provides a hint to the b-tree layer that this
  74240. ** insert is likely to be an append.
  74241. **
  74242. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  74243. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  74244. ** then the change counter is unchanged.
  74245. **
  74246. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  74247. ** just done a seek to the spot where the new entry is to be inserted.
  74248. ** This flag avoids doing an extra seek.
  74249. **
  74250. ** This instruction only works for indices. The equivalent instruction
  74251. ** for tables is OP_Insert.
  74252. */
  74253. case OP_SorterInsert: /* in2 */
  74254. case OP_IdxInsert: { /* in2 */
  74255. VdbeCursor *pC;
  74256. int nKey;
  74257. const char *zKey;
  74258. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74259. pC = p->apCsr[pOp->p1];
  74260. assert( pC!=0 );
  74261. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  74262. pIn2 = &aMem[pOp->p2];
  74263. assert( pIn2->flags & MEM_Blob );
  74264. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  74265. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  74266. assert( pC->isTable==0 );
  74267. rc = ExpandBlob(pIn2);
  74268. if( rc ) goto abort_due_to_error;
  74269. if( pOp->opcode==OP_SorterInsert ){
  74270. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  74271. }else{
  74272. nKey = pIn2->n;
  74273. zKey = pIn2->z;
  74274. rc = sqlite3BtreeInsert(pC->uc.pCursor, zKey, nKey, "", 0, 0, pOp->p3,
  74275. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  74276. );
  74277. assert( pC->deferredMoveto==0 );
  74278. pC->cacheStatus = CACHE_STALE;
  74279. }
  74280. if( rc) goto abort_due_to_error;
  74281. break;
  74282. }
  74283. /* Opcode: IdxDelete P1 P2 P3 * *
  74284. ** Synopsis: key=r[P2@P3]
  74285. **
  74286. ** The content of P3 registers starting at register P2 form
  74287. ** an unpacked index key. This opcode removes that entry from the
  74288. ** index opened by cursor P1.
  74289. */
  74290. case OP_IdxDelete: {
  74291. VdbeCursor *pC;
  74292. BtCursor *pCrsr;
  74293. int res;
  74294. UnpackedRecord r;
  74295. assert( pOp->p3>0 );
  74296. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  74297. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74298. pC = p->apCsr[pOp->p1];
  74299. assert( pC!=0 );
  74300. assert( pC->eCurType==CURTYPE_BTREE );
  74301. pCrsr = pC->uc.pCursor;
  74302. assert( pCrsr!=0 );
  74303. assert( pOp->p5==0 );
  74304. r.pKeyInfo = pC->pKeyInfo;
  74305. r.nField = (u16)pOp->p3;
  74306. r.default_rc = 0;
  74307. r.aMem = &aMem[pOp->p2];
  74308. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  74309. if( rc ) goto abort_due_to_error;
  74310. if( res==0 ){
  74311. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  74312. if( rc ) goto abort_due_to_error;
  74313. }
  74314. assert( pC->deferredMoveto==0 );
  74315. pC->cacheStatus = CACHE_STALE;
  74316. break;
  74317. }
  74318. /* Opcode: Seek P1 * P3 P4 *
  74319. ** Synopsis: Move P3 to P1.rowid
  74320. **
  74321. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  74322. ** table. This opcode does a deferred seek of the P3 table cursor
  74323. ** to the row that corresponds to the current row of P1.
  74324. **
  74325. ** This is a deferred seek. Nothing actually happens until
  74326. ** the cursor is used to read a record. That way, if no reads
  74327. ** occur, no unnecessary I/O happens.
  74328. **
  74329. ** P4 may be an array of integers (type P4_INTARRAY) containing
  74330. ** one entry for each column in the P3 table. If array entry a(i)
  74331. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  74332. ** equivalent to performing the deferred seek and then reading column i
  74333. ** from P1. This information is stored in P3 and used to redirect
  74334. ** reads against P3 over to P1, thus possibly avoiding the need to
  74335. ** seek and read cursor P3.
  74336. */
  74337. /* Opcode: IdxRowid P1 P2 * * *
  74338. ** Synopsis: r[P2]=rowid
  74339. **
  74340. ** Write into register P2 an integer which is the last entry in the record at
  74341. ** the end of the index key pointed to by cursor P1. This integer should be
  74342. ** the rowid of the table entry to which this index entry points.
  74343. **
  74344. ** See also: Rowid, MakeRecord.
  74345. */
  74346. case OP_Seek:
  74347. case OP_IdxRowid: { /* out2 */
  74348. VdbeCursor *pC; /* The P1 index cursor */
  74349. VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */
  74350. i64 rowid; /* Rowid that P1 current points to */
  74351. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74352. pC = p->apCsr[pOp->p1];
  74353. assert( pC!=0 );
  74354. assert( pC->eCurType==CURTYPE_BTREE );
  74355. assert( pC->uc.pCursor!=0 );
  74356. assert( pC->isTable==0 );
  74357. assert( pC->deferredMoveto==0 );
  74358. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  74359. /* The IdxRowid and Seek opcodes are combined because of the commonality
  74360. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  74361. rc = sqlite3VdbeCursorRestore(pC);
  74362. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  74363. ** out from under the cursor. That will never happens for an IdxRowid
  74364. ** or Seek opcode */
  74365. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  74366. if( !pC->nullRow ){
  74367. rowid = 0; /* Not needed. Only used to silence a warning. */
  74368. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  74369. if( rc!=SQLITE_OK ){
  74370. goto abort_due_to_error;
  74371. }
  74372. if( pOp->opcode==OP_Seek ){
  74373. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  74374. pTabCur = p->apCsr[pOp->p3];
  74375. assert( pTabCur!=0 );
  74376. assert( pTabCur->eCurType==CURTYPE_BTREE );
  74377. assert( pTabCur->uc.pCursor!=0 );
  74378. assert( pTabCur->isTable );
  74379. pTabCur->nullRow = 0;
  74380. pTabCur->movetoTarget = rowid;
  74381. pTabCur->deferredMoveto = 1;
  74382. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  74383. pTabCur->aAltMap = pOp->p4.ai;
  74384. pTabCur->pAltCursor = pC;
  74385. }else{
  74386. pOut = out2Prerelease(p, pOp);
  74387. pOut->u.i = rowid;
  74388. pOut->flags = MEM_Int;
  74389. }
  74390. }else{
  74391. assert( pOp->opcode==OP_IdxRowid );
  74392. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  74393. }
  74394. break;
  74395. }
  74396. /* Opcode: IdxGE P1 P2 P3 P4 P5
  74397. ** Synopsis: key=r[P3@P4]
  74398. **
  74399. ** The P4 register values beginning with P3 form an unpacked index
  74400. ** key that omits the PRIMARY KEY. Compare this key value against the index
  74401. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  74402. ** fields at the end.
  74403. **
  74404. ** If the P1 index entry is greater than or equal to the key value
  74405. ** then jump to P2. Otherwise fall through to the next instruction.
  74406. */
  74407. /* Opcode: IdxGT P1 P2 P3 P4 P5
  74408. ** Synopsis: key=r[P3@P4]
  74409. **
  74410. ** The P4 register values beginning with P3 form an unpacked index
  74411. ** key that omits the PRIMARY KEY. Compare this key value against the index
  74412. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  74413. ** fields at the end.
  74414. **
  74415. ** If the P1 index entry is greater than the key value
  74416. ** then jump to P2. Otherwise fall through to the next instruction.
  74417. */
  74418. /* Opcode: IdxLT P1 P2 P3 P4 P5
  74419. ** Synopsis: key=r[P3@P4]
  74420. **
  74421. ** The P4 register values beginning with P3 form an unpacked index
  74422. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  74423. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  74424. ** ROWID on the P1 index.
  74425. **
  74426. ** If the P1 index entry is less than the key value then jump to P2.
  74427. ** Otherwise fall through to the next instruction.
  74428. */
  74429. /* Opcode: IdxLE P1 P2 P3 P4 P5
  74430. ** Synopsis: key=r[P3@P4]
  74431. **
  74432. ** The P4 register values beginning with P3 form an unpacked index
  74433. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  74434. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  74435. ** ROWID on the P1 index.
  74436. **
  74437. ** If the P1 index entry is less than or equal to the key value then jump
  74438. ** to P2. Otherwise fall through to the next instruction.
  74439. */
  74440. case OP_IdxLE: /* jump */
  74441. case OP_IdxGT: /* jump */
  74442. case OP_IdxLT: /* jump */
  74443. case OP_IdxGE: { /* jump */
  74444. VdbeCursor *pC;
  74445. int res;
  74446. UnpackedRecord r;
  74447. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74448. pC = p->apCsr[pOp->p1];
  74449. assert( pC!=0 );
  74450. assert( pC->isOrdered );
  74451. assert( pC->eCurType==CURTYPE_BTREE );
  74452. assert( pC->uc.pCursor!=0);
  74453. assert( pC->deferredMoveto==0 );
  74454. assert( pOp->p5==0 || pOp->p5==1 );
  74455. assert( pOp->p4type==P4_INT32 );
  74456. r.pKeyInfo = pC->pKeyInfo;
  74457. r.nField = (u16)pOp->p4.i;
  74458. if( pOp->opcode<OP_IdxLT ){
  74459. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  74460. r.default_rc = -1;
  74461. }else{
  74462. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  74463. r.default_rc = 0;
  74464. }
  74465. r.aMem = &aMem[pOp->p3];
  74466. #ifdef SQLITE_DEBUG
  74467. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  74468. #endif
  74469. res = 0; /* Not needed. Only used to silence a warning. */
  74470. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  74471. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  74472. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  74473. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  74474. res = -res;
  74475. }else{
  74476. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  74477. res++;
  74478. }
  74479. VdbeBranchTaken(res>0,2);
  74480. if( rc ) goto abort_due_to_error;
  74481. if( res>0 ) goto jump_to_p2;
  74482. break;
  74483. }
  74484. /* Opcode: Destroy P1 P2 P3 * *
  74485. **
  74486. ** Delete an entire database table or index whose root page in the database
  74487. ** file is given by P1.
  74488. **
  74489. ** The table being destroyed is in the main database file if P3==0. If
  74490. ** P3==1 then the table to be clear is in the auxiliary database file
  74491. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  74492. **
  74493. ** If AUTOVACUUM is enabled then it is possible that another root page
  74494. ** might be moved into the newly deleted root page in order to keep all
  74495. ** root pages contiguous at the beginning of the database. The former
  74496. ** value of the root page that moved - its value before the move occurred -
  74497. ** is stored in register P2. If no page
  74498. ** movement was required (because the table being dropped was already
  74499. ** the last one in the database) then a zero is stored in register P2.
  74500. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  74501. **
  74502. ** See also: Clear
  74503. */
  74504. case OP_Destroy: { /* out2 */
  74505. int iMoved;
  74506. int iDb;
  74507. assert( p->readOnly==0 );
  74508. assert( pOp->p1>1 );
  74509. pOut = out2Prerelease(p, pOp);
  74510. pOut->flags = MEM_Null;
  74511. if( db->nVdbeRead > db->nVDestroy+1 ){
  74512. rc = SQLITE_LOCKED;
  74513. p->errorAction = OE_Abort;
  74514. goto abort_due_to_error;
  74515. }else{
  74516. iDb = pOp->p3;
  74517. assert( DbMaskTest(p->btreeMask, iDb) );
  74518. iMoved = 0; /* Not needed. Only to silence a warning. */
  74519. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  74520. pOut->flags = MEM_Int;
  74521. pOut->u.i = iMoved;
  74522. if( rc ) goto abort_due_to_error;
  74523. #ifndef SQLITE_OMIT_AUTOVACUUM
  74524. if( iMoved!=0 ){
  74525. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  74526. /* All OP_Destroy operations occur on the same btree */
  74527. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  74528. resetSchemaOnFault = iDb+1;
  74529. }
  74530. #endif
  74531. }
  74532. break;
  74533. }
  74534. /* Opcode: Clear P1 P2 P3
  74535. **
  74536. ** Delete all contents of the database table or index whose root page
  74537. ** in the database file is given by P1. But, unlike Destroy, do not
  74538. ** remove the table or index from the database file.
  74539. **
  74540. ** The table being clear is in the main database file if P2==0. If
  74541. ** P2==1 then the table to be clear is in the auxiliary database file
  74542. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  74543. **
  74544. ** If the P3 value is non-zero, then the table referred to must be an
  74545. ** intkey table (an SQL table, not an index). In this case the row change
  74546. ** count is incremented by the number of rows in the table being cleared.
  74547. ** If P3 is greater than zero, then the value stored in register P3 is
  74548. ** also incremented by the number of rows in the table being cleared.
  74549. **
  74550. ** See also: Destroy
  74551. */
  74552. case OP_Clear: {
  74553. int nChange;
  74554. nChange = 0;
  74555. assert( p->readOnly==0 );
  74556. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  74557. rc = sqlite3BtreeClearTable(
  74558. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  74559. );
  74560. if( pOp->p3 ){
  74561. p->nChange += nChange;
  74562. if( pOp->p3>0 ){
  74563. assert( memIsValid(&aMem[pOp->p3]) );
  74564. memAboutToChange(p, &aMem[pOp->p3]);
  74565. aMem[pOp->p3].u.i += nChange;
  74566. }
  74567. }
  74568. if( rc ) goto abort_due_to_error;
  74569. break;
  74570. }
  74571. /* Opcode: ResetSorter P1 * * * *
  74572. **
  74573. ** Delete all contents from the ephemeral table or sorter
  74574. ** that is open on cursor P1.
  74575. **
  74576. ** This opcode only works for cursors used for sorting and
  74577. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  74578. */
  74579. case OP_ResetSorter: {
  74580. VdbeCursor *pC;
  74581. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  74582. pC = p->apCsr[pOp->p1];
  74583. assert( pC!=0 );
  74584. if( isSorter(pC) ){
  74585. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  74586. }else{
  74587. assert( pC->eCurType==CURTYPE_BTREE );
  74588. assert( pC->isEphemeral );
  74589. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  74590. if( rc ) goto abort_due_to_error;
  74591. }
  74592. break;
  74593. }
  74594. /* Opcode: CreateTable P1 P2 * * *
  74595. ** Synopsis: r[P2]=root iDb=P1
  74596. **
  74597. ** Allocate a new table in the main database file if P1==0 or in the
  74598. ** auxiliary database file if P1==1 or in an attached database if
  74599. ** P1>1. Write the root page number of the new table into
  74600. ** register P2
  74601. **
  74602. ** The difference between a table and an index is this: A table must
  74603. ** have a 4-byte integer key and can have arbitrary data. An index
  74604. ** has an arbitrary key but no data.
  74605. **
  74606. ** See also: CreateIndex
  74607. */
  74608. /* Opcode: CreateIndex P1 P2 * * *
  74609. ** Synopsis: r[P2]=root iDb=P1
  74610. **
  74611. ** Allocate a new index in the main database file if P1==0 or in the
  74612. ** auxiliary database file if P1==1 or in an attached database if
  74613. ** P1>1. Write the root page number of the new table into
  74614. ** register P2.
  74615. **
  74616. ** See documentation on OP_CreateTable for additional information.
  74617. */
  74618. case OP_CreateIndex: /* out2 */
  74619. case OP_CreateTable: { /* out2 */
  74620. int pgno;
  74621. int flags;
  74622. Db *pDb;
  74623. pOut = out2Prerelease(p, pOp);
  74624. pgno = 0;
  74625. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  74626. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  74627. assert( p->readOnly==0 );
  74628. pDb = &db->aDb[pOp->p1];
  74629. assert( pDb->pBt!=0 );
  74630. if( pOp->opcode==OP_CreateTable ){
  74631. /* flags = BTREE_INTKEY; */
  74632. flags = BTREE_INTKEY;
  74633. }else{
  74634. flags = BTREE_BLOBKEY;
  74635. }
  74636. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  74637. if( rc ) goto abort_due_to_error;
  74638. pOut->u.i = pgno;
  74639. break;
  74640. }
  74641. /* Opcode: ParseSchema P1 * * P4 *
  74642. **
  74643. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  74644. ** that match the WHERE clause P4.
  74645. **
  74646. ** This opcode invokes the parser to create a new virtual machine,
  74647. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  74648. */
  74649. case OP_ParseSchema: {
  74650. int iDb;
  74651. const char *zMaster;
  74652. char *zSql;
  74653. InitData initData;
  74654. /* Any prepared statement that invokes this opcode will hold mutexes
  74655. ** on every btree. This is a prerequisite for invoking
  74656. ** sqlite3InitCallback().
  74657. */
  74658. #ifdef SQLITE_DEBUG
  74659. for(iDb=0; iDb<db->nDb; iDb++){
  74660. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  74661. }
  74662. #endif
  74663. iDb = pOp->p1;
  74664. assert( iDb>=0 && iDb<db->nDb );
  74665. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  74666. /* Used to be a conditional */ {
  74667. zMaster = SCHEMA_TABLE(iDb);
  74668. initData.db = db;
  74669. initData.iDb = pOp->p1;
  74670. initData.pzErrMsg = &p->zErrMsg;
  74671. zSql = sqlite3MPrintf(db,
  74672. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  74673. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  74674. if( zSql==0 ){
  74675. rc = SQLITE_NOMEM_BKPT;
  74676. }else{
  74677. assert( db->init.busy==0 );
  74678. db->init.busy = 1;
  74679. initData.rc = SQLITE_OK;
  74680. assert( !db->mallocFailed );
  74681. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  74682. if( rc==SQLITE_OK ) rc = initData.rc;
  74683. sqlite3DbFree(db, zSql);
  74684. db->init.busy = 0;
  74685. }
  74686. }
  74687. if( rc ){
  74688. sqlite3ResetAllSchemasOfConnection(db);
  74689. if( rc==SQLITE_NOMEM ){
  74690. goto no_mem;
  74691. }
  74692. goto abort_due_to_error;
  74693. }
  74694. break;
  74695. }
  74696. #if !defined(SQLITE_OMIT_ANALYZE)
  74697. /* Opcode: LoadAnalysis P1 * * * *
  74698. **
  74699. ** Read the sqlite_stat1 table for database P1 and load the content
  74700. ** of that table into the internal index hash table. This will cause
  74701. ** the analysis to be used when preparing all subsequent queries.
  74702. */
  74703. case OP_LoadAnalysis: {
  74704. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  74705. rc = sqlite3AnalysisLoad(db, pOp->p1);
  74706. if( rc ) goto abort_due_to_error;
  74707. break;
  74708. }
  74709. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  74710. /* Opcode: DropTable P1 * * P4 *
  74711. **
  74712. ** Remove the internal (in-memory) data structures that describe
  74713. ** the table named P4 in database P1. This is called after a table
  74714. ** is dropped from disk (using the Destroy opcode) in order to keep
  74715. ** the internal representation of the
  74716. ** schema consistent with what is on disk.
  74717. */
  74718. case OP_DropTable: {
  74719. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  74720. break;
  74721. }
  74722. /* Opcode: DropIndex P1 * * P4 *
  74723. **
  74724. ** Remove the internal (in-memory) data structures that describe
  74725. ** the index named P4 in database P1. This is called after an index
  74726. ** is dropped from disk (using the Destroy opcode)
  74727. ** in order to keep the internal representation of the
  74728. ** schema consistent with what is on disk.
  74729. */
  74730. case OP_DropIndex: {
  74731. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  74732. break;
  74733. }
  74734. /* Opcode: DropTrigger P1 * * P4 *
  74735. **
  74736. ** Remove the internal (in-memory) data structures that describe
  74737. ** the trigger named P4 in database P1. This is called after a trigger
  74738. ** is dropped from disk (using the Destroy opcode) in order to keep
  74739. ** the internal representation of the
  74740. ** schema consistent with what is on disk.
  74741. */
  74742. case OP_DropTrigger: {
  74743. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  74744. break;
  74745. }
  74746. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  74747. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  74748. **
  74749. ** Do an analysis of the currently open database. Store in
  74750. ** register P1 the text of an error message describing any problems.
  74751. ** If no problems are found, store a NULL in register P1.
  74752. **
  74753. ** The register P3 contains the maximum number of allowed errors.
  74754. ** At most reg(P3) errors will be reported.
  74755. ** In other words, the analysis stops as soon as reg(P1) errors are
  74756. ** seen. Reg(P1) is updated with the number of errors remaining.
  74757. **
  74758. ** The root page numbers of all tables in the database are integers
  74759. ** stored in P4_INTARRAY argument.
  74760. **
  74761. ** If P5 is not zero, the check is done on the auxiliary database
  74762. ** file, not the main database file.
  74763. **
  74764. ** This opcode is used to implement the integrity_check pragma.
  74765. */
  74766. case OP_IntegrityCk: {
  74767. int nRoot; /* Number of tables to check. (Number of root pages.) */
  74768. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  74769. int nErr; /* Number of errors reported */
  74770. char *z; /* Text of the error report */
  74771. Mem *pnErr; /* Register keeping track of errors remaining */
  74772. assert( p->bIsReader );
  74773. nRoot = pOp->p2;
  74774. aRoot = pOp->p4.ai;
  74775. assert( nRoot>0 );
  74776. assert( aRoot[nRoot]==0 );
  74777. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  74778. pnErr = &aMem[pOp->p3];
  74779. assert( (pnErr->flags & MEM_Int)!=0 );
  74780. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  74781. pIn1 = &aMem[pOp->p1];
  74782. assert( pOp->p5<db->nDb );
  74783. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  74784. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  74785. (int)pnErr->u.i, &nErr);
  74786. pnErr->u.i -= nErr;
  74787. sqlite3VdbeMemSetNull(pIn1);
  74788. if( nErr==0 ){
  74789. assert( z==0 );
  74790. }else if( z==0 ){
  74791. goto no_mem;
  74792. }else{
  74793. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  74794. }
  74795. UPDATE_MAX_BLOBSIZE(pIn1);
  74796. sqlite3VdbeChangeEncoding(pIn1, encoding);
  74797. break;
  74798. }
  74799. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  74800. /* Opcode: RowSetAdd P1 P2 * * *
  74801. ** Synopsis: rowset(P1)=r[P2]
  74802. **
  74803. ** Insert the integer value held by register P2 into a boolean index
  74804. ** held in register P1.
  74805. **
  74806. ** An assertion fails if P2 is not an integer.
  74807. */
  74808. case OP_RowSetAdd: { /* in1, in2 */
  74809. pIn1 = &aMem[pOp->p1];
  74810. pIn2 = &aMem[pOp->p2];
  74811. assert( (pIn2->flags & MEM_Int)!=0 );
  74812. if( (pIn1->flags & MEM_RowSet)==0 ){
  74813. sqlite3VdbeMemSetRowSet(pIn1);
  74814. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  74815. }
  74816. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  74817. break;
  74818. }
  74819. /* Opcode: RowSetRead P1 P2 P3 * *
  74820. ** Synopsis: r[P3]=rowset(P1)
  74821. **
  74822. ** Extract the smallest value from boolean index P1 and put that value into
  74823. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  74824. ** unchanged and jump to instruction P2.
  74825. */
  74826. case OP_RowSetRead: { /* jump, in1, out3 */
  74827. i64 val;
  74828. pIn1 = &aMem[pOp->p1];
  74829. if( (pIn1->flags & MEM_RowSet)==0
  74830. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  74831. ){
  74832. /* The boolean index is empty */
  74833. sqlite3VdbeMemSetNull(pIn1);
  74834. VdbeBranchTaken(1,2);
  74835. goto jump_to_p2_and_check_for_interrupt;
  74836. }else{
  74837. /* A value was pulled from the index */
  74838. VdbeBranchTaken(0,2);
  74839. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  74840. }
  74841. goto check_for_interrupt;
  74842. }
  74843. /* Opcode: RowSetTest P1 P2 P3 P4
  74844. ** Synopsis: if r[P3] in rowset(P1) goto P2
  74845. **
  74846. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  74847. ** contains a RowSet object and that RowSet object contains
  74848. ** the value held in P3, jump to register P2. Otherwise, insert the
  74849. ** integer in P3 into the RowSet and continue on to the
  74850. ** next opcode.
  74851. **
  74852. ** The RowSet object is optimized for the case where successive sets
  74853. ** of integers, where each set contains no duplicates. Each set
  74854. ** of values is identified by a unique P4 value. The first set
  74855. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  74856. ** non-negative. For non-negative values of P4 only the lower 4
  74857. ** bits are significant.
  74858. **
  74859. ** This allows optimizations: (a) when P4==0 there is no need to test
  74860. ** the rowset object for P3, as it is guaranteed not to contain it,
  74861. ** (b) when P4==-1 there is no need to insert the value, as it will
  74862. ** never be tested for, and (c) when a value that is part of set X is
  74863. ** inserted, there is no need to search to see if the same value was
  74864. ** previously inserted as part of set X (only if it was previously
  74865. ** inserted as part of some other set).
  74866. */
  74867. case OP_RowSetTest: { /* jump, in1, in3 */
  74868. int iSet;
  74869. int exists;
  74870. pIn1 = &aMem[pOp->p1];
  74871. pIn3 = &aMem[pOp->p3];
  74872. iSet = pOp->p4.i;
  74873. assert( pIn3->flags&MEM_Int );
  74874. /* If there is anything other than a rowset object in memory cell P1,
  74875. ** delete it now and initialize P1 with an empty rowset
  74876. */
  74877. if( (pIn1->flags & MEM_RowSet)==0 ){
  74878. sqlite3VdbeMemSetRowSet(pIn1);
  74879. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  74880. }
  74881. assert( pOp->p4type==P4_INT32 );
  74882. assert( iSet==-1 || iSet>=0 );
  74883. if( iSet ){
  74884. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  74885. VdbeBranchTaken(exists!=0,2);
  74886. if( exists ) goto jump_to_p2;
  74887. }
  74888. if( iSet>=0 ){
  74889. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  74890. }
  74891. break;
  74892. }
  74893. #ifndef SQLITE_OMIT_TRIGGER
  74894. /* Opcode: Program P1 P2 P3 P4 P5
  74895. **
  74896. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  74897. **
  74898. ** P1 contains the address of the memory cell that contains the first memory
  74899. ** cell in an array of values used as arguments to the sub-program. P2
  74900. ** contains the address to jump to if the sub-program throws an IGNORE
  74901. ** exception using the RAISE() function. Register P3 contains the address
  74902. ** of a memory cell in this (the parent) VM that is used to allocate the
  74903. ** memory required by the sub-vdbe at runtime.
  74904. **
  74905. ** P4 is a pointer to the VM containing the trigger program.
  74906. **
  74907. ** If P5 is non-zero, then recursive program invocation is enabled.
  74908. */
  74909. case OP_Program: { /* jump */
  74910. int nMem; /* Number of memory registers for sub-program */
  74911. int nByte; /* Bytes of runtime space required for sub-program */
  74912. Mem *pRt; /* Register to allocate runtime space */
  74913. Mem *pMem; /* Used to iterate through memory cells */
  74914. Mem *pEnd; /* Last memory cell in new array */
  74915. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  74916. SubProgram *pProgram; /* Sub-program to execute */
  74917. void *t; /* Token identifying trigger */
  74918. pProgram = pOp->p4.pProgram;
  74919. pRt = &aMem[pOp->p3];
  74920. assert( pProgram->nOp>0 );
  74921. /* If the p5 flag is clear, then recursive invocation of triggers is
  74922. ** disabled for backwards compatibility (p5 is set if this sub-program
  74923. ** is really a trigger, not a foreign key action, and the flag set
  74924. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  74925. **
  74926. ** It is recursive invocation of triggers, at the SQL level, that is
  74927. ** disabled. In some cases a single trigger may generate more than one
  74928. ** SubProgram (if the trigger may be executed with more than one different
  74929. ** ON CONFLICT algorithm). SubProgram structures associated with a
  74930. ** single trigger all have the same value for the SubProgram.token
  74931. ** variable. */
  74932. if( pOp->p5 ){
  74933. t = pProgram->token;
  74934. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  74935. if( pFrame ) break;
  74936. }
  74937. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  74938. rc = SQLITE_ERROR;
  74939. sqlite3VdbeError(p, "too many levels of trigger recursion");
  74940. goto abort_due_to_error;
  74941. }
  74942. /* Register pRt is used to store the memory required to save the state
  74943. ** of the current program, and the memory required at runtime to execute
  74944. ** the trigger program. If this trigger has been fired before, then pRt
  74945. ** is already allocated. Otherwise, it must be initialized. */
  74946. if( (pRt->flags&MEM_Frame)==0 ){
  74947. /* SubProgram.nMem is set to the number of memory cells used by the
  74948. ** program stored in SubProgram.aOp. As well as these, one memory
  74949. ** cell is required for each cursor used by the program. Set local
  74950. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  74951. */
  74952. nMem = pProgram->nMem + pProgram->nCsr;
  74953. assert( nMem>0 );
  74954. if( pProgram->nCsr==0 ) nMem++;
  74955. nByte = ROUND8(sizeof(VdbeFrame))
  74956. + nMem * sizeof(Mem)
  74957. + pProgram->nCsr * sizeof(VdbeCursor *)
  74958. + pProgram->nOnce * sizeof(u8);
  74959. pFrame = sqlite3DbMallocZero(db, nByte);
  74960. if( !pFrame ){
  74961. goto no_mem;
  74962. }
  74963. sqlite3VdbeMemRelease(pRt);
  74964. pRt->flags = MEM_Frame;
  74965. pRt->u.pFrame = pFrame;
  74966. pFrame->v = p;
  74967. pFrame->nChildMem = nMem;
  74968. pFrame->nChildCsr = pProgram->nCsr;
  74969. pFrame->pc = (int)(pOp - aOp);
  74970. pFrame->aMem = p->aMem;
  74971. pFrame->nMem = p->nMem;
  74972. pFrame->apCsr = p->apCsr;
  74973. pFrame->nCursor = p->nCursor;
  74974. pFrame->aOp = p->aOp;
  74975. pFrame->nOp = p->nOp;
  74976. pFrame->token = pProgram->token;
  74977. pFrame->aOnceFlag = p->aOnceFlag;
  74978. pFrame->nOnceFlag = p->nOnceFlag;
  74979. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74980. pFrame->anExec = p->anExec;
  74981. #endif
  74982. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  74983. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  74984. pMem->flags = MEM_Undefined;
  74985. pMem->db = db;
  74986. }
  74987. }else{
  74988. pFrame = pRt->u.pFrame;
  74989. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  74990. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  74991. assert( pProgram->nCsr==pFrame->nChildCsr );
  74992. assert( (int)(pOp - aOp)==pFrame->pc );
  74993. }
  74994. p->nFrame++;
  74995. pFrame->pParent = p->pFrame;
  74996. pFrame->lastRowid = lastRowid;
  74997. pFrame->nChange = p->nChange;
  74998. pFrame->nDbChange = p->db->nChange;
  74999. assert( pFrame->pAuxData==0 );
  75000. pFrame->pAuxData = p->pAuxData;
  75001. p->pAuxData = 0;
  75002. p->nChange = 0;
  75003. p->pFrame = pFrame;
  75004. p->aMem = aMem = VdbeFrameMem(pFrame);
  75005. p->nMem = pFrame->nChildMem;
  75006. p->nCursor = (u16)pFrame->nChildCsr;
  75007. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  75008. p->aOp = aOp = pProgram->aOp;
  75009. p->nOp = pProgram->nOp;
  75010. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  75011. p->nOnceFlag = pProgram->nOnce;
  75012. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  75013. p->anExec = 0;
  75014. #endif
  75015. pOp = &aOp[-1];
  75016. memset(p->aOnceFlag, 0, p->nOnceFlag);
  75017. break;
  75018. }
  75019. /* Opcode: Param P1 P2 * * *
  75020. **
  75021. ** This opcode is only ever present in sub-programs called via the
  75022. ** OP_Program instruction. Copy a value currently stored in a memory
  75023. ** cell of the calling (parent) frame to cell P2 in the current frames
  75024. ** address space. This is used by trigger programs to access the new.*
  75025. ** and old.* values.
  75026. **
  75027. ** The address of the cell in the parent frame is determined by adding
  75028. ** the value of the P1 argument to the value of the P1 argument to the
  75029. ** calling OP_Program instruction.
  75030. */
  75031. case OP_Param: { /* out2 */
  75032. VdbeFrame *pFrame;
  75033. Mem *pIn;
  75034. pOut = out2Prerelease(p, pOp);
  75035. pFrame = p->pFrame;
  75036. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  75037. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  75038. break;
  75039. }
  75040. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  75041. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75042. /* Opcode: FkCounter P1 P2 * * *
  75043. ** Synopsis: fkctr[P1]+=P2
  75044. **
  75045. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  75046. ** If P1 is non-zero, the database constraint counter is incremented
  75047. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  75048. ** statement counter is incremented (immediate foreign key constraints).
  75049. */
  75050. case OP_FkCounter: {
  75051. if( db->flags & SQLITE_DeferFKs ){
  75052. db->nDeferredImmCons += pOp->p2;
  75053. }else if( pOp->p1 ){
  75054. db->nDeferredCons += pOp->p2;
  75055. }else{
  75056. p->nFkConstraint += pOp->p2;
  75057. }
  75058. break;
  75059. }
  75060. /* Opcode: FkIfZero P1 P2 * * *
  75061. ** Synopsis: if fkctr[P1]==0 goto P2
  75062. **
  75063. ** This opcode tests if a foreign key constraint-counter is currently zero.
  75064. ** If so, jump to instruction P2. Otherwise, fall through to the next
  75065. ** instruction.
  75066. **
  75067. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  75068. ** is zero (the one that counts deferred constraint violations). If P1 is
  75069. ** zero, the jump is taken if the statement constraint-counter is zero
  75070. ** (immediate foreign key constraint violations).
  75071. */
  75072. case OP_FkIfZero: { /* jump */
  75073. if( pOp->p1 ){
  75074. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  75075. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  75076. }else{
  75077. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  75078. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  75079. }
  75080. break;
  75081. }
  75082. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  75083. #ifndef SQLITE_OMIT_AUTOINCREMENT
  75084. /* Opcode: MemMax P1 P2 * * *
  75085. ** Synopsis: r[P1]=max(r[P1],r[P2])
  75086. **
  75087. ** P1 is a register in the root frame of this VM (the root frame is
  75088. ** different from the current frame if this instruction is being executed
  75089. ** within a sub-program). Set the value of register P1 to the maximum of
  75090. ** its current value and the value in register P2.
  75091. **
  75092. ** This instruction throws an error if the memory cell is not initially
  75093. ** an integer.
  75094. */
  75095. case OP_MemMax: { /* in2 */
  75096. VdbeFrame *pFrame;
  75097. if( p->pFrame ){
  75098. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  75099. pIn1 = &pFrame->aMem[pOp->p1];
  75100. }else{
  75101. pIn1 = &aMem[pOp->p1];
  75102. }
  75103. assert( memIsValid(pIn1) );
  75104. sqlite3VdbeMemIntegerify(pIn1);
  75105. pIn2 = &aMem[pOp->p2];
  75106. sqlite3VdbeMemIntegerify(pIn2);
  75107. if( pIn1->u.i<pIn2->u.i){
  75108. pIn1->u.i = pIn2->u.i;
  75109. }
  75110. break;
  75111. }
  75112. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  75113. /* Opcode: IfPos P1 P2 P3 * *
  75114. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  75115. **
  75116. ** Register P1 must contain an integer.
  75117. ** If the value of register P1 is 1 or greater, subtract P3 from the
  75118. ** value in P1 and jump to P2.
  75119. **
  75120. ** If the initial value of register P1 is less than 1, then the
  75121. ** value is unchanged and control passes through to the next instruction.
  75122. */
  75123. case OP_IfPos: { /* jump, in1 */
  75124. pIn1 = &aMem[pOp->p1];
  75125. assert( pIn1->flags&MEM_Int );
  75126. VdbeBranchTaken( pIn1->u.i>0, 2);
  75127. if( pIn1->u.i>0 ){
  75128. pIn1->u.i -= pOp->p3;
  75129. goto jump_to_p2;
  75130. }
  75131. break;
  75132. }
  75133. /* Opcode: OffsetLimit P1 P2 P3 * *
  75134. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  75135. **
  75136. ** This opcode performs a commonly used computation associated with
  75137. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  75138. ** holds the offset counter. The opcode computes the combined value
  75139. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  75140. ** value computed is the total number of rows that will need to be
  75141. ** visited in order to complete the query.
  75142. **
  75143. ** If r[P3] is zero or negative, that means there is no OFFSET
  75144. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  75145. **
  75146. ** if r[P1] is zero or negative, that means there is no LIMIT
  75147. ** and r[P2] is set to -1.
  75148. **
  75149. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  75150. */
  75151. case OP_OffsetLimit: { /* in1, out2, in3 */
  75152. pIn1 = &aMem[pOp->p1];
  75153. pIn3 = &aMem[pOp->p3];
  75154. pOut = out2Prerelease(p, pOp);
  75155. assert( pIn1->flags & MEM_Int );
  75156. assert( pIn3->flags & MEM_Int );
  75157. pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
  75158. break;
  75159. }
  75160. /* Opcode: IfNotZero P1 P2 P3 * *
  75161. ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
  75162. **
  75163. ** Register P1 must contain an integer. If the content of register P1 is
  75164. ** initially nonzero, then subtract P3 from the value in register P1 and
  75165. ** jump to P2. If register P1 is initially zero, leave it unchanged
  75166. ** and fall through.
  75167. */
  75168. case OP_IfNotZero: { /* jump, in1 */
  75169. pIn1 = &aMem[pOp->p1];
  75170. assert( pIn1->flags&MEM_Int );
  75171. VdbeBranchTaken(pIn1->u.i<0, 2);
  75172. if( pIn1->u.i ){
  75173. pIn1->u.i -= pOp->p3;
  75174. goto jump_to_p2;
  75175. }
  75176. break;
  75177. }
  75178. /* Opcode: DecrJumpZero P1 P2 * * *
  75179. ** Synopsis: if (--r[P1])==0 goto P2
  75180. **
  75181. ** Register P1 must hold an integer. Decrement the value in register P1
  75182. ** then jump to P2 if the new value is exactly zero.
  75183. */
  75184. case OP_DecrJumpZero: { /* jump, in1 */
  75185. pIn1 = &aMem[pOp->p1];
  75186. assert( pIn1->flags&MEM_Int );
  75187. pIn1->u.i--;
  75188. VdbeBranchTaken(pIn1->u.i==0, 2);
  75189. if( pIn1->u.i==0 ) goto jump_to_p2;
  75190. break;
  75191. }
  75192. /* Opcode: JumpZeroIncr P1 P2 * * *
  75193. ** Synopsis: if (r[P1]++)==0 ) goto P2
  75194. **
  75195. ** The register P1 must contain an integer. If register P1 is initially
  75196. ** zero, then jump to P2. Increment register P1 regardless of whether or
  75197. ** not the jump is taken.
  75198. */
  75199. case OP_JumpZeroIncr: { /* jump, in1 */
  75200. pIn1 = &aMem[pOp->p1];
  75201. assert( pIn1->flags&MEM_Int );
  75202. VdbeBranchTaken(pIn1->u.i==0, 2);
  75203. if( (pIn1->u.i++)==0 ) goto jump_to_p2;
  75204. break;
  75205. }
  75206. /* Opcode: AggStep0 * P2 P3 P4 P5
  75207. ** Synopsis: accum=r[P3] step(r[P2@P5])
  75208. **
  75209. ** Execute the step function for an aggregate. The
  75210. ** function has P5 arguments. P4 is a pointer to the FuncDef
  75211. ** structure that specifies the function. Register P3 is the
  75212. ** accumulator.
  75213. **
  75214. ** The P5 arguments are taken from register P2 and its
  75215. ** successors.
  75216. */
  75217. /* Opcode: AggStep * P2 P3 P4 P5
  75218. ** Synopsis: accum=r[P3] step(r[P2@P5])
  75219. **
  75220. ** Execute the step function for an aggregate. The
  75221. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  75222. ** object that is used to run the function. Register P3 is
  75223. ** as the accumulator.
  75224. **
  75225. ** The P5 arguments are taken from register P2 and its
  75226. ** successors.
  75227. **
  75228. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  75229. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  75230. ** the opcode is changed. In this way, the initialization of the
  75231. ** sqlite3_context only happens once, instead of on each call to the
  75232. ** step function.
  75233. */
  75234. case OP_AggStep0: {
  75235. int n;
  75236. sqlite3_context *pCtx;
  75237. assert( pOp->p4type==P4_FUNCDEF );
  75238. n = pOp->p5;
  75239. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  75240. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  75241. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  75242. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  75243. if( pCtx==0 ) goto no_mem;
  75244. pCtx->pMem = 0;
  75245. pCtx->pFunc = pOp->p4.pFunc;
  75246. pCtx->iOp = (int)(pOp - aOp);
  75247. pCtx->pVdbe = p;
  75248. pCtx->argc = n;
  75249. pOp->p4type = P4_FUNCCTX;
  75250. pOp->p4.pCtx = pCtx;
  75251. pOp->opcode = OP_AggStep;
  75252. /* Fall through into OP_AggStep */
  75253. }
  75254. case OP_AggStep: {
  75255. int i;
  75256. sqlite3_context *pCtx;
  75257. Mem *pMem;
  75258. Mem t;
  75259. assert( pOp->p4type==P4_FUNCCTX );
  75260. pCtx = pOp->p4.pCtx;
  75261. pMem = &aMem[pOp->p3];
  75262. /* If this function is inside of a trigger, the register array in aMem[]
  75263. ** might change from one evaluation to the next. The next block of code
  75264. ** checks to see if the register array has changed, and if so it
  75265. ** reinitializes the relavant parts of the sqlite3_context object */
  75266. if( pCtx->pMem != pMem ){
  75267. pCtx->pMem = pMem;
  75268. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  75269. }
  75270. #ifdef SQLITE_DEBUG
  75271. for(i=0; i<pCtx->argc; i++){
  75272. assert( memIsValid(pCtx->argv[i]) );
  75273. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  75274. }
  75275. #endif
  75276. pMem->n++;
  75277. sqlite3VdbeMemInit(&t, db, MEM_Null);
  75278. pCtx->pOut = &t;
  75279. pCtx->fErrorOrAux = 0;
  75280. pCtx->skipFlag = 0;
  75281. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  75282. if( pCtx->fErrorOrAux ){
  75283. if( pCtx->isError ){
  75284. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  75285. rc = pCtx->isError;
  75286. }
  75287. sqlite3VdbeMemRelease(&t);
  75288. if( rc ) goto abort_due_to_error;
  75289. }else{
  75290. assert( t.flags==MEM_Null );
  75291. }
  75292. if( pCtx->skipFlag ){
  75293. assert( pOp[-1].opcode==OP_CollSeq );
  75294. i = pOp[-1].p1;
  75295. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  75296. }
  75297. break;
  75298. }
  75299. /* Opcode: AggFinal P1 P2 * P4 *
  75300. ** Synopsis: accum=r[P1] N=P2
  75301. **
  75302. ** Execute the finalizer function for an aggregate. P1 is
  75303. ** the memory location that is the accumulator for the aggregate.
  75304. **
  75305. ** P2 is the number of arguments that the step function takes and
  75306. ** P4 is a pointer to the FuncDef for this function. The P2
  75307. ** argument is not used by this opcode. It is only there to disambiguate
  75308. ** functions that can take varying numbers of arguments. The
  75309. ** P4 argument is only needed for the degenerate case where
  75310. ** the step function was not previously called.
  75311. */
  75312. case OP_AggFinal: {
  75313. Mem *pMem;
  75314. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  75315. pMem = &aMem[pOp->p1];
  75316. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  75317. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  75318. if( rc ){
  75319. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  75320. goto abort_due_to_error;
  75321. }
  75322. sqlite3VdbeChangeEncoding(pMem, encoding);
  75323. UPDATE_MAX_BLOBSIZE(pMem);
  75324. if( sqlite3VdbeMemTooBig(pMem) ){
  75325. goto too_big;
  75326. }
  75327. break;
  75328. }
  75329. #ifndef SQLITE_OMIT_WAL
  75330. /* Opcode: Checkpoint P1 P2 P3 * *
  75331. **
  75332. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  75333. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  75334. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  75335. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  75336. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  75337. ** in the WAL that have been checkpointed after the checkpoint
  75338. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  75339. ** mem[P3+2] are initialized to -1.
  75340. */
  75341. case OP_Checkpoint: {
  75342. int i; /* Loop counter */
  75343. int aRes[3]; /* Results */
  75344. Mem *pMem; /* Write results here */
  75345. assert( p->readOnly==0 );
  75346. aRes[0] = 0;
  75347. aRes[1] = aRes[2] = -1;
  75348. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  75349. || pOp->p2==SQLITE_CHECKPOINT_FULL
  75350. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  75351. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  75352. );
  75353. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  75354. if( rc ){
  75355. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  75356. rc = SQLITE_OK;
  75357. aRes[0] = 1;
  75358. }
  75359. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  75360. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  75361. }
  75362. break;
  75363. };
  75364. #endif
  75365. #ifndef SQLITE_OMIT_PRAGMA
  75366. /* Opcode: JournalMode P1 P2 P3 * *
  75367. **
  75368. ** Change the journal mode of database P1 to P3. P3 must be one of the
  75369. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  75370. ** modes (delete, truncate, persist, off and memory), this is a simple
  75371. ** operation. No IO is required.
  75372. **
  75373. ** If changing into or out of WAL mode the procedure is more complicated.
  75374. **
  75375. ** Write a string containing the final journal-mode to register P2.
  75376. */
  75377. case OP_JournalMode: { /* out2 */
  75378. Btree *pBt; /* Btree to change journal mode of */
  75379. Pager *pPager; /* Pager associated with pBt */
  75380. int eNew; /* New journal mode */
  75381. int eOld; /* The old journal mode */
  75382. #ifndef SQLITE_OMIT_WAL
  75383. const char *zFilename; /* Name of database file for pPager */
  75384. #endif
  75385. pOut = out2Prerelease(p, pOp);
  75386. eNew = pOp->p3;
  75387. assert( eNew==PAGER_JOURNALMODE_DELETE
  75388. || eNew==PAGER_JOURNALMODE_TRUNCATE
  75389. || eNew==PAGER_JOURNALMODE_PERSIST
  75390. || eNew==PAGER_JOURNALMODE_OFF
  75391. || eNew==PAGER_JOURNALMODE_MEMORY
  75392. || eNew==PAGER_JOURNALMODE_WAL
  75393. || eNew==PAGER_JOURNALMODE_QUERY
  75394. );
  75395. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  75396. assert( p->readOnly==0 );
  75397. pBt = db->aDb[pOp->p1].pBt;
  75398. pPager = sqlite3BtreePager(pBt);
  75399. eOld = sqlite3PagerGetJournalMode(pPager);
  75400. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  75401. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  75402. #ifndef SQLITE_OMIT_WAL
  75403. zFilename = sqlite3PagerFilename(pPager, 1);
  75404. /* Do not allow a transition to journal_mode=WAL for a database
  75405. ** in temporary storage or if the VFS does not support shared memory
  75406. */
  75407. if( eNew==PAGER_JOURNALMODE_WAL
  75408. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  75409. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  75410. ){
  75411. eNew = eOld;
  75412. }
  75413. if( (eNew!=eOld)
  75414. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  75415. ){
  75416. if( !db->autoCommit || db->nVdbeRead>1 ){
  75417. rc = SQLITE_ERROR;
  75418. sqlite3VdbeError(p,
  75419. "cannot change %s wal mode from within a transaction",
  75420. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  75421. );
  75422. goto abort_due_to_error;
  75423. }else{
  75424. if( eOld==PAGER_JOURNALMODE_WAL ){
  75425. /* If leaving WAL mode, close the log file. If successful, the call
  75426. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  75427. ** file. An EXCLUSIVE lock may still be held on the database file
  75428. ** after a successful return.
  75429. */
  75430. rc = sqlite3PagerCloseWal(pPager);
  75431. if( rc==SQLITE_OK ){
  75432. sqlite3PagerSetJournalMode(pPager, eNew);
  75433. }
  75434. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  75435. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  75436. ** as an intermediate */
  75437. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  75438. }
  75439. /* Open a transaction on the database file. Regardless of the journal
  75440. ** mode, this transaction always uses a rollback journal.
  75441. */
  75442. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  75443. if( rc==SQLITE_OK ){
  75444. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  75445. }
  75446. }
  75447. }
  75448. #endif /* ifndef SQLITE_OMIT_WAL */
  75449. if( rc ) eNew = eOld;
  75450. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  75451. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  75452. pOut->z = (char *)sqlite3JournalModename(eNew);
  75453. pOut->n = sqlite3Strlen30(pOut->z);
  75454. pOut->enc = SQLITE_UTF8;
  75455. sqlite3VdbeChangeEncoding(pOut, encoding);
  75456. if( rc ) goto abort_due_to_error;
  75457. break;
  75458. };
  75459. #endif /* SQLITE_OMIT_PRAGMA */
  75460. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  75461. /* Opcode: Vacuum * * * * *
  75462. **
  75463. ** Vacuum the entire database. This opcode will cause other virtual
  75464. ** machines to be created and run. It may not be called from within
  75465. ** a transaction.
  75466. */
  75467. case OP_Vacuum: {
  75468. assert( p->readOnly==0 );
  75469. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  75470. if( rc ) goto abort_due_to_error;
  75471. break;
  75472. }
  75473. #endif
  75474. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  75475. /* Opcode: IncrVacuum P1 P2 * * *
  75476. **
  75477. ** Perform a single step of the incremental vacuum procedure on
  75478. ** the P1 database. If the vacuum has finished, jump to instruction
  75479. ** P2. Otherwise, fall through to the next instruction.
  75480. */
  75481. case OP_IncrVacuum: { /* jump */
  75482. Btree *pBt;
  75483. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  75484. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  75485. assert( p->readOnly==0 );
  75486. pBt = db->aDb[pOp->p1].pBt;
  75487. rc = sqlite3BtreeIncrVacuum(pBt);
  75488. VdbeBranchTaken(rc==SQLITE_DONE,2);
  75489. if( rc ){
  75490. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  75491. rc = SQLITE_OK;
  75492. goto jump_to_p2;
  75493. }
  75494. break;
  75495. }
  75496. #endif
  75497. /* Opcode: Expire P1 * * * *
  75498. **
  75499. ** Cause precompiled statements to expire. When an expired statement
  75500. ** is executed using sqlite3_step() it will either automatically
  75501. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  75502. ** or it will fail with SQLITE_SCHEMA.
  75503. **
  75504. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  75505. ** then only the currently executing statement is expired.
  75506. */
  75507. case OP_Expire: {
  75508. if( !pOp->p1 ){
  75509. sqlite3ExpirePreparedStatements(db);
  75510. }else{
  75511. p->expired = 1;
  75512. }
  75513. break;
  75514. }
  75515. #ifndef SQLITE_OMIT_SHARED_CACHE
  75516. /* Opcode: TableLock P1 P2 P3 P4 *
  75517. ** Synopsis: iDb=P1 root=P2 write=P3
  75518. **
  75519. ** Obtain a lock on a particular table. This instruction is only used when
  75520. ** the shared-cache feature is enabled.
  75521. **
  75522. ** P1 is the index of the database in sqlite3.aDb[] of the database
  75523. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  75524. ** a write lock if P3==1.
  75525. **
  75526. ** P2 contains the root-page of the table to lock.
  75527. **
  75528. ** P4 contains a pointer to the name of the table being locked. This is only
  75529. ** used to generate an error message if the lock cannot be obtained.
  75530. */
  75531. case OP_TableLock: {
  75532. u8 isWriteLock = (u8)pOp->p3;
  75533. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  75534. int p1 = pOp->p1;
  75535. assert( p1>=0 && p1<db->nDb );
  75536. assert( DbMaskTest(p->btreeMask, p1) );
  75537. assert( isWriteLock==0 || isWriteLock==1 );
  75538. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  75539. if( rc ){
  75540. if( (rc&0xFF)==SQLITE_LOCKED ){
  75541. const char *z = pOp->p4.z;
  75542. sqlite3VdbeError(p, "database table is locked: %s", z);
  75543. }
  75544. goto abort_due_to_error;
  75545. }
  75546. }
  75547. break;
  75548. }
  75549. #endif /* SQLITE_OMIT_SHARED_CACHE */
  75550. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75551. /* Opcode: VBegin * * * P4 *
  75552. **
  75553. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  75554. ** xBegin method for that table.
  75555. **
  75556. ** Also, whether or not P4 is set, check that this is not being called from
  75557. ** within a callback to a virtual table xSync() method. If it is, the error
  75558. ** code will be set to SQLITE_LOCKED.
  75559. */
  75560. case OP_VBegin: {
  75561. VTable *pVTab;
  75562. pVTab = pOp->p4.pVtab;
  75563. rc = sqlite3VtabBegin(db, pVTab);
  75564. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  75565. if( rc ) goto abort_due_to_error;
  75566. break;
  75567. }
  75568. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75569. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75570. /* Opcode: VCreate P1 P2 * * *
  75571. **
  75572. ** P2 is a register that holds the name of a virtual table in database
  75573. ** P1. Call the xCreate method for that table.
  75574. */
  75575. case OP_VCreate: {
  75576. Mem sMem; /* For storing the record being decoded */
  75577. const char *zTab; /* Name of the virtual table */
  75578. memset(&sMem, 0, sizeof(sMem));
  75579. sMem.db = db;
  75580. /* Because P2 is always a static string, it is impossible for the
  75581. ** sqlite3VdbeMemCopy() to fail */
  75582. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  75583. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  75584. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  75585. assert( rc==SQLITE_OK );
  75586. zTab = (const char*)sqlite3_value_text(&sMem);
  75587. assert( zTab || db->mallocFailed );
  75588. if( zTab ){
  75589. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  75590. }
  75591. sqlite3VdbeMemRelease(&sMem);
  75592. if( rc ) goto abort_due_to_error;
  75593. break;
  75594. }
  75595. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75596. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75597. /* Opcode: VDestroy P1 * * P4 *
  75598. **
  75599. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  75600. ** of that table.
  75601. */
  75602. case OP_VDestroy: {
  75603. db->nVDestroy++;
  75604. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  75605. db->nVDestroy--;
  75606. if( rc ) goto abort_due_to_error;
  75607. break;
  75608. }
  75609. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75610. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75611. /* Opcode: VOpen P1 * * P4 *
  75612. **
  75613. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  75614. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  75615. ** table and stores that cursor in P1.
  75616. */
  75617. case OP_VOpen: {
  75618. VdbeCursor *pCur;
  75619. sqlite3_vtab_cursor *pVCur;
  75620. sqlite3_vtab *pVtab;
  75621. const sqlite3_module *pModule;
  75622. assert( p->bIsReader );
  75623. pCur = 0;
  75624. pVCur = 0;
  75625. pVtab = pOp->p4.pVtab->pVtab;
  75626. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  75627. rc = SQLITE_LOCKED;
  75628. goto abort_due_to_error;
  75629. }
  75630. pModule = pVtab->pModule;
  75631. rc = pModule->xOpen(pVtab, &pVCur);
  75632. sqlite3VtabImportErrmsg(p, pVtab);
  75633. if( rc ) goto abort_due_to_error;
  75634. /* Initialize sqlite3_vtab_cursor base class */
  75635. pVCur->pVtab = pVtab;
  75636. /* Initialize vdbe cursor object */
  75637. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  75638. if( pCur ){
  75639. pCur->uc.pVCur = pVCur;
  75640. pVtab->nRef++;
  75641. }else{
  75642. assert( db->mallocFailed );
  75643. pModule->xClose(pVCur);
  75644. goto no_mem;
  75645. }
  75646. break;
  75647. }
  75648. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75649. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75650. /* Opcode: VFilter P1 P2 P3 P4 *
  75651. ** Synopsis: iplan=r[P3] zplan='P4'
  75652. **
  75653. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  75654. ** the filtered result set is empty.
  75655. **
  75656. ** P4 is either NULL or a string that was generated by the xBestIndex
  75657. ** method of the module. The interpretation of the P4 string is left
  75658. ** to the module implementation.
  75659. **
  75660. ** This opcode invokes the xFilter method on the virtual table specified
  75661. ** by P1. The integer query plan parameter to xFilter is stored in register
  75662. ** P3. Register P3+1 stores the argc parameter to be passed to the
  75663. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  75664. ** additional parameters which are passed to
  75665. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  75666. **
  75667. ** A jump is made to P2 if the result set after filtering would be empty.
  75668. */
  75669. case OP_VFilter: { /* jump */
  75670. int nArg;
  75671. int iQuery;
  75672. const sqlite3_module *pModule;
  75673. Mem *pQuery;
  75674. Mem *pArgc;
  75675. sqlite3_vtab_cursor *pVCur;
  75676. sqlite3_vtab *pVtab;
  75677. VdbeCursor *pCur;
  75678. int res;
  75679. int i;
  75680. Mem **apArg;
  75681. pQuery = &aMem[pOp->p3];
  75682. pArgc = &pQuery[1];
  75683. pCur = p->apCsr[pOp->p1];
  75684. assert( memIsValid(pQuery) );
  75685. REGISTER_TRACE(pOp->p3, pQuery);
  75686. assert( pCur->eCurType==CURTYPE_VTAB );
  75687. pVCur = pCur->uc.pVCur;
  75688. pVtab = pVCur->pVtab;
  75689. pModule = pVtab->pModule;
  75690. /* Grab the index number and argc parameters */
  75691. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  75692. nArg = (int)pArgc->u.i;
  75693. iQuery = (int)pQuery->u.i;
  75694. /* Invoke the xFilter method */
  75695. res = 0;
  75696. apArg = p->apArg;
  75697. for(i = 0; i<nArg; i++){
  75698. apArg[i] = &pArgc[i+1];
  75699. }
  75700. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  75701. sqlite3VtabImportErrmsg(p, pVtab);
  75702. if( rc ) goto abort_due_to_error;
  75703. res = pModule->xEof(pVCur);
  75704. pCur->nullRow = 0;
  75705. VdbeBranchTaken(res!=0,2);
  75706. if( res ) goto jump_to_p2;
  75707. break;
  75708. }
  75709. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75710. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75711. /* Opcode: VColumn P1 P2 P3 * *
  75712. ** Synopsis: r[P3]=vcolumn(P2)
  75713. **
  75714. ** Store the value of the P2-th column of
  75715. ** the row of the virtual-table that the
  75716. ** P1 cursor is pointing to into register P3.
  75717. */
  75718. case OP_VColumn: {
  75719. sqlite3_vtab *pVtab;
  75720. const sqlite3_module *pModule;
  75721. Mem *pDest;
  75722. sqlite3_context sContext;
  75723. VdbeCursor *pCur = p->apCsr[pOp->p1];
  75724. assert( pCur->eCurType==CURTYPE_VTAB );
  75725. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  75726. pDest = &aMem[pOp->p3];
  75727. memAboutToChange(p, pDest);
  75728. if( pCur->nullRow ){
  75729. sqlite3VdbeMemSetNull(pDest);
  75730. break;
  75731. }
  75732. pVtab = pCur->uc.pVCur->pVtab;
  75733. pModule = pVtab->pModule;
  75734. assert( pModule->xColumn );
  75735. memset(&sContext, 0, sizeof(sContext));
  75736. sContext.pOut = pDest;
  75737. MemSetTypeFlag(pDest, MEM_Null);
  75738. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  75739. sqlite3VtabImportErrmsg(p, pVtab);
  75740. if( sContext.isError ){
  75741. rc = sContext.isError;
  75742. }
  75743. sqlite3VdbeChangeEncoding(pDest, encoding);
  75744. REGISTER_TRACE(pOp->p3, pDest);
  75745. UPDATE_MAX_BLOBSIZE(pDest);
  75746. if( sqlite3VdbeMemTooBig(pDest) ){
  75747. goto too_big;
  75748. }
  75749. if( rc ) goto abort_due_to_error;
  75750. break;
  75751. }
  75752. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75753. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75754. /* Opcode: VNext P1 P2 * * *
  75755. **
  75756. ** Advance virtual table P1 to the next row in its result set and
  75757. ** jump to instruction P2. Or, if the virtual table has reached
  75758. ** the end of its result set, then fall through to the next instruction.
  75759. */
  75760. case OP_VNext: { /* jump */
  75761. sqlite3_vtab *pVtab;
  75762. const sqlite3_module *pModule;
  75763. int res;
  75764. VdbeCursor *pCur;
  75765. res = 0;
  75766. pCur = p->apCsr[pOp->p1];
  75767. assert( pCur->eCurType==CURTYPE_VTAB );
  75768. if( pCur->nullRow ){
  75769. break;
  75770. }
  75771. pVtab = pCur->uc.pVCur->pVtab;
  75772. pModule = pVtab->pModule;
  75773. assert( pModule->xNext );
  75774. /* Invoke the xNext() method of the module. There is no way for the
  75775. ** underlying implementation to return an error if one occurs during
  75776. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  75777. ** data is available) and the error code returned when xColumn or
  75778. ** some other method is next invoked on the save virtual table cursor.
  75779. */
  75780. rc = pModule->xNext(pCur->uc.pVCur);
  75781. sqlite3VtabImportErrmsg(p, pVtab);
  75782. if( rc ) goto abort_due_to_error;
  75783. res = pModule->xEof(pCur->uc.pVCur);
  75784. VdbeBranchTaken(!res,2);
  75785. if( !res ){
  75786. /* If there is data, jump to P2 */
  75787. goto jump_to_p2_and_check_for_interrupt;
  75788. }
  75789. goto check_for_interrupt;
  75790. }
  75791. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75792. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75793. /* Opcode: VRename P1 * * P4 *
  75794. **
  75795. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  75796. ** This opcode invokes the corresponding xRename method. The value
  75797. ** in register P1 is passed as the zName argument to the xRename method.
  75798. */
  75799. case OP_VRename: {
  75800. sqlite3_vtab *pVtab;
  75801. Mem *pName;
  75802. pVtab = pOp->p4.pVtab->pVtab;
  75803. pName = &aMem[pOp->p1];
  75804. assert( pVtab->pModule->xRename );
  75805. assert( memIsValid(pName) );
  75806. assert( p->readOnly==0 );
  75807. REGISTER_TRACE(pOp->p1, pName);
  75808. assert( pName->flags & MEM_Str );
  75809. testcase( pName->enc==SQLITE_UTF8 );
  75810. testcase( pName->enc==SQLITE_UTF16BE );
  75811. testcase( pName->enc==SQLITE_UTF16LE );
  75812. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  75813. if( rc ) goto abort_due_to_error;
  75814. rc = pVtab->pModule->xRename(pVtab, pName->z);
  75815. sqlite3VtabImportErrmsg(p, pVtab);
  75816. p->expired = 0;
  75817. if( rc ) goto abort_due_to_error;
  75818. break;
  75819. }
  75820. #endif
  75821. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75822. /* Opcode: VUpdate P1 P2 P3 P4 P5
  75823. ** Synopsis: data=r[P3@P2]
  75824. **
  75825. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  75826. ** This opcode invokes the corresponding xUpdate method. P2 values
  75827. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  75828. ** invocation. The value in register (P3+P2-1) corresponds to the
  75829. ** p2th element of the argv array passed to xUpdate.
  75830. **
  75831. ** The xUpdate method will do a DELETE or an INSERT or both.
  75832. ** The argv[0] element (which corresponds to memory cell P3)
  75833. ** is the rowid of a row to delete. If argv[0] is NULL then no
  75834. ** deletion occurs. The argv[1] element is the rowid of the new
  75835. ** row. This can be NULL to have the virtual table select the new
  75836. ** rowid for itself. The subsequent elements in the array are
  75837. ** the values of columns in the new row.
  75838. **
  75839. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  75840. ** a row to delete.
  75841. **
  75842. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  75843. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  75844. ** is set to the value of the rowid for the row just inserted.
  75845. **
  75846. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  75847. ** apply in the case of a constraint failure on an insert or update.
  75848. */
  75849. case OP_VUpdate: {
  75850. sqlite3_vtab *pVtab;
  75851. const sqlite3_module *pModule;
  75852. int nArg;
  75853. int i;
  75854. sqlite_int64 rowid;
  75855. Mem **apArg;
  75856. Mem *pX;
  75857. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  75858. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  75859. );
  75860. assert( p->readOnly==0 );
  75861. pVtab = pOp->p4.pVtab->pVtab;
  75862. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  75863. rc = SQLITE_LOCKED;
  75864. goto abort_due_to_error;
  75865. }
  75866. pModule = pVtab->pModule;
  75867. nArg = pOp->p2;
  75868. assert( pOp->p4type==P4_VTAB );
  75869. if( ALWAYS(pModule->xUpdate) ){
  75870. u8 vtabOnConflict = db->vtabOnConflict;
  75871. apArg = p->apArg;
  75872. pX = &aMem[pOp->p3];
  75873. for(i=0; i<nArg; i++){
  75874. assert( memIsValid(pX) );
  75875. memAboutToChange(p, pX);
  75876. apArg[i] = pX;
  75877. pX++;
  75878. }
  75879. db->vtabOnConflict = pOp->p5;
  75880. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  75881. db->vtabOnConflict = vtabOnConflict;
  75882. sqlite3VtabImportErrmsg(p, pVtab);
  75883. if( rc==SQLITE_OK && pOp->p1 ){
  75884. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  75885. db->lastRowid = lastRowid = rowid;
  75886. }
  75887. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  75888. if( pOp->p5==OE_Ignore ){
  75889. rc = SQLITE_OK;
  75890. }else{
  75891. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  75892. }
  75893. }else{
  75894. p->nChange++;
  75895. }
  75896. if( rc ) goto abort_due_to_error;
  75897. }
  75898. break;
  75899. }
  75900. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75901. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  75902. /* Opcode: Pagecount P1 P2 * * *
  75903. **
  75904. ** Write the current number of pages in database P1 to memory cell P2.
  75905. */
  75906. case OP_Pagecount: { /* out2 */
  75907. pOut = out2Prerelease(p, pOp);
  75908. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  75909. break;
  75910. }
  75911. #endif
  75912. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  75913. /* Opcode: MaxPgcnt P1 P2 P3 * *
  75914. **
  75915. ** Try to set the maximum page count for database P1 to the value in P3.
  75916. ** Do not let the maximum page count fall below the current page count and
  75917. ** do not change the maximum page count value if P3==0.
  75918. **
  75919. ** Store the maximum page count after the change in register P2.
  75920. */
  75921. case OP_MaxPgcnt: { /* out2 */
  75922. unsigned int newMax;
  75923. Btree *pBt;
  75924. pOut = out2Prerelease(p, pOp);
  75925. pBt = db->aDb[pOp->p1].pBt;
  75926. newMax = 0;
  75927. if( pOp->p3 ){
  75928. newMax = sqlite3BtreeLastPage(pBt);
  75929. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  75930. }
  75931. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  75932. break;
  75933. }
  75934. #endif
  75935. /* Opcode: Init * P2 * P4 *
  75936. ** Synopsis: Start at P2
  75937. **
  75938. ** Programs contain a single instance of this opcode as the very first
  75939. ** opcode.
  75940. **
  75941. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  75942. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  75943. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  75944. **
  75945. ** If P2 is not zero, jump to instruction P2.
  75946. */
  75947. case OP_Init: { /* jump */
  75948. char *zTrace;
  75949. char *z;
  75950. #ifndef SQLITE_OMIT_TRACE
  75951. if( db->xTrace
  75952. && !p->doingRerun
  75953. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  75954. ){
  75955. z = sqlite3VdbeExpandSql(p, zTrace);
  75956. db->xTrace(db->pTraceArg, z);
  75957. sqlite3DbFree(db, z);
  75958. }
  75959. #ifdef SQLITE_USE_FCNTL_TRACE
  75960. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  75961. if( zTrace ){
  75962. int i;
  75963. for(i=0; i<db->nDb; i++){
  75964. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  75965. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  75966. }
  75967. }
  75968. #endif /* SQLITE_USE_FCNTL_TRACE */
  75969. #ifdef SQLITE_DEBUG
  75970. if( (db->flags & SQLITE_SqlTrace)!=0
  75971. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  75972. ){
  75973. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  75974. }
  75975. #endif /* SQLITE_DEBUG */
  75976. #endif /* SQLITE_OMIT_TRACE */
  75977. if( pOp->p2 ) goto jump_to_p2;
  75978. break;
  75979. }
  75980. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  75981. /* Opcode: CursorHint P1 * * P4 *
  75982. **
  75983. ** Provide a hint to cursor P1 that it only needs to return rows that
  75984. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  75985. ** to values currently held in registers. TK_COLUMN terms in the P4
  75986. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  75987. */
  75988. case OP_CursorHint: {
  75989. VdbeCursor *pC;
  75990. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  75991. assert( pOp->p4type==P4_EXPR );
  75992. pC = p->apCsr[pOp->p1];
  75993. if( pC ){
  75994. assert( pC->eCurType==CURTYPE_BTREE );
  75995. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  75996. pOp->p4.pExpr, aMem);
  75997. }
  75998. break;
  75999. }
  76000. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  76001. /* Opcode: Noop * * * * *
  76002. **
  76003. ** Do nothing. This instruction is often useful as a jump
  76004. ** destination.
  76005. */
  76006. /*
  76007. ** The magic Explain opcode are only inserted when explain==2 (which
  76008. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  76009. ** This opcode records information from the optimizer. It is the
  76010. ** the same as a no-op. This opcodesnever appears in a real VM program.
  76011. */
  76012. default: { /* This is really OP_Noop and OP_Explain */
  76013. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  76014. break;
  76015. }
  76016. /*****************************************************************************
  76017. ** The cases of the switch statement above this line should all be indented
  76018. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  76019. ** readability. From this point on down, the normal indentation rules are
  76020. ** restored.
  76021. *****************************************************************************/
  76022. }
  76023. #ifdef VDBE_PROFILE
  76024. {
  76025. u64 endTime = sqlite3Hwtime();
  76026. if( endTime>start ) pOrigOp->cycles += endTime - start;
  76027. pOrigOp->cnt++;
  76028. }
  76029. #endif
  76030. /* The following code adds nothing to the actual functionality
  76031. ** of the program. It is only here for testing and debugging.
  76032. ** On the other hand, it does burn CPU cycles every time through
  76033. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  76034. */
  76035. #ifndef NDEBUG
  76036. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  76037. #ifdef SQLITE_DEBUG
  76038. if( db->flags & SQLITE_VdbeTrace ){
  76039. if( rc!=0 ) printf("rc=%d\n",rc);
  76040. if( pOrigOp->opflags & (OPFLG_OUT2) ){
  76041. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  76042. }
  76043. if( pOrigOp->opflags & OPFLG_OUT3 ){
  76044. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  76045. }
  76046. }
  76047. #endif /* SQLITE_DEBUG */
  76048. #endif /* NDEBUG */
  76049. } /* The end of the for(;;) loop the loops through opcodes */
  76050. /* If we reach this point, it means that execution is finished with
  76051. ** an error of some kind.
  76052. */
  76053. abort_due_to_error:
  76054. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  76055. assert( rc );
  76056. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  76057. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  76058. }
  76059. p->rc = rc;
  76060. sqlite3SystemError(db, rc);
  76061. testcase( sqlite3GlobalConfig.xLog!=0 );
  76062. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  76063. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  76064. sqlite3VdbeHalt(p);
  76065. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  76066. rc = SQLITE_ERROR;
  76067. if( resetSchemaOnFault>0 ){
  76068. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  76069. }
  76070. /* This is the only way out of this procedure. We have to
  76071. ** release the mutexes on btrees that were acquired at the
  76072. ** top. */
  76073. vdbe_return:
  76074. db->lastRowid = lastRowid;
  76075. testcase( nVmStep>0 );
  76076. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  76077. sqlite3VdbeLeave(p);
  76078. assert( rc!=SQLITE_OK || nExtraDelete==0
  76079. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  76080. );
  76081. return rc;
  76082. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  76083. ** is encountered.
  76084. */
  76085. too_big:
  76086. sqlite3VdbeError(p, "string or blob too big");
  76087. rc = SQLITE_TOOBIG;
  76088. goto abort_due_to_error;
  76089. /* Jump to here if a malloc() fails.
  76090. */
  76091. no_mem:
  76092. sqlite3OomFault(db);
  76093. sqlite3VdbeError(p, "out of memory");
  76094. rc = SQLITE_NOMEM_BKPT;
  76095. goto abort_due_to_error;
  76096. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  76097. ** flag.
  76098. */
  76099. abort_due_to_interrupt:
  76100. assert( db->u1.isInterrupted );
  76101. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  76102. p->rc = rc;
  76103. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  76104. goto abort_due_to_error;
  76105. }
  76106. /************** End of vdbe.c ************************************************/
  76107. /************** Begin file vdbeblob.c ****************************************/
  76108. /*
  76109. ** 2007 May 1
  76110. **
  76111. ** The author disclaims copyright to this source code. In place of
  76112. ** a legal notice, here is a blessing:
  76113. **
  76114. ** May you do good and not evil.
  76115. ** May you find forgiveness for yourself and forgive others.
  76116. ** May you share freely, never taking more than you give.
  76117. **
  76118. *************************************************************************
  76119. **
  76120. ** This file contains code used to implement incremental BLOB I/O.
  76121. */
  76122. /* #include "sqliteInt.h" */
  76123. /* #include "vdbeInt.h" */
  76124. #ifndef SQLITE_OMIT_INCRBLOB
  76125. /*
  76126. ** Valid sqlite3_blob* handles point to Incrblob structures.
  76127. */
  76128. typedef struct Incrblob Incrblob;
  76129. struct Incrblob {
  76130. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  76131. int nByte; /* Size of open blob, in bytes */
  76132. int iOffset; /* Byte offset of blob in cursor data */
  76133. int iCol; /* Table column this handle is open on */
  76134. BtCursor *pCsr; /* Cursor pointing at blob row */
  76135. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  76136. sqlite3 *db; /* The associated database */
  76137. };
  76138. /*
  76139. ** This function is used by both blob_open() and blob_reopen(). It seeks
  76140. ** the b-tree cursor associated with blob handle p to point to row iRow.
  76141. ** If successful, SQLITE_OK is returned and subsequent calls to
  76142. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  76143. **
  76144. ** If an error occurs, or if the specified row does not exist or does not
  76145. ** contain a value of type TEXT or BLOB in the column nominated when the
  76146. ** blob handle was opened, then an error code is returned and *pzErr may
  76147. ** be set to point to a buffer containing an error message. It is the
  76148. ** responsibility of the caller to free the error message buffer using
  76149. ** sqlite3DbFree().
  76150. **
  76151. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  76152. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  76153. ** immediately return SQLITE_ABORT.
  76154. */
  76155. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  76156. int rc; /* Error code */
  76157. char *zErr = 0; /* Error message */
  76158. Vdbe *v = (Vdbe *)p->pStmt;
  76159. /* Set the value of the SQL statements only variable to integer iRow.
  76160. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  76161. ** triggering asserts related to mutexes.
  76162. */
  76163. assert( v->aVar[0].flags&MEM_Int );
  76164. v->aVar[0].u.i = iRow;
  76165. rc = sqlite3_step(p->pStmt);
  76166. if( rc==SQLITE_ROW ){
  76167. VdbeCursor *pC = v->apCsr[0];
  76168. u32 type = pC->aType[p->iCol];
  76169. if( type<12 ){
  76170. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  76171. type==0?"null": type==7?"real": "integer"
  76172. );
  76173. rc = SQLITE_ERROR;
  76174. sqlite3_finalize(p->pStmt);
  76175. p->pStmt = 0;
  76176. }else{
  76177. p->iOffset = pC->aType[p->iCol + pC->nField];
  76178. p->nByte = sqlite3VdbeSerialTypeLen(type);
  76179. p->pCsr = pC->uc.pCursor;
  76180. sqlite3BtreeIncrblobCursor(p->pCsr);
  76181. }
  76182. }
  76183. if( rc==SQLITE_ROW ){
  76184. rc = SQLITE_OK;
  76185. }else if( p->pStmt ){
  76186. rc = sqlite3_finalize(p->pStmt);
  76187. p->pStmt = 0;
  76188. if( rc==SQLITE_OK ){
  76189. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  76190. rc = SQLITE_ERROR;
  76191. }else{
  76192. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  76193. }
  76194. }
  76195. assert( rc!=SQLITE_OK || zErr==0 );
  76196. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  76197. *pzErr = zErr;
  76198. return rc;
  76199. }
  76200. /*
  76201. ** Open a blob handle.
  76202. */
  76203. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  76204. sqlite3* db, /* The database connection */
  76205. const char *zDb, /* The attached database containing the blob */
  76206. const char *zTable, /* The table containing the blob */
  76207. const char *zColumn, /* The column containing the blob */
  76208. sqlite_int64 iRow, /* The row containing the glob */
  76209. int flags, /* True -> read/write access, false -> read-only */
  76210. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  76211. ){
  76212. int nAttempt = 0;
  76213. int iCol; /* Index of zColumn in row-record */
  76214. int rc = SQLITE_OK;
  76215. char *zErr = 0;
  76216. Table *pTab;
  76217. Parse *pParse = 0;
  76218. Incrblob *pBlob = 0;
  76219. #ifdef SQLITE_ENABLE_API_ARMOR
  76220. if( ppBlob==0 ){
  76221. return SQLITE_MISUSE_BKPT;
  76222. }
  76223. #endif
  76224. *ppBlob = 0;
  76225. #ifdef SQLITE_ENABLE_API_ARMOR
  76226. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  76227. return SQLITE_MISUSE_BKPT;
  76228. }
  76229. #endif
  76230. flags = !!flags; /* flags = (flags ? 1 : 0); */
  76231. sqlite3_mutex_enter(db->mutex);
  76232. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  76233. if( !pBlob ) goto blob_open_out;
  76234. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  76235. if( !pParse ) goto blob_open_out;
  76236. do {
  76237. memset(pParse, 0, sizeof(Parse));
  76238. pParse->db = db;
  76239. sqlite3DbFree(db, zErr);
  76240. zErr = 0;
  76241. sqlite3BtreeEnterAll(db);
  76242. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  76243. if( pTab && IsVirtual(pTab) ){
  76244. pTab = 0;
  76245. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  76246. }
  76247. if( pTab && !HasRowid(pTab) ){
  76248. pTab = 0;
  76249. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  76250. }
  76251. #ifndef SQLITE_OMIT_VIEW
  76252. if( pTab && pTab->pSelect ){
  76253. pTab = 0;
  76254. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  76255. }
  76256. #endif
  76257. if( !pTab ){
  76258. if( pParse->zErrMsg ){
  76259. sqlite3DbFree(db, zErr);
  76260. zErr = pParse->zErrMsg;
  76261. pParse->zErrMsg = 0;
  76262. }
  76263. rc = SQLITE_ERROR;
  76264. sqlite3BtreeLeaveAll(db);
  76265. goto blob_open_out;
  76266. }
  76267. /* Now search pTab for the exact column. */
  76268. for(iCol=0; iCol<pTab->nCol; iCol++) {
  76269. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  76270. break;
  76271. }
  76272. }
  76273. if( iCol==pTab->nCol ){
  76274. sqlite3DbFree(db, zErr);
  76275. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  76276. rc = SQLITE_ERROR;
  76277. sqlite3BtreeLeaveAll(db);
  76278. goto blob_open_out;
  76279. }
  76280. /* If the value is being opened for writing, check that the
  76281. ** column is not indexed, and that it is not part of a foreign key.
  76282. ** It is against the rules to open a column to which either of these
  76283. ** descriptions applies for writing. */
  76284. if( flags ){
  76285. const char *zFault = 0;
  76286. Index *pIdx;
  76287. #ifndef SQLITE_OMIT_FOREIGN_KEY
  76288. if( db->flags&SQLITE_ForeignKeys ){
  76289. /* Check that the column is not part of an FK child key definition. It
  76290. ** is not necessary to check if it is part of a parent key, as parent
  76291. ** key columns must be indexed. The check below will pick up this
  76292. ** case. */
  76293. FKey *pFKey;
  76294. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  76295. int j;
  76296. for(j=0; j<pFKey->nCol; j++){
  76297. if( pFKey->aCol[j].iFrom==iCol ){
  76298. zFault = "foreign key";
  76299. }
  76300. }
  76301. }
  76302. }
  76303. #endif
  76304. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  76305. int j;
  76306. for(j=0; j<pIdx->nKeyCol; j++){
  76307. /* FIXME: Be smarter about indexes that use expressions */
  76308. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  76309. zFault = "indexed";
  76310. }
  76311. }
  76312. }
  76313. if( zFault ){
  76314. sqlite3DbFree(db, zErr);
  76315. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  76316. rc = SQLITE_ERROR;
  76317. sqlite3BtreeLeaveAll(db);
  76318. goto blob_open_out;
  76319. }
  76320. }
  76321. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  76322. assert( pBlob->pStmt || db->mallocFailed );
  76323. if( pBlob->pStmt ){
  76324. /* This VDBE program seeks a btree cursor to the identified
  76325. ** db/table/row entry. The reason for using a vdbe program instead
  76326. ** of writing code to use the b-tree layer directly is that the
  76327. ** vdbe program will take advantage of the various transaction,
  76328. ** locking and error handling infrastructure built into the vdbe.
  76329. **
  76330. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  76331. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  76332. ** uses it to implement the blob_read(), blob_write() and
  76333. ** blob_bytes() functions.
  76334. **
  76335. ** The sqlite3_blob_close() function finalizes the vdbe program,
  76336. ** which closes the b-tree cursor and (possibly) commits the
  76337. ** transaction.
  76338. */
  76339. static const int iLn = VDBE_OFFSET_LINENO(2);
  76340. static const VdbeOpList openBlob[] = {
  76341. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  76342. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  76343. {OP_Variable, 1, 1, 0}, /* 2: Move ?1 into reg[1] */
  76344. {OP_NotExists, 0, 7, 1}, /* 3: Seek the cursor */
  76345. {OP_Column, 0, 0, 1}, /* 4 */
  76346. {OP_ResultRow, 1, 0, 0}, /* 5 */
  76347. {OP_Goto, 0, 2, 0}, /* 6 */
  76348. {OP_Close, 0, 0, 0}, /* 7 */
  76349. {OP_Halt, 0, 0, 0}, /* 8 */
  76350. };
  76351. Vdbe *v = (Vdbe *)pBlob->pStmt;
  76352. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  76353. VdbeOp *aOp;
  76354. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  76355. pTab->pSchema->schema_cookie,
  76356. pTab->pSchema->iGeneration);
  76357. sqlite3VdbeChangeP5(v, 1);
  76358. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  76359. /* Make sure a mutex is held on the table to be accessed */
  76360. sqlite3VdbeUsesBtree(v, iDb);
  76361. if( db->mallocFailed==0 ){
  76362. assert( aOp!=0 );
  76363. /* Configure the OP_TableLock instruction */
  76364. #ifdef SQLITE_OMIT_SHARED_CACHE
  76365. aOp[0].opcode = OP_Noop;
  76366. #else
  76367. aOp[0].p1 = iDb;
  76368. aOp[0].p2 = pTab->tnum;
  76369. aOp[0].p3 = flags;
  76370. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  76371. }
  76372. if( db->mallocFailed==0 ){
  76373. #endif
  76374. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  76375. ** parameter of the other to pTab->tnum. */
  76376. if( flags ) aOp[1].opcode = OP_OpenWrite;
  76377. aOp[1].p2 = pTab->tnum;
  76378. aOp[1].p3 = iDb;
  76379. /* Configure the number of columns. Configure the cursor to
  76380. ** think that the table has one more column than it really
  76381. ** does. An OP_Column to retrieve this imaginary column will
  76382. ** always return an SQL NULL. This is useful because it means
  76383. ** we can invoke OP_Column to fill in the vdbe cursors type
  76384. ** and offset cache without causing any IO.
  76385. */
  76386. aOp[1].p4type = P4_INT32;
  76387. aOp[1].p4.i = pTab->nCol+1;
  76388. aOp[4].p2 = pTab->nCol;
  76389. pParse->nVar = 1;
  76390. pParse->nMem = 1;
  76391. pParse->nTab = 1;
  76392. sqlite3VdbeMakeReady(v, pParse);
  76393. }
  76394. }
  76395. pBlob->flags = flags;
  76396. pBlob->iCol = iCol;
  76397. pBlob->db = db;
  76398. sqlite3BtreeLeaveAll(db);
  76399. if( db->mallocFailed ){
  76400. goto blob_open_out;
  76401. }
  76402. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  76403. rc = blobSeekToRow(pBlob, iRow, &zErr);
  76404. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  76405. blob_open_out:
  76406. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  76407. *ppBlob = (sqlite3_blob *)pBlob;
  76408. }else{
  76409. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  76410. sqlite3DbFree(db, pBlob);
  76411. }
  76412. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  76413. sqlite3DbFree(db, zErr);
  76414. sqlite3ParserReset(pParse);
  76415. sqlite3StackFree(db, pParse);
  76416. rc = sqlite3ApiExit(db, rc);
  76417. sqlite3_mutex_leave(db->mutex);
  76418. return rc;
  76419. }
  76420. /*
  76421. ** Close a blob handle that was previously created using
  76422. ** sqlite3_blob_open().
  76423. */
  76424. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
  76425. Incrblob *p = (Incrblob *)pBlob;
  76426. int rc;
  76427. sqlite3 *db;
  76428. if( p ){
  76429. db = p->db;
  76430. sqlite3_mutex_enter(db->mutex);
  76431. rc = sqlite3_finalize(p->pStmt);
  76432. sqlite3DbFree(db, p);
  76433. sqlite3_mutex_leave(db->mutex);
  76434. }else{
  76435. rc = SQLITE_OK;
  76436. }
  76437. return rc;
  76438. }
  76439. /*
  76440. ** Perform a read or write operation on a blob
  76441. */
  76442. static int blobReadWrite(
  76443. sqlite3_blob *pBlob,
  76444. void *z,
  76445. int n,
  76446. int iOffset,
  76447. int (*xCall)(BtCursor*, u32, u32, void*)
  76448. ){
  76449. int rc;
  76450. Incrblob *p = (Incrblob *)pBlob;
  76451. Vdbe *v;
  76452. sqlite3 *db;
  76453. if( p==0 ) return SQLITE_MISUSE_BKPT;
  76454. db = p->db;
  76455. sqlite3_mutex_enter(db->mutex);
  76456. v = (Vdbe*)p->pStmt;
  76457. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  76458. /* Request is out of range. Return a transient error. */
  76459. rc = SQLITE_ERROR;
  76460. }else if( v==0 ){
  76461. /* If there is no statement handle, then the blob-handle has
  76462. ** already been invalidated. Return SQLITE_ABORT in this case.
  76463. */
  76464. rc = SQLITE_ABORT;
  76465. }else{
  76466. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  76467. ** returned, clean-up the statement handle.
  76468. */
  76469. assert( db == v->db );
  76470. sqlite3BtreeEnterCursor(p->pCsr);
  76471. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  76472. sqlite3BtreeLeaveCursor(p->pCsr);
  76473. if( rc==SQLITE_ABORT ){
  76474. sqlite3VdbeFinalize(v);
  76475. p->pStmt = 0;
  76476. }else{
  76477. v->rc = rc;
  76478. }
  76479. }
  76480. sqlite3Error(db, rc);
  76481. rc = sqlite3ApiExit(db, rc);
  76482. sqlite3_mutex_leave(db->mutex);
  76483. return rc;
  76484. }
  76485. /*
  76486. ** Read data from a blob handle.
  76487. */
  76488. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  76489. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  76490. }
  76491. /*
  76492. ** Write data to a blob handle.
  76493. */
  76494. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  76495. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  76496. }
  76497. /*
  76498. ** Query a blob handle for the size of the data.
  76499. **
  76500. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  76501. ** so no mutex is required for access.
  76502. */
  76503. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
  76504. Incrblob *p = (Incrblob *)pBlob;
  76505. return (p && p->pStmt) ? p->nByte : 0;
  76506. }
  76507. /*
  76508. ** Move an existing blob handle to point to a different row of the same
  76509. ** database table.
  76510. **
  76511. ** If an error occurs, or if the specified row does not exist or does not
  76512. ** contain a blob or text value, then an error code is returned and the
  76513. ** database handle error code and message set. If this happens, then all
  76514. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  76515. ** immediately return SQLITE_ABORT.
  76516. */
  76517. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  76518. int rc;
  76519. Incrblob *p = (Incrblob *)pBlob;
  76520. sqlite3 *db;
  76521. if( p==0 ) return SQLITE_MISUSE_BKPT;
  76522. db = p->db;
  76523. sqlite3_mutex_enter(db->mutex);
  76524. if( p->pStmt==0 ){
  76525. /* If there is no statement handle, then the blob-handle has
  76526. ** already been invalidated. Return SQLITE_ABORT in this case.
  76527. */
  76528. rc = SQLITE_ABORT;
  76529. }else{
  76530. char *zErr;
  76531. rc = blobSeekToRow(p, iRow, &zErr);
  76532. if( rc!=SQLITE_OK ){
  76533. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  76534. sqlite3DbFree(db, zErr);
  76535. }
  76536. assert( rc!=SQLITE_SCHEMA );
  76537. }
  76538. rc = sqlite3ApiExit(db, rc);
  76539. assert( rc==SQLITE_OK || p->pStmt==0 );
  76540. sqlite3_mutex_leave(db->mutex);
  76541. return rc;
  76542. }
  76543. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  76544. /************** End of vdbeblob.c ********************************************/
  76545. /************** Begin file vdbesort.c ****************************************/
  76546. /*
  76547. ** 2011-07-09
  76548. **
  76549. ** The author disclaims copyright to this source code. In place of
  76550. ** a legal notice, here is a blessing:
  76551. **
  76552. ** May you do good and not evil.
  76553. ** May you find forgiveness for yourself and forgive others.
  76554. ** May you share freely, never taking more than you give.
  76555. **
  76556. *************************************************************************
  76557. ** This file contains code for the VdbeSorter object, used in concert with
  76558. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  76559. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  76560. ** using indexes and without LIMIT clauses.
  76561. **
  76562. ** The VdbeSorter object implements a multi-threaded external merge sort
  76563. ** algorithm that is efficient even if the number of elements being sorted
  76564. ** exceeds the available memory.
  76565. **
  76566. ** Here is the (internal, non-API) interface between this module and the
  76567. ** rest of the SQLite system:
  76568. **
  76569. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  76570. **
  76571. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  76572. ** object. The row is a binary blob in the
  76573. ** OP_MakeRecord format that contains both
  76574. ** the ORDER BY key columns and result columns
  76575. ** in the case of a SELECT w/ ORDER BY, or
  76576. ** the complete record for an index entry
  76577. ** in the case of a CREATE INDEX.
  76578. **
  76579. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  76580. ** Position the read cursor on the
  76581. ** first sorted element.
  76582. **
  76583. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  76584. ** element.
  76585. **
  76586. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  76587. ** row currently under the read cursor.
  76588. **
  76589. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  76590. ** currently under the read cursor against
  76591. ** another binary blob X and report if
  76592. ** X is strictly less than the read cursor.
  76593. ** Used to enforce uniqueness in a
  76594. ** CREATE UNIQUE INDEX statement.
  76595. **
  76596. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  76597. ** all resources.
  76598. **
  76599. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  76600. ** is like Close() followed by Init() only
  76601. ** much faster.
  76602. **
  76603. ** The interfaces above must be called in a particular order. Write() can
  76604. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  76605. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  76606. **
  76607. ** Init()
  76608. ** for each record: Write()
  76609. ** Rewind()
  76610. ** Rowkey()/Compare()
  76611. ** Next()
  76612. ** Close()
  76613. **
  76614. ** Algorithm:
  76615. **
  76616. ** Records passed to the sorter via calls to Write() are initially held
  76617. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  76618. ** a threshold, when Rewind() is called the set of records is sorted using
  76619. ** an in-memory merge sort. In this case, no temporary files are required
  76620. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  76621. ** directly from main memory.
  76622. **
  76623. ** If the amount of space used to store records in main memory exceeds the
  76624. ** threshold, then the set of records currently in memory are sorted and
  76625. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  76626. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  76627. ** of PMAs may be created by merging existing PMAs together - for example
  76628. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  76629. **
  76630. ** The threshold for the amount of main memory to use before flushing
  76631. ** records to a PMA is roughly the same as the limit configured for the
  76632. ** page-cache of the main database. Specifically, the threshold is set to
  76633. ** the value returned by "PRAGMA main.page_size" multipled by
  76634. ** that returned by "PRAGMA main.cache_size", in bytes.
  76635. **
  76636. ** If the sorter is running in single-threaded mode, then all PMAs generated
  76637. ** are appended to a single temporary file. Or, if the sorter is running in
  76638. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  76639. ** N is the configured number of worker threads. In this case, instead of
  76640. ** sorting the records and writing the PMA to a temporary file itself, the
  76641. ** calling thread usually launches a worker thread to do so. Except, if
  76642. ** there are already N worker threads running, the main thread does the work
  76643. ** itself.
  76644. **
  76645. ** The sorter is running in multi-threaded mode if (a) the library was built
  76646. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  76647. ** than zero, and (b) worker threads have been enabled at runtime by calling
  76648. ** "PRAGMA threads=N" with some value of N greater than 0.
  76649. **
  76650. ** When Rewind() is called, any data remaining in memory is flushed to a
  76651. ** final PMA. So at this point the data is stored in some number of sorted
  76652. ** PMAs within temporary files on disk.
  76653. **
  76654. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  76655. ** sorter is running in single-threaded mode, then these PMAs are merged
  76656. ** incrementally as keys are retreived from the sorter by the VDBE. The
  76657. ** MergeEngine object, described in further detail below, performs this
  76658. ** merge.
  76659. **
  76660. ** Or, if running in multi-threaded mode, then a background thread is
  76661. ** launched to merge the existing PMAs. Once the background thread has
  76662. ** merged T bytes of data into a single sorted PMA, the main thread
  76663. ** begins reading keys from that PMA while the background thread proceeds
  76664. ** with merging the next T bytes of data. And so on.
  76665. **
  76666. ** Parameter T is set to half the value of the memory threshold used
  76667. ** by Write() above to determine when to create a new PMA.
  76668. **
  76669. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  76670. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  76671. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  76672. ** disk are merged together. Then T bytes of data from the second set, and
  76673. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  76674. ** PMAs at a time. This done is to improve locality.
  76675. **
  76676. ** If running in multi-threaded mode and there are more than
  76677. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  76678. ** than one background thread may be created. Specifically, there may be
  76679. ** one background thread for each temporary file on disk, and one background
  76680. ** thread to merge the output of each of the others to a single PMA for
  76681. ** the main thread to read from.
  76682. */
  76683. /* #include "sqliteInt.h" */
  76684. /* #include "vdbeInt.h" */
  76685. /*
  76686. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  76687. ** messages to stderr that may be helpful in understanding the performance
  76688. ** characteristics of the sorter in multi-threaded mode.
  76689. */
  76690. #if 0
  76691. # define SQLITE_DEBUG_SORTER_THREADS 1
  76692. #endif
  76693. /*
  76694. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  76695. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  76696. ** overflows. 512MiB.
  76697. */
  76698. #define SQLITE_MAX_PMASZ (1<<29)
  76699. /*
  76700. ** Private objects used by the sorter
  76701. */
  76702. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  76703. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  76704. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  76705. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  76706. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  76707. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  76708. typedef struct SorterList SorterList; /* In-memory list of records */
  76709. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  76710. /*
  76711. ** A container for a temp file handle and the current amount of data
  76712. ** stored in the file.
  76713. */
  76714. struct SorterFile {
  76715. sqlite3_file *pFd; /* File handle */
  76716. i64 iEof; /* Bytes of data stored in pFd */
  76717. };
  76718. /*
  76719. ** An in-memory list of objects to be sorted.
  76720. **
  76721. ** If aMemory==0 then each object is allocated separately and the objects
  76722. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  76723. ** are stored in the aMemory[] bulk memory, one right after the other, and
  76724. ** are connected using SorterRecord.u.iNext.
  76725. */
  76726. struct SorterList {
  76727. SorterRecord *pList; /* Linked list of records */
  76728. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  76729. int szPMA; /* Size of pList as PMA in bytes */
  76730. };
  76731. /*
  76732. ** The MergeEngine object is used to combine two or more smaller PMAs into
  76733. ** one big PMA using a merge operation. Separate PMAs all need to be
  76734. ** combined into one big PMA in order to be able to step through the sorted
  76735. ** records in order.
  76736. **
  76737. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  76738. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  76739. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  76740. ** For the purposes of the paragraphs below, we assume that the array is
  76741. ** actually N elements in size, where N is the smallest power of 2 greater
  76742. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  76743. ** are treated as if they are empty (always at EOF).
  76744. **
  76745. ** The aTree[] array is also N elements in size. The value of N is stored in
  76746. ** the MergeEngine.nTree variable.
  76747. **
  76748. ** The final (N/2) elements of aTree[] contain the results of comparing
  76749. ** pairs of PMA keys together. Element i contains the result of
  76750. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  76751. ** aTree element is set to the index of it.
  76752. **
  76753. ** For the purposes of this comparison, EOF is considered greater than any
  76754. ** other key value. If the keys are equal (only possible with two EOF
  76755. ** values), it doesn't matter which index is stored.
  76756. **
  76757. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  76758. ** above contains the index of the smallest of each block of 4 PmaReaders
  76759. ** And so on. So that aTree[1] contains the index of the PmaReader that
  76760. ** currently points to the smallest key value. aTree[0] is unused.
  76761. **
  76762. ** Example:
  76763. **
  76764. ** aReadr[0] -> Banana
  76765. ** aReadr[1] -> Feijoa
  76766. ** aReadr[2] -> Elderberry
  76767. ** aReadr[3] -> Currant
  76768. ** aReadr[4] -> Grapefruit
  76769. ** aReadr[5] -> Apple
  76770. ** aReadr[6] -> Durian
  76771. ** aReadr[7] -> EOF
  76772. **
  76773. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  76774. **
  76775. ** The current element is "Apple" (the value of the key indicated by
  76776. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  76777. ** be advanced to the next key in its segment. Say the next key is
  76778. ** "Eggplant":
  76779. **
  76780. ** aReadr[5] -> Eggplant
  76781. **
  76782. ** The contents of aTree[] are updated first by comparing the new PmaReader
  76783. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  76784. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  76785. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  76786. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  76787. ** so the value written into element 1 of the array is 0. As follows:
  76788. **
  76789. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  76790. **
  76791. ** In other words, each time we advance to the next sorter element, log2(N)
  76792. ** key comparison operations are required, where N is the number of segments
  76793. ** being merged (rounded up to the next power of 2).
  76794. */
  76795. struct MergeEngine {
  76796. int nTree; /* Used size of aTree/aReadr (power of 2) */
  76797. SortSubtask *pTask; /* Used by this thread only */
  76798. int *aTree; /* Current state of incremental merge */
  76799. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  76800. };
  76801. /*
  76802. ** This object represents a single thread of control in a sort operation.
  76803. ** Exactly VdbeSorter.nTask instances of this object are allocated
  76804. ** as part of each VdbeSorter object. Instances are never allocated any
  76805. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  76806. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  76807. ** single-threaded operation, there is exactly one instance of this object
  76808. ** and for multi-threaded operation there are two or more instances.
  76809. **
  76810. ** Essentially, this structure contains all those fields of the VdbeSorter
  76811. ** structure for which each thread requires a separate instance. For example,
  76812. ** each thread requries its own UnpackedRecord object to unpack records in
  76813. ** as part of comparison operations.
  76814. **
  76815. ** Before a background thread is launched, variable bDone is set to 0. Then,
  76816. ** right before it exits, the thread itself sets bDone to 1. This is used for
  76817. ** two purposes:
  76818. **
  76819. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  76820. ** attempt to select a SortSubtask for which there is not already an
  76821. ** active background thread (since doing so causes the main thread
  76822. ** to block until it finishes).
  76823. **
  76824. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  76825. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  76826. ** block provoke debugging output.
  76827. **
  76828. ** In both cases, the effects of the main thread seeing (bDone==0) even
  76829. ** after the thread has finished are not dire. So we don't worry about
  76830. ** memory barriers and such here.
  76831. */
  76832. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  76833. struct SortSubtask {
  76834. SQLiteThread *pThread; /* Background thread, if any */
  76835. int bDone; /* Set if thread is finished but not joined */
  76836. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  76837. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  76838. SorterList list; /* List for thread to write to a PMA */
  76839. int nPMA; /* Number of PMAs currently in file */
  76840. SorterCompare xCompare; /* Compare function to use */
  76841. SorterFile file; /* Temp file for level-0 PMAs */
  76842. SorterFile file2; /* Space for other PMAs */
  76843. };
  76844. /*
  76845. ** Main sorter structure. A single instance of this is allocated for each
  76846. ** sorter cursor created by the VDBE.
  76847. **
  76848. ** mxKeysize:
  76849. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  76850. ** this variable is updated so as to be set to the size on disk of the
  76851. ** largest record in the sorter.
  76852. */
  76853. struct VdbeSorter {
  76854. int mnPmaSize; /* Minimum PMA size, in bytes */
  76855. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  76856. int mxKeysize; /* Largest serialized key seen so far */
  76857. int pgsz; /* Main database page size */
  76858. PmaReader *pReader; /* Readr data from here after Rewind() */
  76859. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  76860. sqlite3 *db; /* Database connection */
  76861. KeyInfo *pKeyInfo; /* How to compare records */
  76862. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  76863. SorterList list; /* List of in-memory records */
  76864. int iMemory; /* Offset of free space in list.aMemory */
  76865. int nMemory; /* Size of list.aMemory allocation in bytes */
  76866. u8 bUsePMA; /* True if one or more PMAs created */
  76867. u8 bUseThreads; /* True to use background threads */
  76868. u8 iPrev; /* Previous thread used to flush PMA */
  76869. u8 nTask; /* Size of aTask[] array */
  76870. u8 typeMask;
  76871. SortSubtask aTask[1]; /* One or more subtasks */
  76872. };
  76873. #define SORTER_TYPE_INTEGER 0x01
  76874. #define SORTER_TYPE_TEXT 0x02
  76875. /*
  76876. ** An instance of the following object is used to read records out of a
  76877. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  76878. ** aKey might point into aMap or into aBuffer. If neither of those locations
  76879. ** contain a contiguous representation of the key, then aAlloc is allocated
  76880. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  76881. **
  76882. ** pFd==0 at EOF.
  76883. */
  76884. struct PmaReader {
  76885. i64 iReadOff; /* Current read offset */
  76886. i64 iEof; /* 1 byte past EOF for this PmaReader */
  76887. int nAlloc; /* Bytes of space at aAlloc */
  76888. int nKey; /* Number of bytes in key */
  76889. sqlite3_file *pFd; /* File handle we are reading from */
  76890. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  76891. u8 *aKey; /* Pointer to current key */
  76892. u8 *aBuffer; /* Current read buffer */
  76893. int nBuffer; /* Size of read buffer in bytes */
  76894. u8 *aMap; /* Pointer to mapping of entire file */
  76895. IncrMerger *pIncr; /* Incremental merger */
  76896. };
  76897. /*
  76898. ** Normally, a PmaReader object iterates through an existing PMA stored
  76899. ** within a temp file. However, if the PmaReader.pIncr variable points to
  76900. ** an object of the following type, it may be used to iterate/merge through
  76901. ** multiple PMAs simultaneously.
  76902. **
  76903. ** There are two types of IncrMerger object - single (bUseThread==0) and
  76904. ** multi-threaded (bUseThread==1).
  76905. **
  76906. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  76907. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  76908. ** size. When the IncrMerger is initialized, it reads enough data from
  76909. ** pMerger to populate aFile[0]. It then sets variables within the
  76910. ** corresponding PmaReader object to read from that file and kicks off
  76911. ** a background thread to populate aFile[1] with the next mxSz bytes of
  76912. ** sorted record data from pMerger.
  76913. **
  76914. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  76915. ** background thread has finished populating aFile[1]. It then exchanges
  76916. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  76917. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  76918. ** another background thread to populate the new aFile[1]. And so on, until
  76919. ** the contents of pMerger are exhausted.
  76920. **
  76921. ** A single-threaded IncrMerger does not open any temporary files of its
  76922. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  76923. ** at offset iStartOff of file pTask->file2. And instead of using a
  76924. ** background thread to prepare data for the PmaReader, with a single
  76925. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  76926. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  76927. ** of data.
  76928. */
  76929. struct IncrMerger {
  76930. SortSubtask *pTask; /* Task that owns this merger */
  76931. MergeEngine *pMerger; /* Merge engine thread reads data from */
  76932. i64 iStartOff; /* Offset to start writing file at */
  76933. int mxSz; /* Maximum bytes of data to store */
  76934. int bEof; /* Set to true when merge is finished */
  76935. int bUseThread; /* True to use a bg thread for this object */
  76936. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  76937. };
  76938. /*
  76939. ** An instance of this object is used for writing a PMA.
  76940. **
  76941. ** The PMA is written one record at a time. Each record is of an arbitrary
  76942. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  76943. ** each block is aligned on a page boundary. This object caches writes to
  76944. ** the PMA so that aligned, page-size blocks are written.
  76945. */
  76946. struct PmaWriter {
  76947. int eFWErr; /* Non-zero if in an error state */
  76948. u8 *aBuffer; /* Pointer to write buffer */
  76949. int nBuffer; /* Size of write buffer in bytes */
  76950. int iBufStart; /* First byte of buffer to write */
  76951. int iBufEnd; /* Last byte of buffer to write */
  76952. i64 iWriteOff; /* Offset of start of buffer in file */
  76953. sqlite3_file *pFd; /* File handle to write to */
  76954. };
  76955. /*
  76956. ** This object is the header on a single record while that record is being
  76957. ** held in memory and prior to being written out as part of a PMA.
  76958. **
  76959. ** How the linked list is connected depends on how memory is being managed
  76960. ** by this module. If using a separate allocation for each in-memory record
  76961. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  76962. ** SorterRecord.u.pNext pointers.
  76963. **
  76964. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  76965. ** then while records are being accumulated the list is linked using the
  76966. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  76967. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  76968. ** has finished passing records to the sorter, or when the in-memory buffer
  76969. ** is full, the list is sorted. As part of the sorting process, it is
  76970. ** converted to use the SorterRecord.u.pNext pointers. See function
  76971. ** vdbeSorterSort() for details.
  76972. */
  76973. struct SorterRecord {
  76974. int nVal; /* Size of the record in bytes */
  76975. union {
  76976. SorterRecord *pNext; /* Pointer to next record in list */
  76977. int iNext; /* Offset within aMemory of next record */
  76978. } u;
  76979. /* The data for the record immediately follows this header */
  76980. };
  76981. /* Return a pointer to the buffer containing the record data for SorterRecord
  76982. ** object p. Should be used as if:
  76983. **
  76984. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  76985. */
  76986. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  76987. /* Maximum number of PMAs that a single MergeEngine can merge */
  76988. #define SORTER_MAX_MERGE_COUNT 16
  76989. static int vdbeIncrSwap(IncrMerger*);
  76990. static void vdbeIncrFree(IncrMerger *);
  76991. /*
  76992. ** Free all memory belonging to the PmaReader object passed as the
  76993. ** argument. All structure fields are set to zero before returning.
  76994. */
  76995. static void vdbePmaReaderClear(PmaReader *pReadr){
  76996. sqlite3_free(pReadr->aAlloc);
  76997. sqlite3_free(pReadr->aBuffer);
  76998. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  76999. vdbeIncrFree(pReadr->pIncr);
  77000. memset(pReadr, 0, sizeof(PmaReader));
  77001. }
  77002. /*
  77003. ** Read the next nByte bytes of data from the PMA p.
  77004. ** If successful, set *ppOut to point to a buffer containing the data
  77005. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  77006. ** error code.
  77007. **
  77008. ** The buffer returned in *ppOut is only valid until the
  77009. ** next call to this function.
  77010. */
  77011. static int vdbePmaReadBlob(
  77012. PmaReader *p, /* PmaReader from which to take the blob */
  77013. int nByte, /* Bytes of data to read */
  77014. u8 **ppOut /* OUT: Pointer to buffer containing data */
  77015. ){
  77016. int iBuf; /* Offset within buffer to read from */
  77017. int nAvail; /* Bytes of data available in buffer */
  77018. if( p->aMap ){
  77019. *ppOut = &p->aMap[p->iReadOff];
  77020. p->iReadOff += nByte;
  77021. return SQLITE_OK;
  77022. }
  77023. assert( p->aBuffer );
  77024. /* If there is no more data to be read from the buffer, read the next
  77025. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  77026. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  77027. iBuf = p->iReadOff % p->nBuffer;
  77028. if( iBuf==0 ){
  77029. int nRead; /* Bytes to read from disk */
  77030. int rc; /* sqlite3OsRead() return code */
  77031. /* Determine how many bytes of data to read. */
  77032. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  77033. nRead = p->nBuffer;
  77034. }else{
  77035. nRead = (int)(p->iEof - p->iReadOff);
  77036. }
  77037. assert( nRead>0 );
  77038. /* Readr data from the file. Return early if an error occurs. */
  77039. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  77040. assert( rc!=SQLITE_IOERR_SHORT_READ );
  77041. if( rc!=SQLITE_OK ) return rc;
  77042. }
  77043. nAvail = p->nBuffer - iBuf;
  77044. if( nByte<=nAvail ){
  77045. /* The requested data is available in the in-memory buffer. In this
  77046. ** case there is no need to make a copy of the data, just return a
  77047. ** pointer into the buffer to the caller. */
  77048. *ppOut = &p->aBuffer[iBuf];
  77049. p->iReadOff += nByte;
  77050. }else{
  77051. /* The requested data is not all available in the in-memory buffer.
  77052. ** In this case, allocate space at p->aAlloc[] to copy the requested
  77053. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  77054. int nRem; /* Bytes remaining to copy */
  77055. /* Extend the p->aAlloc[] allocation if required. */
  77056. if( p->nAlloc<nByte ){
  77057. u8 *aNew;
  77058. int nNew = MAX(128, p->nAlloc*2);
  77059. while( nByte>nNew ) nNew = nNew*2;
  77060. aNew = sqlite3Realloc(p->aAlloc, nNew);
  77061. if( !aNew ) return SQLITE_NOMEM_BKPT;
  77062. p->nAlloc = nNew;
  77063. p->aAlloc = aNew;
  77064. }
  77065. /* Copy as much data as is available in the buffer into the start of
  77066. ** p->aAlloc[]. */
  77067. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  77068. p->iReadOff += nAvail;
  77069. nRem = nByte - nAvail;
  77070. /* The following loop copies up to p->nBuffer bytes per iteration into
  77071. ** the p->aAlloc[] buffer. */
  77072. while( nRem>0 ){
  77073. int rc; /* vdbePmaReadBlob() return code */
  77074. int nCopy; /* Number of bytes to copy */
  77075. u8 *aNext; /* Pointer to buffer to copy data from */
  77076. nCopy = nRem;
  77077. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  77078. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  77079. if( rc!=SQLITE_OK ) return rc;
  77080. assert( aNext!=p->aAlloc );
  77081. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  77082. nRem -= nCopy;
  77083. }
  77084. *ppOut = p->aAlloc;
  77085. }
  77086. return SQLITE_OK;
  77087. }
  77088. /*
  77089. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  77090. ** the value read.
  77091. */
  77092. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  77093. int iBuf;
  77094. if( p->aMap ){
  77095. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  77096. }else{
  77097. iBuf = p->iReadOff % p->nBuffer;
  77098. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  77099. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  77100. }else{
  77101. u8 aVarint[16], *a;
  77102. int i = 0, rc;
  77103. do{
  77104. rc = vdbePmaReadBlob(p, 1, &a);
  77105. if( rc ) return rc;
  77106. aVarint[(i++)&0xf] = a[0];
  77107. }while( (a[0]&0x80)!=0 );
  77108. sqlite3GetVarint(aVarint, pnOut);
  77109. }
  77110. }
  77111. return SQLITE_OK;
  77112. }
  77113. /*
  77114. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  77115. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  77116. ** (because the file is too large or the VFS layer is configured not to use
  77117. ** mmap), return SQLITE_OK and set *pp to NULL.
  77118. **
  77119. ** Or, if an error occurs, return an SQLite error code. The final value of
  77120. ** *pp is undefined in this case.
  77121. */
  77122. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  77123. int rc = SQLITE_OK;
  77124. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  77125. sqlite3_file *pFd = pFile->pFd;
  77126. if( pFd->pMethods->iVersion>=3 ){
  77127. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  77128. testcase( rc!=SQLITE_OK );
  77129. }
  77130. }
  77131. return rc;
  77132. }
  77133. /*
  77134. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  77135. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  77136. ** if successful, or an SQLite error code if an error occurs.
  77137. */
  77138. static int vdbePmaReaderSeek(
  77139. SortSubtask *pTask, /* Task context */
  77140. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  77141. SorterFile *pFile, /* Sorter file to read from */
  77142. i64 iOff /* Offset in pFile */
  77143. ){
  77144. int rc = SQLITE_OK;
  77145. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  77146. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  77147. if( pReadr->aMap ){
  77148. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  77149. pReadr->aMap = 0;
  77150. }
  77151. pReadr->iReadOff = iOff;
  77152. pReadr->iEof = pFile->iEof;
  77153. pReadr->pFd = pFile->pFd;
  77154. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  77155. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  77156. int pgsz = pTask->pSorter->pgsz;
  77157. int iBuf = pReadr->iReadOff % pgsz;
  77158. if( pReadr->aBuffer==0 ){
  77159. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  77160. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  77161. pReadr->nBuffer = pgsz;
  77162. }
  77163. if( rc==SQLITE_OK && iBuf ){
  77164. int nRead = pgsz - iBuf;
  77165. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  77166. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  77167. }
  77168. rc = sqlite3OsRead(
  77169. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  77170. );
  77171. testcase( rc!=SQLITE_OK );
  77172. }
  77173. }
  77174. return rc;
  77175. }
  77176. /*
  77177. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  77178. ** no error occurs, or an SQLite error code if one does.
  77179. */
  77180. static int vdbePmaReaderNext(PmaReader *pReadr){
  77181. int rc = SQLITE_OK; /* Return Code */
  77182. u64 nRec = 0; /* Size of record in bytes */
  77183. if( pReadr->iReadOff>=pReadr->iEof ){
  77184. IncrMerger *pIncr = pReadr->pIncr;
  77185. int bEof = 1;
  77186. if( pIncr ){
  77187. rc = vdbeIncrSwap(pIncr);
  77188. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  77189. rc = vdbePmaReaderSeek(
  77190. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  77191. );
  77192. bEof = 0;
  77193. }
  77194. }
  77195. if( bEof ){
  77196. /* This is an EOF condition */
  77197. vdbePmaReaderClear(pReadr);
  77198. testcase( rc!=SQLITE_OK );
  77199. return rc;
  77200. }
  77201. }
  77202. if( rc==SQLITE_OK ){
  77203. rc = vdbePmaReadVarint(pReadr, &nRec);
  77204. }
  77205. if( rc==SQLITE_OK ){
  77206. pReadr->nKey = (int)nRec;
  77207. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  77208. testcase( rc!=SQLITE_OK );
  77209. }
  77210. return rc;
  77211. }
  77212. /*
  77213. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  77214. ** starting at offset iStart and ending at offset iEof-1. This function
  77215. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  77216. ** PMA is empty).
  77217. **
  77218. ** If the pnByte parameter is NULL, then it is assumed that the file
  77219. ** contains a single PMA, and that that PMA omits the initial length varint.
  77220. */
  77221. static int vdbePmaReaderInit(
  77222. SortSubtask *pTask, /* Task context */
  77223. SorterFile *pFile, /* Sorter file to read from */
  77224. i64 iStart, /* Start offset in pFile */
  77225. PmaReader *pReadr, /* PmaReader to populate */
  77226. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  77227. ){
  77228. int rc;
  77229. assert( pFile->iEof>iStart );
  77230. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  77231. assert( pReadr->aBuffer==0 );
  77232. assert( pReadr->aMap==0 );
  77233. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  77234. if( rc==SQLITE_OK ){
  77235. u64 nByte = 0; /* Size of PMA in bytes */
  77236. rc = vdbePmaReadVarint(pReadr, &nByte);
  77237. pReadr->iEof = pReadr->iReadOff + nByte;
  77238. *pnByte += nByte;
  77239. }
  77240. if( rc==SQLITE_OK ){
  77241. rc = vdbePmaReaderNext(pReadr);
  77242. }
  77243. return rc;
  77244. }
  77245. /*
  77246. ** A version of vdbeSorterCompare() that assumes that it has already been
  77247. ** determined that the first field of key1 is equal to the first field of
  77248. ** key2.
  77249. */
  77250. static int vdbeSorterCompareTail(
  77251. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  77252. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  77253. const void *pKey1, int nKey1, /* Left side of comparison */
  77254. const void *pKey2, int nKey2 /* Right side of comparison */
  77255. ){
  77256. UnpackedRecord *r2 = pTask->pUnpacked;
  77257. if( *pbKey2Cached==0 ){
  77258. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  77259. *pbKey2Cached = 1;
  77260. }
  77261. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  77262. }
  77263. /*
  77264. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  77265. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  77266. ** used by the comparison. Return the result of the comparison.
  77267. **
  77268. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  77269. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  77270. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  77271. ** version of key2 and *pbKey2Cached set to true before returning.
  77272. **
  77273. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  77274. ** to SQLITE_NOMEM.
  77275. */
  77276. static int vdbeSorterCompare(
  77277. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  77278. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  77279. const void *pKey1, int nKey1, /* Left side of comparison */
  77280. const void *pKey2, int nKey2 /* Right side of comparison */
  77281. ){
  77282. UnpackedRecord *r2 = pTask->pUnpacked;
  77283. if( !*pbKey2Cached ){
  77284. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  77285. *pbKey2Cached = 1;
  77286. }
  77287. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  77288. }
  77289. /*
  77290. ** A specially optimized version of vdbeSorterCompare() that assumes that
  77291. ** the first field of each key is a TEXT value and that the collation
  77292. ** sequence to compare them with is BINARY.
  77293. */
  77294. static int vdbeSorterCompareText(
  77295. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  77296. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  77297. const void *pKey1, int nKey1, /* Left side of comparison */
  77298. const void *pKey2, int nKey2 /* Right side of comparison */
  77299. ){
  77300. const u8 * const p1 = (const u8 * const)pKey1;
  77301. const u8 * const p2 = (const u8 * const)pKey2;
  77302. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  77303. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  77304. int n1;
  77305. int n2;
  77306. int res;
  77307. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  77308. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  77309. res = memcmp(v1, v2, MIN(n1, n2));
  77310. if( res==0 ){
  77311. res = n1 - n2;
  77312. }
  77313. if( res==0 ){
  77314. if( pTask->pSorter->pKeyInfo->nField>1 ){
  77315. res = vdbeSorterCompareTail(
  77316. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  77317. );
  77318. }
  77319. }else{
  77320. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  77321. res = res * -1;
  77322. }
  77323. }
  77324. return res;
  77325. }
  77326. /*
  77327. ** A specially optimized version of vdbeSorterCompare() that assumes that
  77328. ** the first field of each key is an INTEGER value.
  77329. */
  77330. static int vdbeSorterCompareInt(
  77331. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  77332. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  77333. const void *pKey1, int nKey1, /* Left side of comparison */
  77334. const void *pKey2, int nKey2 /* Right side of comparison */
  77335. ){
  77336. const u8 * const p1 = (const u8 * const)pKey1;
  77337. const u8 * const p2 = (const u8 * const)pKey2;
  77338. const int s1 = p1[1]; /* Left hand serial type */
  77339. const int s2 = p2[1]; /* Right hand serial type */
  77340. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  77341. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  77342. int res; /* Return value */
  77343. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  77344. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  77345. if( s1>7 && s2>7 ){
  77346. res = s1 - s2;
  77347. }else{
  77348. if( s1==s2 ){
  77349. if( (*v1 ^ *v2) & 0x80 ){
  77350. /* The two values have different signs */
  77351. res = (*v1 & 0x80) ? -1 : +1;
  77352. }else{
  77353. /* The two values have the same sign. Compare using memcmp(). */
  77354. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
  77355. int i;
  77356. res = 0;
  77357. for(i=0; i<aLen[s1]; i++){
  77358. if( (res = v1[i] - v2[i]) ) break;
  77359. }
  77360. }
  77361. }else{
  77362. if( s2>7 ){
  77363. res = +1;
  77364. }else if( s1>7 ){
  77365. res = -1;
  77366. }else{
  77367. res = s1 - s2;
  77368. }
  77369. assert( res!=0 );
  77370. if( res>0 ){
  77371. if( *v1 & 0x80 ) res = -1;
  77372. }else{
  77373. if( *v2 & 0x80 ) res = +1;
  77374. }
  77375. }
  77376. }
  77377. if( res==0 ){
  77378. if( pTask->pSorter->pKeyInfo->nField>1 ){
  77379. res = vdbeSorterCompareTail(
  77380. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  77381. );
  77382. }
  77383. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  77384. res = res * -1;
  77385. }
  77386. return res;
  77387. }
  77388. /*
  77389. ** Initialize the temporary index cursor just opened as a sorter cursor.
  77390. **
  77391. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  77392. ** to determine the number of fields that should be compared from the
  77393. ** records being sorted. However, if the value passed as argument nField
  77394. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  77395. ** is used instead. This is used when sorting records for a CREATE INDEX
  77396. ** statement. In this case, keys are always delivered to the sorter in
  77397. ** order of the primary key, which happens to be make up the final part
  77398. ** of the records being sorted. So if the sort is stable, there is never
  77399. ** any reason to compare PK fields and they can be ignored for a small
  77400. ** performance boost.
  77401. **
  77402. ** The sorter can guarantee a stable sort when running in single-threaded
  77403. ** mode, but not in multi-threaded mode.
  77404. **
  77405. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  77406. */
  77407. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  77408. sqlite3 *db, /* Database connection (for malloc()) */
  77409. int nField, /* Number of key fields in each record */
  77410. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  77411. ){
  77412. int pgsz; /* Page size of main database */
  77413. int i; /* Used to iterate through aTask[] */
  77414. int mxCache; /* Cache size */
  77415. VdbeSorter *pSorter; /* The new sorter */
  77416. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  77417. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  77418. int sz; /* Size of pSorter in bytes */
  77419. int rc = SQLITE_OK;
  77420. #if SQLITE_MAX_WORKER_THREADS==0
  77421. # define nWorker 0
  77422. #else
  77423. int nWorker;
  77424. #endif
  77425. /* Initialize the upper limit on the number of worker threads */
  77426. #if SQLITE_MAX_WORKER_THREADS>0
  77427. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  77428. nWorker = 0;
  77429. }else{
  77430. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  77431. }
  77432. #endif
  77433. /* Do not allow the total number of threads (main thread + all workers)
  77434. ** to exceed the maximum merge count */
  77435. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  77436. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  77437. nWorker = SORTER_MAX_MERGE_COUNT-1;
  77438. }
  77439. #endif
  77440. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  77441. assert( pCsr->eCurType==CURTYPE_SORTER );
  77442. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  77443. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  77444. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  77445. pCsr->uc.pSorter = pSorter;
  77446. if( pSorter==0 ){
  77447. rc = SQLITE_NOMEM_BKPT;
  77448. }else{
  77449. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  77450. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  77451. pKeyInfo->db = 0;
  77452. if( nField && nWorker==0 ){
  77453. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  77454. pKeyInfo->nField = nField;
  77455. }
  77456. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  77457. pSorter->nTask = nWorker + 1;
  77458. pSorter->iPrev = (u8)(nWorker - 1);
  77459. pSorter->bUseThreads = (pSorter->nTask>1);
  77460. pSorter->db = db;
  77461. for(i=0; i<pSorter->nTask; i++){
  77462. SortSubtask *pTask = &pSorter->aTask[i];
  77463. pTask->pSorter = pSorter;
  77464. }
  77465. if( !sqlite3TempInMemory(db) ){
  77466. u32 szPma = sqlite3GlobalConfig.szPma;
  77467. pSorter->mnPmaSize = szPma * pgsz;
  77468. mxCache = db->aDb[0].pSchema->cache_size;
  77469. if( mxCache<(int)szPma ) mxCache = (int)szPma;
  77470. pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
  77471. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  77472. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  77473. ** large heap allocations.
  77474. */
  77475. if( sqlite3GlobalConfig.pScratch==0 ){
  77476. assert( pSorter->iMemory==0 );
  77477. pSorter->nMemory = pgsz;
  77478. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  77479. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  77480. }
  77481. }
  77482. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  77483. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  77484. ){
  77485. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  77486. }
  77487. }
  77488. return rc;
  77489. }
  77490. #undef nWorker /* Defined at the top of this function */
  77491. /*
  77492. ** Free the list of sorted records starting at pRecord.
  77493. */
  77494. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  77495. SorterRecord *p;
  77496. SorterRecord *pNext;
  77497. for(p=pRecord; p; p=pNext){
  77498. pNext = p->u.pNext;
  77499. sqlite3DbFree(db, p);
  77500. }
  77501. }
  77502. /*
  77503. ** Free all resources owned by the object indicated by argument pTask. All
  77504. ** fields of *pTask are zeroed before returning.
  77505. */
  77506. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  77507. sqlite3DbFree(db, pTask->pUnpacked);
  77508. #if SQLITE_MAX_WORKER_THREADS>0
  77509. /* pTask->list.aMemory can only be non-zero if it was handed memory
  77510. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  77511. if( pTask->list.aMemory ){
  77512. sqlite3_free(pTask->list.aMemory);
  77513. }else
  77514. #endif
  77515. {
  77516. assert( pTask->list.aMemory==0 );
  77517. vdbeSorterRecordFree(0, pTask->list.pList);
  77518. }
  77519. if( pTask->file.pFd ){
  77520. sqlite3OsCloseFree(pTask->file.pFd);
  77521. }
  77522. if( pTask->file2.pFd ){
  77523. sqlite3OsCloseFree(pTask->file2.pFd);
  77524. }
  77525. memset(pTask, 0, sizeof(SortSubtask));
  77526. }
  77527. #ifdef SQLITE_DEBUG_SORTER_THREADS
  77528. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  77529. i64 t;
  77530. int iTask = (pTask - pTask->pSorter->aTask);
  77531. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  77532. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  77533. }
  77534. static void vdbeSorterRewindDebug(const char *zEvent){
  77535. i64 t;
  77536. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  77537. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  77538. }
  77539. static void vdbeSorterPopulateDebug(
  77540. SortSubtask *pTask,
  77541. const char *zEvent
  77542. ){
  77543. i64 t;
  77544. int iTask = (pTask - pTask->pSorter->aTask);
  77545. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  77546. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  77547. }
  77548. static void vdbeSorterBlockDebug(
  77549. SortSubtask *pTask,
  77550. int bBlocked,
  77551. const char *zEvent
  77552. ){
  77553. if( bBlocked ){
  77554. i64 t;
  77555. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  77556. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  77557. }
  77558. }
  77559. #else
  77560. # define vdbeSorterWorkDebug(x,y)
  77561. # define vdbeSorterRewindDebug(y)
  77562. # define vdbeSorterPopulateDebug(x,y)
  77563. # define vdbeSorterBlockDebug(x,y,z)
  77564. #endif
  77565. #if SQLITE_MAX_WORKER_THREADS>0
  77566. /*
  77567. ** Join thread pTask->thread.
  77568. */
  77569. static int vdbeSorterJoinThread(SortSubtask *pTask){
  77570. int rc = SQLITE_OK;
  77571. if( pTask->pThread ){
  77572. #ifdef SQLITE_DEBUG_SORTER_THREADS
  77573. int bDone = pTask->bDone;
  77574. #endif
  77575. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  77576. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  77577. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  77578. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  77579. rc = SQLITE_PTR_TO_INT(pRet);
  77580. assert( pTask->bDone==1 );
  77581. pTask->bDone = 0;
  77582. pTask->pThread = 0;
  77583. }
  77584. return rc;
  77585. }
  77586. /*
  77587. ** Launch a background thread to run xTask(pIn).
  77588. */
  77589. static int vdbeSorterCreateThread(
  77590. SortSubtask *pTask, /* Thread will use this task object */
  77591. void *(*xTask)(void*), /* Routine to run in a separate thread */
  77592. void *pIn /* Argument passed into xTask() */
  77593. ){
  77594. assert( pTask->pThread==0 && pTask->bDone==0 );
  77595. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  77596. }
  77597. /*
  77598. ** Join all outstanding threads launched by SorterWrite() to create
  77599. ** level-0 PMAs.
  77600. */
  77601. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  77602. int rc = rcin;
  77603. int i;
  77604. /* This function is always called by the main user thread.
  77605. **
  77606. ** If this function is being called after SorterRewind() has been called,
  77607. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  77608. ** is currently attempt to join one of the other threads. To avoid a race
  77609. ** condition where this thread also attempts to join the same object, join
  77610. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  77611. for(i=pSorter->nTask-1; i>=0; i--){
  77612. SortSubtask *pTask = &pSorter->aTask[i];
  77613. int rc2 = vdbeSorterJoinThread(pTask);
  77614. if( rc==SQLITE_OK ) rc = rc2;
  77615. }
  77616. return rc;
  77617. }
  77618. #else
  77619. # define vdbeSorterJoinAll(x,rcin) (rcin)
  77620. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  77621. #endif
  77622. /*
  77623. ** Allocate a new MergeEngine object capable of handling up to
  77624. ** nReader PmaReader inputs.
  77625. **
  77626. ** nReader is automatically rounded up to the next power of two.
  77627. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  77628. */
  77629. static MergeEngine *vdbeMergeEngineNew(int nReader){
  77630. int N = 2; /* Smallest power of two >= nReader */
  77631. int nByte; /* Total bytes of space to allocate */
  77632. MergeEngine *pNew; /* Pointer to allocated object to return */
  77633. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  77634. while( N<nReader ) N += N;
  77635. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  77636. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  77637. if( pNew ){
  77638. pNew->nTree = N;
  77639. pNew->pTask = 0;
  77640. pNew->aReadr = (PmaReader*)&pNew[1];
  77641. pNew->aTree = (int*)&pNew->aReadr[N];
  77642. }
  77643. return pNew;
  77644. }
  77645. /*
  77646. ** Free the MergeEngine object passed as the only argument.
  77647. */
  77648. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  77649. int i;
  77650. if( pMerger ){
  77651. for(i=0; i<pMerger->nTree; i++){
  77652. vdbePmaReaderClear(&pMerger->aReadr[i]);
  77653. }
  77654. }
  77655. sqlite3_free(pMerger);
  77656. }
  77657. /*
  77658. ** Free all resources associated with the IncrMerger object indicated by
  77659. ** the first argument.
  77660. */
  77661. static void vdbeIncrFree(IncrMerger *pIncr){
  77662. if( pIncr ){
  77663. #if SQLITE_MAX_WORKER_THREADS>0
  77664. if( pIncr->bUseThread ){
  77665. vdbeSorterJoinThread(pIncr->pTask);
  77666. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  77667. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  77668. }
  77669. #endif
  77670. vdbeMergeEngineFree(pIncr->pMerger);
  77671. sqlite3_free(pIncr);
  77672. }
  77673. }
  77674. /*
  77675. ** Reset a sorting cursor back to its original empty state.
  77676. */
  77677. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  77678. int i;
  77679. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  77680. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  77681. #if SQLITE_MAX_WORKER_THREADS>0
  77682. if( pSorter->pReader ){
  77683. vdbePmaReaderClear(pSorter->pReader);
  77684. sqlite3DbFree(db, pSorter->pReader);
  77685. pSorter->pReader = 0;
  77686. }
  77687. #endif
  77688. vdbeMergeEngineFree(pSorter->pMerger);
  77689. pSorter->pMerger = 0;
  77690. for(i=0; i<pSorter->nTask; i++){
  77691. SortSubtask *pTask = &pSorter->aTask[i];
  77692. vdbeSortSubtaskCleanup(db, pTask);
  77693. pTask->pSorter = pSorter;
  77694. }
  77695. if( pSorter->list.aMemory==0 ){
  77696. vdbeSorterRecordFree(0, pSorter->list.pList);
  77697. }
  77698. pSorter->list.pList = 0;
  77699. pSorter->list.szPMA = 0;
  77700. pSorter->bUsePMA = 0;
  77701. pSorter->iMemory = 0;
  77702. pSorter->mxKeysize = 0;
  77703. sqlite3DbFree(db, pSorter->pUnpacked);
  77704. pSorter->pUnpacked = 0;
  77705. }
  77706. /*
  77707. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  77708. */
  77709. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  77710. VdbeSorter *pSorter;
  77711. assert( pCsr->eCurType==CURTYPE_SORTER );
  77712. pSorter = pCsr->uc.pSorter;
  77713. if( pSorter ){
  77714. sqlite3VdbeSorterReset(db, pSorter);
  77715. sqlite3_free(pSorter->list.aMemory);
  77716. sqlite3DbFree(db, pSorter);
  77717. pCsr->uc.pSorter = 0;
  77718. }
  77719. }
  77720. #if SQLITE_MAX_MMAP_SIZE>0
  77721. /*
  77722. ** The first argument is a file-handle open on a temporary file. The file
  77723. ** is guaranteed to be nByte bytes or smaller in size. This function
  77724. ** attempts to extend the file to nByte bytes in size and to ensure that
  77725. ** the VFS has memory mapped it.
  77726. **
  77727. ** Whether or not the file does end up memory mapped of course depends on
  77728. ** the specific VFS implementation.
  77729. */
  77730. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  77731. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  77732. void *p = 0;
  77733. int chunksize = 4*1024;
  77734. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  77735. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  77736. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  77737. sqlite3OsUnfetch(pFd, 0, p);
  77738. }
  77739. }
  77740. #else
  77741. # define vdbeSorterExtendFile(x,y,z)
  77742. #endif
  77743. /*
  77744. ** Allocate space for a file-handle and open a temporary file. If successful,
  77745. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  77746. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  77747. */
  77748. static int vdbeSorterOpenTempFile(
  77749. sqlite3 *db, /* Database handle doing sort */
  77750. i64 nExtend, /* Attempt to extend file to this size */
  77751. sqlite3_file **ppFd
  77752. ){
  77753. int rc;
  77754. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  77755. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  77756. SQLITE_OPEN_TEMP_JOURNAL |
  77757. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  77758. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  77759. );
  77760. if( rc==SQLITE_OK ){
  77761. i64 max = SQLITE_MAX_MMAP_SIZE;
  77762. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  77763. if( nExtend>0 ){
  77764. vdbeSorterExtendFile(db, *ppFd, nExtend);
  77765. }
  77766. }
  77767. return rc;
  77768. }
  77769. /*
  77770. ** If it has not already been allocated, allocate the UnpackedRecord
  77771. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  77772. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  77773. */
  77774. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  77775. if( pTask->pUnpacked==0 ){
  77776. char *pFree;
  77777. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  77778. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  77779. );
  77780. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  77781. if( pFree==0 ) return SQLITE_NOMEM_BKPT;
  77782. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  77783. pTask->pUnpacked->errCode = 0;
  77784. }
  77785. return SQLITE_OK;
  77786. }
  77787. /*
  77788. ** Merge the two sorted lists p1 and p2 into a single list.
  77789. ** Set *ppOut to the head of the new list.
  77790. */
  77791. static void vdbeSorterMerge(
  77792. SortSubtask *pTask, /* Calling thread context */
  77793. SorterRecord *p1, /* First list to merge */
  77794. SorterRecord *p2, /* Second list to merge */
  77795. SorterRecord **ppOut /* OUT: Head of merged list */
  77796. ){
  77797. SorterRecord *pFinal = 0;
  77798. SorterRecord **pp = &pFinal;
  77799. int bCached = 0;
  77800. while( p1 && p2 ){
  77801. int res;
  77802. res = pTask->xCompare(
  77803. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  77804. );
  77805. if( res<=0 ){
  77806. *pp = p1;
  77807. pp = &p1->u.pNext;
  77808. p1 = p1->u.pNext;
  77809. }else{
  77810. *pp = p2;
  77811. pp = &p2->u.pNext;
  77812. p2 = p2->u.pNext;
  77813. bCached = 0;
  77814. }
  77815. }
  77816. *pp = p1 ? p1 : p2;
  77817. *ppOut = pFinal;
  77818. }
  77819. /*
  77820. ** Return the SorterCompare function to compare values collected by the
  77821. ** sorter object passed as the only argument.
  77822. */
  77823. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  77824. if( p->typeMask==SORTER_TYPE_INTEGER ){
  77825. return vdbeSorterCompareInt;
  77826. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  77827. return vdbeSorterCompareText;
  77828. }
  77829. return vdbeSorterCompare;
  77830. }
  77831. /*
  77832. ** Sort the linked list of records headed at pTask->pList. Return
  77833. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  77834. ** an error occurs.
  77835. */
  77836. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  77837. int i;
  77838. SorterRecord **aSlot;
  77839. SorterRecord *p;
  77840. int rc;
  77841. rc = vdbeSortAllocUnpacked(pTask);
  77842. if( rc!=SQLITE_OK ) return rc;
  77843. p = pList->pList;
  77844. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  77845. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  77846. if( !aSlot ){
  77847. return SQLITE_NOMEM_BKPT;
  77848. }
  77849. while( p ){
  77850. SorterRecord *pNext;
  77851. if( pList->aMemory ){
  77852. if( (u8*)p==pList->aMemory ){
  77853. pNext = 0;
  77854. }else{
  77855. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  77856. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  77857. }
  77858. }else{
  77859. pNext = p->u.pNext;
  77860. }
  77861. p->u.pNext = 0;
  77862. for(i=0; aSlot[i]; i++){
  77863. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  77864. aSlot[i] = 0;
  77865. }
  77866. aSlot[i] = p;
  77867. p = pNext;
  77868. }
  77869. p = 0;
  77870. for(i=0; i<64; i++){
  77871. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  77872. }
  77873. pList->pList = p;
  77874. sqlite3_free(aSlot);
  77875. assert( pTask->pUnpacked->errCode==SQLITE_OK
  77876. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  77877. );
  77878. return pTask->pUnpacked->errCode;
  77879. }
  77880. /*
  77881. ** Initialize a PMA-writer object.
  77882. */
  77883. static void vdbePmaWriterInit(
  77884. sqlite3_file *pFd, /* File handle to write to */
  77885. PmaWriter *p, /* Object to populate */
  77886. int nBuf, /* Buffer size */
  77887. i64 iStart /* Offset of pFd to begin writing at */
  77888. ){
  77889. memset(p, 0, sizeof(PmaWriter));
  77890. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  77891. if( !p->aBuffer ){
  77892. p->eFWErr = SQLITE_NOMEM_BKPT;
  77893. }else{
  77894. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  77895. p->iWriteOff = iStart - p->iBufStart;
  77896. p->nBuffer = nBuf;
  77897. p->pFd = pFd;
  77898. }
  77899. }
  77900. /*
  77901. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  77902. ** if successful, or an SQLite error code if an error occurs.
  77903. */
  77904. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  77905. int nRem = nData;
  77906. while( nRem>0 && p->eFWErr==0 ){
  77907. int nCopy = nRem;
  77908. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  77909. nCopy = p->nBuffer - p->iBufEnd;
  77910. }
  77911. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  77912. p->iBufEnd += nCopy;
  77913. if( p->iBufEnd==p->nBuffer ){
  77914. p->eFWErr = sqlite3OsWrite(p->pFd,
  77915. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  77916. p->iWriteOff + p->iBufStart
  77917. );
  77918. p->iBufStart = p->iBufEnd = 0;
  77919. p->iWriteOff += p->nBuffer;
  77920. }
  77921. assert( p->iBufEnd<p->nBuffer );
  77922. nRem -= nCopy;
  77923. }
  77924. }
  77925. /*
  77926. ** Flush any buffered data to disk and clean up the PMA-writer object.
  77927. ** The results of using the PMA-writer after this call are undefined.
  77928. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  77929. ** required. Otherwise, return an SQLite error code.
  77930. **
  77931. ** Before returning, set *piEof to the offset immediately following the
  77932. ** last byte written to the file.
  77933. */
  77934. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  77935. int rc;
  77936. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  77937. p->eFWErr = sqlite3OsWrite(p->pFd,
  77938. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  77939. p->iWriteOff + p->iBufStart
  77940. );
  77941. }
  77942. *piEof = (p->iWriteOff + p->iBufEnd);
  77943. sqlite3_free(p->aBuffer);
  77944. rc = p->eFWErr;
  77945. memset(p, 0, sizeof(PmaWriter));
  77946. return rc;
  77947. }
  77948. /*
  77949. ** Write value iVal encoded as a varint to the PMA. Return
  77950. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  77951. */
  77952. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  77953. int nByte;
  77954. u8 aByte[10];
  77955. nByte = sqlite3PutVarint(aByte, iVal);
  77956. vdbePmaWriteBlob(p, aByte, nByte);
  77957. }
  77958. /*
  77959. ** Write the current contents of in-memory linked-list pList to a level-0
  77960. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  77961. ** successful, or an SQLite error code otherwise.
  77962. **
  77963. ** The format of a PMA is:
  77964. **
  77965. ** * A varint. This varint contains the total number of bytes of content
  77966. ** in the PMA (not including the varint itself).
  77967. **
  77968. ** * One or more records packed end-to-end in order of ascending keys.
  77969. ** Each record consists of a varint followed by a blob of data (the
  77970. ** key). The varint is the number of bytes in the blob of data.
  77971. */
  77972. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  77973. sqlite3 *db = pTask->pSorter->db;
  77974. int rc = SQLITE_OK; /* Return code */
  77975. PmaWriter writer; /* Object used to write to the file */
  77976. #ifdef SQLITE_DEBUG
  77977. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  77978. ** This is used by an assert() statement at the end of this function. */
  77979. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  77980. #endif
  77981. vdbeSorterWorkDebug(pTask, "enter");
  77982. memset(&writer, 0, sizeof(PmaWriter));
  77983. assert( pList->szPMA>0 );
  77984. /* If the first temporary PMA file has not been opened, open it now. */
  77985. if( pTask->file.pFd==0 ){
  77986. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  77987. assert( rc!=SQLITE_OK || pTask->file.pFd );
  77988. assert( pTask->file.iEof==0 );
  77989. assert( pTask->nPMA==0 );
  77990. }
  77991. /* Try to get the file to memory map */
  77992. if( rc==SQLITE_OK ){
  77993. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  77994. }
  77995. /* Sort the list */
  77996. if( rc==SQLITE_OK ){
  77997. rc = vdbeSorterSort(pTask, pList);
  77998. }
  77999. if( rc==SQLITE_OK ){
  78000. SorterRecord *p;
  78001. SorterRecord *pNext = 0;
  78002. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  78003. pTask->file.iEof);
  78004. pTask->nPMA++;
  78005. vdbePmaWriteVarint(&writer, pList->szPMA);
  78006. for(p=pList->pList; p; p=pNext){
  78007. pNext = p->u.pNext;
  78008. vdbePmaWriteVarint(&writer, p->nVal);
  78009. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  78010. if( pList->aMemory==0 ) sqlite3_free(p);
  78011. }
  78012. pList->pList = p;
  78013. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  78014. }
  78015. vdbeSorterWorkDebug(pTask, "exit");
  78016. assert( rc!=SQLITE_OK || pList->pList==0 );
  78017. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  78018. return rc;
  78019. }
  78020. /*
  78021. ** Advance the MergeEngine to its next entry.
  78022. ** Set *pbEof to true there is no next entry because
  78023. ** the MergeEngine has reached the end of all its inputs.
  78024. **
  78025. ** Return SQLITE_OK if successful or an error code if an error occurs.
  78026. */
  78027. static int vdbeMergeEngineStep(
  78028. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  78029. int *pbEof /* Set TRUE at EOF. Set false for more content */
  78030. ){
  78031. int rc;
  78032. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  78033. SortSubtask *pTask = pMerger->pTask;
  78034. /* Advance the current PmaReader */
  78035. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  78036. /* Update contents of aTree[] */
  78037. if( rc==SQLITE_OK ){
  78038. int i; /* Index of aTree[] to recalculate */
  78039. PmaReader *pReadr1; /* First PmaReader to compare */
  78040. PmaReader *pReadr2; /* Second PmaReader to compare */
  78041. int bCached = 0;
  78042. /* Find the first two PmaReaders to compare. The one that was just
  78043. ** advanced (iPrev) and the one next to it in the array. */
  78044. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  78045. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  78046. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  78047. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  78048. int iRes;
  78049. if( pReadr1->pFd==0 ){
  78050. iRes = +1;
  78051. }else if( pReadr2->pFd==0 ){
  78052. iRes = -1;
  78053. }else{
  78054. iRes = pTask->xCompare(pTask, &bCached,
  78055. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  78056. );
  78057. }
  78058. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  78059. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  78060. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  78061. ** pKey2 to point to the record belonging to pReadr2.
  78062. **
  78063. ** Alternatively, if pReadr2 contains the smaller of the two values,
  78064. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  78065. ** was actually called above, then pTask->pUnpacked now contains
  78066. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  78067. ** vdbeSorterCompare() from decoding pReadr2 again.
  78068. **
  78069. ** If the two values were equal, then the value from the oldest
  78070. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  78071. ** is sorted from oldest to newest, so pReadr1 contains older values
  78072. ** than pReadr2 iff (pReadr1<pReadr2). */
  78073. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  78074. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  78075. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  78076. bCached = 0;
  78077. }else{
  78078. if( pReadr1->pFd ) bCached = 0;
  78079. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  78080. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  78081. }
  78082. }
  78083. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  78084. }
  78085. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  78086. }
  78087. #if SQLITE_MAX_WORKER_THREADS>0
  78088. /*
  78089. ** The main routine for background threads that write level-0 PMAs.
  78090. */
  78091. static void *vdbeSorterFlushThread(void *pCtx){
  78092. SortSubtask *pTask = (SortSubtask*)pCtx;
  78093. int rc; /* Return code */
  78094. assert( pTask->bDone==0 );
  78095. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  78096. pTask->bDone = 1;
  78097. return SQLITE_INT_TO_PTR(rc);
  78098. }
  78099. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  78100. /*
  78101. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  78102. ** using a background thread.
  78103. */
  78104. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  78105. #if SQLITE_MAX_WORKER_THREADS==0
  78106. pSorter->bUsePMA = 1;
  78107. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  78108. #else
  78109. int rc = SQLITE_OK;
  78110. int i;
  78111. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  78112. int nWorker = (pSorter->nTask-1);
  78113. /* Set the flag to indicate that at least one PMA has been written.
  78114. ** Or will be, anyhow. */
  78115. pSorter->bUsePMA = 1;
  78116. /* Select a sub-task to sort and flush the current list of in-memory
  78117. ** records to disk. If the sorter is running in multi-threaded mode,
  78118. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  78119. ** the background thread from a sub-tasks previous turn is still running,
  78120. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  78121. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  78122. ** sub-tasks are prefered as they use background threads - the final
  78123. ** sub-task uses the main thread. */
  78124. for(i=0; i<nWorker; i++){
  78125. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  78126. pTask = &pSorter->aTask[iTest];
  78127. if( pTask->bDone ){
  78128. rc = vdbeSorterJoinThread(pTask);
  78129. }
  78130. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  78131. }
  78132. if( rc==SQLITE_OK ){
  78133. if( i==nWorker ){
  78134. /* Use the foreground thread for this operation */
  78135. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  78136. }else{
  78137. /* Launch a background thread for this operation */
  78138. u8 *aMem = pTask->list.aMemory;
  78139. void *pCtx = (void*)pTask;
  78140. assert( pTask->pThread==0 && pTask->bDone==0 );
  78141. assert( pTask->list.pList==0 );
  78142. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  78143. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  78144. pTask->list = pSorter->list;
  78145. pSorter->list.pList = 0;
  78146. pSorter->list.szPMA = 0;
  78147. if( aMem ){
  78148. pSorter->list.aMemory = aMem;
  78149. pSorter->nMemory = sqlite3MallocSize(aMem);
  78150. }else if( pSorter->list.aMemory ){
  78151. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  78152. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  78153. }
  78154. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  78155. }
  78156. }
  78157. return rc;
  78158. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  78159. }
  78160. /*
  78161. ** Add a record to the sorter.
  78162. */
  78163. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  78164. const VdbeCursor *pCsr, /* Sorter cursor */
  78165. Mem *pVal /* Memory cell containing record */
  78166. ){
  78167. VdbeSorter *pSorter;
  78168. int rc = SQLITE_OK; /* Return Code */
  78169. SorterRecord *pNew; /* New list element */
  78170. int bFlush; /* True to flush contents of memory to PMA */
  78171. int nReq; /* Bytes of memory required */
  78172. int nPMA; /* Bytes of PMA space required */
  78173. int t; /* serial type of first record field */
  78174. assert( pCsr->eCurType==CURTYPE_SORTER );
  78175. pSorter = pCsr->uc.pSorter;
  78176. getVarint32((const u8*)&pVal->z[1], t);
  78177. if( t>0 && t<10 && t!=7 ){
  78178. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  78179. }else if( t>10 && (t & 0x01) ){
  78180. pSorter->typeMask &= SORTER_TYPE_TEXT;
  78181. }else{
  78182. pSorter->typeMask = 0;
  78183. }
  78184. assert( pSorter );
  78185. /* Figure out whether or not the current contents of memory should be
  78186. ** flushed to a PMA before continuing. If so, do so.
  78187. **
  78188. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  78189. ** flush the contents of memory to a new PMA if (a) at least one value is
  78190. ** already in memory and (b) the new value will not fit in memory.
  78191. **
  78192. ** Or, if using separate allocations for each record, flush the contents
  78193. ** of memory to a PMA if either of the following are true:
  78194. **
  78195. ** * The total memory allocated for the in-memory list is greater
  78196. ** than (page-size * cache-size), or
  78197. **
  78198. ** * The total memory allocated for the in-memory list is greater
  78199. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  78200. */
  78201. nReq = pVal->n + sizeof(SorterRecord);
  78202. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  78203. if( pSorter->mxPmaSize ){
  78204. if( pSorter->list.aMemory ){
  78205. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  78206. }else{
  78207. bFlush = (
  78208. (pSorter->list.szPMA > pSorter->mxPmaSize)
  78209. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  78210. );
  78211. }
  78212. if( bFlush ){
  78213. rc = vdbeSorterFlushPMA(pSorter);
  78214. pSorter->list.szPMA = 0;
  78215. pSorter->iMemory = 0;
  78216. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  78217. }
  78218. }
  78219. pSorter->list.szPMA += nPMA;
  78220. if( nPMA>pSorter->mxKeysize ){
  78221. pSorter->mxKeysize = nPMA;
  78222. }
  78223. if( pSorter->list.aMemory ){
  78224. int nMin = pSorter->iMemory + nReq;
  78225. if( nMin>pSorter->nMemory ){
  78226. u8 *aNew;
  78227. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  78228. int nNew = pSorter->nMemory * 2;
  78229. while( nNew < nMin ) nNew = nNew*2;
  78230. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  78231. if( nNew < nMin ) nNew = nMin;
  78232. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  78233. if( !aNew ) return SQLITE_NOMEM_BKPT;
  78234. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  78235. pSorter->list.aMemory = aNew;
  78236. pSorter->nMemory = nNew;
  78237. }
  78238. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  78239. pSorter->iMemory += ROUND8(nReq);
  78240. if( pSorter->list.pList ){
  78241. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  78242. }
  78243. }else{
  78244. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  78245. if( pNew==0 ){
  78246. return SQLITE_NOMEM_BKPT;
  78247. }
  78248. pNew->u.pNext = pSorter->list.pList;
  78249. }
  78250. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  78251. pNew->nVal = pVal->n;
  78252. pSorter->list.pList = pNew;
  78253. return rc;
  78254. }
  78255. /*
  78256. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  78257. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  78258. ** except that the number-of-bytes varint is omitted from the start.
  78259. */
  78260. static int vdbeIncrPopulate(IncrMerger *pIncr){
  78261. int rc = SQLITE_OK;
  78262. int rc2;
  78263. i64 iStart = pIncr->iStartOff;
  78264. SorterFile *pOut = &pIncr->aFile[1];
  78265. SortSubtask *pTask = pIncr->pTask;
  78266. MergeEngine *pMerger = pIncr->pMerger;
  78267. PmaWriter writer;
  78268. assert( pIncr->bEof==0 );
  78269. vdbeSorterPopulateDebug(pTask, "enter");
  78270. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  78271. while( rc==SQLITE_OK ){
  78272. int dummy;
  78273. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  78274. int nKey = pReader->nKey;
  78275. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  78276. /* Check if the output file is full or if the input has been exhausted.
  78277. ** In either case exit the loop. */
  78278. if( pReader->pFd==0 ) break;
  78279. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  78280. /* Write the next key to the output. */
  78281. vdbePmaWriteVarint(&writer, nKey);
  78282. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  78283. assert( pIncr->pMerger->pTask==pTask );
  78284. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  78285. }
  78286. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  78287. if( rc==SQLITE_OK ) rc = rc2;
  78288. vdbeSorterPopulateDebug(pTask, "exit");
  78289. return rc;
  78290. }
  78291. #if SQLITE_MAX_WORKER_THREADS>0
  78292. /*
  78293. ** The main routine for background threads that populate aFile[1] of
  78294. ** multi-threaded IncrMerger objects.
  78295. */
  78296. static void *vdbeIncrPopulateThread(void *pCtx){
  78297. IncrMerger *pIncr = (IncrMerger*)pCtx;
  78298. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  78299. pIncr->pTask->bDone = 1;
  78300. return pRet;
  78301. }
  78302. /*
  78303. ** Launch a background thread to populate aFile[1] of pIncr.
  78304. */
  78305. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  78306. void *p = (void*)pIncr;
  78307. assert( pIncr->bUseThread );
  78308. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  78309. }
  78310. #endif
  78311. /*
  78312. ** This function is called when the PmaReader corresponding to pIncr has
  78313. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  78314. ** aFile[0] such that the PmaReader should start rereading it from the
  78315. ** beginning.
  78316. **
  78317. ** For single-threaded objects, this is accomplished by literally reading
  78318. ** keys from pIncr->pMerger and repopulating aFile[0].
  78319. **
  78320. ** For multi-threaded objects, all that is required is to wait until the
  78321. ** background thread is finished (if it is not already) and then swap
  78322. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  78323. ** been exhausted, this function also launches a new background thread
  78324. ** to populate the new aFile[1].
  78325. **
  78326. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  78327. */
  78328. static int vdbeIncrSwap(IncrMerger *pIncr){
  78329. int rc = SQLITE_OK;
  78330. #if SQLITE_MAX_WORKER_THREADS>0
  78331. if( pIncr->bUseThread ){
  78332. rc = vdbeSorterJoinThread(pIncr->pTask);
  78333. if( rc==SQLITE_OK ){
  78334. SorterFile f0 = pIncr->aFile[0];
  78335. pIncr->aFile[0] = pIncr->aFile[1];
  78336. pIncr->aFile[1] = f0;
  78337. }
  78338. if( rc==SQLITE_OK ){
  78339. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  78340. pIncr->bEof = 1;
  78341. }else{
  78342. rc = vdbeIncrBgPopulate(pIncr);
  78343. }
  78344. }
  78345. }else
  78346. #endif
  78347. {
  78348. rc = vdbeIncrPopulate(pIncr);
  78349. pIncr->aFile[0] = pIncr->aFile[1];
  78350. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  78351. pIncr->bEof = 1;
  78352. }
  78353. }
  78354. return rc;
  78355. }
  78356. /*
  78357. ** Allocate and return a new IncrMerger object to read data from pMerger.
  78358. **
  78359. ** If an OOM condition is encountered, return NULL. In this case free the
  78360. ** pMerger argument before returning.
  78361. */
  78362. static int vdbeIncrMergerNew(
  78363. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  78364. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  78365. IncrMerger **ppOut /* Write the new IncrMerger here */
  78366. ){
  78367. int rc = SQLITE_OK;
  78368. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  78369. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  78370. if( pIncr ){
  78371. pIncr->pMerger = pMerger;
  78372. pIncr->pTask = pTask;
  78373. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  78374. pTask->file2.iEof += pIncr->mxSz;
  78375. }else{
  78376. vdbeMergeEngineFree(pMerger);
  78377. rc = SQLITE_NOMEM_BKPT;
  78378. }
  78379. return rc;
  78380. }
  78381. #if SQLITE_MAX_WORKER_THREADS>0
  78382. /*
  78383. ** Set the "use-threads" flag on object pIncr.
  78384. */
  78385. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  78386. pIncr->bUseThread = 1;
  78387. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  78388. }
  78389. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  78390. /*
  78391. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  78392. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  78393. ** are advanced. This routine merely does the comparison.
  78394. */
  78395. static void vdbeMergeEngineCompare(
  78396. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  78397. int iOut /* Store the result in pMerger->aTree[iOut] */
  78398. ){
  78399. int i1;
  78400. int i2;
  78401. int iRes;
  78402. PmaReader *p1;
  78403. PmaReader *p2;
  78404. assert( iOut<pMerger->nTree && iOut>0 );
  78405. if( iOut>=(pMerger->nTree/2) ){
  78406. i1 = (iOut - pMerger->nTree/2) * 2;
  78407. i2 = i1 + 1;
  78408. }else{
  78409. i1 = pMerger->aTree[iOut*2];
  78410. i2 = pMerger->aTree[iOut*2+1];
  78411. }
  78412. p1 = &pMerger->aReadr[i1];
  78413. p2 = &pMerger->aReadr[i2];
  78414. if( p1->pFd==0 ){
  78415. iRes = i2;
  78416. }else if( p2->pFd==0 ){
  78417. iRes = i1;
  78418. }else{
  78419. SortSubtask *pTask = pMerger->pTask;
  78420. int bCached = 0;
  78421. int res;
  78422. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  78423. res = pTask->xCompare(
  78424. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  78425. );
  78426. if( res<=0 ){
  78427. iRes = i1;
  78428. }else{
  78429. iRes = i2;
  78430. }
  78431. }
  78432. pMerger->aTree[iOut] = iRes;
  78433. }
  78434. /*
  78435. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  78436. ** and vdbePmaReaderIncrMergeInit().
  78437. **
  78438. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  78439. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  78440. ** when there exists one or more separate worker threads.
  78441. */
  78442. #define INCRINIT_NORMAL 0
  78443. #define INCRINIT_TASK 1
  78444. #define INCRINIT_ROOT 2
  78445. /*
  78446. ** Forward reference required as the vdbeIncrMergeInit() and
  78447. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  78448. ** building a merge tree.
  78449. */
  78450. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  78451. /*
  78452. ** Initialize the MergeEngine object passed as the second argument. Once this
  78453. ** function returns, the first key of merged data may be read from the
  78454. ** MergeEngine object in the usual fashion.
  78455. **
  78456. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  78457. ** objects attached to the PmaReader objects that the merger reads from have
  78458. ** already been populated, but that they have not yet populated aFile[0] and
  78459. ** set the PmaReader objects up to read from it. In this case all that is
  78460. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  78461. ** its first key.
  78462. **
  78463. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  78464. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  78465. ** to pMerger.
  78466. **
  78467. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  78468. */
  78469. static int vdbeMergeEngineInit(
  78470. SortSubtask *pTask, /* Thread that will run pMerger */
  78471. MergeEngine *pMerger, /* MergeEngine to initialize */
  78472. int eMode /* One of the INCRINIT_XXX constants */
  78473. ){
  78474. int rc = SQLITE_OK; /* Return code */
  78475. int i; /* For looping over PmaReader objects */
  78476. int nTree = pMerger->nTree;
  78477. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  78478. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  78479. /* Verify that the MergeEngine is assigned to a single thread */
  78480. assert( pMerger->pTask==0 );
  78481. pMerger->pTask = pTask;
  78482. for(i=0; i<nTree; i++){
  78483. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  78484. /* PmaReaders should be normally initialized in order, as if they are
  78485. ** reading from the same temp file this makes for more linear file IO.
  78486. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  78487. ** in use it will block the vdbePmaReaderNext() call while it uses
  78488. ** the main thread to fill its buffer. So calling PmaReaderNext()
  78489. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  78490. ** better advantage of multi-processor hardware. */
  78491. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  78492. }else{
  78493. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  78494. }
  78495. if( rc!=SQLITE_OK ) return rc;
  78496. }
  78497. for(i=pMerger->nTree-1; i>0; i--){
  78498. vdbeMergeEngineCompare(pMerger, i);
  78499. }
  78500. return pTask->pUnpacked->errCode;
  78501. }
  78502. /*
  78503. ** The PmaReader passed as the first argument is guaranteed to be an
  78504. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  78505. ** and/or initialize the temp file related fields of the IncrMerge
  78506. ** object at (pReadr->pIncr).
  78507. **
  78508. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  78509. ** in the sub-tree headed by pReadr are also initialized. Data is then
  78510. ** loaded into the buffers belonging to pReadr and it is set to point to
  78511. ** the first key in its range.
  78512. **
  78513. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  78514. ** to be a multi-threaded PmaReader and this function is being called in a
  78515. ** background thread. In this case all PmaReaders in the sub-tree are
  78516. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  78517. ** pReadr is populated. However, pReadr itself is not set up to point
  78518. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  78519. ** that.
  78520. **
  78521. ** The reason this function does not call vdbePmaReaderNext() immediately
  78522. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  78523. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  78524. ** this entire function is being run by thread (pTask->thread), that will
  78525. ** lead to the current background thread attempting to join itself.
  78526. **
  78527. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  78528. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  78529. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  78530. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  78531. ** the current PmaReader set to point to the first key in its range.
  78532. **
  78533. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  78534. */
  78535. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  78536. int rc = SQLITE_OK;
  78537. IncrMerger *pIncr = pReadr->pIncr;
  78538. SortSubtask *pTask = pIncr->pTask;
  78539. sqlite3 *db = pTask->pSorter->db;
  78540. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  78541. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  78542. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  78543. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  78544. ** requires two temp files to itself, whereas a single-threaded object
  78545. ** only requires a region of pTask->file2. */
  78546. if( rc==SQLITE_OK ){
  78547. int mxSz = pIncr->mxSz;
  78548. #if SQLITE_MAX_WORKER_THREADS>0
  78549. if( pIncr->bUseThread ){
  78550. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  78551. if( rc==SQLITE_OK ){
  78552. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  78553. }
  78554. }else
  78555. #endif
  78556. /*if( !pIncr->bUseThread )*/{
  78557. if( pTask->file2.pFd==0 ){
  78558. assert( pTask->file2.iEof>0 );
  78559. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  78560. pTask->file2.iEof = 0;
  78561. }
  78562. if( rc==SQLITE_OK ){
  78563. pIncr->aFile[1].pFd = pTask->file2.pFd;
  78564. pIncr->iStartOff = pTask->file2.iEof;
  78565. pTask->file2.iEof += mxSz;
  78566. }
  78567. }
  78568. }
  78569. #if SQLITE_MAX_WORKER_THREADS>0
  78570. if( rc==SQLITE_OK && pIncr->bUseThread ){
  78571. /* Use the current thread to populate aFile[1], even though this
  78572. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  78573. ** then this function is already running in background thread
  78574. ** pIncr->pTask->thread.
  78575. **
  78576. ** If this is the INCRINIT_ROOT object, then it is running in the
  78577. ** main VDBE thread. But that is Ok, as that thread cannot return
  78578. ** control to the VDBE or proceed with anything useful until the
  78579. ** first results are ready from this merger object anyway.
  78580. */
  78581. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  78582. rc = vdbeIncrPopulate(pIncr);
  78583. }
  78584. #endif
  78585. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  78586. rc = vdbePmaReaderNext(pReadr);
  78587. }
  78588. return rc;
  78589. }
  78590. #if SQLITE_MAX_WORKER_THREADS>0
  78591. /*
  78592. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  78593. ** background threads.
  78594. */
  78595. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  78596. PmaReader *pReader = (PmaReader*)pCtx;
  78597. void *pRet = SQLITE_INT_TO_PTR(
  78598. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  78599. );
  78600. pReader->pIncr->pTask->bDone = 1;
  78601. return pRet;
  78602. }
  78603. #endif
  78604. /*
  78605. ** If the PmaReader passed as the first argument is not an incremental-reader
  78606. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  78607. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  78608. ** this routine to initialize the incremental merge.
  78609. **
  78610. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  78611. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  78612. ** Or, if the IncrMerger is single threaded, the same function is called
  78613. ** using the current thread.
  78614. */
  78615. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  78616. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  78617. int rc = SQLITE_OK; /* Return code */
  78618. if( pIncr ){
  78619. #if SQLITE_MAX_WORKER_THREADS>0
  78620. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  78621. if( pIncr->bUseThread ){
  78622. void *pCtx = (void*)pReadr;
  78623. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  78624. }else
  78625. #endif
  78626. {
  78627. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  78628. }
  78629. }
  78630. return rc;
  78631. }
  78632. /*
  78633. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  78634. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  78635. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  78636. ** to NULL and return an SQLite error code.
  78637. **
  78638. ** When this function is called, *piOffset is set to the offset of the
  78639. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  78640. ** set to the offset immediately following the last byte of the last
  78641. ** PMA before returning. If an error does occur, then the final value of
  78642. ** *piOffset is undefined.
  78643. */
  78644. static int vdbeMergeEngineLevel0(
  78645. SortSubtask *pTask, /* Sorter task to read from */
  78646. int nPMA, /* Number of PMAs to read */
  78647. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  78648. MergeEngine **ppOut /* OUT: New merge-engine */
  78649. ){
  78650. MergeEngine *pNew; /* Merge engine to return */
  78651. i64 iOff = *piOffset;
  78652. int i;
  78653. int rc = SQLITE_OK;
  78654. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  78655. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  78656. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  78657. i64 nDummy = 0;
  78658. PmaReader *pReadr = &pNew->aReadr[i];
  78659. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  78660. iOff = pReadr->iEof;
  78661. }
  78662. if( rc!=SQLITE_OK ){
  78663. vdbeMergeEngineFree(pNew);
  78664. *ppOut = 0;
  78665. }
  78666. *piOffset = iOff;
  78667. return rc;
  78668. }
  78669. /*
  78670. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  78671. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  78672. **
  78673. ** i.e.
  78674. **
  78675. ** nPMA<=16 -> TreeDepth() == 0
  78676. ** nPMA<=256 -> TreeDepth() == 1
  78677. ** nPMA<=65536 -> TreeDepth() == 2
  78678. */
  78679. static int vdbeSorterTreeDepth(int nPMA){
  78680. int nDepth = 0;
  78681. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  78682. while( nDiv < (i64)nPMA ){
  78683. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  78684. nDepth++;
  78685. }
  78686. return nDepth;
  78687. }
  78688. /*
  78689. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  78690. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  78691. ** tree, counting from zero. This function adds pLeaf to the tree.
  78692. **
  78693. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  78694. ** code is returned and pLeaf is freed.
  78695. */
  78696. static int vdbeSorterAddToTree(
  78697. SortSubtask *pTask, /* Task context */
  78698. int nDepth, /* Depth of tree according to TreeDepth() */
  78699. int iSeq, /* Sequence number of leaf within tree */
  78700. MergeEngine *pRoot, /* Root of tree */
  78701. MergeEngine *pLeaf /* Leaf to add to tree */
  78702. ){
  78703. int rc = SQLITE_OK;
  78704. int nDiv = 1;
  78705. int i;
  78706. MergeEngine *p = pRoot;
  78707. IncrMerger *pIncr;
  78708. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  78709. for(i=1; i<nDepth; i++){
  78710. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  78711. }
  78712. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  78713. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  78714. PmaReader *pReadr = &p->aReadr[iIter];
  78715. if( pReadr->pIncr==0 ){
  78716. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  78717. if( pNew==0 ){
  78718. rc = SQLITE_NOMEM_BKPT;
  78719. }else{
  78720. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  78721. }
  78722. }
  78723. if( rc==SQLITE_OK ){
  78724. p = pReadr->pIncr->pMerger;
  78725. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  78726. }
  78727. }
  78728. if( rc==SQLITE_OK ){
  78729. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  78730. }else{
  78731. vdbeIncrFree(pIncr);
  78732. }
  78733. return rc;
  78734. }
  78735. /*
  78736. ** This function is called as part of a SorterRewind() operation on a sorter
  78737. ** that has already written two or more level-0 PMAs to one or more temp
  78738. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  78739. ** can be used to incrementally merge all PMAs on disk.
  78740. **
  78741. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  78742. ** MergeEngine object at the root of the tree before returning. Or, if an
  78743. ** error occurs, an SQLite error code is returned and the final value
  78744. ** of *ppOut is undefined.
  78745. */
  78746. static int vdbeSorterMergeTreeBuild(
  78747. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  78748. MergeEngine **ppOut /* Write the MergeEngine here */
  78749. ){
  78750. MergeEngine *pMain = 0;
  78751. int rc = SQLITE_OK;
  78752. int iTask;
  78753. #if SQLITE_MAX_WORKER_THREADS>0
  78754. /* If the sorter uses more than one task, then create the top-level
  78755. ** MergeEngine here. This MergeEngine will read data from exactly
  78756. ** one PmaReader per sub-task. */
  78757. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  78758. if( pSorter->nTask>1 ){
  78759. pMain = vdbeMergeEngineNew(pSorter->nTask);
  78760. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  78761. }
  78762. #endif
  78763. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  78764. SortSubtask *pTask = &pSorter->aTask[iTask];
  78765. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  78766. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  78767. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  78768. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  78769. i64 iReadOff = 0;
  78770. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  78771. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  78772. }else{
  78773. int i;
  78774. int iSeq = 0;
  78775. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  78776. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  78777. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  78778. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  78779. int nReader; /* Number of level-0 PMAs to merge */
  78780. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  78781. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  78782. if( rc==SQLITE_OK ){
  78783. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  78784. }
  78785. }
  78786. }
  78787. if( rc==SQLITE_OK ){
  78788. #if SQLITE_MAX_WORKER_THREADS>0
  78789. if( pMain!=0 ){
  78790. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  78791. }else
  78792. #endif
  78793. {
  78794. assert( pMain==0 );
  78795. pMain = pRoot;
  78796. }
  78797. }else{
  78798. vdbeMergeEngineFree(pRoot);
  78799. }
  78800. }
  78801. }
  78802. if( rc!=SQLITE_OK ){
  78803. vdbeMergeEngineFree(pMain);
  78804. pMain = 0;
  78805. }
  78806. *ppOut = pMain;
  78807. return rc;
  78808. }
  78809. /*
  78810. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  78811. ** on a sorter that has written two or more PMAs to temporary files. It sets
  78812. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  78813. ** (for multi-threaded sorters) so that it can be used to iterate through
  78814. ** all records stored in the sorter.
  78815. **
  78816. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  78817. */
  78818. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  78819. int rc; /* Return code */
  78820. SortSubtask *pTask0 = &pSorter->aTask[0];
  78821. MergeEngine *pMain = 0;
  78822. #if SQLITE_MAX_WORKER_THREADS
  78823. sqlite3 *db = pTask0->pSorter->db;
  78824. int i;
  78825. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  78826. for(i=0; i<pSorter->nTask; i++){
  78827. pSorter->aTask[i].xCompare = xCompare;
  78828. }
  78829. #endif
  78830. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  78831. if( rc==SQLITE_OK ){
  78832. #if SQLITE_MAX_WORKER_THREADS
  78833. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  78834. if( pSorter->bUseThreads ){
  78835. int iTask;
  78836. PmaReader *pReadr = 0;
  78837. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  78838. rc = vdbeSortAllocUnpacked(pLast);
  78839. if( rc==SQLITE_OK ){
  78840. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  78841. pSorter->pReader = pReadr;
  78842. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  78843. }
  78844. if( rc==SQLITE_OK ){
  78845. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  78846. if( rc==SQLITE_OK ){
  78847. vdbeIncrMergerSetThreads(pReadr->pIncr);
  78848. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  78849. IncrMerger *pIncr;
  78850. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  78851. vdbeIncrMergerSetThreads(pIncr);
  78852. assert( pIncr->pTask!=pLast );
  78853. }
  78854. }
  78855. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  78856. /* Check that:
  78857. **
  78858. ** a) The incremental merge object is configured to use the
  78859. ** right task, and
  78860. ** b) If it is using task (nTask-1), it is configured to run
  78861. ** in single-threaded mode. This is important, as the
  78862. ** root merge (INCRINIT_ROOT) will be using the same task
  78863. ** object.
  78864. */
  78865. PmaReader *p = &pMain->aReadr[iTask];
  78866. assert( p->pIncr==0 || (
  78867. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  78868. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  78869. ));
  78870. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  78871. }
  78872. }
  78873. pMain = 0;
  78874. }
  78875. if( rc==SQLITE_OK ){
  78876. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  78877. }
  78878. }else
  78879. #endif
  78880. {
  78881. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  78882. pSorter->pMerger = pMain;
  78883. pMain = 0;
  78884. }
  78885. }
  78886. if( rc!=SQLITE_OK ){
  78887. vdbeMergeEngineFree(pMain);
  78888. }
  78889. return rc;
  78890. }
  78891. /*
  78892. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  78893. ** this function is called to prepare for iterating through the records
  78894. ** in sorted order.
  78895. */
  78896. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  78897. VdbeSorter *pSorter;
  78898. int rc = SQLITE_OK; /* Return code */
  78899. assert( pCsr->eCurType==CURTYPE_SORTER );
  78900. pSorter = pCsr->uc.pSorter;
  78901. assert( pSorter );
  78902. /* If no data has been written to disk, then do not do so now. Instead,
  78903. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  78904. ** from the in-memory list. */
  78905. if( pSorter->bUsePMA==0 ){
  78906. if( pSorter->list.pList ){
  78907. *pbEof = 0;
  78908. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  78909. }else{
  78910. *pbEof = 1;
  78911. }
  78912. return rc;
  78913. }
  78914. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  78915. ** function flushes the contents of memory to disk, it immediately always
  78916. ** creates a new list consisting of a single key immediately afterwards.
  78917. ** So the list is never empty at this point. */
  78918. assert( pSorter->list.pList );
  78919. rc = vdbeSorterFlushPMA(pSorter);
  78920. /* Join all threads */
  78921. rc = vdbeSorterJoinAll(pSorter, rc);
  78922. vdbeSorterRewindDebug("rewind");
  78923. /* Assuming no errors have occurred, set up a merger structure to
  78924. ** incrementally read and merge all remaining PMAs. */
  78925. assert( pSorter->pReader==0 );
  78926. if( rc==SQLITE_OK ){
  78927. rc = vdbeSorterSetupMerge(pSorter);
  78928. *pbEof = 0;
  78929. }
  78930. vdbeSorterRewindDebug("rewinddone");
  78931. return rc;
  78932. }
  78933. /*
  78934. ** Advance to the next element in the sorter.
  78935. */
  78936. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  78937. VdbeSorter *pSorter;
  78938. int rc; /* Return code */
  78939. assert( pCsr->eCurType==CURTYPE_SORTER );
  78940. pSorter = pCsr->uc.pSorter;
  78941. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  78942. if( pSorter->bUsePMA ){
  78943. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  78944. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  78945. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  78946. #if SQLITE_MAX_WORKER_THREADS>0
  78947. if( pSorter->bUseThreads ){
  78948. rc = vdbePmaReaderNext(pSorter->pReader);
  78949. *pbEof = (pSorter->pReader->pFd==0);
  78950. }else
  78951. #endif
  78952. /*if( !pSorter->bUseThreads )*/ {
  78953. assert( pSorter->pMerger!=0 );
  78954. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  78955. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  78956. }
  78957. }else{
  78958. SorterRecord *pFree = pSorter->list.pList;
  78959. pSorter->list.pList = pFree->u.pNext;
  78960. pFree->u.pNext = 0;
  78961. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  78962. *pbEof = !pSorter->list.pList;
  78963. rc = SQLITE_OK;
  78964. }
  78965. return rc;
  78966. }
  78967. /*
  78968. ** Return a pointer to a buffer owned by the sorter that contains the
  78969. ** current key.
  78970. */
  78971. static void *vdbeSorterRowkey(
  78972. const VdbeSorter *pSorter, /* Sorter object */
  78973. int *pnKey /* OUT: Size of current key in bytes */
  78974. ){
  78975. void *pKey;
  78976. if( pSorter->bUsePMA ){
  78977. PmaReader *pReader;
  78978. #if SQLITE_MAX_WORKER_THREADS>0
  78979. if( pSorter->bUseThreads ){
  78980. pReader = pSorter->pReader;
  78981. }else
  78982. #endif
  78983. /*if( !pSorter->bUseThreads )*/{
  78984. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  78985. }
  78986. *pnKey = pReader->nKey;
  78987. pKey = pReader->aKey;
  78988. }else{
  78989. *pnKey = pSorter->list.pList->nVal;
  78990. pKey = SRVAL(pSorter->list.pList);
  78991. }
  78992. return pKey;
  78993. }
  78994. /*
  78995. ** Copy the current sorter key into the memory cell pOut.
  78996. */
  78997. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  78998. VdbeSorter *pSorter;
  78999. void *pKey; int nKey; /* Sorter key to copy into pOut */
  79000. assert( pCsr->eCurType==CURTYPE_SORTER );
  79001. pSorter = pCsr->uc.pSorter;
  79002. pKey = vdbeSorterRowkey(pSorter, &nKey);
  79003. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  79004. return SQLITE_NOMEM_BKPT;
  79005. }
  79006. pOut->n = nKey;
  79007. MemSetTypeFlag(pOut, MEM_Blob);
  79008. memcpy(pOut->z, pKey, nKey);
  79009. return SQLITE_OK;
  79010. }
  79011. /*
  79012. ** Compare the key in memory cell pVal with the key that the sorter cursor
  79013. ** passed as the first argument currently points to. For the purposes of
  79014. ** the comparison, ignore the rowid field at the end of each record.
  79015. **
  79016. ** If the sorter cursor key contains any NULL values, consider it to be
  79017. ** less than pVal. Even if pVal also contains NULL values.
  79018. **
  79019. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  79020. ** Otherwise, set *pRes to a negative, zero or positive value if the
  79021. ** key in pVal is smaller than, equal to or larger than the current sorter
  79022. ** key.
  79023. **
  79024. ** This routine forms the core of the OP_SorterCompare opcode, which in
  79025. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  79026. */
  79027. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  79028. const VdbeCursor *pCsr, /* Sorter cursor */
  79029. Mem *pVal, /* Value to compare to current sorter key */
  79030. int nKeyCol, /* Compare this many columns */
  79031. int *pRes /* OUT: Result of comparison */
  79032. ){
  79033. VdbeSorter *pSorter;
  79034. UnpackedRecord *r2;
  79035. KeyInfo *pKeyInfo;
  79036. int i;
  79037. void *pKey; int nKey; /* Sorter key to compare pVal with */
  79038. assert( pCsr->eCurType==CURTYPE_SORTER );
  79039. pSorter = pCsr->uc.pSorter;
  79040. r2 = pSorter->pUnpacked;
  79041. pKeyInfo = pCsr->pKeyInfo;
  79042. if( r2==0 ){
  79043. char *p;
  79044. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  79045. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  79046. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  79047. r2->nField = nKeyCol;
  79048. }
  79049. assert( r2->nField==nKeyCol );
  79050. pKey = vdbeSorterRowkey(pSorter, &nKey);
  79051. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  79052. for(i=0; i<nKeyCol; i++){
  79053. if( r2->aMem[i].flags & MEM_Null ){
  79054. *pRes = -1;
  79055. return SQLITE_OK;
  79056. }
  79057. }
  79058. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  79059. return SQLITE_OK;
  79060. }
  79061. /************** End of vdbesort.c ********************************************/
  79062. /************** Begin file memjournal.c **************************************/
  79063. /*
  79064. ** 2008 October 7
  79065. **
  79066. ** The author disclaims copyright to this source code. In place of
  79067. ** a legal notice, here is a blessing:
  79068. **
  79069. ** May you do good and not evil.
  79070. ** May you find forgiveness for yourself and forgive others.
  79071. ** May you share freely, never taking more than you give.
  79072. **
  79073. *************************************************************************
  79074. **
  79075. ** This file contains code use to implement an in-memory rollback journal.
  79076. ** The in-memory rollback journal is used to journal transactions for
  79077. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  79078. */
  79079. /* #include "sqliteInt.h" */
  79080. /* Forward references to internal structures */
  79081. typedef struct MemJournal MemJournal;
  79082. typedef struct FilePoint FilePoint;
  79083. typedef struct FileChunk FileChunk;
  79084. /*
  79085. ** The rollback journal is composed of a linked list of these structures.
  79086. **
  79087. ** The zChunk array is always at least 8 bytes in size - usually much more.
  79088. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  79089. */
  79090. struct FileChunk {
  79091. FileChunk *pNext; /* Next chunk in the journal */
  79092. u8 zChunk[8]; /* Content of this chunk */
  79093. };
  79094. /*
  79095. ** By default, allocate this many bytes of memory for each FileChunk object.
  79096. */
  79097. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  79098. /*
  79099. ** For chunk size nChunkSize, return the number of bytes that should
  79100. ** be allocated for each FileChunk structure.
  79101. */
  79102. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  79103. /*
  79104. ** An instance of this object serves as a cursor into the rollback journal.
  79105. ** The cursor can be either for reading or writing.
  79106. */
  79107. struct FilePoint {
  79108. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  79109. FileChunk *pChunk; /* Specific chunk into which cursor points */
  79110. };
  79111. /*
  79112. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  79113. ** is an instance of this class.
  79114. */
  79115. struct MemJournal {
  79116. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  79117. int nChunkSize; /* In-memory chunk-size */
  79118. int nSpill; /* Bytes of data before flushing */
  79119. int nSize; /* Bytes of data currently in memory */
  79120. FileChunk *pFirst; /* Head of in-memory chunk-list */
  79121. FilePoint endpoint; /* Pointer to the end of the file */
  79122. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  79123. int flags; /* xOpen flags */
  79124. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  79125. const char *zJournal; /* Name of the journal file */
  79126. };
  79127. /*
  79128. ** Read data from the in-memory journal file. This is the implementation
  79129. ** of the sqlite3_vfs.xRead method.
  79130. */
  79131. static int memjrnlRead(
  79132. sqlite3_file *pJfd, /* The journal file from which to read */
  79133. void *zBuf, /* Put the results here */
  79134. int iAmt, /* Number of bytes to read */
  79135. sqlite_int64 iOfst /* Begin reading at this offset */
  79136. ){
  79137. MemJournal *p = (MemJournal *)pJfd;
  79138. u8 *zOut = zBuf;
  79139. int nRead = iAmt;
  79140. int iChunkOffset;
  79141. FileChunk *pChunk;
  79142. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  79143. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  79144. return SQLITE_IOERR_SHORT_READ;
  79145. }
  79146. #endif
  79147. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  79148. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  79149. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  79150. sqlite3_int64 iOff = 0;
  79151. for(pChunk=p->pFirst;
  79152. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  79153. pChunk=pChunk->pNext
  79154. ){
  79155. iOff += p->nChunkSize;
  79156. }
  79157. }else{
  79158. pChunk = p->readpoint.pChunk;
  79159. assert( pChunk!=0 );
  79160. }
  79161. iChunkOffset = (int)(iOfst%p->nChunkSize);
  79162. do {
  79163. int iSpace = p->nChunkSize - iChunkOffset;
  79164. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  79165. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  79166. zOut += nCopy;
  79167. nRead -= iSpace;
  79168. iChunkOffset = 0;
  79169. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  79170. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  79171. p->readpoint.pChunk = pChunk;
  79172. return SQLITE_OK;
  79173. }
  79174. /*
  79175. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  79176. */
  79177. static void memjrnlFreeChunks(MemJournal *p){
  79178. FileChunk *pIter;
  79179. FileChunk *pNext;
  79180. for(pIter=p->pFirst; pIter; pIter=pNext){
  79181. pNext = pIter->pNext;
  79182. sqlite3_free(pIter);
  79183. }
  79184. p->pFirst = 0;
  79185. }
  79186. /*
  79187. ** Flush the contents of memory to a real file on disk.
  79188. */
  79189. static int memjrnlCreateFile(MemJournal *p){
  79190. int rc;
  79191. sqlite3_file *pReal = (sqlite3_file*)p;
  79192. MemJournal copy = *p;
  79193. memset(p, 0, sizeof(MemJournal));
  79194. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  79195. if( rc==SQLITE_OK ){
  79196. int nChunk = copy.nChunkSize;
  79197. i64 iOff = 0;
  79198. FileChunk *pIter;
  79199. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  79200. if( iOff + nChunk > copy.endpoint.iOffset ){
  79201. nChunk = copy.endpoint.iOffset - iOff;
  79202. }
  79203. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  79204. if( rc ) break;
  79205. iOff += nChunk;
  79206. }
  79207. if( rc==SQLITE_OK ){
  79208. /* No error has occurred. Free the in-memory buffers. */
  79209. memjrnlFreeChunks(&copy);
  79210. }
  79211. }
  79212. if( rc!=SQLITE_OK ){
  79213. /* If an error occurred while creating or writing to the file, restore
  79214. ** the original before returning. This way, SQLite uses the in-memory
  79215. ** journal data to roll back changes made to the internal page-cache
  79216. ** before this function was called. */
  79217. sqlite3OsClose(pReal);
  79218. *p = copy;
  79219. }
  79220. return rc;
  79221. }
  79222. /*
  79223. ** Write data to the file.
  79224. */
  79225. static int memjrnlWrite(
  79226. sqlite3_file *pJfd, /* The journal file into which to write */
  79227. const void *zBuf, /* Take data to be written from here */
  79228. int iAmt, /* Number of bytes to write */
  79229. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  79230. ){
  79231. MemJournal *p = (MemJournal *)pJfd;
  79232. int nWrite = iAmt;
  79233. u8 *zWrite = (u8 *)zBuf;
  79234. /* If the file should be created now, create it and write the new data
  79235. ** into the file on disk. */
  79236. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  79237. int rc = memjrnlCreateFile(p);
  79238. if( rc==SQLITE_OK ){
  79239. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  79240. }
  79241. return rc;
  79242. }
  79243. /* If the contents of this write should be stored in memory */
  79244. else{
  79245. /* An in-memory journal file should only ever be appended to. Random
  79246. ** access writes are not required. The only exception to this is when
  79247. ** the in-memory journal is being used by a connection using the
  79248. ** atomic-write optimization. In this case the first 28 bytes of the
  79249. ** journal file may be written as part of committing the transaction. */
  79250. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  79251. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  79252. if( iOfst==0 && p->pFirst ){
  79253. assert( p->nChunkSize>iAmt );
  79254. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  79255. }else
  79256. #else
  79257. assert( iOfst>0 || p->pFirst==0 );
  79258. #endif
  79259. {
  79260. while( nWrite>0 ){
  79261. FileChunk *pChunk = p->endpoint.pChunk;
  79262. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  79263. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  79264. if( iChunkOffset==0 ){
  79265. /* New chunk is required to extend the file. */
  79266. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  79267. if( !pNew ){
  79268. return SQLITE_IOERR_NOMEM_BKPT;
  79269. }
  79270. pNew->pNext = 0;
  79271. if( pChunk ){
  79272. assert( p->pFirst );
  79273. pChunk->pNext = pNew;
  79274. }else{
  79275. assert( !p->pFirst );
  79276. p->pFirst = pNew;
  79277. }
  79278. p->endpoint.pChunk = pNew;
  79279. }
  79280. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  79281. zWrite += iSpace;
  79282. nWrite -= iSpace;
  79283. p->endpoint.iOffset += iSpace;
  79284. }
  79285. p->nSize = iAmt + iOfst;
  79286. }
  79287. }
  79288. return SQLITE_OK;
  79289. }
  79290. /*
  79291. ** Truncate the file.
  79292. **
  79293. ** If the journal file is already on disk, truncate it there. Or, if it
  79294. ** is still in main memory but is being truncated to zero bytes in size,
  79295. ** ignore
  79296. */
  79297. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  79298. MemJournal *p = (MemJournal *)pJfd;
  79299. if( ALWAYS(size==0) ){
  79300. memjrnlFreeChunks(p);
  79301. p->nSize = 0;
  79302. p->endpoint.pChunk = 0;
  79303. p->endpoint.iOffset = 0;
  79304. p->readpoint.pChunk = 0;
  79305. p->readpoint.iOffset = 0;
  79306. }
  79307. return SQLITE_OK;
  79308. }
  79309. /*
  79310. ** Close the file.
  79311. */
  79312. static int memjrnlClose(sqlite3_file *pJfd){
  79313. MemJournal *p = (MemJournal *)pJfd;
  79314. memjrnlFreeChunks(p);
  79315. return SQLITE_OK;
  79316. }
  79317. /*
  79318. ** Sync the file.
  79319. **
  79320. ** If the real file has been created, call its xSync method. Otherwise,
  79321. ** syncing an in-memory journal is a no-op.
  79322. */
  79323. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  79324. UNUSED_PARAMETER2(pJfd, flags);
  79325. return SQLITE_OK;
  79326. }
  79327. /*
  79328. ** Query the size of the file in bytes.
  79329. */
  79330. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  79331. MemJournal *p = (MemJournal *)pJfd;
  79332. *pSize = (sqlite_int64) p->endpoint.iOffset;
  79333. return SQLITE_OK;
  79334. }
  79335. /*
  79336. ** Table of methods for MemJournal sqlite3_file object.
  79337. */
  79338. static const struct sqlite3_io_methods MemJournalMethods = {
  79339. 1, /* iVersion */
  79340. memjrnlClose, /* xClose */
  79341. memjrnlRead, /* xRead */
  79342. memjrnlWrite, /* xWrite */
  79343. memjrnlTruncate, /* xTruncate */
  79344. memjrnlSync, /* xSync */
  79345. memjrnlFileSize, /* xFileSize */
  79346. 0, /* xLock */
  79347. 0, /* xUnlock */
  79348. 0, /* xCheckReservedLock */
  79349. 0, /* xFileControl */
  79350. 0, /* xSectorSize */
  79351. 0, /* xDeviceCharacteristics */
  79352. 0, /* xShmMap */
  79353. 0, /* xShmLock */
  79354. 0, /* xShmBarrier */
  79355. 0, /* xShmUnmap */
  79356. 0, /* xFetch */
  79357. 0 /* xUnfetch */
  79358. };
  79359. /*
  79360. ** Open a journal file.
  79361. **
  79362. ** The behaviour of the journal file depends on the value of parameter
  79363. ** nSpill. If nSpill is 0, then the journal file is always create and
  79364. ** accessed using the underlying VFS. If nSpill is less than zero, then
  79365. ** all content is always stored in main-memory. Finally, if nSpill is a
  79366. ** positive value, then the journal file is initially created in-memory
  79367. ** but may be flushed to disk later on. In this case the journal file is
  79368. ** flushed to disk either when it grows larger than nSpill bytes in size,
  79369. ** or when sqlite3JournalCreate() is called.
  79370. */
  79371. SQLITE_PRIVATE int sqlite3JournalOpen(
  79372. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  79373. const char *zName, /* Name of the journal file */
  79374. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  79375. int flags, /* Opening flags */
  79376. int nSpill /* Bytes buffered before opening the file */
  79377. ){
  79378. MemJournal *p = (MemJournal*)pJfd;
  79379. /* Zero the file-handle object. If nSpill was passed zero, initialize
  79380. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  79381. ** case none of the code in this module is executed as a result of calls
  79382. ** made on the journal file-handle. */
  79383. memset(p, 0, sizeof(MemJournal));
  79384. if( nSpill==0 ){
  79385. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  79386. }
  79387. if( nSpill>0 ){
  79388. p->nChunkSize = nSpill;
  79389. }else{
  79390. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  79391. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  79392. }
  79393. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  79394. p->nSpill = nSpill;
  79395. p->flags = flags;
  79396. p->zJournal = zName;
  79397. p->pVfs = pVfs;
  79398. return SQLITE_OK;
  79399. }
  79400. /*
  79401. ** Open an in-memory journal file.
  79402. */
  79403. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  79404. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  79405. }
  79406. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  79407. /*
  79408. ** If the argument p points to a MemJournal structure that is not an
  79409. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  79410. ** nSpill parameter), and the underlying file has not yet been created,
  79411. ** create it now.
  79412. */
  79413. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  79414. int rc = SQLITE_OK;
  79415. if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
  79416. rc = memjrnlCreateFile((MemJournal*)p);
  79417. }
  79418. return rc;
  79419. }
  79420. #endif
  79421. /*
  79422. ** The file-handle passed as the only argument is open on a journal file.
  79423. ** Return true if this "journal file" is currently stored in heap memory,
  79424. ** or false otherwise.
  79425. */
  79426. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  79427. return p->pMethods==&MemJournalMethods;
  79428. }
  79429. /*
  79430. ** Return the number of bytes required to store a JournalFile that uses vfs
  79431. ** pVfs to create the underlying on-disk files.
  79432. */
  79433. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  79434. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  79435. }
  79436. /************** End of memjournal.c ******************************************/
  79437. /************** Begin file walker.c ******************************************/
  79438. /*
  79439. ** 2008 August 16
  79440. **
  79441. ** The author disclaims copyright to this source code. In place of
  79442. ** a legal notice, here is a blessing:
  79443. **
  79444. ** May you do good and not evil.
  79445. ** May you find forgiveness for yourself and forgive others.
  79446. ** May you share freely, never taking more than you give.
  79447. **
  79448. *************************************************************************
  79449. ** This file contains routines used for walking the parser tree for
  79450. ** an SQL statement.
  79451. */
  79452. /* #include "sqliteInt.h" */
  79453. /* #include <stdlib.h> */
  79454. /* #include <string.h> */
  79455. /*
  79456. ** Walk an expression tree. Invoke the callback once for each node
  79457. ** of the expression, while descending. (In other words, the callback
  79458. ** is invoked before visiting children.)
  79459. **
  79460. ** The return value from the callback should be one of the WRC_*
  79461. ** constants to specify how to proceed with the walk.
  79462. **
  79463. ** WRC_Continue Continue descending down the tree.
  79464. **
  79465. ** WRC_Prune Do not descend into child nodes. But allow
  79466. ** the walk to continue with sibling nodes.
  79467. **
  79468. ** WRC_Abort Do no more callbacks. Unwind the stack and
  79469. ** return the top-level walk call.
  79470. **
  79471. ** The return value from this routine is WRC_Abort to abandon the tree walk
  79472. ** and WRC_Continue to continue.
  79473. */
  79474. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  79475. int rc;
  79476. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  79477. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  79478. rc = pWalker->xExprCallback(pWalker, pExpr);
  79479. if( rc==WRC_Continue
  79480. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  79481. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  79482. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  79483. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  79484. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  79485. }else{
  79486. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  79487. }
  79488. }
  79489. return rc & WRC_Abort;
  79490. }
  79491. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  79492. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  79493. }
  79494. /*
  79495. ** Call sqlite3WalkExpr() for every expression in list p or until
  79496. ** an abort request is seen.
  79497. */
  79498. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  79499. int i;
  79500. struct ExprList_item *pItem;
  79501. if( p ){
  79502. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  79503. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  79504. }
  79505. }
  79506. return WRC_Continue;
  79507. }
  79508. /*
  79509. ** Walk all expressions associated with SELECT statement p. Do
  79510. ** not invoke the SELECT callback on p, but do (of course) invoke
  79511. ** any expr callbacks and SELECT callbacks that come from subqueries.
  79512. ** Return WRC_Abort or WRC_Continue.
  79513. */
  79514. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  79515. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  79516. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  79517. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  79518. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  79519. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  79520. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  79521. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  79522. return WRC_Continue;
  79523. }
  79524. /*
  79525. ** Walk the parse trees associated with all subqueries in the
  79526. ** FROM clause of SELECT statement p. Do not invoke the select
  79527. ** callback on p, but do invoke it on each FROM clause subquery
  79528. ** and on any subqueries further down in the tree. Return
  79529. ** WRC_Abort or WRC_Continue;
  79530. */
  79531. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  79532. SrcList *pSrc;
  79533. int i;
  79534. struct SrcList_item *pItem;
  79535. pSrc = p->pSrc;
  79536. if( ALWAYS(pSrc) ){
  79537. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  79538. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  79539. return WRC_Abort;
  79540. }
  79541. if( pItem->fg.isTabFunc
  79542. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  79543. ){
  79544. return WRC_Abort;
  79545. }
  79546. }
  79547. }
  79548. return WRC_Continue;
  79549. }
  79550. /*
  79551. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  79552. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  79553. ** on the compound select chain, p->pPrior.
  79554. **
  79555. ** If it is not NULL, the xSelectCallback() callback is invoked before
  79556. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  79557. ** method, if it is not NULL, is invoked following the walk of the
  79558. ** expressions and FROM clause.
  79559. **
  79560. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  79561. ** there is an abort request.
  79562. **
  79563. ** If the Walker does not have an xSelectCallback() then this routine
  79564. ** is a no-op returning WRC_Continue.
  79565. */
  79566. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  79567. int rc;
  79568. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  79569. return WRC_Continue;
  79570. }
  79571. rc = WRC_Continue;
  79572. pWalker->walkerDepth++;
  79573. while( p ){
  79574. if( pWalker->xSelectCallback ){
  79575. rc = pWalker->xSelectCallback(pWalker, p);
  79576. if( rc ) break;
  79577. }
  79578. if( sqlite3WalkSelectExpr(pWalker, p)
  79579. || sqlite3WalkSelectFrom(pWalker, p)
  79580. ){
  79581. pWalker->walkerDepth--;
  79582. return WRC_Abort;
  79583. }
  79584. if( pWalker->xSelectCallback2 ){
  79585. pWalker->xSelectCallback2(pWalker, p);
  79586. }
  79587. p = p->pPrior;
  79588. }
  79589. pWalker->walkerDepth--;
  79590. return rc & WRC_Abort;
  79591. }
  79592. /************** End of walker.c **********************************************/
  79593. /************** Begin file resolve.c *****************************************/
  79594. /*
  79595. ** 2008 August 18
  79596. **
  79597. ** The author disclaims copyright to this source code. In place of
  79598. ** a legal notice, here is a blessing:
  79599. **
  79600. ** May you do good and not evil.
  79601. ** May you find forgiveness for yourself and forgive others.
  79602. ** May you share freely, never taking more than you give.
  79603. **
  79604. *************************************************************************
  79605. **
  79606. ** This file contains routines used for walking the parser tree and
  79607. ** resolve all identifiers by associating them with a particular
  79608. ** table and column.
  79609. */
  79610. /* #include "sqliteInt.h" */
  79611. /* #include <stdlib.h> */
  79612. /* #include <string.h> */
  79613. /*
  79614. ** Walk the expression tree pExpr and increase the aggregate function
  79615. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  79616. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  79617. ** outer query into an inner subquery.
  79618. **
  79619. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  79620. ** is a helper function - a callback for the tree walker.
  79621. */
  79622. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  79623. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  79624. return WRC_Continue;
  79625. }
  79626. static void incrAggFunctionDepth(Expr *pExpr, int N){
  79627. if( N>0 ){
  79628. Walker w;
  79629. memset(&w, 0, sizeof(w));
  79630. w.xExprCallback = incrAggDepth;
  79631. w.u.n = N;
  79632. sqlite3WalkExpr(&w, pExpr);
  79633. }
  79634. }
  79635. /*
  79636. ** Turn the pExpr expression into an alias for the iCol-th column of the
  79637. ** result set in pEList.
  79638. **
  79639. ** If the reference is followed by a COLLATE operator, then make sure
  79640. ** the COLLATE operator is preserved. For example:
  79641. **
  79642. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  79643. **
  79644. ** Should be transformed into:
  79645. **
  79646. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  79647. **
  79648. ** The nSubquery parameter specifies how many levels of subquery the
  79649. ** alias is removed from the original expression. The usual value is
  79650. ** zero but it might be more if the alias is contained within a subquery
  79651. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  79652. ** structures must be increased by the nSubquery amount.
  79653. */
  79654. static void resolveAlias(
  79655. Parse *pParse, /* Parsing context */
  79656. ExprList *pEList, /* A result set */
  79657. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  79658. Expr *pExpr, /* Transform this into an alias to the result set */
  79659. const char *zType, /* "GROUP" or "ORDER" or "" */
  79660. int nSubquery /* Number of subqueries that the label is moving */
  79661. ){
  79662. Expr *pOrig; /* The iCol-th column of the result set */
  79663. Expr *pDup; /* Copy of pOrig */
  79664. sqlite3 *db; /* The database connection */
  79665. assert( iCol>=0 && iCol<pEList->nExpr );
  79666. pOrig = pEList->a[iCol].pExpr;
  79667. assert( pOrig!=0 );
  79668. db = pParse->db;
  79669. pDup = sqlite3ExprDup(db, pOrig, 0);
  79670. if( pDup==0 ) return;
  79671. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  79672. if( pExpr->op==TK_COLLATE ){
  79673. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  79674. }
  79675. ExprSetProperty(pDup, EP_Alias);
  79676. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  79677. ** prevents ExprDelete() from deleting the Expr structure itself,
  79678. ** allowing it to be repopulated by the memcpy() on the following line.
  79679. ** The pExpr->u.zToken might point into memory that will be freed by the
  79680. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  79681. ** make a copy of the token before doing the sqlite3DbFree().
  79682. */
  79683. ExprSetProperty(pExpr, EP_Static);
  79684. sqlite3ExprDelete(db, pExpr);
  79685. memcpy(pExpr, pDup, sizeof(*pExpr));
  79686. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  79687. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  79688. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  79689. pExpr->flags |= EP_MemToken;
  79690. }
  79691. sqlite3DbFree(db, pDup);
  79692. }
  79693. /*
  79694. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  79695. **
  79696. ** Return FALSE if the USING clause is NULL or if it does not contain
  79697. ** zCol.
  79698. */
  79699. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  79700. if( pUsing ){
  79701. int k;
  79702. for(k=0; k<pUsing->nId; k++){
  79703. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  79704. }
  79705. }
  79706. return 0;
  79707. }
  79708. /*
  79709. ** Subqueries stores the original database, table and column names for their
  79710. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  79711. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  79712. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  79713. ** match anything.
  79714. */
  79715. SQLITE_PRIVATE int sqlite3MatchSpanName(
  79716. const char *zSpan,
  79717. const char *zCol,
  79718. const char *zTab,
  79719. const char *zDb
  79720. ){
  79721. int n;
  79722. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  79723. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  79724. return 0;
  79725. }
  79726. zSpan += n+1;
  79727. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  79728. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  79729. return 0;
  79730. }
  79731. zSpan += n+1;
  79732. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  79733. return 0;
  79734. }
  79735. return 1;
  79736. }
  79737. /*
  79738. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  79739. ** that name in the set of source tables in pSrcList and make the pExpr
  79740. ** expression node refer back to that source column. The following changes
  79741. ** are made to pExpr:
  79742. **
  79743. ** pExpr->iDb Set the index in db->aDb[] of the database X
  79744. ** (even if X is implied).
  79745. ** pExpr->iTable Set to the cursor number for the table obtained
  79746. ** from pSrcList.
  79747. ** pExpr->pTab Points to the Table structure of X.Y (even if
  79748. ** X and/or Y are implied.)
  79749. ** pExpr->iColumn Set to the column number within the table.
  79750. ** pExpr->op Set to TK_COLUMN.
  79751. ** pExpr->pLeft Any expression this points to is deleted
  79752. ** pExpr->pRight Any expression this points to is deleted.
  79753. **
  79754. ** The zDb variable is the name of the database (the "X"). This value may be
  79755. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  79756. ** can be used. The zTable variable is the name of the table (the "Y"). This
  79757. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  79758. ** means that the form of the name is Z and that columns from any table
  79759. ** can be used.
  79760. **
  79761. ** If the name cannot be resolved unambiguously, leave an error message
  79762. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  79763. */
  79764. static int lookupName(
  79765. Parse *pParse, /* The parsing context */
  79766. const char *zDb, /* Name of the database containing table, or NULL */
  79767. const char *zTab, /* Name of table containing column, or NULL */
  79768. const char *zCol, /* Name of the column. */
  79769. NameContext *pNC, /* The name context used to resolve the name */
  79770. Expr *pExpr /* Make this EXPR node point to the selected column */
  79771. ){
  79772. int i, j; /* Loop counters */
  79773. int cnt = 0; /* Number of matching column names */
  79774. int cntTab = 0; /* Number of matching table names */
  79775. int nSubquery = 0; /* How many levels of subquery */
  79776. sqlite3 *db = pParse->db; /* The database connection */
  79777. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  79778. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  79779. NameContext *pTopNC = pNC; /* First namecontext in the list */
  79780. Schema *pSchema = 0; /* Schema of the expression */
  79781. int isTrigger = 0; /* True if resolved to a trigger column */
  79782. Table *pTab = 0; /* Table hold the row */
  79783. Column *pCol; /* A column of pTab */
  79784. assert( pNC ); /* the name context cannot be NULL. */
  79785. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  79786. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  79787. /* Initialize the node to no-match */
  79788. pExpr->iTable = -1;
  79789. pExpr->pTab = 0;
  79790. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79791. /* Translate the schema name in zDb into a pointer to the corresponding
  79792. ** schema. If not found, pSchema will remain NULL and nothing will match
  79793. ** resulting in an appropriate error message toward the end of this routine
  79794. */
  79795. if( zDb ){
  79796. testcase( pNC->ncFlags & NC_PartIdx );
  79797. testcase( pNC->ncFlags & NC_IsCheck );
  79798. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  79799. /* Silently ignore database qualifiers inside CHECK constraints and
  79800. ** partial indices. Do not raise errors because that might break
  79801. ** legacy and because it does not hurt anything to just ignore the
  79802. ** database name. */
  79803. zDb = 0;
  79804. }else{
  79805. for(i=0; i<db->nDb; i++){
  79806. assert( db->aDb[i].zName );
  79807. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  79808. pSchema = db->aDb[i].pSchema;
  79809. break;
  79810. }
  79811. }
  79812. }
  79813. }
  79814. /* Start at the inner-most context and move outward until a match is found */
  79815. while( pNC && cnt==0 ){
  79816. ExprList *pEList;
  79817. SrcList *pSrcList = pNC->pSrcList;
  79818. if( pSrcList ){
  79819. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  79820. pTab = pItem->pTab;
  79821. assert( pTab!=0 && pTab->zName!=0 );
  79822. assert( pTab->nCol>0 );
  79823. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  79824. int hit = 0;
  79825. pEList = pItem->pSelect->pEList;
  79826. for(j=0; j<pEList->nExpr; j++){
  79827. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  79828. cnt++;
  79829. cntTab = 2;
  79830. pMatch = pItem;
  79831. pExpr->iColumn = j;
  79832. hit = 1;
  79833. }
  79834. }
  79835. if( hit || zTab==0 ) continue;
  79836. }
  79837. if( zDb && pTab->pSchema!=pSchema ){
  79838. continue;
  79839. }
  79840. if( zTab ){
  79841. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  79842. assert( zTabName!=0 );
  79843. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  79844. continue;
  79845. }
  79846. }
  79847. if( 0==(cntTab++) ){
  79848. pMatch = pItem;
  79849. }
  79850. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  79851. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  79852. /* If there has been exactly one prior match and this match
  79853. ** is for the right-hand table of a NATURAL JOIN or is in a
  79854. ** USING clause, then skip this match.
  79855. */
  79856. if( cnt==1 ){
  79857. if( pItem->fg.jointype & JT_NATURAL ) continue;
  79858. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  79859. }
  79860. cnt++;
  79861. pMatch = pItem;
  79862. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  79863. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  79864. break;
  79865. }
  79866. }
  79867. }
  79868. if( pMatch ){
  79869. pExpr->iTable = pMatch->iCursor;
  79870. pExpr->pTab = pMatch->pTab;
  79871. /* RIGHT JOIN not (yet) supported */
  79872. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  79873. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  79874. ExprSetProperty(pExpr, EP_CanBeNull);
  79875. }
  79876. pSchema = pExpr->pTab->pSchema;
  79877. }
  79878. } /* if( pSrcList ) */
  79879. #ifndef SQLITE_OMIT_TRIGGER
  79880. /* If we have not already resolved the name, then maybe
  79881. ** it is a new.* or old.* trigger argument reference
  79882. */
  79883. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  79884. int op = pParse->eTriggerOp;
  79885. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  79886. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  79887. pExpr->iTable = 1;
  79888. pTab = pParse->pTriggerTab;
  79889. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  79890. pExpr->iTable = 0;
  79891. pTab = pParse->pTriggerTab;
  79892. }else{
  79893. pTab = 0;
  79894. }
  79895. if( pTab ){
  79896. int iCol;
  79897. pSchema = pTab->pSchema;
  79898. cntTab++;
  79899. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  79900. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  79901. if( iCol==pTab->iPKey ){
  79902. iCol = -1;
  79903. }
  79904. break;
  79905. }
  79906. }
  79907. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  79908. /* IMP: R-51414-32910 */
  79909. iCol = -1;
  79910. }
  79911. if( iCol<pTab->nCol ){
  79912. cnt++;
  79913. if( iCol<0 ){
  79914. pExpr->affinity = SQLITE_AFF_INTEGER;
  79915. }else if( pExpr->iTable==0 ){
  79916. testcase( iCol==31 );
  79917. testcase( iCol==32 );
  79918. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  79919. }else{
  79920. testcase( iCol==31 );
  79921. testcase( iCol==32 );
  79922. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  79923. }
  79924. pExpr->iColumn = (i16)iCol;
  79925. pExpr->pTab = pTab;
  79926. isTrigger = 1;
  79927. }
  79928. }
  79929. }
  79930. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  79931. /*
  79932. ** Perhaps the name is a reference to the ROWID
  79933. */
  79934. if( cnt==0
  79935. && cntTab==1
  79936. && pMatch
  79937. && (pNC->ncFlags & NC_IdxExpr)==0
  79938. && sqlite3IsRowid(zCol)
  79939. && VisibleRowid(pMatch->pTab)
  79940. ){
  79941. cnt = 1;
  79942. pExpr->iColumn = -1;
  79943. pExpr->affinity = SQLITE_AFF_INTEGER;
  79944. }
  79945. /*
  79946. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  79947. ** might refer to an result-set alias. This happens, for example, when
  79948. ** we are resolving names in the WHERE clause of the following command:
  79949. **
  79950. ** SELECT a+b AS x FROM table WHERE x<10;
  79951. **
  79952. ** In cases like this, replace pExpr with a copy of the expression that
  79953. ** forms the result set entry ("a+b" in the example) and return immediately.
  79954. ** Note that the expression in the result set should have already been
  79955. ** resolved by the time the WHERE clause is resolved.
  79956. **
  79957. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  79958. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  79959. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  79960. ** is supported for backwards compatibility only. Hence, we issue a warning
  79961. ** on sqlite3_log() whenever the capability is used.
  79962. */
  79963. if( (pEList = pNC->pEList)!=0
  79964. && zTab==0
  79965. && cnt==0
  79966. ){
  79967. for(j=0; j<pEList->nExpr; j++){
  79968. char *zAs = pEList->a[j].zName;
  79969. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  79970. Expr *pOrig;
  79971. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  79972. assert( pExpr->x.pList==0 );
  79973. assert( pExpr->x.pSelect==0 );
  79974. pOrig = pEList->a[j].pExpr;
  79975. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  79976. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  79977. return WRC_Abort;
  79978. }
  79979. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  79980. cnt = 1;
  79981. pMatch = 0;
  79982. assert( zTab==0 && zDb==0 );
  79983. goto lookupname_end;
  79984. }
  79985. }
  79986. }
  79987. /* Advance to the next name context. The loop will exit when either
  79988. ** we have a match (cnt>0) or when we run out of name contexts.
  79989. */
  79990. if( cnt==0 ){
  79991. pNC = pNC->pNext;
  79992. nSubquery++;
  79993. }
  79994. }
  79995. /*
  79996. ** If X and Y are NULL (in other words if only the column name Z is
  79997. ** supplied) and the value of Z is enclosed in double-quotes, then
  79998. ** Z is a string literal if it doesn't match any column names. In that
  79999. ** case, we need to return right away and not make any changes to
  80000. ** pExpr.
  80001. **
  80002. ** Because no reference was made to outer contexts, the pNC->nRef
  80003. ** fields are not changed in any context.
  80004. */
  80005. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  80006. pExpr->op = TK_STRING;
  80007. pExpr->pTab = 0;
  80008. return WRC_Prune;
  80009. }
  80010. /*
  80011. ** cnt==0 means there was not match. cnt>1 means there were two or
  80012. ** more matches. Either way, we have an error.
  80013. */
  80014. if( cnt!=1 ){
  80015. const char *zErr;
  80016. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  80017. if( zDb ){
  80018. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  80019. }else if( zTab ){
  80020. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  80021. }else{
  80022. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  80023. }
  80024. pParse->checkSchema = 1;
  80025. pTopNC->nErr++;
  80026. }
  80027. /* If a column from a table in pSrcList is referenced, then record
  80028. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  80029. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  80030. ** column number is greater than the number of bits in the bitmask
  80031. ** then set the high-order bit of the bitmask.
  80032. */
  80033. if( pExpr->iColumn>=0 && pMatch!=0 ){
  80034. int n = pExpr->iColumn;
  80035. testcase( n==BMS-1 );
  80036. if( n>=BMS ){
  80037. n = BMS-1;
  80038. }
  80039. assert( pMatch->iCursor==pExpr->iTable );
  80040. pMatch->colUsed |= ((Bitmask)1)<<n;
  80041. }
  80042. /* Clean up and return
  80043. */
  80044. sqlite3ExprDelete(db, pExpr->pLeft);
  80045. pExpr->pLeft = 0;
  80046. sqlite3ExprDelete(db, pExpr->pRight);
  80047. pExpr->pRight = 0;
  80048. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  80049. lookupname_end:
  80050. if( cnt==1 ){
  80051. assert( pNC!=0 );
  80052. if( !ExprHasProperty(pExpr, EP_Alias) ){
  80053. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  80054. }
  80055. /* Increment the nRef value on all name contexts from TopNC up to
  80056. ** the point where the name matched. */
  80057. for(;;){
  80058. assert( pTopNC!=0 );
  80059. pTopNC->nRef++;
  80060. if( pTopNC==pNC ) break;
  80061. pTopNC = pTopNC->pNext;
  80062. }
  80063. return WRC_Prune;
  80064. } else {
  80065. return WRC_Abort;
  80066. }
  80067. }
  80068. /*
  80069. ** Allocate and return a pointer to an expression to load the column iCol
  80070. ** from datasource iSrc in SrcList pSrc.
  80071. */
  80072. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  80073. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  80074. if( p ){
  80075. struct SrcList_item *pItem = &pSrc->a[iSrc];
  80076. p->pTab = pItem->pTab;
  80077. p->iTable = pItem->iCursor;
  80078. if( p->pTab->iPKey==iCol ){
  80079. p->iColumn = -1;
  80080. }else{
  80081. p->iColumn = (ynVar)iCol;
  80082. testcase( iCol==BMS );
  80083. testcase( iCol==BMS-1 );
  80084. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  80085. }
  80086. ExprSetProperty(p, EP_Resolved);
  80087. }
  80088. return p;
  80089. }
  80090. /*
  80091. ** Report an error that an expression is not valid for some set of
  80092. ** pNC->ncFlags values determined by validMask.
  80093. */
  80094. static void notValid(
  80095. Parse *pParse, /* Leave error message here */
  80096. NameContext *pNC, /* The name context */
  80097. const char *zMsg, /* Type of error */
  80098. int validMask /* Set of contexts for which prohibited */
  80099. ){
  80100. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  80101. if( (pNC->ncFlags & validMask)!=0 ){
  80102. const char *zIn = "partial index WHERE clauses";
  80103. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  80104. #ifndef SQLITE_OMIT_CHECK
  80105. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  80106. #endif
  80107. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  80108. }
  80109. }
  80110. /*
  80111. ** Expression p should encode a floating point value between 1.0 and 0.0.
  80112. ** Return 1024 times this value. Or return -1 if p is not a floating point
  80113. ** value between 1.0 and 0.0.
  80114. */
  80115. static int exprProbability(Expr *p){
  80116. double r = -1.0;
  80117. if( p->op!=TK_FLOAT ) return -1;
  80118. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  80119. assert( r>=0.0 );
  80120. if( r>1.0 ) return -1;
  80121. return (int)(r*134217728.0);
  80122. }
  80123. /*
  80124. ** This routine is callback for sqlite3WalkExpr().
  80125. **
  80126. ** Resolve symbolic names into TK_COLUMN operators for the current
  80127. ** node in the expression tree. Return 0 to continue the search down
  80128. ** the tree or 2 to abort the tree walk.
  80129. **
  80130. ** This routine also does error checking and name resolution for
  80131. ** function names. The operator for aggregate functions is changed
  80132. ** to TK_AGG_FUNCTION.
  80133. */
  80134. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  80135. NameContext *pNC;
  80136. Parse *pParse;
  80137. pNC = pWalker->u.pNC;
  80138. assert( pNC!=0 );
  80139. pParse = pNC->pParse;
  80140. assert( pParse==pWalker->pParse );
  80141. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  80142. ExprSetProperty(pExpr, EP_Resolved);
  80143. #ifndef NDEBUG
  80144. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  80145. SrcList *pSrcList = pNC->pSrcList;
  80146. int i;
  80147. for(i=0; i<pNC->pSrcList->nSrc; i++){
  80148. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  80149. }
  80150. }
  80151. #endif
  80152. switch( pExpr->op ){
  80153. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  80154. /* The special operator TK_ROW means use the rowid for the first
  80155. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  80156. ** clause processing on UPDATE and DELETE statements.
  80157. */
  80158. case TK_ROW: {
  80159. SrcList *pSrcList = pNC->pSrcList;
  80160. struct SrcList_item *pItem;
  80161. assert( pSrcList && pSrcList->nSrc==1 );
  80162. pItem = pSrcList->a;
  80163. pExpr->op = TK_COLUMN;
  80164. pExpr->pTab = pItem->pTab;
  80165. pExpr->iTable = pItem->iCursor;
  80166. pExpr->iColumn = -1;
  80167. pExpr->affinity = SQLITE_AFF_INTEGER;
  80168. break;
  80169. }
  80170. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  80171. && !defined(SQLITE_OMIT_SUBQUERY) */
  80172. /* A lone identifier is the name of a column.
  80173. */
  80174. case TK_ID: {
  80175. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  80176. }
  80177. /* A table name and column name: ID.ID
  80178. ** Or a database, table and column: ID.ID.ID
  80179. */
  80180. case TK_DOT: {
  80181. const char *zColumn;
  80182. const char *zTable;
  80183. const char *zDb;
  80184. Expr *pRight;
  80185. /* if( pSrcList==0 ) break; */
  80186. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  80187. /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
  80188. pRight = pExpr->pRight;
  80189. if( pRight->op==TK_ID ){
  80190. zDb = 0;
  80191. zTable = pExpr->pLeft->u.zToken;
  80192. zColumn = pRight->u.zToken;
  80193. }else{
  80194. assert( pRight->op==TK_DOT );
  80195. zDb = pExpr->pLeft->u.zToken;
  80196. zTable = pRight->pLeft->u.zToken;
  80197. zColumn = pRight->pRight->u.zToken;
  80198. }
  80199. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  80200. }
  80201. /* Resolve function names
  80202. */
  80203. case TK_FUNCTION: {
  80204. ExprList *pList = pExpr->x.pList; /* The argument list */
  80205. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  80206. int no_such_func = 0; /* True if no such function exists */
  80207. int wrong_num_args = 0; /* True if wrong number of arguments */
  80208. int is_agg = 0; /* True if is an aggregate function */
  80209. int auth; /* Authorization to use the function */
  80210. int nId; /* Number of characters in function name */
  80211. const char *zId; /* The function name. */
  80212. FuncDef *pDef; /* Information about the function */
  80213. u8 enc = ENC(pParse->db); /* The database encoding */
  80214. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  80215. notValid(pParse, pNC, "functions", NC_PartIdx);
  80216. zId = pExpr->u.zToken;
  80217. nId = sqlite3Strlen30(zId);
  80218. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  80219. if( pDef==0 ){
  80220. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  80221. if( pDef==0 ){
  80222. no_such_func = 1;
  80223. }else{
  80224. wrong_num_args = 1;
  80225. }
  80226. }else{
  80227. is_agg = pDef->xFinalize!=0;
  80228. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  80229. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  80230. if( n==2 ){
  80231. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  80232. if( pExpr->iTable<0 ){
  80233. sqlite3ErrorMsg(pParse,
  80234. "second argument to likelihood() must be a "
  80235. "constant between 0.0 and 1.0");
  80236. pNC->nErr++;
  80237. }
  80238. }else{
  80239. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  80240. ** equivalent to likelihood(X, 0.0625).
  80241. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  80242. ** short-hand for likelihood(X,0.0625).
  80243. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  80244. ** for likelihood(X,0.9375).
  80245. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  80246. ** to likelihood(X,0.9375). */
  80247. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  80248. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  80249. }
  80250. }
  80251. #ifndef SQLITE_OMIT_AUTHORIZATION
  80252. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  80253. if( auth!=SQLITE_OK ){
  80254. if( auth==SQLITE_DENY ){
  80255. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  80256. pDef->zName);
  80257. pNC->nErr++;
  80258. }
  80259. pExpr->op = TK_NULL;
  80260. return WRC_Prune;
  80261. }
  80262. #endif
  80263. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  80264. /* For the purposes of the EP_ConstFunc flag, date and time
  80265. ** functions and other functions that change slowly are considered
  80266. ** constant because they are constant for the duration of one query */
  80267. ExprSetProperty(pExpr,EP_ConstFunc);
  80268. }
  80269. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  80270. /* Date/time functions that use 'now', and other functions like
  80271. ** sqlite_version() that might change over time cannot be used
  80272. ** in an index. */
  80273. notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
  80274. }
  80275. }
  80276. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  80277. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  80278. pNC->nErr++;
  80279. is_agg = 0;
  80280. }else if( no_such_func && pParse->db->init.busy==0 ){
  80281. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  80282. pNC->nErr++;
  80283. }else if( wrong_num_args ){
  80284. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  80285. nId, zId);
  80286. pNC->nErr++;
  80287. }
  80288. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  80289. sqlite3WalkExprList(pWalker, pList);
  80290. if( is_agg ){
  80291. NameContext *pNC2 = pNC;
  80292. pExpr->op = TK_AGG_FUNCTION;
  80293. pExpr->op2 = 0;
  80294. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  80295. pExpr->op2++;
  80296. pNC2 = pNC2->pNext;
  80297. }
  80298. assert( pDef!=0 );
  80299. if( pNC2 ){
  80300. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  80301. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  80302. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  80303. }
  80304. pNC->ncFlags |= NC_AllowAgg;
  80305. }
  80306. /* FIX ME: Compute pExpr->affinity based on the expected return
  80307. ** type of the function
  80308. */
  80309. return WRC_Prune;
  80310. }
  80311. #ifndef SQLITE_OMIT_SUBQUERY
  80312. case TK_SELECT:
  80313. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  80314. #endif
  80315. case TK_IN: {
  80316. testcase( pExpr->op==TK_IN );
  80317. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  80318. int nRef = pNC->nRef;
  80319. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  80320. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  80321. assert( pNC->nRef>=nRef );
  80322. if( nRef!=pNC->nRef ){
  80323. ExprSetProperty(pExpr, EP_VarSelect);
  80324. }
  80325. }
  80326. break;
  80327. }
  80328. case TK_VARIABLE: {
  80329. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  80330. break;
  80331. }
  80332. }
  80333. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  80334. }
  80335. /*
  80336. ** pEList is a list of expressions which are really the result set of the
  80337. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  80338. ** This routine checks to see if pE is a simple identifier which corresponds
  80339. ** to the AS-name of one of the terms of the expression list. If it is,
  80340. ** this routine return an integer between 1 and N where N is the number of
  80341. ** elements in pEList, corresponding to the matching entry. If there is
  80342. ** no match, or if pE is not a simple identifier, then this routine
  80343. ** return 0.
  80344. **
  80345. ** pEList has been resolved. pE has not.
  80346. */
  80347. static int resolveAsName(
  80348. Parse *pParse, /* Parsing context for error messages */
  80349. ExprList *pEList, /* List of expressions to scan */
  80350. Expr *pE /* Expression we are trying to match */
  80351. ){
  80352. int i; /* Loop counter */
  80353. UNUSED_PARAMETER(pParse);
  80354. if( pE->op==TK_ID ){
  80355. char *zCol = pE->u.zToken;
  80356. for(i=0; i<pEList->nExpr; i++){
  80357. char *zAs = pEList->a[i].zName;
  80358. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  80359. return i+1;
  80360. }
  80361. }
  80362. }
  80363. return 0;
  80364. }
  80365. /*
  80366. ** pE is a pointer to an expression which is a single term in the
  80367. ** ORDER BY of a compound SELECT. The expression has not been
  80368. ** name resolved.
  80369. **
  80370. ** At the point this routine is called, we already know that the
  80371. ** ORDER BY term is not an integer index into the result set. That
  80372. ** case is handled by the calling routine.
  80373. **
  80374. ** Attempt to match pE against result set columns in the left-most
  80375. ** SELECT statement. Return the index i of the matching column,
  80376. ** as an indication to the caller that it should sort by the i-th column.
  80377. ** The left-most column is 1. In other words, the value returned is the
  80378. ** same integer value that would be used in the SQL statement to indicate
  80379. ** the column.
  80380. **
  80381. ** If there is no match, return 0. Return -1 if an error occurs.
  80382. */
  80383. static int resolveOrderByTermToExprList(
  80384. Parse *pParse, /* Parsing context for error messages */
  80385. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  80386. Expr *pE /* The specific ORDER BY term */
  80387. ){
  80388. int i; /* Loop counter */
  80389. ExprList *pEList; /* The columns of the result set */
  80390. NameContext nc; /* Name context for resolving pE */
  80391. sqlite3 *db; /* Database connection */
  80392. int rc; /* Return code from subprocedures */
  80393. u8 savedSuppErr; /* Saved value of db->suppressErr */
  80394. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  80395. pEList = pSelect->pEList;
  80396. /* Resolve all names in the ORDER BY term expression
  80397. */
  80398. memset(&nc, 0, sizeof(nc));
  80399. nc.pParse = pParse;
  80400. nc.pSrcList = pSelect->pSrc;
  80401. nc.pEList = pEList;
  80402. nc.ncFlags = NC_AllowAgg;
  80403. nc.nErr = 0;
  80404. db = pParse->db;
  80405. savedSuppErr = db->suppressErr;
  80406. db->suppressErr = 1;
  80407. rc = sqlite3ResolveExprNames(&nc, pE);
  80408. db->suppressErr = savedSuppErr;
  80409. if( rc ) return 0;
  80410. /* Try to match the ORDER BY expression against an expression
  80411. ** in the result set. Return an 1-based index of the matching
  80412. ** result-set entry.
  80413. */
  80414. for(i=0; i<pEList->nExpr; i++){
  80415. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  80416. return i+1;
  80417. }
  80418. }
  80419. /* If no match, return 0. */
  80420. return 0;
  80421. }
  80422. /*
  80423. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  80424. */
  80425. static void resolveOutOfRangeError(
  80426. Parse *pParse, /* The error context into which to write the error */
  80427. const char *zType, /* "ORDER" or "GROUP" */
  80428. int i, /* The index (1-based) of the term out of range */
  80429. int mx /* Largest permissible value of i */
  80430. ){
  80431. sqlite3ErrorMsg(pParse,
  80432. "%r %s BY term out of range - should be "
  80433. "between 1 and %d", i, zType, mx);
  80434. }
  80435. /*
  80436. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  80437. ** each term of the ORDER BY clause is a constant integer between 1
  80438. ** and N where N is the number of columns in the compound SELECT.
  80439. **
  80440. ** ORDER BY terms that are already an integer between 1 and N are
  80441. ** unmodified. ORDER BY terms that are integers outside the range of
  80442. ** 1 through N generate an error. ORDER BY terms that are expressions
  80443. ** are matched against result set expressions of compound SELECT
  80444. ** beginning with the left-most SELECT and working toward the right.
  80445. ** At the first match, the ORDER BY expression is transformed into
  80446. ** the integer column number.
  80447. **
  80448. ** Return the number of errors seen.
  80449. */
  80450. static int resolveCompoundOrderBy(
  80451. Parse *pParse, /* Parsing context. Leave error messages here */
  80452. Select *pSelect /* The SELECT statement containing the ORDER BY */
  80453. ){
  80454. int i;
  80455. ExprList *pOrderBy;
  80456. ExprList *pEList;
  80457. sqlite3 *db;
  80458. int moreToDo = 1;
  80459. pOrderBy = pSelect->pOrderBy;
  80460. if( pOrderBy==0 ) return 0;
  80461. db = pParse->db;
  80462. #if SQLITE_MAX_COLUMN
  80463. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  80464. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  80465. return 1;
  80466. }
  80467. #endif
  80468. for(i=0; i<pOrderBy->nExpr; i++){
  80469. pOrderBy->a[i].done = 0;
  80470. }
  80471. pSelect->pNext = 0;
  80472. while( pSelect->pPrior ){
  80473. pSelect->pPrior->pNext = pSelect;
  80474. pSelect = pSelect->pPrior;
  80475. }
  80476. while( pSelect && moreToDo ){
  80477. struct ExprList_item *pItem;
  80478. moreToDo = 0;
  80479. pEList = pSelect->pEList;
  80480. assert( pEList!=0 );
  80481. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  80482. int iCol = -1;
  80483. Expr *pE, *pDup;
  80484. if( pItem->done ) continue;
  80485. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  80486. if( sqlite3ExprIsInteger(pE, &iCol) ){
  80487. if( iCol<=0 || iCol>pEList->nExpr ){
  80488. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  80489. return 1;
  80490. }
  80491. }else{
  80492. iCol = resolveAsName(pParse, pEList, pE);
  80493. if( iCol==0 ){
  80494. pDup = sqlite3ExprDup(db, pE, 0);
  80495. if( !db->mallocFailed ){
  80496. assert(pDup);
  80497. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  80498. }
  80499. sqlite3ExprDelete(db, pDup);
  80500. }
  80501. }
  80502. if( iCol>0 ){
  80503. /* Convert the ORDER BY term into an integer column number iCol,
  80504. ** taking care to preserve the COLLATE clause if it exists */
  80505. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  80506. if( pNew==0 ) return 1;
  80507. pNew->flags |= EP_IntValue;
  80508. pNew->u.iValue = iCol;
  80509. if( pItem->pExpr==pE ){
  80510. pItem->pExpr = pNew;
  80511. }else{
  80512. Expr *pParent = pItem->pExpr;
  80513. assert( pParent->op==TK_COLLATE );
  80514. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  80515. assert( pParent->pLeft==pE );
  80516. pParent->pLeft = pNew;
  80517. }
  80518. sqlite3ExprDelete(db, pE);
  80519. pItem->u.x.iOrderByCol = (u16)iCol;
  80520. pItem->done = 1;
  80521. }else{
  80522. moreToDo = 1;
  80523. }
  80524. }
  80525. pSelect = pSelect->pNext;
  80526. }
  80527. for(i=0; i<pOrderBy->nExpr; i++){
  80528. if( pOrderBy->a[i].done==0 ){
  80529. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  80530. "column in the result set", i+1);
  80531. return 1;
  80532. }
  80533. }
  80534. return 0;
  80535. }
  80536. /*
  80537. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  80538. ** the SELECT statement pSelect. If any term is reference to a
  80539. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  80540. ** field) then convert that term into a copy of the corresponding result set
  80541. ** column.
  80542. **
  80543. ** If any errors are detected, add an error message to pParse and
  80544. ** return non-zero. Return zero if no errors are seen.
  80545. */
  80546. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  80547. Parse *pParse, /* Parsing context. Leave error messages here */
  80548. Select *pSelect, /* The SELECT statement containing the clause */
  80549. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  80550. const char *zType /* "ORDER" or "GROUP" */
  80551. ){
  80552. int i;
  80553. sqlite3 *db = pParse->db;
  80554. ExprList *pEList;
  80555. struct ExprList_item *pItem;
  80556. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  80557. #if SQLITE_MAX_COLUMN
  80558. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  80559. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  80560. return 1;
  80561. }
  80562. #endif
  80563. pEList = pSelect->pEList;
  80564. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  80565. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  80566. if( pItem->u.x.iOrderByCol ){
  80567. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  80568. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  80569. return 1;
  80570. }
  80571. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  80572. zType,0);
  80573. }
  80574. }
  80575. return 0;
  80576. }
  80577. /*
  80578. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  80579. ** The Name context of the SELECT statement is pNC. zType is either
  80580. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  80581. **
  80582. ** This routine resolves each term of the clause into an expression.
  80583. ** If the order-by term is an integer I between 1 and N (where N is the
  80584. ** number of columns in the result set of the SELECT) then the expression
  80585. ** in the resolution is a copy of the I-th result-set expression. If
  80586. ** the order-by term is an identifier that corresponds to the AS-name of
  80587. ** a result-set expression, then the term resolves to a copy of the
  80588. ** result-set expression. Otherwise, the expression is resolved in
  80589. ** the usual way - using sqlite3ResolveExprNames().
  80590. **
  80591. ** This routine returns the number of errors. If errors occur, then
  80592. ** an appropriate error message might be left in pParse. (OOM errors
  80593. ** excepted.)
  80594. */
  80595. static int resolveOrderGroupBy(
  80596. NameContext *pNC, /* The name context of the SELECT statement */
  80597. Select *pSelect, /* The SELECT statement holding pOrderBy */
  80598. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  80599. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  80600. ){
  80601. int i, j; /* Loop counters */
  80602. int iCol; /* Column number */
  80603. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  80604. Parse *pParse; /* Parsing context */
  80605. int nResult; /* Number of terms in the result set */
  80606. if( pOrderBy==0 ) return 0;
  80607. nResult = pSelect->pEList->nExpr;
  80608. pParse = pNC->pParse;
  80609. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  80610. Expr *pE = pItem->pExpr;
  80611. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  80612. if( zType[0]!='G' ){
  80613. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  80614. if( iCol>0 ){
  80615. /* If an AS-name match is found, mark this ORDER BY column as being
  80616. ** a copy of the iCol-th result-set column. The subsequent call to
  80617. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  80618. ** copy of the iCol-th result-set expression. */
  80619. pItem->u.x.iOrderByCol = (u16)iCol;
  80620. continue;
  80621. }
  80622. }
  80623. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  80624. /* The ORDER BY term is an integer constant. Again, set the column
  80625. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  80626. ** order-by term to a copy of the result-set expression */
  80627. if( iCol<1 || iCol>0xffff ){
  80628. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  80629. return 1;
  80630. }
  80631. pItem->u.x.iOrderByCol = (u16)iCol;
  80632. continue;
  80633. }
  80634. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  80635. pItem->u.x.iOrderByCol = 0;
  80636. if( sqlite3ResolveExprNames(pNC, pE) ){
  80637. return 1;
  80638. }
  80639. for(j=0; j<pSelect->pEList->nExpr; j++){
  80640. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  80641. pItem->u.x.iOrderByCol = j+1;
  80642. }
  80643. }
  80644. }
  80645. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  80646. }
  80647. /*
  80648. ** Resolve names in the SELECT statement p and all of its descendants.
  80649. */
  80650. static int resolveSelectStep(Walker *pWalker, Select *p){
  80651. NameContext *pOuterNC; /* Context that contains this SELECT */
  80652. NameContext sNC; /* Name context of this SELECT */
  80653. int isCompound; /* True if p is a compound select */
  80654. int nCompound; /* Number of compound terms processed so far */
  80655. Parse *pParse; /* Parsing context */
  80656. int i; /* Loop counter */
  80657. ExprList *pGroupBy; /* The GROUP BY clause */
  80658. Select *pLeftmost; /* Left-most of SELECT of a compound */
  80659. sqlite3 *db; /* Database connection */
  80660. assert( p!=0 );
  80661. if( p->selFlags & SF_Resolved ){
  80662. return WRC_Prune;
  80663. }
  80664. pOuterNC = pWalker->u.pNC;
  80665. pParse = pWalker->pParse;
  80666. db = pParse->db;
  80667. /* Normally sqlite3SelectExpand() will be called first and will have
  80668. ** already expanded this SELECT. However, if this is a subquery within
  80669. ** an expression, sqlite3ResolveExprNames() will be called without a
  80670. ** prior call to sqlite3SelectExpand(). When that happens, let
  80671. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  80672. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  80673. ** this routine in the correct order.
  80674. */
  80675. if( (p->selFlags & SF_Expanded)==0 ){
  80676. sqlite3SelectPrep(pParse, p, pOuterNC);
  80677. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  80678. }
  80679. isCompound = p->pPrior!=0;
  80680. nCompound = 0;
  80681. pLeftmost = p;
  80682. while( p ){
  80683. assert( (p->selFlags & SF_Expanded)!=0 );
  80684. assert( (p->selFlags & SF_Resolved)==0 );
  80685. p->selFlags |= SF_Resolved;
  80686. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  80687. ** are not allowed to refer to any names, so pass an empty NameContext.
  80688. */
  80689. memset(&sNC, 0, sizeof(sNC));
  80690. sNC.pParse = pParse;
  80691. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  80692. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  80693. return WRC_Abort;
  80694. }
  80695. /* If the SF_Converted flags is set, then this Select object was
  80696. ** was created by the convertCompoundSelectToSubquery() function.
  80697. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  80698. ** as if it were part of the sub-query, not the parent. This block
  80699. ** moves the pOrderBy down to the sub-query. It will be moved back
  80700. ** after the names have been resolved. */
  80701. if( p->selFlags & SF_Converted ){
  80702. Select *pSub = p->pSrc->a[0].pSelect;
  80703. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  80704. assert( pSub->pPrior && pSub->pOrderBy==0 );
  80705. pSub->pOrderBy = p->pOrderBy;
  80706. p->pOrderBy = 0;
  80707. }
  80708. /* Recursively resolve names in all subqueries
  80709. */
  80710. for(i=0; i<p->pSrc->nSrc; i++){
  80711. struct SrcList_item *pItem = &p->pSrc->a[i];
  80712. if( pItem->pSelect ){
  80713. NameContext *pNC; /* Used to iterate name contexts */
  80714. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  80715. const char *zSavedContext = pParse->zAuthContext;
  80716. /* Count the total number of references to pOuterNC and all of its
  80717. ** parent contexts. After resolving references to expressions in
  80718. ** pItem->pSelect, check if this value has changed. If so, then
  80719. ** SELECT statement pItem->pSelect must be correlated. Set the
  80720. ** pItem->fg.isCorrelated flag if this is the case. */
  80721. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  80722. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  80723. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  80724. pParse->zAuthContext = zSavedContext;
  80725. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  80726. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  80727. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  80728. pItem->fg.isCorrelated = (nRef!=0);
  80729. }
  80730. }
  80731. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  80732. ** resolve the result-set expression list.
  80733. */
  80734. sNC.ncFlags = NC_AllowAgg;
  80735. sNC.pSrcList = p->pSrc;
  80736. sNC.pNext = pOuterNC;
  80737. /* Resolve names in the result set. */
  80738. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  80739. /* If there are no aggregate functions in the result-set, and no GROUP BY
  80740. ** expression, do not allow aggregates in any of the other expressions.
  80741. */
  80742. assert( (p->selFlags & SF_Aggregate)==0 );
  80743. pGroupBy = p->pGroupBy;
  80744. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  80745. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  80746. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  80747. }else{
  80748. sNC.ncFlags &= ~NC_AllowAgg;
  80749. }
  80750. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  80751. */
  80752. if( p->pHaving && !pGroupBy ){
  80753. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  80754. return WRC_Abort;
  80755. }
  80756. /* Add the output column list to the name-context before parsing the
  80757. ** other expressions in the SELECT statement. This is so that
  80758. ** expressions in the WHERE clause (etc.) can refer to expressions by
  80759. ** aliases in the result set.
  80760. **
  80761. ** Minor point: If this is the case, then the expression will be
  80762. ** re-evaluated for each reference to it.
  80763. */
  80764. sNC.pEList = p->pEList;
  80765. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  80766. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  80767. /* Resolve names in table-valued-function arguments */
  80768. for(i=0; i<p->pSrc->nSrc; i++){
  80769. struct SrcList_item *pItem = &p->pSrc->a[i];
  80770. if( pItem->fg.isTabFunc
  80771. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  80772. ){
  80773. return WRC_Abort;
  80774. }
  80775. }
  80776. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  80777. ** outer queries
  80778. */
  80779. sNC.pNext = 0;
  80780. sNC.ncFlags |= NC_AllowAgg;
  80781. /* If this is a converted compound query, move the ORDER BY clause from
  80782. ** the sub-query back to the parent query. At this point each term
  80783. ** within the ORDER BY clause has been transformed to an integer value.
  80784. ** These integers will be replaced by copies of the corresponding result
  80785. ** set expressions by the call to resolveOrderGroupBy() below. */
  80786. if( p->selFlags & SF_Converted ){
  80787. Select *pSub = p->pSrc->a[0].pSelect;
  80788. p->pOrderBy = pSub->pOrderBy;
  80789. pSub->pOrderBy = 0;
  80790. }
  80791. /* Process the ORDER BY clause for singleton SELECT statements.
  80792. ** The ORDER BY clause for compounds SELECT statements is handled
  80793. ** below, after all of the result-sets for all of the elements of
  80794. ** the compound have been resolved.
  80795. **
  80796. ** If there is an ORDER BY clause on a term of a compound-select other
  80797. ** than the right-most term, then that is a syntax error. But the error
  80798. ** is not detected until much later, and so we need to go ahead and
  80799. ** resolve those symbols on the incorrect ORDER BY for consistency.
  80800. */
  80801. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  80802. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  80803. ){
  80804. return WRC_Abort;
  80805. }
  80806. if( db->mallocFailed ){
  80807. return WRC_Abort;
  80808. }
  80809. /* Resolve the GROUP BY clause. At the same time, make sure
  80810. ** the GROUP BY clause does not contain aggregate functions.
  80811. */
  80812. if( pGroupBy ){
  80813. struct ExprList_item *pItem;
  80814. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  80815. return WRC_Abort;
  80816. }
  80817. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  80818. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  80819. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  80820. "the GROUP BY clause");
  80821. return WRC_Abort;
  80822. }
  80823. }
  80824. }
  80825. /* If this is part of a compound SELECT, check that it has the right
  80826. ** number of expressions in the select list. */
  80827. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  80828. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  80829. return WRC_Abort;
  80830. }
  80831. /* Advance to the next term of the compound
  80832. */
  80833. p = p->pPrior;
  80834. nCompound++;
  80835. }
  80836. /* Resolve the ORDER BY on a compound SELECT after all terms of
  80837. ** the compound have been resolved.
  80838. */
  80839. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  80840. return WRC_Abort;
  80841. }
  80842. return WRC_Prune;
  80843. }
  80844. /*
  80845. ** This routine walks an expression tree and resolves references to
  80846. ** table columns and result-set columns. At the same time, do error
  80847. ** checking on function usage and set a flag if any aggregate functions
  80848. ** are seen.
  80849. **
  80850. ** To resolve table columns references we look for nodes (or subtrees) of the
  80851. ** form X.Y.Z or Y.Z or just Z where
  80852. **
  80853. ** X: The name of a database. Ex: "main" or "temp" or
  80854. ** the symbolic name assigned to an ATTACH-ed database.
  80855. **
  80856. ** Y: The name of a table in a FROM clause. Or in a trigger
  80857. ** one of the special names "old" or "new".
  80858. **
  80859. ** Z: The name of a column in table Y.
  80860. **
  80861. ** The node at the root of the subtree is modified as follows:
  80862. **
  80863. ** Expr.op Changed to TK_COLUMN
  80864. ** Expr.pTab Points to the Table object for X.Y
  80865. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  80866. ** Expr.iTable The VDBE cursor number for X.Y
  80867. **
  80868. **
  80869. ** To resolve result-set references, look for expression nodes of the
  80870. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  80871. ** size of an AS clause in the result-set of a SELECT. The Z expression
  80872. ** is replaced by a copy of the left-hand side of the result-set expression.
  80873. ** Table-name and function resolution occurs on the substituted expression
  80874. ** tree. For example, in:
  80875. **
  80876. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  80877. **
  80878. ** The "x" term of the order by is replaced by "a+b" to render:
  80879. **
  80880. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  80881. **
  80882. ** Function calls are checked to make sure that the function is
  80883. ** defined and that the correct number of arguments are specified.
  80884. ** If the function is an aggregate function, then the NC_HasAgg flag is
  80885. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  80886. ** If an expression contains aggregate functions then the EP_Agg
  80887. ** property on the expression is set.
  80888. **
  80889. ** An error message is left in pParse if anything is amiss. The number
  80890. ** if errors is returned.
  80891. */
  80892. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  80893. NameContext *pNC, /* Namespace to resolve expressions in. */
  80894. Expr *pExpr /* The expression to be analyzed. */
  80895. ){
  80896. u16 savedHasAgg;
  80897. Walker w;
  80898. if( pExpr==0 ) return 0;
  80899. #if SQLITE_MAX_EXPR_DEPTH>0
  80900. {
  80901. Parse *pParse = pNC->pParse;
  80902. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  80903. return 1;
  80904. }
  80905. pParse->nHeight += pExpr->nHeight;
  80906. }
  80907. #endif
  80908. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  80909. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  80910. w.pParse = pNC->pParse;
  80911. w.xExprCallback = resolveExprStep;
  80912. w.xSelectCallback = resolveSelectStep;
  80913. w.xSelectCallback2 = 0;
  80914. w.walkerDepth = 0;
  80915. w.eCode = 0;
  80916. w.u.pNC = pNC;
  80917. sqlite3WalkExpr(&w, pExpr);
  80918. #if SQLITE_MAX_EXPR_DEPTH>0
  80919. pNC->pParse->nHeight -= pExpr->nHeight;
  80920. #endif
  80921. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  80922. ExprSetProperty(pExpr, EP_Error);
  80923. }
  80924. if( pNC->ncFlags & NC_HasAgg ){
  80925. ExprSetProperty(pExpr, EP_Agg);
  80926. }
  80927. pNC->ncFlags |= savedHasAgg;
  80928. return ExprHasProperty(pExpr, EP_Error);
  80929. }
  80930. /*
  80931. ** Resolve all names for all expression in an expression list. This is
  80932. ** just like sqlite3ResolveExprNames() except that it works for an expression
  80933. ** list rather than a single expression.
  80934. */
  80935. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  80936. NameContext *pNC, /* Namespace to resolve expressions in. */
  80937. ExprList *pList /* The expression list to be analyzed. */
  80938. ){
  80939. int i;
  80940. if( pList ){
  80941. for(i=0; i<pList->nExpr; i++){
  80942. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  80943. }
  80944. }
  80945. return WRC_Continue;
  80946. }
  80947. /*
  80948. ** Resolve all names in all expressions of a SELECT and in all
  80949. ** decendents of the SELECT, including compounds off of p->pPrior,
  80950. ** subqueries in expressions, and subqueries used as FROM clause
  80951. ** terms.
  80952. **
  80953. ** See sqlite3ResolveExprNames() for a description of the kinds of
  80954. ** transformations that occur.
  80955. **
  80956. ** All SELECT statements should have been expanded using
  80957. ** sqlite3SelectExpand() prior to invoking this routine.
  80958. */
  80959. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  80960. Parse *pParse, /* The parser context */
  80961. Select *p, /* The SELECT statement being coded. */
  80962. NameContext *pOuterNC /* Name context for parent SELECT statement */
  80963. ){
  80964. Walker w;
  80965. assert( p!=0 );
  80966. memset(&w, 0, sizeof(w));
  80967. w.xExprCallback = resolveExprStep;
  80968. w.xSelectCallback = resolveSelectStep;
  80969. w.pParse = pParse;
  80970. w.u.pNC = pOuterNC;
  80971. sqlite3WalkSelect(&w, p);
  80972. }
  80973. /*
  80974. ** Resolve names in expressions that can only reference a single table:
  80975. **
  80976. ** * CHECK constraints
  80977. ** * WHERE clauses on partial indices
  80978. **
  80979. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  80980. ** is set to -1 and the Expr.iColumn value is set to the column number.
  80981. **
  80982. ** Any errors cause an error message to be set in pParse.
  80983. */
  80984. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  80985. Parse *pParse, /* Parsing context */
  80986. Table *pTab, /* The table being referenced */
  80987. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  80988. Expr *pExpr, /* Expression to resolve. May be NULL. */
  80989. ExprList *pList /* Expression list to resolve. May be NUL. */
  80990. ){
  80991. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  80992. NameContext sNC; /* Name context for pParse->pNewTable */
  80993. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  80994. memset(&sNC, 0, sizeof(sNC));
  80995. memset(&sSrc, 0, sizeof(sSrc));
  80996. sSrc.nSrc = 1;
  80997. sSrc.a[0].zName = pTab->zName;
  80998. sSrc.a[0].pTab = pTab;
  80999. sSrc.a[0].iCursor = -1;
  81000. sNC.pParse = pParse;
  81001. sNC.pSrcList = &sSrc;
  81002. sNC.ncFlags = type;
  81003. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  81004. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  81005. }
  81006. /************** End of resolve.c *********************************************/
  81007. /************** Begin file expr.c ********************************************/
  81008. /*
  81009. ** 2001 September 15
  81010. **
  81011. ** The author disclaims copyright to this source code. In place of
  81012. ** a legal notice, here is a blessing:
  81013. **
  81014. ** May you do good and not evil.
  81015. ** May you find forgiveness for yourself and forgive others.
  81016. ** May you share freely, never taking more than you give.
  81017. **
  81018. *************************************************************************
  81019. ** This file contains routines used for analyzing expressions and
  81020. ** for generating VDBE code that evaluates expressions in SQLite.
  81021. */
  81022. /* #include "sqliteInt.h" */
  81023. /*
  81024. ** Return the 'affinity' of the expression pExpr if any.
  81025. **
  81026. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  81027. ** or a sub-select with a column as the return value, then the
  81028. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  81029. ** indicating no affinity for the expression.
  81030. **
  81031. ** i.e. the WHERE clause expressions in the following statements all
  81032. ** have an affinity:
  81033. **
  81034. ** CREATE TABLE t1(a);
  81035. ** SELECT * FROM t1 WHERE a;
  81036. ** SELECT a AS b FROM t1 WHERE b;
  81037. ** SELECT * FROM t1 WHERE (select a from t1);
  81038. */
  81039. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  81040. int op;
  81041. pExpr = sqlite3ExprSkipCollate(pExpr);
  81042. if( pExpr->flags & EP_Generic ) return 0;
  81043. op = pExpr->op;
  81044. if( op==TK_SELECT ){
  81045. assert( pExpr->flags&EP_xIsSelect );
  81046. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  81047. }
  81048. #ifndef SQLITE_OMIT_CAST
  81049. if( op==TK_CAST ){
  81050. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81051. return sqlite3AffinityType(pExpr->u.zToken, 0);
  81052. }
  81053. #endif
  81054. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  81055. && pExpr->pTab!=0
  81056. ){
  81057. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  81058. ** a TK_COLUMN but was previously evaluated and cached in a register */
  81059. int j = pExpr->iColumn;
  81060. if( j<0 ) return SQLITE_AFF_INTEGER;
  81061. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  81062. return pExpr->pTab->aCol[j].affinity;
  81063. }
  81064. return pExpr->affinity;
  81065. }
  81066. /*
  81067. ** Set the collating sequence for expression pExpr to be the collating
  81068. ** sequence named by pToken. Return a pointer to a new Expr node that
  81069. ** implements the COLLATE operator.
  81070. **
  81071. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  81072. ** and the pExpr parameter is returned unchanged.
  81073. */
  81074. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  81075. Parse *pParse, /* Parsing context */
  81076. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  81077. const Token *pCollName, /* Name of collating sequence */
  81078. int dequote /* True to dequote pCollName */
  81079. ){
  81080. if( pCollName->n>0 ){
  81081. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  81082. if( pNew ){
  81083. pNew->pLeft = pExpr;
  81084. pNew->flags |= EP_Collate|EP_Skip;
  81085. pExpr = pNew;
  81086. }
  81087. }
  81088. return pExpr;
  81089. }
  81090. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  81091. Token s;
  81092. assert( zC!=0 );
  81093. sqlite3TokenInit(&s, (char*)zC);
  81094. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  81095. }
  81096. /*
  81097. ** Skip over any TK_COLLATE operators and any unlikely()
  81098. ** or likelihood() function at the root of an expression.
  81099. */
  81100. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  81101. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  81102. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  81103. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  81104. assert( pExpr->x.pList->nExpr>0 );
  81105. assert( pExpr->op==TK_FUNCTION );
  81106. pExpr = pExpr->x.pList->a[0].pExpr;
  81107. }else{
  81108. assert( pExpr->op==TK_COLLATE );
  81109. pExpr = pExpr->pLeft;
  81110. }
  81111. }
  81112. return pExpr;
  81113. }
  81114. /*
  81115. ** Return the collation sequence for the expression pExpr. If
  81116. ** there is no defined collating sequence, return NULL.
  81117. **
  81118. ** The collating sequence might be determined by a COLLATE operator
  81119. ** or by the presence of a column with a defined collating sequence.
  81120. ** COLLATE operators take first precedence. Left operands take
  81121. ** precedence over right operands.
  81122. */
  81123. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  81124. sqlite3 *db = pParse->db;
  81125. CollSeq *pColl = 0;
  81126. Expr *p = pExpr;
  81127. while( p ){
  81128. int op = p->op;
  81129. if( p->flags & EP_Generic ) break;
  81130. if( op==TK_CAST || op==TK_UPLUS ){
  81131. p = p->pLeft;
  81132. continue;
  81133. }
  81134. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  81135. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  81136. break;
  81137. }
  81138. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  81139. || op==TK_REGISTER || op==TK_TRIGGER)
  81140. && p->pTab!=0
  81141. ){
  81142. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  81143. ** a TK_COLUMN but was previously evaluated and cached in a register */
  81144. int j = p->iColumn;
  81145. if( j>=0 ){
  81146. const char *zColl = p->pTab->aCol[j].zColl;
  81147. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  81148. }
  81149. break;
  81150. }
  81151. if( p->flags & EP_Collate ){
  81152. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  81153. p = p->pLeft;
  81154. }else{
  81155. Expr *pNext = p->pRight;
  81156. /* The Expr.x union is never used at the same time as Expr.pRight */
  81157. assert( p->x.pList==0 || p->pRight==0 );
  81158. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  81159. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  81160. ** least one EP_Collate. Thus the following two ALWAYS. */
  81161. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  81162. int i;
  81163. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  81164. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  81165. pNext = p->x.pList->a[i].pExpr;
  81166. break;
  81167. }
  81168. }
  81169. }
  81170. p = pNext;
  81171. }
  81172. }else{
  81173. break;
  81174. }
  81175. }
  81176. if( sqlite3CheckCollSeq(pParse, pColl) ){
  81177. pColl = 0;
  81178. }
  81179. return pColl;
  81180. }
  81181. /*
  81182. ** pExpr is an operand of a comparison operator. aff2 is the
  81183. ** type affinity of the other operand. This routine returns the
  81184. ** type affinity that should be used for the comparison operator.
  81185. */
  81186. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  81187. char aff1 = sqlite3ExprAffinity(pExpr);
  81188. if( aff1 && aff2 ){
  81189. /* Both sides of the comparison are columns. If one has numeric
  81190. ** affinity, use that. Otherwise use no affinity.
  81191. */
  81192. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  81193. return SQLITE_AFF_NUMERIC;
  81194. }else{
  81195. return SQLITE_AFF_BLOB;
  81196. }
  81197. }else if( !aff1 && !aff2 ){
  81198. /* Neither side of the comparison is a column. Compare the
  81199. ** results directly.
  81200. */
  81201. return SQLITE_AFF_BLOB;
  81202. }else{
  81203. /* One side is a column, the other is not. Use the columns affinity. */
  81204. assert( aff1==0 || aff2==0 );
  81205. return (aff1 + aff2);
  81206. }
  81207. }
  81208. /*
  81209. ** pExpr is a comparison operator. Return the type affinity that should
  81210. ** be applied to both operands prior to doing the comparison.
  81211. */
  81212. static char comparisonAffinity(Expr *pExpr){
  81213. char aff;
  81214. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  81215. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  81216. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  81217. assert( pExpr->pLeft );
  81218. aff = sqlite3ExprAffinity(pExpr->pLeft);
  81219. if( pExpr->pRight ){
  81220. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  81221. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  81222. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  81223. }else if( !aff ){
  81224. aff = SQLITE_AFF_BLOB;
  81225. }
  81226. return aff;
  81227. }
  81228. /*
  81229. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  81230. ** idx_affinity is the affinity of an indexed column. Return true
  81231. ** if the index with affinity idx_affinity may be used to implement
  81232. ** the comparison in pExpr.
  81233. */
  81234. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  81235. char aff = comparisonAffinity(pExpr);
  81236. switch( aff ){
  81237. case SQLITE_AFF_BLOB:
  81238. return 1;
  81239. case SQLITE_AFF_TEXT:
  81240. return idx_affinity==SQLITE_AFF_TEXT;
  81241. default:
  81242. return sqlite3IsNumericAffinity(idx_affinity);
  81243. }
  81244. }
  81245. /*
  81246. ** Return the P5 value that should be used for a binary comparison
  81247. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  81248. */
  81249. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  81250. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  81251. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  81252. return aff;
  81253. }
  81254. /*
  81255. ** Return a pointer to the collation sequence that should be used by
  81256. ** a binary comparison operator comparing pLeft and pRight.
  81257. **
  81258. ** If the left hand expression has a collating sequence type, then it is
  81259. ** used. Otherwise the collation sequence for the right hand expression
  81260. ** is used, or the default (BINARY) if neither expression has a collating
  81261. ** type.
  81262. **
  81263. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  81264. ** it is not considered.
  81265. */
  81266. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  81267. Parse *pParse,
  81268. Expr *pLeft,
  81269. Expr *pRight
  81270. ){
  81271. CollSeq *pColl;
  81272. assert( pLeft );
  81273. if( pLeft->flags & EP_Collate ){
  81274. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  81275. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  81276. pColl = sqlite3ExprCollSeq(pParse, pRight);
  81277. }else{
  81278. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  81279. if( !pColl ){
  81280. pColl = sqlite3ExprCollSeq(pParse, pRight);
  81281. }
  81282. }
  81283. return pColl;
  81284. }
  81285. /*
  81286. ** Generate code for a comparison operator.
  81287. */
  81288. static int codeCompare(
  81289. Parse *pParse, /* The parsing (and code generating) context */
  81290. Expr *pLeft, /* The left operand */
  81291. Expr *pRight, /* The right operand */
  81292. int opcode, /* The comparison opcode */
  81293. int in1, int in2, /* Register holding operands */
  81294. int dest, /* Jump here if true. */
  81295. int jumpIfNull /* If true, jump if either operand is NULL */
  81296. ){
  81297. int p5;
  81298. int addr;
  81299. CollSeq *p4;
  81300. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  81301. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  81302. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  81303. (void*)p4, P4_COLLSEQ);
  81304. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  81305. return addr;
  81306. }
  81307. #if SQLITE_MAX_EXPR_DEPTH>0
  81308. /*
  81309. ** Check that argument nHeight is less than or equal to the maximum
  81310. ** expression depth allowed. If it is not, leave an error message in
  81311. ** pParse.
  81312. */
  81313. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  81314. int rc = SQLITE_OK;
  81315. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  81316. if( nHeight>mxHeight ){
  81317. sqlite3ErrorMsg(pParse,
  81318. "Expression tree is too large (maximum depth %d)", mxHeight
  81319. );
  81320. rc = SQLITE_ERROR;
  81321. }
  81322. return rc;
  81323. }
  81324. /* The following three functions, heightOfExpr(), heightOfExprList()
  81325. ** and heightOfSelect(), are used to determine the maximum height
  81326. ** of any expression tree referenced by the structure passed as the
  81327. ** first argument.
  81328. **
  81329. ** If this maximum height is greater than the current value pointed
  81330. ** to by pnHeight, the second parameter, then set *pnHeight to that
  81331. ** value.
  81332. */
  81333. static void heightOfExpr(Expr *p, int *pnHeight){
  81334. if( p ){
  81335. if( p->nHeight>*pnHeight ){
  81336. *pnHeight = p->nHeight;
  81337. }
  81338. }
  81339. }
  81340. static void heightOfExprList(ExprList *p, int *pnHeight){
  81341. if( p ){
  81342. int i;
  81343. for(i=0; i<p->nExpr; i++){
  81344. heightOfExpr(p->a[i].pExpr, pnHeight);
  81345. }
  81346. }
  81347. }
  81348. static void heightOfSelect(Select *p, int *pnHeight){
  81349. if( p ){
  81350. heightOfExpr(p->pWhere, pnHeight);
  81351. heightOfExpr(p->pHaving, pnHeight);
  81352. heightOfExpr(p->pLimit, pnHeight);
  81353. heightOfExpr(p->pOffset, pnHeight);
  81354. heightOfExprList(p->pEList, pnHeight);
  81355. heightOfExprList(p->pGroupBy, pnHeight);
  81356. heightOfExprList(p->pOrderBy, pnHeight);
  81357. heightOfSelect(p->pPrior, pnHeight);
  81358. }
  81359. }
  81360. /*
  81361. ** Set the Expr.nHeight variable in the structure passed as an
  81362. ** argument. An expression with no children, Expr.pList or
  81363. ** Expr.pSelect member has a height of 1. Any other expression
  81364. ** has a height equal to the maximum height of any other
  81365. ** referenced Expr plus one.
  81366. **
  81367. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  81368. ** if appropriate.
  81369. */
  81370. static void exprSetHeight(Expr *p){
  81371. int nHeight = 0;
  81372. heightOfExpr(p->pLeft, &nHeight);
  81373. heightOfExpr(p->pRight, &nHeight);
  81374. if( ExprHasProperty(p, EP_xIsSelect) ){
  81375. heightOfSelect(p->x.pSelect, &nHeight);
  81376. }else if( p->x.pList ){
  81377. heightOfExprList(p->x.pList, &nHeight);
  81378. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  81379. }
  81380. p->nHeight = nHeight + 1;
  81381. }
  81382. /*
  81383. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  81384. ** the height is greater than the maximum allowed expression depth,
  81385. ** leave an error in pParse.
  81386. **
  81387. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  81388. ** Expr.flags.
  81389. */
  81390. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  81391. if( pParse->nErr ) return;
  81392. exprSetHeight(p);
  81393. sqlite3ExprCheckHeight(pParse, p->nHeight);
  81394. }
  81395. /*
  81396. ** Return the maximum height of any expression tree referenced
  81397. ** by the select statement passed as an argument.
  81398. */
  81399. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  81400. int nHeight = 0;
  81401. heightOfSelect(p, &nHeight);
  81402. return nHeight;
  81403. }
  81404. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  81405. /*
  81406. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  81407. ** Expr.flags.
  81408. */
  81409. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  81410. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  81411. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  81412. }
  81413. }
  81414. #define exprSetHeight(y)
  81415. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  81416. /*
  81417. ** This routine is the core allocator for Expr nodes.
  81418. **
  81419. ** Construct a new expression node and return a pointer to it. Memory
  81420. ** for this node and for the pToken argument is a single allocation
  81421. ** obtained from sqlite3DbMalloc(). The calling function
  81422. ** is responsible for making sure the node eventually gets freed.
  81423. **
  81424. ** If dequote is true, then the token (if it exists) is dequoted.
  81425. ** If dequote is false, no dequoting is performed. The deQuote
  81426. ** parameter is ignored if pToken is NULL or if the token does not
  81427. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  81428. ** then the EP_DblQuoted flag is set on the expression node.
  81429. **
  81430. ** Special case: If op==TK_INTEGER and pToken points to a string that
  81431. ** can be translated into a 32-bit integer, then the token is not
  81432. ** stored in u.zToken. Instead, the integer values is written
  81433. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  81434. ** is allocated to hold the integer text and the dequote flag is ignored.
  81435. */
  81436. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  81437. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  81438. int op, /* Expression opcode */
  81439. const Token *pToken, /* Token argument. Might be NULL */
  81440. int dequote /* True to dequote */
  81441. ){
  81442. Expr *pNew;
  81443. int nExtra = 0;
  81444. int iValue = 0;
  81445. assert( db!=0 );
  81446. if( pToken ){
  81447. if( op!=TK_INTEGER || pToken->z==0
  81448. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  81449. nExtra = pToken->n+1;
  81450. assert( iValue>=0 );
  81451. }
  81452. }
  81453. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  81454. if( pNew ){
  81455. memset(pNew, 0, sizeof(Expr));
  81456. pNew->op = (u8)op;
  81457. pNew->iAgg = -1;
  81458. if( pToken ){
  81459. if( nExtra==0 ){
  81460. pNew->flags |= EP_IntValue;
  81461. pNew->u.iValue = iValue;
  81462. }else{
  81463. int c;
  81464. pNew->u.zToken = (char*)&pNew[1];
  81465. assert( pToken->z!=0 || pToken->n==0 );
  81466. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  81467. pNew->u.zToken[pToken->n] = 0;
  81468. if( dequote && nExtra>=3
  81469. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  81470. sqlite3Dequote(pNew->u.zToken);
  81471. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  81472. }
  81473. }
  81474. }
  81475. #if SQLITE_MAX_EXPR_DEPTH>0
  81476. pNew->nHeight = 1;
  81477. #endif
  81478. }
  81479. return pNew;
  81480. }
  81481. /*
  81482. ** Allocate a new expression node from a zero-terminated token that has
  81483. ** already been dequoted.
  81484. */
  81485. SQLITE_PRIVATE Expr *sqlite3Expr(
  81486. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  81487. int op, /* Expression opcode */
  81488. const char *zToken /* Token argument. Might be NULL */
  81489. ){
  81490. Token x;
  81491. x.z = zToken;
  81492. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  81493. return sqlite3ExprAlloc(db, op, &x, 0);
  81494. }
  81495. /*
  81496. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  81497. **
  81498. ** If pRoot==NULL that means that a memory allocation error has occurred.
  81499. ** In that case, delete the subtrees pLeft and pRight.
  81500. */
  81501. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  81502. sqlite3 *db,
  81503. Expr *pRoot,
  81504. Expr *pLeft,
  81505. Expr *pRight
  81506. ){
  81507. if( pRoot==0 ){
  81508. assert( db->mallocFailed );
  81509. sqlite3ExprDelete(db, pLeft);
  81510. sqlite3ExprDelete(db, pRight);
  81511. }else{
  81512. if( pRight ){
  81513. pRoot->pRight = pRight;
  81514. pRoot->flags |= EP_Propagate & pRight->flags;
  81515. }
  81516. if( pLeft ){
  81517. pRoot->pLeft = pLeft;
  81518. pRoot->flags |= EP_Propagate & pLeft->flags;
  81519. }
  81520. exprSetHeight(pRoot);
  81521. }
  81522. }
  81523. /*
  81524. ** Allocate an Expr node which joins as many as two subtrees.
  81525. **
  81526. ** One or both of the subtrees can be NULL. Return a pointer to the new
  81527. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  81528. ** free the subtrees and return NULL.
  81529. */
  81530. SQLITE_PRIVATE Expr *sqlite3PExpr(
  81531. Parse *pParse, /* Parsing context */
  81532. int op, /* Expression opcode */
  81533. Expr *pLeft, /* Left operand */
  81534. Expr *pRight, /* Right operand */
  81535. const Token *pToken /* Argument token */
  81536. ){
  81537. Expr *p;
  81538. if( op==TK_AND && pParse->nErr==0 ){
  81539. /* Take advantage of short-circuit false optimization for AND */
  81540. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  81541. }else{
  81542. p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
  81543. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  81544. }
  81545. if( p ) {
  81546. sqlite3ExprCheckHeight(pParse, p->nHeight);
  81547. }
  81548. return p;
  81549. }
  81550. /*
  81551. ** If the expression is always either TRUE or FALSE (respectively),
  81552. ** then return 1. If one cannot determine the truth value of the
  81553. ** expression at compile-time return 0.
  81554. **
  81555. ** This is an optimization. If is OK to return 0 here even if
  81556. ** the expression really is always false or false (a false negative).
  81557. ** But it is a bug to return 1 if the expression might have different
  81558. ** boolean values in different circumstances (a false positive.)
  81559. **
  81560. ** Note that if the expression is part of conditional for a
  81561. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  81562. ** is it true or false, so always return 0.
  81563. */
  81564. static int exprAlwaysTrue(Expr *p){
  81565. int v = 0;
  81566. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  81567. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  81568. return v!=0;
  81569. }
  81570. static int exprAlwaysFalse(Expr *p){
  81571. int v = 0;
  81572. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  81573. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  81574. return v==0;
  81575. }
  81576. /*
  81577. ** Join two expressions using an AND operator. If either expression is
  81578. ** NULL, then just return the other expression.
  81579. **
  81580. ** If one side or the other of the AND is known to be false, then instead
  81581. ** of returning an AND expression, just return a constant expression with
  81582. ** a value of false.
  81583. */
  81584. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  81585. if( pLeft==0 ){
  81586. return pRight;
  81587. }else if( pRight==0 ){
  81588. return pLeft;
  81589. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  81590. sqlite3ExprDelete(db, pLeft);
  81591. sqlite3ExprDelete(db, pRight);
  81592. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  81593. }else{
  81594. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  81595. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  81596. return pNew;
  81597. }
  81598. }
  81599. /*
  81600. ** Construct a new expression node for a function with multiple
  81601. ** arguments.
  81602. */
  81603. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  81604. Expr *pNew;
  81605. sqlite3 *db = pParse->db;
  81606. assert( pToken );
  81607. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  81608. if( pNew==0 ){
  81609. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  81610. return 0;
  81611. }
  81612. pNew->x.pList = pList;
  81613. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  81614. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  81615. return pNew;
  81616. }
  81617. /*
  81618. ** Assign a variable number to an expression that encodes a wildcard
  81619. ** in the original SQL statement.
  81620. **
  81621. ** Wildcards consisting of a single "?" are assigned the next sequential
  81622. ** variable number.
  81623. **
  81624. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  81625. ** sure "nnn" is not too be to avoid a denial of service attack when
  81626. ** the SQL statement comes from an external source.
  81627. **
  81628. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  81629. ** as the previous instance of the same wildcard. Or if this is the first
  81630. ** instance of the wildcard, the next sequential variable number is
  81631. ** assigned.
  81632. */
  81633. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  81634. sqlite3 *db = pParse->db;
  81635. const char *z;
  81636. if( pExpr==0 ) return;
  81637. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  81638. z = pExpr->u.zToken;
  81639. assert( z!=0 );
  81640. assert( z[0]!=0 );
  81641. if( z[1]==0 ){
  81642. /* Wildcard of the form "?". Assign the next variable number */
  81643. assert( z[0]=='?' );
  81644. pExpr->iColumn = (ynVar)(++pParse->nVar);
  81645. }else{
  81646. ynVar x = 0;
  81647. u32 n = sqlite3Strlen30(z);
  81648. if( z[0]=='?' ){
  81649. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  81650. ** use it as the variable number */
  81651. i64 i;
  81652. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  81653. pExpr->iColumn = x = (ynVar)i;
  81654. testcase( i==0 );
  81655. testcase( i==1 );
  81656. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  81657. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  81658. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  81659. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  81660. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  81661. x = 0;
  81662. }
  81663. if( i>pParse->nVar ){
  81664. pParse->nVar = (int)i;
  81665. }
  81666. }else{
  81667. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  81668. ** number as the prior appearance of the same name, or if the name
  81669. ** has never appeared before, reuse the same variable number
  81670. */
  81671. ynVar i;
  81672. for(i=0; i<pParse->nzVar; i++){
  81673. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  81674. pExpr->iColumn = x = (ynVar)i+1;
  81675. break;
  81676. }
  81677. }
  81678. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  81679. }
  81680. if( x>0 ){
  81681. if( x>pParse->nzVar ){
  81682. char **a;
  81683. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  81684. if( a==0 ){
  81685. assert( db->mallocFailed ); /* Error reported through mallocFailed */
  81686. return;
  81687. }
  81688. pParse->azVar = a;
  81689. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  81690. pParse->nzVar = x;
  81691. }
  81692. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  81693. sqlite3DbFree(db, pParse->azVar[x-1]);
  81694. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  81695. }
  81696. }
  81697. }
  81698. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  81699. sqlite3ErrorMsg(pParse, "too many SQL variables");
  81700. }
  81701. }
  81702. /*
  81703. ** Recursively delete an expression tree.
  81704. */
  81705. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  81706. if( p==0 ) return;
  81707. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  81708. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  81709. if( !ExprHasProperty(p, EP_TokenOnly) ){
  81710. /* The Expr.x union is never used at the same time as Expr.pRight */
  81711. assert( p->x.pList==0 || p->pRight==0 );
  81712. sqlite3ExprDelete(db, p->pLeft);
  81713. sqlite3ExprDelete(db, p->pRight);
  81714. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  81715. if( ExprHasProperty(p, EP_xIsSelect) ){
  81716. sqlite3SelectDelete(db, p->x.pSelect);
  81717. }else{
  81718. sqlite3ExprListDelete(db, p->x.pList);
  81719. }
  81720. }
  81721. if( !ExprHasProperty(p, EP_Static) ){
  81722. sqlite3DbFree(db, p);
  81723. }
  81724. }
  81725. /*
  81726. ** Return the number of bytes allocated for the expression structure
  81727. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  81728. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  81729. */
  81730. static int exprStructSize(Expr *p){
  81731. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  81732. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  81733. return EXPR_FULLSIZE;
  81734. }
  81735. /*
  81736. ** The dupedExpr*Size() routines each return the number of bytes required
  81737. ** to store a copy of an expression or expression tree. They differ in
  81738. ** how much of the tree is measured.
  81739. **
  81740. ** dupedExprStructSize() Size of only the Expr structure
  81741. ** dupedExprNodeSize() Size of Expr + space for token
  81742. ** dupedExprSize() Expr + token + subtree components
  81743. **
  81744. ***************************************************************************
  81745. **
  81746. ** The dupedExprStructSize() function returns two values OR-ed together:
  81747. ** (1) the space required for a copy of the Expr structure only and
  81748. ** (2) the EP_xxx flags that indicate what the structure size should be.
  81749. ** The return values is always one of:
  81750. **
  81751. ** EXPR_FULLSIZE
  81752. ** EXPR_REDUCEDSIZE | EP_Reduced
  81753. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  81754. **
  81755. ** The size of the structure can be found by masking the return value
  81756. ** of this routine with 0xfff. The flags can be found by masking the
  81757. ** return value with EP_Reduced|EP_TokenOnly.
  81758. **
  81759. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  81760. ** (unreduced) Expr objects as they or originally constructed by the parser.
  81761. ** During expression analysis, extra information is computed and moved into
  81762. ** later parts of teh Expr object and that extra information might get chopped
  81763. ** off if the expression is reduced. Note also that it does not work to
  81764. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  81765. ** to reduce a pristine expression tree from the parser. The implementation
  81766. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  81767. ** to enforce this constraint.
  81768. */
  81769. static int dupedExprStructSize(Expr *p, int flags){
  81770. int nSize;
  81771. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  81772. assert( EXPR_FULLSIZE<=0xfff );
  81773. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  81774. if( 0==(flags&EXPRDUP_REDUCE) ){
  81775. nSize = EXPR_FULLSIZE;
  81776. }else{
  81777. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  81778. assert( !ExprHasProperty(p, EP_FromJoin) );
  81779. assert( !ExprHasProperty(p, EP_MemToken) );
  81780. assert( !ExprHasProperty(p, EP_NoReduce) );
  81781. if( p->pLeft || p->x.pList ){
  81782. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  81783. }else{
  81784. assert( p->pRight==0 );
  81785. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  81786. }
  81787. }
  81788. return nSize;
  81789. }
  81790. /*
  81791. ** This function returns the space in bytes required to store the copy
  81792. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  81793. ** string is defined.)
  81794. */
  81795. static int dupedExprNodeSize(Expr *p, int flags){
  81796. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  81797. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  81798. nByte += sqlite3Strlen30(p->u.zToken)+1;
  81799. }
  81800. return ROUND8(nByte);
  81801. }
  81802. /*
  81803. ** Return the number of bytes required to create a duplicate of the
  81804. ** expression passed as the first argument. The second argument is a
  81805. ** mask containing EXPRDUP_XXX flags.
  81806. **
  81807. ** The value returned includes space to create a copy of the Expr struct
  81808. ** itself and the buffer referred to by Expr.u.zToken, if any.
  81809. **
  81810. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  81811. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  81812. ** and Expr.pRight variables (but not for any structures pointed to or
  81813. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  81814. */
  81815. static int dupedExprSize(Expr *p, int flags){
  81816. int nByte = 0;
  81817. if( p ){
  81818. nByte = dupedExprNodeSize(p, flags);
  81819. if( flags&EXPRDUP_REDUCE ){
  81820. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  81821. }
  81822. }
  81823. return nByte;
  81824. }
  81825. /*
  81826. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  81827. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  81828. ** to store the copy of expression p, the copies of p->u.zToken
  81829. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  81830. ** if any. Before returning, *pzBuffer is set to the first byte past the
  81831. ** portion of the buffer copied into by this function.
  81832. */
  81833. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  81834. Expr *pNew = 0; /* Value to return */
  81835. assert( flags==0 || flags==EXPRDUP_REDUCE );
  81836. assert( db!=0 );
  81837. if( p ){
  81838. const int isReduced = (flags&EXPRDUP_REDUCE);
  81839. u8 *zAlloc;
  81840. u32 staticFlag = 0;
  81841. assert( pzBuffer==0 || isReduced );
  81842. /* Figure out where to write the new Expr structure. */
  81843. if( pzBuffer ){
  81844. zAlloc = *pzBuffer;
  81845. staticFlag = EP_Static;
  81846. }else{
  81847. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, flags));
  81848. }
  81849. pNew = (Expr *)zAlloc;
  81850. if( pNew ){
  81851. /* Set nNewSize to the size allocated for the structure pointed to
  81852. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  81853. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  81854. ** by the copy of the p->u.zToken string (if any).
  81855. */
  81856. const unsigned nStructSize = dupedExprStructSize(p, flags);
  81857. const int nNewSize = nStructSize & 0xfff;
  81858. int nToken;
  81859. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  81860. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  81861. }else{
  81862. nToken = 0;
  81863. }
  81864. if( isReduced ){
  81865. assert( ExprHasProperty(p, EP_Reduced)==0 );
  81866. memcpy(zAlloc, p, nNewSize);
  81867. }else{
  81868. u32 nSize = (u32)exprStructSize(p);
  81869. memcpy(zAlloc, p, nSize);
  81870. if( nSize<EXPR_FULLSIZE ){
  81871. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  81872. }
  81873. }
  81874. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  81875. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  81876. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  81877. pNew->flags |= staticFlag;
  81878. /* Copy the p->u.zToken string, if any. */
  81879. if( nToken ){
  81880. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  81881. memcpy(zToken, p->u.zToken, nToken);
  81882. }
  81883. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  81884. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  81885. if( ExprHasProperty(p, EP_xIsSelect) ){
  81886. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  81887. }else{
  81888. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  81889. }
  81890. }
  81891. /* Fill in pNew->pLeft and pNew->pRight. */
  81892. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  81893. zAlloc += dupedExprNodeSize(p, flags);
  81894. if( ExprHasProperty(pNew, EP_Reduced) ){
  81895. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  81896. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  81897. }
  81898. if( pzBuffer ){
  81899. *pzBuffer = zAlloc;
  81900. }
  81901. }else{
  81902. if( !ExprHasProperty(p, EP_TokenOnly) ){
  81903. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  81904. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  81905. }
  81906. }
  81907. }
  81908. }
  81909. return pNew;
  81910. }
  81911. /*
  81912. ** Create and return a deep copy of the object passed as the second
  81913. ** argument. If an OOM condition is encountered, NULL is returned
  81914. ** and the db->mallocFailed flag set.
  81915. */
  81916. #ifndef SQLITE_OMIT_CTE
  81917. static With *withDup(sqlite3 *db, With *p){
  81918. With *pRet = 0;
  81919. if( p ){
  81920. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  81921. pRet = sqlite3DbMallocZero(db, nByte);
  81922. if( pRet ){
  81923. int i;
  81924. pRet->nCte = p->nCte;
  81925. for(i=0; i<p->nCte; i++){
  81926. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  81927. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  81928. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  81929. }
  81930. }
  81931. }
  81932. return pRet;
  81933. }
  81934. #else
  81935. # define withDup(x,y) 0
  81936. #endif
  81937. /*
  81938. ** The following group of routines make deep copies of expressions,
  81939. ** expression lists, ID lists, and select statements. The copies can
  81940. ** be deleted (by being passed to their respective ...Delete() routines)
  81941. ** without effecting the originals.
  81942. **
  81943. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  81944. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  81945. ** by subsequent calls to sqlite*ListAppend() routines.
  81946. **
  81947. ** Any tables that the SrcList might point to are not duplicated.
  81948. **
  81949. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  81950. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  81951. ** truncated version of the usual Expr structure that will be stored as
  81952. ** part of the in-memory representation of the database schema.
  81953. */
  81954. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  81955. assert( flags==0 || flags==EXPRDUP_REDUCE );
  81956. return exprDup(db, p, flags, 0);
  81957. }
  81958. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  81959. ExprList *pNew;
  81960. struct ExprList_item *pItem, *pOldItem;
  81961. int i;
  81962. assert( db!=0 );
  81963. if( p==0 ) return 0;
  81964. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  81965. if( pNew==0 ) return 0;
  81966. pNew->nExpr = i = p->nExpr;
  81967. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  81968. pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
  81969. if( pItem==0 ){
  81970. sqlite3DbFree(db, pNew);
  81971. return 0;
  81972. }
  81973. pOldItem = p->a;
  81974. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  81975. Expr *pOldExpr = pOldItem->pExpr;
  81976. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  81977. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  81978. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  81979. pItem->sortOrder = pOldItem->sortOrder;
  81980. pItem->done = 0;
  81981. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  81982. pItem->u = pOldItem->u;
  81983. }
  81984. return pNew;
  81985. }
  81986. /*
  81987. ** If cursors, triggers, views and subqueries are all omitted from
  81988. ** the build, then none of the following routines, except for
  81989. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  81990. ** called with a NULL argument.
  81991. */
  81992. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  81993. || !defined(SQLITE_OMIT_SUBQUERY)
  81994. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  81995. SrcList *pNew;
  81996. int i;
  81997. int nByte;
  81998. assert( db!=0 );
  81999. if( p==0 ) return 0;
  82000. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  82001. pNew = sqlite3DbMallocRawNN(db, nByte );
  82002. if( pNew==0 ) return 0;
  82003. pNew->nSrc = pNew->nAlloc = p->nSrc;
  82004. for(i=0; i<p->nSrc; i++){
  82005. struct SrcList_item *pNewItem = &pNew->a[i];
  82006. struct SrcList_item *pOldItem = &p->a[i];
  82007. Table *pTab;
  82008. pNewItem->pSchema = pOldItem->pSchema;
  82009. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  82010. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  82011. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  82012. pNewItem->fg = pOldItem->fg;
  82013. pNewItem->iCursor = pOldItem->iCursor;
  82014. pNewItem->addrFillSub = pOldItem->addrFillSub;
  82015. pNewItem->regReturn = pOldItem->regReturn;
  82016. if( pNewItem->fg.isIndexedBy ){
  82017. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  82018. }
  82019. pNewItem->pIBIndex = pOldItem->pIBIndex;
  82020. if( pNewItem->fg.isTabFunc ){
  82021. pNewItem->u1.pFuncArg =
  82022. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  82023. }
  82024. pTab = pNewItem->pTab = pOldItem->pTab;
  82025. if( pTab ){
  82026. pTab->nRef++;
  82027. }
  82028. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  82029. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  82030. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  82031. pNewItem->colUsed = pOldItem->colUsed;
  82032. }
  82033. return pNew;
  82034. }
  82035. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  82036. IdList *pNew;
  82037. int i;
  82038. assert( db!=0 );
  82039. if( p==0 ) return 0;
  82040. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  82041. if( pNew==0 ) return 0;
  82042. pNew->nId = p->nId;
  82043. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  82044. if( pNew->a==0 ){
  82045. sqlite3DbFree(db, pNew);
  82046. return 0;
  82047. }
  82048. /* Note that because the size of the allocation for p->a[] is not
  82049. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  82050. ** on the duplicate created by this function. */
  82051. for(i=0; i<p->nId; i++){
  82052. struct IdList_item *pNewItem = &pNew->a[i];
  82053. struct IdList_item *pOldItem = &p->a[i];
  82054. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  82055. pNewItem->idx = pOldItem->idx;
  82056. }
  82057. return pNew;
  82058. }
  82059. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  82060. Select *pNew, *pPrior;
  82061. assert( db!=0 );
  82062. if( p==0 ) return 0;
  82063. pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  82064. if( pNew==0 ) return 0;
  82065. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  82066. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  82067. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  82068. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  82069. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  82070. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  82071. pNew->op = p->op;
  82072. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  82073. if( pPrior ) pPrior->pNext = pNew;
  82074. pNew->pNext = 0;
  82075. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  82076. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  82077. pNew->iLimit = 0;
  82078. pNew->iOffset = 0;
  82079. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  82080. pNew->addrOpenEphm[0] = -1;
  82081. pNew->addrOpenEphm[1] = -1;
  82082. pNew->nSelectRow = p->nSelectRow;
  82083. pNew->pWith = withDup(db, p->pWith);
  82084. sqlite3SelectSetName(pNew, p->zSelName);
  82085. return pNew;
  82086. }
  82087. #else
  82088. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  82089. assert( p==0 );
  82090. return 0;
  82091. }
  82092. #endif
  82093. /*
  82094. ** Add a new element to the end of an expression list. If pList is
  82095. ** initially NULL, then create a new expression list.
  82096. **
  82097. ** If a memory allocation error occurs, the entire list is freed and
  82098. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  82099. ** that the new entry was successfully appended.
  82100. */
  82101. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  82102. Parse *pParse, /* Parsing context */
  82103. ExprList *pList, /* List to which to append. Might be NULL */
  82104. Expr *pExpr /* Expression to be appended. Might be NULL */
  82105. ){
  82106. sqlite3 *db = pParse->db;
  82107. assert( db!=0 );
  82108. if( pList==0 ){
  82109. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  82110. if( pList==0 ){
  82111. goto no_mem;
  82112. }
  82113. pList->nExpr = 0;
  82114. pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
  82115. if( pList->a==0 ) goto no_mem;
  82116. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  82117. struct ExprList_item *a;
  82118. assert( pList->nExpr>0 );
  82119. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  82120. if( a==0 ){
  82121. goto no_mem;
  82122. }
  82123. pList->a = a;
  82124. }
  82125. assert( pList->a!=0 );
  82126. if( 1 ){
  82127. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  82128. memset(pItem, 0, sizeof(*pItem));
  82129. pItem->pExpr = pExpr;
  82130. }
  82131. return pList;
  82132. no_mem:
  82133. /* Avoid leaking memory if malloc has failed. */
  82134. sqlite3ExprDelete(db, pExpr);
  82135. sqlite3ExprListDelete(db, pList);
  82136. return 0;
  82137. }
  82138. /*
  82139. ** Set the sort order for the last element on the given ExprList.
  82140. */
  82141. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  82142. if( p==0 ) return;
  82143. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  82144. assert( p->nExpr>0 );
  82145. if( iSortOrder<0 ){
  82146. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  82147. return;
  82148. }
  82149. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  82150. }
  82151. /*
  82152. ** Set the ExprList.a[].zName element of the most recently added item
  82153. ** on the expression list.
  82154. **
  82155. ** pList might be NULL following an OOM error. But pName should never be
  82156. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  82157. ** is set.
  82158. */
  82159. SQLITE_PRIVATE void sqlite3ExprListSetName(
  82160. Parse *pParse, /* Parsing context */
  82161. ExprList *pList, /* List to which to add the span. */
  82162. Token *pName, /* Name to be added */
  82163. int dequote /* True to cause the name to be dequoted */
  82164. ){
  82165. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  82166. if( pList ){
  82167. struct ExprList_item *pItem;
  82168. assert( pList->nExpr>0 );
  82169. pItem = &pList->a[pList->nExpr-1];
  82170. assert( pItem->zName==0 );
  82171. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  82172. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  82173. }
  82174. }
  82175. /*
  82176. ** Set the ExprList.a[].zSpan element of the most recently added item
  82177. ** on the expression list.
  82178. **
  82179. ** pList might be NULL following an OOM error. But pSpan should never be
  82180. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  82181. ** is set.
  82182. */
  82183. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  82184. Parse *pParse, /* Parsing context */
  82185. ExprList *pList, /* List to which to add the span. */
  82186. ExprSpan *pSpan /* The span to be added */
  82187. ){
  82188. sqlite3 *db = pParse->db;
  82189. assert( pList!=0 || db->mallocFailed!=0 );
  82190. if( pList ){
  82191. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  82192. assert( pList->nExpr>0 );
  82193. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  82194. sqlite3DbFree(db, pItem->zSpan);
  82195. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  82196. (int)(pSpan->zEnd - pSpan->zStart));
  82197. }
  82198. }
  82199. /*
  82200. ** If the expression list pEList contains more than iLimit elements,
  82201. ** leave an error message in pParse.
  82202. */
  82203. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  82204. Parse *pParse,
  82205. ExprList *pEList,
  82206. const char *zObject
  82207. ){
  82208. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  82209. testcase( pEList && pEList->nExpr==mx );
  82210. testcase( pEList && pEList->nExpr==mx+1 );
  82211. if( pEList && pEList->nExpr>mx ){
  82212. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  82213. }
  82214. }
  82215. /*
  82216. ** Delete an entire expression list.
  82217. */
  82218. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  82219. int i;
  82220. struct ExprList_item *pItem;
  82221. if( pList==0 ) return;
  82222. assert( pList->a!=0 || pList->nExpr==0 );
  82223. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  82224. sqlite3ExprDelete(db, pItem->pExpr);
  82225. sqlite3DbFree(db, pItem->zName);
  82226. sqlite3DbFree(db, pItem->zSpan);
  82227. }
  82228. sqlite3DbFree(db, pList->a);
  82229. sqlite3DbFree(db, pList);
  82230. }
  82231. /*
  82232. ** Return the bitwise-OR of all Expr.flags fields in the given
  82233. ** ExprList.
  82234. */
  82235. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  82236. int i;
  82237. u32 m = 0;
  82238. if( pList ){
  82239. for(i=0; i<pList->nExpr; i++){
  82240. Expr *pExpr = pList->a[i].pExpr;
  82241. assert( pExpr!=0 );
  82242. m |= pExpr->flags;
  82243. }
  82244. }
  82245. return m;
  82246. }
  82247. /*
  82248. ** These routines are Walker callbacks used to check expressions to
  82249. ** see if they are "constant" for some definition of constant. The
  82250. ** Walker.eCode value determines the type of "constant" we are looking
  82251. ** for.
  82252. **
  82253. ** These callback routines are used to implement the following:
  82254. **
  82255. ** sqlite3ExprIsConstant() pWalker->eCode==1
  82256. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  82257. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  82258. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  82259. **
  82260. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  82261. ** is found to not be a constant.
  82262. **
  82263. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  82264. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  82265. ** an existing schema and 4 when processing a new statement. A bound
  82266. ** parameter raises an error for new statements, but is silently converted
  82267. ** to NULL for existing schemas. This allows sqlite_master tables that
  82268. ** contain a bound parameter because they were generated by older versions
  82269. ** of SQLite to be parsed by newer versions of SQLite without raising a
  82270. ** malformed schema error.
  82271. */
  82272. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  82273. /* If pWalker->eCode is 2 then any term of the expression that comes from
  82274. ** the ON or USING clauses of a left join disqualifies the expression
  82275. ** from being considered constant. */
  82276. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  82277. pWalker->eCode = 0;
  82278. return WRC_Abort;
  82279. }
  82280. switch( pExpr->op ){
  82281. /* Consider functions to be constant if all their arguments are constant
  82282. ** and either pWalker->eCode==4 or 5 or the function has the
  82283. ** SQLITE_FUNC_CONST flag. */
  82284. case TK_FUNCTION:
  82285. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  82286. return WRC_Continue;
  82287. }else{
  82288. pWalker->eCode = 0;
  82289. return WRC_Abort;
  82290. }
  82291. case TK_ID:
  82292. case TK_COLUMN:
  82293. case TK_AGG_FUNCTION:
  82294. case TK_AGG_COLUMN:
  82295. testcase( pExpr->op==TK_ID );
  82296. testcase( pExpr->op==TK_COLUMN );
  82297. testcase( pExpr->op==TK_AGG_FUNCTION );
  82298. testcase( pExpr->op==TK_AGG_COLUMN );
  82299. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  82300. return WRC_Continue;
  82301. }else{
  82302. pWalker->eCode = 0;
  82303. return WRC_Abort;
  82304. }
  82305. case TK_VARIABLE:
  82306. if( pWalker->eCode==5 ){
  82307. /* Silently convert bound parameters that appear inside of CREATE
  82308. ** statements into a NULL when parsing the CREATE statement text out
  82309. ** of the sqlite_master table */
  82310. pExpr->op = TK_NULL;
  82311. }else if( pWalker->eCode==4 ){
  82312. /* A bound parameter in a CREATE statement that originates from
  82313. ** sqlite3_prepare() causes an error */
  82314. pWalker->eCode = 0;
  82315. return WRC_Abort;
  82316. }
  82317. /* Fall through */
  82318. default:
  82319. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  82320. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  82321. return WRC_Continue;
  82322. }
  82323. }
  82324. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  82325. UNUSED_PARAMETER(NotUsed);
  82326. pWalker->eCode = 0;
  82327. return WRC_Abort;
  82328. }
  82329. static int exprIsConst(Expr *p, int initFlag, int iCur){
  82330. Walker w;
  82331. memset(&w, 0, sizeof(w));
  82332. w.eCode = initFlag;
  82333. w.xExprCallback = exprNodeIsConstant;
  82334. w.xSelectCallback = selectNodeIsConstant;
  82335. w.u.iCur = iCur;
  82336. sqlite3WalkExpr(&w, p);
  82337. return w.eCode;
  82338. }
  82339. /*
  82340. ** Walk an expression tree. Return non-zero if the expression is constant
  82341. ** and 0 if it involves variables or function calls.
  82342. **
  82343. ** For the purposes of this function, a double-quoted string (ex: "abc")
  82344. ** is considered a variable but a single-quoted string (ex: 'abc') is
  82345. ** a constant.
  82346. */
  82347. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  82348. return exprIsConst(p, 1, 0);
  82349. }
  82350. /*
  82351. ** Walk an expression tree. Return non-zero if the expression is constant
  82352. ** that does no originate from the ON or USING clauses of a join.
  82353. ** Return 0 if it involves variables or function calls or terms from
  82354. ** an ON or USING clause.
  82355. */
  82356. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  82357. return exprIsConst(p, 2, 0);
  82358. }
  82359. /*
  82360. ** Walk an expression tree. Return non-zero if the expression is constant
  82361. ** for any single row of the table with cursor iCur. In other words, the
  82362. ** expression must not refer to any non-deterministic function nor any
  82363. ** table other than iCur.
  82364. */
  82365. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  82366. return exprIsConst(p, 3, iCur);
  82367. }
  82368. /*
  82369. ** Walk an expression tree. Return non-zero if the expression is constant
  82370. ** or a function call with constant arguments. Return and 0 if there
  82371. ** are any variables.
  82372. **
  82373. ** For the purposes of this function, a double-quoted string (ex: "abc")
  82374. ** is considered a variable but a single-quoted string (ex: 'abc') is
  82375. ** a constant.
  82376. */
  82377. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  82378. assert( isInit==0 || isInit==1 );
  82379. return exprIsConst(p, 4+isInit, 0);
  82380. }
  82381. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  82382. /*
  82383. ** Walk an expression tree. Return 1 if the expression contains a
  82384. ** subquery of some kind. Return 0 if there are no subqueries.
  82385. */
  82386. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  82387. Walker w;
  82388. memset(&w, 0, sizeof(w));
  82389. w.eCode = 1;
  82390. w.xExprCallback = sqlite3ExprWalkNoop;
  82391. w.xSelectCallback = selectNodeIsConstant;
  82392. sqlite3WalkExpr(&w, p);
  82393. return w.eCode==0;
  82394. }
  82395. #endif
  82396. /*
  82397. ** If the expression p codes a constant integer that is small enough
  82398. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  82399. ** in *pValue. If the expression is not an integer or if it is too big
  82400. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  82401. */
  82402. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  82403. int rc = 0;
  82404. /* If an expression is an integer literal that fits in a signed 32-bit
  82405. ** integer, then the EP_IntValue flag will have already been set */
  82406. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  82407. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  82408. if( p->flags & EP_IntValue ){
  82409. *pValue = p->u.iValue;
  82410. return 1;
  82411. }
  82412. switch( p->op ){
  82413. case TK_UPLUS: {
  82414. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  82415. break;
  82416. }
  82417. case TK_UMINUS: {
  82418. int v;
  82419. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  82420. assert( v!=(-2147483647-1) );
  82421. *pValue = -v;
  82422. rc = 1;
  82423. }
  82424. break;
  82425. }
  82426. default: break;
  82427. }
  82428. return rc;
  82429. }
  82430. /*
  82431. ** Return FALSE if there is no chance that the expression can be NULL.
  82432. **
  82433. ** If the expression might be NULL or if the expression is too complex
  82434. ** to tell return TRUE.
  82435. **
  82436. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  82437. ** when we know that a value cannot be NULL. Hence, a false positive
  82438. ** (returning TRUE when in fact the expression can never be NULL) might
  82439. ** be a small performance hit but is otherwise harmless. On the other
  82440. ** hand, a false negative (returning FALSE when the result could be NULL)
  82441. ** will likely result in an incorrect answer. So when in doubt, return
  82442. ** TRUE.
  82443. */
  82444. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  82445. u8 op;
  82446. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  82447. op = p->op;
  82448. if( op==TK_REGISTER ) op = p->op2;
  82449. switch( op ){
  82450. case TK_INTEGER:
  82451. case TK_STRING:
  82452. case TK_FLOAT:
  82453. case TK_BLOB:
  82454. return 0;
  82455. case TK_COLUMN:
  82456. assert( p->pTab!=0 );
  82457. return ExprHasProperty(p, EP_CanBeNull) ||
  82458. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  82459. default:
  82460. return 1;
  82461. }
  82462. }
  82463. /*
  82464. ** Return TRUE if the given expression is a constant which would be
  82465. ** unchanged by OP_Affinity with the affinity given in the second
  82466. ** argument.
  82467. **
  82468. ** This routine is used to determine if the OP_Affinity operation
  82469. ** can be omitted. When in doubt return FALSE. A false negative
  82470. ** is harmless. A false positive, however, can result in the wrong
  82471. ** answer.
  82472. */
  82473. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  82474. u8 op;
  82475. if( aff==SQLITE_AFF_BLOB ) return 1;
  82476. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  82477. op = p->op;
  82478. if( op==TK_REGISTER ) op = p->op2;
  82479. switch( op ){
  82480. case TK_INTEGER: {
  82481. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  82482. }
  82483. case TK_FLOAT: {
  82484. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  82485. }
  82486. case TK_STRING: {
  82487. return aff==SQLITE_AFF_TEXT;
  82488. }
  82489. case TK_BLOB: {
  82490. return 1;
  82491. }
  82492. case TK_COLUMN: {
  82493. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  82494. return p->iColumn<0
  82495. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  82496. }
  82497. default: {
  82498. return 0;
  82499. }
  82500. }
  82501. }
  82502. /*
  82503. ** Return TRUE if the given string is a row-id column name.
  82504. */
  82505. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  82506. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  82507. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  82508. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  82509. return 0;
  82510. }
  82511. /*
  82512. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  82513. ** that can be simplified to a direct table access, then return
  82514. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  82515. ** or if the SELECT statement needs to be manifested into a transient
  82516. ** table, then return NULL.
  82517. */
  82518. #ifndef SQLITE_OMIT_SUBQUERY
  82519. static Select *isCandidateForInOpt(Expr *pX){
  82520. Select *p;
  82521. SrcList *pSrc;
  82522. ExprList *pEList;
  82523. Expr *pRes;
  82524. Table *pTab;
  82525. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  82526. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  82527. p = pX->x.pSelect;
  82528. if( p->pPrior ) return 0; /* Not a compound SELECT */
  82529. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  82530. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  82531. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  82532. return 0; /* No DISTINCT keyword and no aggregate functions */
  82533. }
  82534. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  82535. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  82536. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  82537. if( p->pWhere ) return 0; /* Has no WHERE clause */
  82538. pSrc = p->pSrc;
  82539. assert( pSrc!=0 );
  82540. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  82541. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  82542. pTab = pSrc->a[0].pTab;
  82543. assert( pTab!=0 );
  82544. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  82545. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  82546. pEList = p->pEList;
  82547. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  82548. pRes = pEList->a[0].pExpr;
  82549. if( pRes->op!=TK_COLUMN ) return 0; /* Result is a column */
  82550. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  82551. return p;
  82552. }
  82553. #endif /* SQLITE_OMIT_SUBQUERY */
  82554. /*
  82555. ** Code an OP_Once instruction and allocate space for its flag. Return the
  82556. ** address of the new instruction.
  82557. */
  82558. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  82559. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  82560. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  82561. }
  82562. /*
  82563. ** Generate code that checks the left-most column of index table iCur to see if
  82564. ** it contains any NULL entries. Cause the register at regHasNull to be set
  82565. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  82566. ** to be set to NULL if iCur contains one or more NULL values.
  82567. */
  82568. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  82569. int addr1;
  82570. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  82571. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  82572. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  82573. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  82574. VdbeComment((v, "first_entry_in(%d)", iCur));
  82575. sqlite3VdbeJumpHere(v, addr1);
  82576. }
  82577. #ifndef SQLITE_OMIT_SUBQUERY
  82578. /*
  82579. ** The argument is an IN operator with a list (not a subquery) on the
  82580. ** right-hand side. Return TRUE if that list is constant.
  82581. */
  82582. static int sqlite3InRhsIsConstant(Expr *pIn){
  82583. Expr *pLHS;
  82584. int res;
  82585. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  82586. pLHS = pIn->pLeft;
  82587. pIn->pLeft = 0;
  82588. res = sqlite3ExprIsConstant(pIn);
  82589. pIn->pLeft = pLHS;
  82590. return res;
  82591. }
  82592. #endif
  82593. /*
  82594. ** This function is used by the implementation of the IN (...) operator.
  82595. ** The pX parameter is the expression on the RHS of the IN operator, which
  82596. ** might be either a list of expressions or a subquery.
  82597. **
  82598. ** The job of this routine is to find or create a b-tree object that can
  82599. ** be used either to test for membership in the RHS set or to iterate through
  82600. ** all members of the RHS set, skipping duplicates.
  82601. **
  82602. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  82603. ** and pX->iTable is set to the index of that cursor.
  82604. **
  82605. ** The returned value of this function indicates the b-tree type, as follows:
  82606. **
  82607. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  82608. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  82609. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  82610. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  82611. ** populated epheremal table.
  82612. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  82613. ** implemented as a sequence of comparisons.
  82614. **
  82615. ** An existing b-tree might be used if the RHS expression pX is a simple
  82616. ** subquery such as:
  82617. **
  82618. ** SELECT <column> FROM <table>
  82619. **
  82620. ** If the RHS of the IN operator is a list or a more complex subquery, then
  82621. ** an ephemeral table might need to be generated from the RHS and then
  82622. ** pX->iTable made to point to the ephemeral table instead of an
  82623. ** existing table.
  82624. **
  82625. ** The inFlags parameter must contain exactly one of the bits
  82626. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  82627. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  82628. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  82629. ** IN index will be used to loop over all values of the RHS of the
  82630. ** IN operator.
  82631. **
  82632. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  82633. ** through the set members) then the b-tree must not contain duplicates.
  82634. ** An epheremal table must be used unless the selected <column> is guaranteed
  82635. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  82636. ** has a UNIQUE constraint or UNIQUE index.
  82637. **
  82638. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  82639. ** for fast set membership tests) then an epheremal table must
  82640. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  82641. ** be found with <column> as its left-most column.
  82642. **
  82643. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  82644. ** if the RHS of the IN operator is a list (not a subquery) then this
  82645. ** routine might decide that creating an ephemeral b-tree for membership
  82646. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  82647. ** calling routine should implement the IN operator using a sequence
  82648. ** of Eq or Ne comparison operations.
  82649. **
  82650. ** When the b-tree is being used for membership tests, the calling function
  82651. ** might need to know whether or not the RHS side of the IN operator
  82652. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  82653. ** if there is any chance that the (...) might contain a NULL value at
  82654. ** runtime, then a register is allocated and the register number written
  82655. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  82656. ** NULL value, then *prRhsHasNull is left unchanged.
  82657. **
  82658. ** If a register is allocated and its location stored in *prRhsHasNull, then
  82659. ** the value in that register will be NULL if the b-tree contains one or more
  82660. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  82661. ** NULL values.
  82662. */
  82663. #ifndef SQLITE_OMIT_SUBQUERY
  82664. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  82665. Select *p; /* SELECT to the right of IN operator */
  82666. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  82667. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  82668. int mustBeUnique; /* True if RHS must be unique */
  82669. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  82670. assert( pX->op==TK_IN );
  82671. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  82672. /* Check to see if an existing table or index can be used to
  82673. ** satisfy the query. This is preferable to generating a new
  82674. ** ephemeral table.
  82675. */
  82676. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  82677. sqlite3 *db = pParse->db; /* Database connection */
  82678. Table *pTab; /* Table <table>. */
  82679. Expr *pExpr; /* Expression <column> */
  82680. i16 iCol; /* Index of column <column> */
  82681. i16 iDb; /* Database idx for pTab */
  82682. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  82683. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  82684. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  82685. pTab = p->pSrc->a[0].pTab;
  82686. pExpr = p->pEList->a[0].pExpr;
  82687. iCol = (i16)pExpr->iColumn;
  82688. /* Code an OP_Transaction and OP_TableLock for <table>. */
  82689. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  82690. sqlite3CodeVerifySchema(pParse, iDb);
  82691. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  82692. /* This function is only called from two places. In both cases the vdbe
  82693. ** has already been allocated. So assume sqlite3GetVdbe() is always
  82694. ** successful here.
  82695. */
  82696. assert(v);
  82697. if( iCol<0 ){
  82698. int iAddr = sqlite3CodeOnce(pParse);
  82699. VdbeCoverage(v);
  82700. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  82701. eType = IN_INDEX_ROWID;
  82702. sqlite3VdbeJumpHere(v, iAddr);
  82703. }else{
  82704. Index *pIdx; /* Iterator variable */
  82705. /* The collation sequence used by the comparison. If an index is to
  82706. ** be used in place of a temp-table, it must be ordered according
  82707. ** to this collation sequence. */
  82708. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  82709. /* Check that the affinity that will be used to perform the
  82710. ** comparison is the same as the affinity of the column. If
  82711. ** it is not, it is not possible to use any index.
  82712. */
  82713. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  82714. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  82715. if( (pIdx->aiColumn[0]==iCol)
  82716. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  82717. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  82718. ){
  82719. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  82720. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  82721. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  82722. VdbeComment((v, "%s", pIdx->zName));
  82723. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  82724. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  82725. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  82726. *prRhsHasNull = ++pParse->nMem;
  82727. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  82728. }
  82729. sqlite3VdbeJumpHere(v, iAddr);
  82730. }
  82731. }
  82732. }
  82733. }
  82734. /* If no preexisting index is available for the IN clause
  82735. ** and IN_INDEX_NOOP is an allowed reply
  82736. ** and the RHS of the IN operator is a list, not a subquery
  82737. ** and the RHS is not contant or has two or fewer terms,
  82738. ** then it is not worth creating an ephemeral table to evaluate
  82739. ** the IN operator so return IN_INDEX_NOOP.
  82740. */
  82741. if( eType==0
  82742. && (inFlags & IN_INDEX_NOOP_OK)
  82743. && !ExprHasProperty(pX, EP_xIsSelect)
  82744. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  82745. ){
  82746. eType = IN_INDEX_NOOP;
  82747. }
  82748. if( eType==0 ){
  82749. /* Could not find an existing table or index to use as the RHS b-tree.
  82750. ** We will have to generate an ephemeral table to do the job.
  82751. */
  82752. u32 savedNQueryLoop = pParse->nQueryLoop;
  82753. int rMayHaveNull = 0;
  82754. eType = IN_INDEX_EPH;
  82755. if( inFlags & IN_INDEX_LOOP ){
  82756. pParse->nQueryLoop = 0;
  82757. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  82758. eType = IN_INDEX_ROWID;
  82759. }
  82760. }else if( prRhsHasNull ){
  82761. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  82762. }
  82763. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  82764. pParse->nQueryLoop = savedNQueryLoop;
  82765. }else{
  82766. pX->iTable = iTab;
  82767. }
  82768. return eType;
  82769. }
  82770. #endif
  82771. /*
  82772. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  82773. ** or IN operators. Examples:
  82774. **
  82775. ** (SELECT a FROM b) -- subquery
  82776. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  82777. ** x IN (4,5,11) -- IN operator with list on right-hand side
  82778. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  82779. **
  82780. ** The pExpr parameter describes the expression that contains the IN
  82781. ** operator or subquery.
  82782. **
  82783. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  82784. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  82785. ** to some integer key column of a table B-Tree. In this case, use an
  82786. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  82787. ** (slower) variable length keys B-Tree.
  82788. **
  82789. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  82790. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  82791. ** All this routine does is initialize the register given by rMayHaveNull
  82792. ** to NULL. Calling routines will take care of changing this register
  82793. ** value to non-NULL if the RHS is NULL-free.
  82794. **
  82795. ** For a SELECT or EXISTS operator, return the register that holds the
  82796. ** result. For IN operators or if an error occurs, the return value is 0.
  82797. */
  82798. #ifndef SQLITE_OMIT_SUBQUERY
  82799. SQLITE_PRIVATE int sqlite3CodeSubselect(
  82800. Parse *pParse, /* Parsing context */
  82801. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  82802. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  82803. int isRowid /* If true, LHS of IN operator is a rowid */
  82804. ){
  82805. int jmpIfDynamic = -1; /* One-time test address */
  82806. int rReg = 0; /* Register storing resulting */
  82807. Vdbe *v = sqlite3GetVdbe(pParse);
  82808. if( NEVER(v==0) ) return 0;
  82809. sqlite3ExprCachePush(pParse);
  82810. /* This code must be run in its entirety every time it is encountered
  82811. ** if any of the following is true:
  82812. **
  82813. ** * The right-hand side is a correlated subquery
  82814. ** * The right-hand side is an expression list containing variables
  82815. ** * We are inside a trigger
  82816. **
  82817. ** If all of the above are false, then we can run this code just once
  82818. ** save the results, and reuse the same result on subsequent invocations.
  82819. */
  82820. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  82821. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  82822. }
  82823. #ifndef SQLITE_OMIT_EXPLAIN
  82824. if( pParse->explain==2 ){
  82825. char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
  82826. jmpIfDynamic>=0?"":"CORRELATED ",
  82827. pExpr->op==TK_IN?"LIST":"SCALAR",
  82828. pParse->iNextSelectId
  82829. );
  82830. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  82831. }
  82832. #endif
  82833. switch( pExpr->op ){
  82834. case TK_IN: {
  82835. char affinity; /* Affinity of the LHS of the IN */
  82836. int addr; /* Address of OP_OpenEphemeral instruction */
  82837. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  82838. KeyInfo *pKeyInfo = 0; /* Key information */
  82839. affinity = sqlite3ExprAffinity(pLeft);
  82840. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  82841. ** expression it is handled the same way. An ephemeral table is
  82842. ** filled with single-field index keys representing the results
  82843. ** from the SELECT or the <exprlist>.
  82844. **
  82845. ** If the 'x' expression is a column value, or the SELECT...
  82846. ** statement returns a column value, then the affinity of that
  82847. ** column is used to build the index keys. If both 'x' and the
  82848. ** SELECT... statement are columns, then numeric affinity is used
  82849. ** if either column has NUMERIC or INTEGER affinity. If neither
  82850. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  82851. ** is used.
  82852. */
  82853. pExpr->iTable = pParse->nTab++;
  82854. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  82855. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  82856. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  82857. /* Case 1: expr IN (SELECT ...)
  82858. **
  82859. ** Generate code to write the results of the select into the temporary
  82860. ** table allocated and opened above.
  82861. */
  82862. Select *pSelect = pExpr->x.pSelect;
  82863. SelectDest dest;
  82864. ExprList *pEList;
  82865. assert( !isRowid );
  82866. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  82867. dest.affSdst = (u8)affinity;
  82868. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  82869. pSelect->iLimit = 0;
  82870. testcase( pSelect->selFlags & SF_Distinct );
  82871. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  82872. if( sqlite3Select(pParse, pSelect, &dest) ){
  82873. sqlite3KeyInfoUnref(pKeyInfo);
  82874. return 0;
  82875. }
  82876. pEList = pSelect->pEList;
  82877. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  82878. assert( pEList!=0 );
  82879. assert( pEList->nExpr>0 );
  82880. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  82881. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  82882. pEList->a[0].pExpr);
  82883. }else if( ALWAYS(pExpr->x.pList!=0) ){
  82884. /* Case 2: expr IN (exprlist)
  82885. **
  82886. ** For each expression, build an index key from the evaluation and
  82887. ** store it in the temporary table. If <expr> is a column, then use
  82888. ** that columns affinity when building index keys. If <expr> is not
  82889. ** a column, use numeric affinity.
  82890. */
  82891. int i;
  82892. ExprList *pList = pExpr->x.pList;
  82893. struct ExprList_item *pItem;
  82894. int r1, r2, r3;
  82895. if( !affinity ){
  82896. affinity = SQLITE_AFF_BLOB;
  82897. }
  82898. if( pKeyInfo ){
  82899. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  82900. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  82901. }
  82902. /* Loop through each expression in <exprlist>. */
  82903. r1 = sqlite3GetTempReg(pParse);
  82904. r2 = sqlite3GetTempReg(pParse);
  82905. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  82906. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  82907. Expr *pE2 = pItem->pExpr;
  82908. int iValToIns;
  82909. /* If the expression is not constant then we will need to
  82910. ** disable the test that was generated above that makes sure
  82911. ** this code only executes once. Because for a non-constant
  82912. ** expression we need to rerun this code each time.
  82913. */
  82914. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  82915. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  82916. jmpIfDynamic = -1;
  82917. }
  82918. /* Evaluate the expression and insert it into the temp table */
  82919. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  82920. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  82921. }else{
  82922. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  82923. if( isRowid ){
  82924. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  82925. sqlite3VdbeCurrentAddr(v)+2);
  82926. VdbeCoverage(v);
  82927. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  82928. }else{
  82929. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  82930. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  82931. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  82932. }
  82933. }
  82934. }
  82935. sqlite3ReleaseTempReg(pParse, r1);
  82936. sqlite3ReleaseTempReg(pParse, r2);
  82937. }
  82938. if( pKeyInfo ){
  82939. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  82940. }
  82941. break;
  82942. }
  82943. case TK_EXISTS:
  82944. case TK_SELECT:
  82945. default: {
  82946. /* If this has to be a scalar SELECT. Generate code to put the
  82947. ** value of this select in a memory cell and record the number
  82948. ** of the memory cell in iColumn. If this is an EXISTS, write
  82949. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  82950. ** and record that memory cell in iColumn.
  82951. */
  82952. Select *pSel; /* SELECT statement to encode */
  82953. SelectDest dest; /* How to deal with SELECt result */
  82954. testcase( pExpr->op==TK_EXISTS );
  82955. testcase( pExpr->op==TK_SELECT );
  82956. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  82957. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  82958. pSel = pExpr->x.pSelect;
  82959. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  82960. if( pExpr->op==TK_SELECT ){
  82961. dest.eDest = SRT_Mem;
  82962. dest.iSdst = dest.iSDParm;
  82963. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  82964. VdbeComment((v, "Init subquery result"));
  82965. }else{
  82966. dest.eDest = SRT_Exists;
  82967. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  82968. VdbeComment((v, "Init EXISTS result"));
  82969. }
  82970. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  82971. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  82972. &sqlite3IntTokens[1]);
  82973. pSel->iLimit = 0;
  82974. pSel->selFlags &= ~SF_MultiValue;
  82975. if( sqlite3Select(pParse, pSel, &dest) ){
  82976. return 0;
  82977. }
  82978. rReg = dest.iSDParm;
  82979. ExprSetVVAProperty(pExpr, EP_NoReduce);
  82980. break;
  82981. }
  82982. }
  82983. if( rHasNullFlag ){
  82984. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  82985. }
  82986. if( jmpIfDynamic>=0 ){
  82987. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  82988. }
  82989. sqlite3ExprCachePop(pParse);
  82990. return rReg;
  82991. }
  82992. #endif /* SQLITE_OMIT_SUBQUERY */
  82993. #ifndef SQLITE_OMIT_SUBQUERY
  82994. /*
  82995. ** Generate code for an IN expression.
  82996. **
  82997. ** x IN (SELECT ...)
  82998. ** x IN (value, value, ...)
  82999. **
  83000. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  83001. ** is an array of zero or more values. The expression is true if the LHS is
  83002. ** contained within the RHS. The value of the expression is unknown (NULL)
  83003. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  83004. ** RHS contains one or more NULL values.
  83005. **
  83006. ** This routine generates code that jumps to destIfFalse if the LHS is not
  83007. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  83008. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  83009. ** within the RHS then fall through.
  83010. */
  83011. static void sqlite3ExprCodeIN(
  83012. Parse *pParse, /* Parsing and code generating context */
  83013. Expr *pExpr, /* The IN expression */
  83014. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  83015. int destIfNull /* Jump here if the results are unknown due to NULLs */
  83016. ){
  83017. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  83018. char affinity; /* Comparison affinity to use */
  83019. int eType; /* Type of the RHS */
  83020. int r1; /* Temporary use register */
  83021. Vdbe *v; /* Statement under construction */
  83022. /* Compute the RHS. After this step, the table with cursor
  83023. ** pExpr->iTable will contains the values that make up the RHS.
  83024. */
  83025. v = pParse->pVdbe;
  83026. assert( v!=0 ); /* OOM detected prior to this routine */
  83027. VdbeNoopComment((v, "begin IN expr"));
  83028. eType = sqlite3FindInIndex(pParse, pExpr,
  83029. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  83030. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  83031. /* Figure out the affinity to use to create a key from the results
  83032. ** of the expression. affinityStr stores a static string suitable for
  83033. ** P4 of OP_MakeRecord.
  83034. */
  83035. affinity = comparisonAffinity(pExpr);
  83036. /* Code the LHS, the <expr> from "<expr> IN (...)".
  83037. */
  83038. sqlite3ExprCachePush(pParse);
  83039. r1 = sqlite3GetTempReg(pParse);
  83040. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  83041. /* If sqlite3FindInIndex() did not find or create an index that is
  83042. ** suitable for evaluating the IN operator, then evaluate using a
  83043. ** sequence of comparisons.
  83044. */
  83045. if( eType==IN_INDEX_NOOP ){
  83046. ExprList *pList = pExpr->x.pList;
  83047. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  83048. int labelOk = sqlite3VdbeMakeLabel(v);
  83049. int r2, regToFree;
  83050. int regCkNull = 0;
  83051. int ii;
  83052. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  83053. if( destIfNull!=destIfFalse ){
  83054. regCkNull = sqlite3GetTempReg(pParse);
  83055. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  83056. }
  83057. for(ii=0; ii<pList->nExpr; ii++){
  83058. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  83059. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  83060. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  83061. }
  83062. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  83063. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  83064. (void*)pColl, P4_COLLSEQ);
  83065. VdbeCoverageIf(v, ii<pList->nExpr-1);
  83066. VdbeCoverageIf(v, ii==pList->nExpr-1);
  83067. sqlite3VdbeChangeP5(v, affinity);
  83068. }else{
  83069. assert( destIfNull==destIfFalse );
  83070. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  83071. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  83072. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  83073. }
  83074. sqlite3ReleaseTempReg(pParse, regToFree);
  83075. }
  83076. if( regCkNull ){
  83077. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  83078. sqlite3VdbeGoto(v, destIfFalse);
  83079. }
  83080. sqlite3VdbeResolveLabel(v, labelOk);
  83081. sqlite3ReleaseTempReg(pParse, regCkNull);
  83082. }else{
  83083. /* If the LHS is NULL, then the result is either false or NULL depending
  83084. ** on whether the RHS is empty or not, respectively.
  83085. */
  83086. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  83087. if( destIfNull==destIfFalse ){
  83088. /* Shortcut for the common case where the false and NULL outcomes are
  83089. ** the same. */
  83090. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  83091. }else{
  83092. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  83093. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  83094. VdbeCoverage(v);
  83095. sqlite3VdbeGoto(v, destIfNull);
  83096. sqlite3VdbeJumpHere(v, addr1);
  83097. }
  83098. }
  83099. if( eType==IN_INDEX_ROWID ){
  83100. /* In this case, the RHS is the ROWID of table b-tree
  83101. */
  83102. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  83103. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  83104. VdbeCoverage(v);
  83105. }else{
  83106. /* In this case, the RHS is an index b-tree.
  83107. */
  83108. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  83109. /* If the set membership test fails, then the result of the
  83110. ** "x IN (...)" expression must be either 0 or NULL. If the set
  83111. ** contains no NULL values, then the result is 0. If the set
  83112. ** contains one or more NULL values, then the result of the
  83113. ** expression is also NULL.
  83114. */
  83115. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  83116. if( rRhsHasNull==0 ){
  83117. /* This branch runs if it is known at compile time that the RHS
  83118. ** cannot contain NULL values. This happens as the result
  83119. ** of a "NOT NULL" constraint in the database schema.
  83120. **
  83121. ** Also run this branch if NULL is equivalent to FALSE
  83122. ** for this particular IN operator.
  83123. */
  83124. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  83125. VdbeCoverage(v);
  83126. }else{
  83127. /* In this branch, the RHS of the IN might contain a NULL and
  83128. ** the presence of a NULL on the RHS makes a difference in the
  83129. ** outcome.
  83130. */
  83131. int addr1;
  83132. /* First check to see if the LHS is contained in the RHS. If so,
  83133. ** then the answer is TRUE the presence of NULLs in the RHS does
  83134. ** not matter. If the LHS is not contained in the RHS, then the
  83135. ** answer is NULL if the RHS contains NULLs and the answer is
  83136. ** FALSE if the RHS is NULL-free.
  83137. */
  83138. addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  83139. VdbeCoverage(v);
  83140. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  83141. VdbeCoverage(v);
  83142. sqlite3VdbeGoto(v, destIfFalse);
  83143. sqlite3VdbeJumpHere(v, addr1);
  83144. }
  83145. }
  83146. }
  83147. sqlite3ReleaseTempReg(pParse, r1);
  83148. sqlite3ExprCachePop(pParse);
  83149. VdbeComment((v, "end IN expr"));
  83150. }
  83151. #endif /* SQLITE_OMIT_SUBQUERY */
  83152. #ifndef SQLITE_OMIT_FLOATING_POINT
  83153. /*
  83154. ** Generate an instruction that will put the floating point
  83155. ** value described by z[0..n-1] into register iMem.
  83156. **
  83157. ** The z[] string will probably not be zero-terminated. But the
  83158. ** z[n] character is guaranteed to be something that does not look
  83159. ** like the continuation of the number.
  83160. */
  83161. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  83162. if( ALWAYS(z!=0) ){
  83163. double value;
  83164. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  83165. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  83166. if( negateFlag ) value = -value;
  83167. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  83168. }
  83169. }
  83170. #endif
  83171. /*
  83172. ** Generate an instruction that will put the integer describe by
  83173. ** text z[0..n-1] into register iMem.
  83174. **
  83175. ** Expr.u.zToken is always UTF8 and zero-terminated.
  83176. */
  83177. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  83178. Vdbe *v = pParse->pVdbe;
  83179. if( pExpr->flags & EP_IntValue ){
  83180. int i = pExpr->u.iValue;
  83181. assert( i>=0 );
  83182. if( negFlag ) i = -i;
  83183. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  83184. }else{
  83185. int c;
  83186. i64 value;
  83187. const char *z = pExpr->u.zToken;
  83188. assert( z!=0 );
  83189. c = sqlite3DecOrHexToI64(z, &value);
  83190. if( c==0 || (c==2 && negFlag) ){
  83191. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  83192. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  83193. }else{
  83194. #ifdef SQLITE_OMIT_FLOATING_POINT
  83195. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  83196. #else
  83197. #ifndef SQLITE_OMIT_HEX_INTEGER
  83198. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  83199. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  83200. }else
  83201. #endif
  83202. {
  83203. codeReal(v, z, negFlag, iMem);
  83204. }
  83205. #endif
  83206. }
  83207. }
  83208. }
  83209. /*
  83210. ** Clear a cache entry.
  83211. */
  83212. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  83213. if( p->tempReg ){
  83214. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  83215. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  83216. }
  83217. p->tempReg = 0;
  83218. }
  83219. }
  83220. /*
  83221. ** Record in the column cache that a particular column from a
  83222. ** particular table is stored in a particular register.
  83223. */
  83224. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  83225. int i;
  83226. int minLru;
  83227. int idxLru;
  83228. struct yColCache *p;
  83229. /* Unless an error has occurred, register numbers are always positive. */
  83230. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  83231. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  83232. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  83233. ** for testing only - to verify that SQLite always gets the same answer
  83234. ** with and without the column cache.
  83235. */
  83236. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  83237. /* First replace any existing entry.
  83238. **
  83239. ** Actually, the way the column cache is currently used, we are guaranteed
  83240. ** that the object will never already be in cache. Verify this guarantee.
  83241. */
  83242. #ifndef NDEBUG
  83243. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83244. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  83245. }
  83246. #endif
  83247. /* Find an empty slot and replace it */
  83248. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83249. if( p->iReg==0 ){
  83250. p->iLevel = pParse->iCacheLevel;
  83251. p->iTable = iTab;
  83252. p->iColumn = iCol;
  83253. p->iReg = iReg;
  83254. p->tempReg = 0;
  83255. p->lru = pParse->iCacheCnt++;
  83256. return;
  83257. }
  83258. }
  83259. /* Replace the last recently used */
  83260. minLru = 0x7fffffff;
  83261. idxLru = -1;
  83262. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83263. if( p->lru<minLru ){
  83264. idxLru = i;
  83265. minLru = p->lru;
  83266. }
  83267. }
  83268. if( ALWAYS(idxLru>=0) ){
  83269. p = &pParse->aColCache[idxLru];
  83270. p->iLevel = pParse->iCacheLevel;
  83271. p->iTable = iTab;
  83272. p->iColumn = iCol;
  83273. p->iReg = iReg;
  83274. p->tempReg = 0;
  83275. p->lru = pParse->iCacheCnt++;
  83276. return;
  83277. }
  83278. }
  83279. /*
  83280. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  83281. ** Purge the range of registers from the column cache.
  83282. */
  83283. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  83284. int i;
  83285. int iLast = iReg + nReg - 1;
  83286. struct yColCache *p;
  83287. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83288. int r = p->iReg;
  83289. if( r>=iReg && r<=iLast ){
  83290. cacheEntryClear(pParse, p);
  83291. p->iReg = 0;
  83292. }
  83293. }
  83294. }
  83295. /*
  83296. ** Remember the current column cache context. Any new entries added
  83297. ** added to the column cache after this call are removed when the
  83298. ** corresponding pop occurs.
  83299. */
  83300. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  83301. pParse->iCacheLevel++;
  83302. #ifdef SQLITE_DEBUG
  83303. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  83304. printf("PUSH to %d\n", pParse->iCacheLevel);
  83305. }
  83306. #endif
  83307. }
  83308. /*
  83309. ** Remove from the column cache any entries that were added since the
  83310. ** the previous sqlite3ExprCachePush operation. In other words, restore
  83311. ** the cache to the state it was in prior the most recent Push.
  83312. */
  83313. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  83314. int i;
  83315. struct yColCache *p;
  83316. assert( pParse->iCacheLevel>=1 );
  83317. pParse->iCacheLevel--;
  83318. #ifdef SQLITE_DEBUG
  83319. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  83320. printf("POP to %d\n", pParse->iCacheLevel);
  83321. }
  83322. #endif
  83323. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83324. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  83325. cacheEntryClear(pParse, p);
  83326. p->iReg = 0;
  83327. }
  83328. }
  83329. }
  83330. /*
  83331. ** When a cached column is reused, make sure that its register is
  83332. ** no longer available as a temp register. ticket #3879: that same
  83333. ** register might be in the cache in multiple places, so be sure to
  83334. ** get them all.
  83335. */
  83336. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  83337. int i;
  83338. struct yColCache *p;
  83339. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83340. if( p->iReg==iReg ){
  83341. p->tempReg = 0;
  83342. }
  83343. }
  83344. }
  83345. /* Generate code that will load into register regOut a value that is
  83346. ** appropriate for the iIdxCol-th column of index pIdx.
  83347. */
  83348. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  83349. Parse *pParse, /* The parsing context */
  83350. Index *pIdx, /* The index whose column is to be loaded */
  83351. int iTabCur, /* Cursor pointing to a table row */
  83352. int iIdxCol, /* The column of the index to be loaded */
  83353. int regOut /* Store the index column value in this register */
  83354. ){
  83355. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  83356. if( iTabCol==XN_EXPR ){
  83357. assert( pIdx->aColExpr );
  83358. assert( pIdx->aColExpr->nExpr>iIdxCol );
  83359. pParse->iSelfTab = iTabCur;
  83360. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  83361. }else{
  83362. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  83363. iTabCol, regOut);
  83364. }
  83365. }
  83366. /*
  83367. ** Generate code to extract the value of the iCol-th column of a table.
  83368. */
  83369. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  83370. Vdbe *v, /* The VDBE under construction */
  83371. Table *pTab, /* The table containing the value */
  83372. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  83373. int iCol, /* Index of the column to extract */
  83374. int regOut /* Extract the value into this register */
  83375. ){
  83376. if( iCol<0 || iCol==pTab->iPKey ){
  83377. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  83378. }else{
  83379. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  83380. int x = iCol;
  83381. if( !HasRowid(pTab) ){
  83382. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  83383. }
  83384. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  83385. }
  83386. if( iCol>=0 ){
  83387. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  83388. }
  83389. }
  83390. /*
  83391. ** Generate code that will extract the iColumn-th column from
  83392. ** table pTab and store the column value in a register.
  83393. **
  83394. ** An effort is made to store the column value in register iReg. This
  83395. ** is not garanteeed for GetColumn() - the result can be stored in
  83396. ** any register. But the result is guaranteed to land in register iReg
  83397. ** for GetColumnToReg().
  83398. **
  83399. ** There must be an open cursor to pTab in iTable when this routine
  83400. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  83401. */
  83402. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  83403. Parse *pParse, /* Parsing and code generating context */
  83404. Table *pTab, /* Description of the table we are reading from */
  83405. int iColumn, /* Index of the table column */
  83406. int iTable, /* The cursor pointing to the table */
  83407. int iReg, /* Store results here */
  83408. u8 p5 /* P5 value for OP_Column + FLAGS */
  83409. ){
  83410. Vdbe *v = pParse->pVdbe;
  83411. int i;
  83412. struct yColCache *p;
  83413. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83414. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  83415. p->lru = pParse->iCacheCnt++;
  83416. sqlite3ExprCachePinRegister(pParse, p->iReg);
  83417. return p->iReg;
  83418. }
  83419. }
  83420. assert( v!=0 );
  83421. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  83422. if( p5 ){
  83423. sqlite3VdbeChangeP5(v, p5);
  83424. }else{
  83425. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  83426. }
  83427. return iReg;
  83428. }
  83429. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  83430. Parse *pParse, /* Parsing and code generating context */
  83431. Table *pTab, /* Description of the table we are reading from */
  83432. int iColumn, /* Index of the table column */
  83433. int iTable, /* The cursor pointing to the table */
  83434. int iReg /* Store results here */
  83435. ){
  83436. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  83437. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  83438. }
  83439. /*
  83440. ** Clear all column cache entries.
  83441. */
  83442. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  83443. int i;
  83444. struct yColCache *p;
  83445. #if SQLITE_DEBUG
  83446. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  83447. printf("CLEAR\n");
  83448. }
  83449. #endif
  83450. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83451. if( p->iReg ){
  83452. cacheEntryClear(pParse, p);
  83453. p->iReg = 0;
  83454. }
  83455. }
  83456. }
  83457. /*
  83458. ** Record the fact that an affinity change has occurred on iCount
  83459. ** registers starting with iStart.
  83460. */
  83461. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  83462. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  83463. }
  83464. /*
  83465. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  83466. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  83467. */
  83468. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  83469. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  83470. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  83471. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  83472. }
  83473. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  83474. /*
  83475. ** Return true if any register in the range iFrom..iTo (inclusive)
  83476. ** is used as part of the column cache.
  83477. **
  83478. ** This routine is used within assert() and testcase() macros only
  83479. ** and does not appear in a normal build.
  83480. */
  83481. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  83482. int i;
  83483. struct yColCache *p;
  83484. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  83485. int r = p->iReg;
  83486. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  83487. }
  83488. return 0;
  83489. }
  83490. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  83491. /*
  83492. ** Convert an expression node to a TK_REGISTER
  83493. */
  83494. static void exprToRegister(Expr *p, int iReg){
  83495. p->op2 = p->op;
  83496. p->op = TK_REGISTER;
  83497. p->iTable = iReg;
  83498. ExprClearProperty(p, EP_Skip);
  83499. }
  83500. /*
  83501. ** Generate code into the current Vdbe to evaluate the given
  83502. ** expression. Attempt to store the results in register "target".
  83503. ** Return the register where results are stored.
  83504. **
  83505. ** With this routine, there is no guarantee that results will
  83506. ** be stored in target. The result might be stored in some other
  83507. ** register if it is convenient to do so. The calling function
  83508. ** must check the return code and move the results to the desired
  83509. ** register.
  83510. */
  83511. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  83512. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  83513. int op; /* The opcode being coded */
  83514. int inReg = target; /* Results stored in register inReg */
  83515. int regFree1 = 0; /* If non-zero free this temporary register */
  83516. int regFree2 = 0; /* If non-zero free this temporary register */
  83517. int r1, r2, r3, r4; /* Various register numbers */
  83518. sqlite3 *db = pParse->db; /* The database connection */
  83519. Expr tempX; /* Temporary expression node */
  83520. assert( target>0 && target<=pParse->nMem );
  83521. if( v==0 ){
  83522. assert( pParse->db->mallocFailed );
  83523. return 0;
  83524. }
  83525. if( pExpr==0 ){
  83526. op = TK_NULL;
  83527. }else{
  83528. op = pExpr->op;
  83529. }
  83530. switch( op ){
  83531. case TK_AGG_COLUMN: {
  83532. AggInfo *pAggInfo = pExpr->pAggInfo;
  83533. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  83534. if( !pAggInfo->directMode ){
  83535. assert( pCol->iMem>0 );
  83536. inReg = pCol->iMem;
  83537. break;
  83538. }else if( pAggInfo->useSortingIdx ){
  83539. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  83540. pCol->iSorterColumn, target);
  83541. break;
  83542. }
  83543. /* Otherwise, fall thru into the TK_COLUMN case */
  83544. }
  83545. case TK_COLUMN: {
  83546. int iTab = pExpr->iTable;
  83547. if( iTab<0 ){
  83548. if( pParse->ckBase>0 ){
  83549. /* Generating CHECK constraints or inserting into partial index */
  83550. inReg = pExpr->iColumn + pParse->ckBase;
  83551. break;
  83552. }else{
  83553. /* Coding an expression that is part of an index where column names
  83554. ** in the index refer to the table to which the index belongs */
  83555. iTab = pParse->iSelfTab;
  83556. }
  83557. }
  83558. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  83559. pExpr->iColumn, iTab, target,
  83560. pExpr->op2);
  83561. break;
  83562. }
  83563. case TK_INTEGER: {
  83564. codeInteger(pParse, pExpr, 0, target);
  83565. break;
  83566. }
  83567. #ifndef SQLITE_OMIT_FLOATING_POINT
  83568. case TK_FLOAT: {
  83569. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83570. codeReal(v, pExpr->u.zToken, 0, target);
  83571. break;
  83572. }
  83573. #endif
  83574. case TK_STRING: {
  83575. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83576. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  83577. break;
  83578. }
  83579. case TK_NULL: {
  83580. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  83581. break;
  83582. }
  83583. #ifndef SQLITE_OMIT_BLOB_LITERAL
  83584. case TK_BLOB: {
  83585. int n;
  83586. const char *z;
  83587. char *zBlob;
  83588. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83589. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  83590. assert( pExpr->u.zToken[1]=='\'' );
  83591. z = &pExpr->u.zToken[2];
  83592. n = sqlite3Strlen30(z) - 1;
  83593. assert( z[n]=='\'' );
  83594. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  83595. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  83596. break;
  83597. }
  83598. #endif
  83599. case TK_VARIABLE: {
  83600. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83601. assert( pExpr->u.zToken!=0 );
  83602. assert( pExpr->u.zToken[0]!=0 );
  83603. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  83604. if( pExpr->u.zToken[1]!=0 ){
  83605. assert( pExpr->u.zToken[0]=='?'
  83606. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  83607. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  83608. }
  83609. break;
  83610. }
  83611. case TK_REGISTER: {
  83612. inReg = pExpr->iTable;
  83613. break;
  83614. }
  83615. #ifndef SQLITE_OMIT_CAST
  83616. case TK_CAST: {
  83617. /* Expressions of the form: CAST(pLeft AS token) */
  83618. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  83619. if( inReg!=target ){
  83620. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  83621. inReg = target;
  83622. }
  83623. sqlite3VdbeAddOp2(v, OP_Cast, target,
  83624. sqlite3AffinityType(pExpr->u.zToken, 0));
  83625. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  83626. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  83627. break;
  83628. }
  83629. #endif /* SQLITE_OMIT_CAST */
  83630. case TK_LT:
  83631. case TK_LE:
  83632. case TK_GT:
  83633. case TK_GE:
  83634. case TK_NE:
  83635. case TK_EQ: {
  83636. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83637. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83638. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  83639. r1, r2, inReg, SQLITE_STOREP2);
  83640. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  83641. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  83642. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  83643. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  83644. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  83645. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  83646. testcase( regFree1==0 );
  83647. testcase( regFree2==0 );
  83648. break;
  83649. }
  83650. case TK_IS:
  83651. case TK_ISNOT: {
  83652. testcase( op==TK_IS );
  83653. testcase( op==TK_ISNOT );
  83654. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83655. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83656. op = (op==TK_IS) ? TK_EQ : TK_NE;
  83657. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  83658. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  83659. VdbeCoverageIf(v, op==TK_EQ);
  83660. VdbeCoverageIf(v, op==TK_NE);
  83661. testcase( regFree1==0 );
  83662. testcase( regFree2==0 );
  83663. break;
  83664. }
  83665. case TK_AND:
  83666. case TK_OR:
  83667. case TK_PLUS:
  83668. case TK_STAR:
  83669. case TK_MINUS:
  83670. case TK_REM:
  83671. case TK_BITAND:
  83672. case TK_BITOR:
  83673. case TK_SLASH:
  83674. case TK_LSHIFT:
  83675. case TK_RSHIFT:
  83676. case TK_CONCAT: {
  83677. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  83678. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  83679. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  83680. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  83681. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  83682. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  83683. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  83684. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  83685. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  83686. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  83687. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  83688. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83689. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83690. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  83691. testcase( regFree1==0 );
  83692. testcase( regFree2==0 );
  83693. break;
  83694. }
  83695. case TK_UMINUS: {
  83696. Expr *pLeft = pExpr->pLeft;
  83697. assert( pLeft );
  83698. if( pLeft->op==TK_INTEGER ){
  83699. codeInteger(pParse, pLeft, 1, target);
  83700. #ifndef SQLITE_OMIT_FLOATING_POINT
  83701. }else if( pLeft->op==TK_FLOAT ){
  83702. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83703. codeReal(v, pLeft->u.zToken, 1, target);
  83704. #endif
  83705. }else{
  83706. tempX.op = TK_INTEGER;
  83707. tempX.flags = EP_IntValue|EP_TokenOnly;
  83708. tempX.u.iValue = 0;
  83709. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  83710. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  83711. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  83712. testcase( regFree2==0 );
  83713. }
  83714. inReg = target;
  83715. break;
  83716. }
  83717. case TK_BITNOT:
  83718. case TK_NOT: {
  83719. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  83720. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  83721. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83722. testcase( regFree1==0 );
  83723. inReg = target;
  83724. sqlite3VdbeAddOp2(v, op, r1, inReg);
  83725. break;
  83726. }
  83727. case TK_ISNULL:
  83728. case TK_NOTNULL: {
  83729. int addr;
  83730. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  83731. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  83732. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  83733. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83734. testcase( regFree1==0 );
  83735. addr = sqlite3VdbeAddOp1(v, op, r1);
  83736. VdbeCoverageIf(v, op==TK_ISNULL);
  83737. VdbeCoverageIf(v, op==TK_NOTNULL);
  83738. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  83739. sqlite3VdbeJumpHere(v, addr);
  83740. break;
  83741. }
  83742. case TK_AGG_FUNCTION: {
  83743. AggInfo *pInfo = pExpr->pAggInfo;
  83744. if( pInfo==0 ){
  83745. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83746. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  83747. }else{
  83748. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  83749. }
  83750. break;
  83751. }
  83752. case TK_FUNCTION: {
  83753. ExprList *pFarg; /* List of function arguments */
  83754. int nFarg; /* Number of function arguments */
  83755. FuncDef *pDef; /* The function definition object */
  83756. const char *zId; /* The function name */
  83757. u32 constMask = 0; /* Mask of function arguments that are constant */
  83758. int i; /* Loop counter */
  83759. u8 enc = ENC(db); /* The text encoding used by this database */
  83760. CollSeq *pColl = 0; /* A collating sequence */
  83761. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  83762. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  83763. pFarg = 0;
  83764. }else{
  83765. pFarg = pExpr->x.pList;
  83766. }
  83767. nFarg = pFarg ? pFarg->nExpr : 0;
  83768. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83769. zId = pExpr->u.zToken;
  83770. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  83771. if( pDef==0 || pDef->xFinalize!=0 ){
  83772. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  83773. break;
  83774. }
  83775. /* Attempt a direct implementation of the built-in COALESCE() and
  83776. ** IFNULL() functions. This avoids unnecessary evaluation of
  83777. ** arguments past the first non-NULL argument.
  83778. */
  83779. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  83780. int endCoalesce = sqlite3VdbeMakeLabel(v);
  83781. assert( nFarg>=2 );
  83782. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  83783. for(i=1; i<nFarg; i++){
  83784. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  83785. VdbeCoverage(v);
  83786. sqlite3ExprCacheRemove(pParse, target, 1);
  83787. sqlite3ExprCachePush(pParse);
  83788. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  83789. sqlite3ExprCachePop(pParse);
  83790. }
  83791. sqlite3VdbeResolveLabel(v, endCoalesce);
  83792. break;
  83793. }
  83794. /* The UNLIKELY() function is a no-op. The result is the value
  83795. ** of the first argument.
  83796. */
  83797. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  83798. assert( nFarg>=1 );
  83799. inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  83800. break;
  83801. }
  83802. for(i=0; i<nFarg; i++){
  83803. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  83804. testcase( i==31 );
  83805. constMask |= MASKBIT32(i);
  83806. }
  83807. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  83808. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  83809. }
  83810. }
  83811. if( pFarg ){
  83812. if( constMask ){
  83813. r1 = pParse->nMem+1;
  83814. pParse->nMem += nFarg;
  83815. }else{
  83816. r1 = sqlite3GetTempRange(pParse, nFarg);
  83817. }
  83818. /* For length() and typeof() functions with a column argument,
  83819. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  83820. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  83821. ** loading.
  83822. */
  83823. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  83824. u8 exprOp;
  83825. assert( nFarg==1 );
  83826. assert( pFarg->a[0].pExpr!=0 );
  83827. exprOp = pFarg->a[0].pExpr->op;
  83828. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  83829. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  83830. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  83831. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  83832. pFarg->a[0].pExpr->op2 =
  83833. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  83834. }
  83835. }
  83836. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  83837. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  83838. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  83839. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  83840. }else{
  83841. r1 = 0;
  83842. }
  83843. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83844. /* Possibly overload the function if the first argument is
  83845. ** a virtual table column.
  83846. **
  83847. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  83848. ** second argument, not the first, as the argument to test to
  83849. ** see if it is a column in a virtual table. This is done because
  83850. ** the left operand of infix functions (the operand we want to
  83851. ** control overloading) ends up as the second argument to the
  83852. ** function. The expression "A glob B" is equivalent to
  83853. ** "glob(B,A). We want to use the A in "A glob B" to test
  83854. ** for function overloading. But we use the B term in "glob(B,A)".
  83855. */
  83856. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  83857. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  83858. }else if( nFarg>0 ){
  83859. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  83860. }
  83861. #endif
  83862. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  83863. if( !pColl ) pColl = db->pDfltColl;
  83864. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  83865. }
  83866. sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
  83867. (char*)pDef, P4_FUNCDEF);
  83868. sqlite3VdbeChangeP5(v, (u8)nFarg);
  83869. if( nFarg && constMask==0 ){
  83870. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  83871. }
  83872. break;
  83873. }
  83874. #ifndef SQLITE_OMIT_SUBQUERY
  83875. case TK_EXISTS:
  83876. case TK_SELECT: {
  83877. testcase( op==TK_EXISTS );
  83878. testcase( op==TK_SELECT );
  83879. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  83880. break;
  83881. }
  83882. case TK_IN: {
  83883. int destIfFalse = sqlite3VdbeMakeLabel(v);
  83884. int destIfNull = sqlite3VdbeMakeLabel(v);
  83885. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  83886. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  83887. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  83888. sqlite3VdbeResolveLabel(v, destIfFalse);
  83889. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  83890. sqlite3VdbeResolveLabel(v, destIfNull);
  83891. break;
  83892. }
  83893. #endif /* SQLITE_OMIT_SUBQUERY */
  83894. /*
  83895. ** x BETWEEN y AND z
  83896. **
  83897. ** This is equivalent to
  83898. **
  83899. ** x>=y AND x<=z
  83900. **
  83901. ** X is stored in pExpr->pLeft.
  83902. ** Y is stored in pExpr->pList->a[0].pExpr.
  83903. ** Z is stored in pExpr->pList->a[1].pExpr.
  83904. */
  83905. case TK_BETWEEN: {
  83906. Expr *pLeft = pExpr->pLeft;
  83907. struct ExprList_item *pLItem = pExpr->x.pList->a;
  83908. Expr *pRight = pLItem->pExpr;
  83909. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  83910. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  83911. testcase( regFree1==0 );
  83912. testcase( regFree2==0 );
  83913. r3 = sqlite3GetTempReg(pParse);
  83914. r4 = sqlite3GetTempReg(pParse);
  83915. codeCompare(pParse, pLeft, pRight, OP_Ge,
  83916. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  83917. pLItem++;
  83918. pRight = pLItem->pExpr;
  83919. sqlite3ReleaseTempReg(pParse, regFree2);
  83920. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  83921. testcase( regFree2==0 );
  83922. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  83923. VdbeCoverage(v);
  83924. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  83925. sqlite3ReleaseTempReg(pParse, r3);
  83926. sqlite3ReleaseTempReg(pParse, r4);
  83927. break;
  83928. }
  83929. case TK_SPAN:
  83930. case TK_COLLATE:
  83931. case TK_UPLUS: {
  83932. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  83933. break;
  83934. }
  83935. case TK_TRIGGER: {
  83936. /* If the opcode is TK_TRIGGER, then the expression is a reference
  83937. ** to a column in the new.* or old.* pseudo-tables available to
  83938. ** trigger programs. In this case Expr.iTable is set to 1 for the
  83939. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  83940. ** is set to the column of the pseudo-table to read, or to -1 to
  83941. ** read the rowid field.
  83942. **
  83943. ** The expression is implemented using an OP_Param opcode. The p1
  83944. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  83945. ** to reference another column of the old.* pseudo-table, where
  83946. ** i is the index of the column. For a new.rowid reference, p1 is
  83947. ** set to (n+1), where n is the number of columns in each pseudo-table.
  83948. ** For a reference to any other column in the new.* pseudo-table, p1
  83949. ** is set to (n+2+i), where n and i are as defined previously. For
  83950. ** example, if the table on which triggers are being fired is
  83951. ** declared as:
  83952. **
  83953. ** CREATE TABLE t1(a, b);
  83954. **
  83955. ** Then p1 is interpreted as follows:
  83956. **
  83957. ** p1==0 -> old.rowid p1==3 -> new.rowid
  83958. ** p1==1 -> old.a p1==4 -> new.a
  83959. ** p1==2 -> old.b p1==5 -> new.b
  83960. */
  83961. Table *pTab = pExpr->pTab;
  83962. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  83963. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  83964. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  83965. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  83966. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  83967. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  83968. VdbeComment((v, "%s.%s -> $%d",
  83969. (pExpr->iTable ? "new" : "old"),
  83970. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  83971. target
  83972. ));
  83973. #ifndef SQLITE_OMIT_FLOATING_POINT
  83974. /* If the column has REAL affinity, it may currently be stored as an
  83975. ** integer. Use OP_RealAffinity to make sure it is really real.
  83976. **
  83977. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  83978. ** floating point when extracting it from the record. */
  83979. if( pExpr->iColumn>=0
  83980. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  83981. ){
  83982. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  83983. }
  83984. #endif
  83985. break;
  83986. }
  83987. /*
  83988. ** Form A:
  83989. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  83990. **
  83991. ** Form B:
  83992. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  83993. **
  83994. ** Form A is can be transformed into the equivalent form B as follows:
  83995. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  83996. ** WHEN x=eN THEN rN ELSE y END
  83997. **
  83998. ** X (if it exists) is in pExpr->pLeft.
  83999. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  84000. ** odd. The Y is also optional. If the number of elements in x.pList
  84001. ** is even, then Y is omitted and the "otherwise" result is NULL.
  84002. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  84003. **
  84004. ** The result of the expression is the Ri for the first matching Ei,
  84005. ** or if there is no matching Ei, the ELSE term Y, or if there is
  84006. ** no ELSE term, NULL.
  84007. */
  84008. default: assert( op==TK_CASE ); {
  84009. int endLabel; /* GOTO label for end of CASE stmt */
  84010. int nextCase; /* GOTO label for next WHEN clause */
  84011. int nExpr; /* 2x number of WHEN terms */
  84012. int i; /* Loop counter */
  84013. ExprList *pEList; /* List of WHEN terms */
  84014. struct ExprList_item *aListelem; /* Array of WHEN terms */
  84015. Expr opCompare; /* The X==Ei expression */
  84016. Expr *pX; /* The X expression */
  84017. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  84018. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  84019. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  84020. assert(pExpr->x.pList->nExpr > 0);
  84021. pEList = pExpr->x.pList;
  84022. aListelem = pEList->a;
  84023. nExpr = pEList->nExpr;
  84024. endLabel = sqlite3VdbeMakeLabel(v);
  84025. if( (pX = pExpr->pLeft)!=0 ){
  84026. tempX = *pX;
  84027. testcase( pX->op==TK_COLUMN );
  84028. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  84029. testcase( regFree1==0 );
  84030. opCompare.op = TK_EQ;
  84031. opCompare.pLeft = &tempX;
  84032. pTest = &opCompare;
  84033. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  84034. ** The value in regFree1 might get SCopy-ed into the file result.
  84035. ** So make sure that the regFree1 register is not reused for other
  84036. ** purposes and possibly overwritten. */
  84037. regFree1 = 0;
  84038. }
  84039. for(i=0; i<nExpr-1; i=i+2){
  84040. sqlite3ExprCachePush(pParse);
  84041. if( pX ){
  84042. assert( pTest!=0 );
  84043. opCompare.pRight = aListelem[i].pExpr;
  84044. }else{
  84045. pTest = aListelem[i].pExpr;
  84046. }
  84047. nextCase = sqlite3VdbeMakeLabel(v);
  84048. testcase( pTest->op==TK_COLUMN );
  84049. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  84050. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  84051. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  84052. sqlite3VdbeGoto(v, endLabel);
  84053. sqlite3ExprCachePop(pParse);
  84054. sqlite3VdbeResolveLabel(v, nextCase);
  84055. }
  84056. if( (nExpr&1)!=0 ){
  84057. sqlite3ExprCachePush(pParse);
  84058. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  84059. sqlite3ExprCachePop(pParse);
  84060. }else{
  84061. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  84062. }
  84063. assert( db->mallocFailed || pParse->nErr>0
  84064. || pParse->iCacheLevel==iCacheLevel );
  84065. sqlite3VdbeResolveLabel(v, endLabel);
  84066. break;
  84067. }
  84068. #ifndef SQLITE_OMIT_TRIGGER
  84069. case TK_RAISE: {
  84070. assert( pExpr->affinity==OE_Rollback
  84071. || pExpr->affinity==OE_Abort
  84072. || pExpr->affinity==OE_Fail
  84073. || pExpr->affinity==OE_Ignore
  84074. );
  84075. if( !pParse->pTriggerTab ){
  84076. sqlite3ErrorMsg(pParse,
  84077. "RAISE() may only be used within a trigger-program");
  84078. return 0;
  84079. }
  84080. if( pExpr->affinity==OE_Abort ){
  84081. sqlite3MayAbort(pParse);
  84082. }
  84083. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  84084. if( pExpr->affinity==OE_Ignore ){
  84085. sqlite3VdbeAddOp4(
  84086. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  84087. VdbeCoverage(v);
  84088. }else{
  84089. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  84090. pExpr->affinity, pExpr->u.zToken, 0, 0);
  84091. }
  84092. break;
  84093. }
  84094. #endif
  84095. }
  84096. sqlite3ReleaseTempReg(pParse, regFree1);
  84097. sqlite3ReleaseTempReg(pParse, regFree2);
  84098. return inReg;
  84099. }
  84100. /*
  84101. ** Factor out the code of the given expression to initialization time.
  84102. */
  84103. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  84104. Parse *pParse, /* Parsing context */
  84105. Expr *pExpr, /* The expression to code when the VDBE initializes */
  84106. int regDest, /* Store the value in this register */
  84107. u8 reusable /* True if this expression is reusable */
  84108. ){
  84109. ExprList *p;
  84110. assert( ConstFactorOk(pParse) );
  84111. p = pParse->pConstExpr;
  84112. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  84113. p = sqlite3ExprListAppend(pParse, p, pExpr);
  84114. if( p ){
  84115. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  84116. pItem->u.iConstExprReg = regDest;
  84117. pItem->reusable = reusable;
  84118. }
  84119. pParse->pConstExpr = p;
  84120. }
  84121. /*
  84122. ** Generate code to evaluate an expression and store the results
  84123. ** into a register. Return the register number where the results
  84124. ** are stored.
  84125. **
  84126. ** If the register is a temporary register that can be deallocated,
  84127. ** then write its number into *pReg. If the result register is not
  84128. ** a temporary, then set *pReg to zero.
  84129. **
  84130. ** If pExpr is a constant, then this routine might generate this
  84131. ** code to fill the register in the initialization section of the
  84132. ** VDBE program, in order to factor it out of the evaluation loop.
  84133. */
  84134. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  84135. int r2;
  84136. pExpr = sqlite3ExprSkipCollate(pExpr);
  84137. if( ConstFactorOk(pParse)
  84138. && pExpr->op!=TK_REGISTER
  84139. && sqlite3ExprIsConstantNotJoin(pExpr)
  84140. ){
  84141. ExprList *p = pParse->pConstExpr;
  84142. int i;
  84143. *pReg = 0;
  84144. if( p ){
  84145. struct ExprList_item *pItem;
  84146. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  84147. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  84148. return pItem->u.iConstExprReg;
  84149. }
  84150. }
  84151. }
  84152. r2 = ++pParse->nMem;
  84153. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  84154. }else{
  84155. int r1 = sqlite3GetTempReg(pParse);
  84156. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  84157. if( r2==r1 ){
  84158. *pReg = r1;
  84159. }else{
  84160. sqlite3ReleaseTempReg(pParse, r1);
  84161. *pReg = 0;
  84162. }
  84163. }
  84164. return r2;
  84165. }
  84166. /*
  84167. ** Generate code that will evaluate expression pExpr and store the
  84168. ** results in register target. The results are guaranteed to appear
  84169. ** in register target.
  84170. */
  84171. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  84172. int inReg;
  84173. assert( target>0 && target<=pParse->nMem );
  84174. if( pExpr && pExpr->op==TK_REGISTER ){
  84175. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  84176. }else{
  84177. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  84178. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  84179. if( inReg!=target && pParse->pVdbe ){
  84180. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  84181. }
  84182. }
  84183. }
  84184. /*
  84185. ** Make a transient copy of expression pExpr and then code it using
  84186. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  84187. ** except that the input expression is guaranteed to be unchanged.
  84188. */
  84189. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  84190. sqlite3 *db = pParse->db;
  84191. pExpr = sqlite3ExprDup(db, pExpr, 0);
  84192. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  84193. sqlite3ExprDelete(db, pExpr);
  84194. }
  84195. /*
  84196. ** Generate code that will evaluate expression pExpr and store the
  84197. ** results in register target. The results are guaranteed to appear
  84198. ** in register target. If the expression is constant, then this routine
  84199. ** might choose to code the expression at initialization time.
  84200. */
  84201. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  84202. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  84203. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  84204. }else{
  84205. sqlite3ExprCode(pParse, pExpr, target);
  84206. }
  84207. }
  84208. /*
  84209. ** Generate code that evaluates the given expression and puts the result
  84210. ** in register target.
  84211. **
  84212. ** Also make a copy of the expression results into another "cache" register
  84213. ** and modify the expression so that the next time it is evaluated,
  84214. ** the result is a copy of the cache register.
  84215. **
  84216. ** This routine is used for expressions that are used multiple
  84217. ** times. They are evaluated once and the results of the expression
  84218. ** are reused.
  84219. */
  84220. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  84221. Vdbe *v = pParse->pVdbe;
  84222. int iMem;
  84223. assert( target>0 );
  84224. assert( pExpr->op!=TK_REGISTER );
  84225. sqlite3ExprCode(pParse, pExpr, target);
  84226. iMem = ++pParse->nMem;
  84227. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  84228. exprToRegister(pExpr, iMem);
  84229. }
  84230. /*
  84231. ** Generate code that pushes the value of every element of the given
  84232. ** expression list into a sequence of registers beginning at target.
  84233. **
  84234. ** Return the number of elements evaluated.
  84235. **
  84236. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  84237. ** filled using OP_SCopy. OP_Copy must be used instead.
  84238. **
  84239. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  84240. ** factored out into initialization code.
  84241. **
  84242. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  84243. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  84244. ** in registers at srcReg, and so the value can be copied from there.
  84245. */
  84246. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  84247. Parse *pParse, /* Parsing context */
  84248. ExprList *pList, /* The expression list to be coded */
  84249. int target, /* Where to write results */
  84250. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  84251. u8 flags /* SQLITE_ECEL_* flags */
  84252. ){
  84253. struct ExprList_item *pItem;
  84254. int i, j, n;
  84255. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  84256. Vdbe *v = pParse->pVdbe;
  84257. assert( pList!=0 );
  84258. assert( target>0 );
  84259. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  84260. n = pList->nExpr;
  84261. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  84262. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  84263. Expr *pExpr = pItem->pExpr;
  84264. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
  84265. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  84266. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  84267. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  84268. }else{
  84269. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  84270. if( inReg!=target+i ){
  84271. VdbeOp *pOp;
  84272. if( copyOp==OP_Copy
  84273. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  84274. && pOp->p1+pOp->p3+1==inReg
  84275. && pOp->p2+pOp->p3+1==target+i
  84276. ){
  84277. pOp->p3++;
  84278. }else{
  84279. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  84280. }
  84281. }
  84282. }
  84283. }
  84284. return n;
  84285. }
  84286. /*
  84287. ** Generate code for a BETWEEN operator.
  84288. **
  84289. ** x BETWEEN y AND z
  84290. **
  84291. ** The above is equivalent to
  84292. **
  84293. ** x>=y AND x<=z
  84294. **
  84295. ** Code it as such, taking care to do the common subexpression
  84296. ** elimination of x.
  84297. */
  84298. static void exprCodeBetween(
  84299. Parse *pParse, /* Parsing and code generating context */
  84300. Expr *pExpr, /* The BETWEEN expression */
  84301. int dest, /* Jump here if the jump is taken */
  84302. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  84303. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  84304. ){
  84305. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  84306. Expr compLeft; /* The x>=y term */
  84307. Expr compRight; /* The x<=z term */
  84308. Expr exprX; /* The x subexpression */
  84309. int regFree1 = 0; /* Temporary use register */
  84310. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  84311. exprX = *pExpr->pLeft;
  84312. exprAnd.op = TK_AND;
  84313. exprAnd.pLeft = &compLeft;
  84314. exprAnd.pRight = &compRight;
  84315. compLeft.op = TK_GE;
  84316. compLeft.pLeft = &exprX;
  84317. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  84318. compRight.op = TK_LE;
  84319. compRight.pLeft = &exprX;
  84320. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  84321. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  84322. if( jumpIfTrue ){
  84323. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  84324. }else{
  84325. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  84326. }
  84327. sqlite3ReleaseTempReg(pParse, regFree1);
  84328. /* Ensure adequate test coverage */
  84329. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  84330. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  84331. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  84332. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  84333. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  84334. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  84335. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  84336. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  84337. }
  84338. /*
  84339. ** Generate code for a boolean expression such that a jump is made
  84340. ** to the label "dest" if the expression is true but execution
  84341. ** continues straight thru if the expression is false.
  84342. **
  84343. ** If the expression evaluates to NULL (neither true nor false), then
  84344. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  84345. **
  84346. ** This code depends on the fact that certain token values (ex: TK_EQ)
  84347. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  84348. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  84349. ** the make process cause these values to align. Assert()s in the code
  84350. ** below verify that the numbers are aligned correctly.
  84351. */
  84352. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  84353. Vdbe *v = pParse->pVdbe;
  84354. int op = 0;
  84355. int regFree1 = 0;
  84356. int regFree2 = 0;
  84357. int r1, r2;
  84358. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  84359. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  84360. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  84361. op = pExpr->op;
  84362. switch( op ){
  84363. case TK_AND: {
  84364. int d2 = sqlite3VdbeMakeLabel(v);
  84365. testcase( jumpIfNull==0 );
  84366. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  84367. sqlite3ExprCachePush(pParse);
  84368. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  84369. sqlite3VdbeResolveLabel(v, d2);
  84370. sqlite3ExprCachePop(pParse);
  84371. break;
  84372. }
  84373. case TK_OR: {
  84374. testcase( jumpIfNull==0 );
  84375. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  84376. sqlite3ExprCachePush(pParse);
  84377. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  84378. sqlite3ExprCachePop(pParse);
  84379. break;
  84380. }
  84381. case TK_NOT: {
  84382. testcase( jumpIfNull==0 );
  84383. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  84384. break;
  84385. }
  84386. case TK_IS:
  84387. case TK_ISNOT:
  84388. testcase( op==TK_IS );
  84389. testcase( op==TK_ISNOT );
  84390. op = (op==TK_IS) ? TK_EQ : TK_NE;
  84391. jumpIfNull = SQLITE_NULLEQ;
  84392. /* Fall thru */
  84393. case TK_LT:
  84394. case TK_LE:
  84395. case TK_GT:
  84396. case TK_GE:
  84397. case TK_NE:
  84398. case TK_EQ: {
  84399. testcase( jumpIfNull==0 );
  84400. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  84401. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  84402. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  84403. r1, r2, dest, jumpIfNull);
  84404. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  84405. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  84406. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  84407. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  84408. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  84409. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  84410. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  84411. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  84412. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  84413. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  84414. testcase( regFree1==0 );
  84415. testcase( regFree2==0 );
  84416. break;
  84417. }
  84418. case TK_ISNULL:
  84419. case TK_NOTNULL: {
  84420. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  84421. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  84422. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  84423. sqlite3VdbeAddOp2(v, op, r1, dest);
  84424. VdbeCoverageIf(v, op==TK_ISNULL);
  84425. VdbeCoverageIf(v, op==TK_NOTNULL);
  84426. testcase( regFree1==0 );
  84427. break;
  84428. }
  84429. case TK_BETWEEN: {
  84430. testcase( jumpIfNull==0 );
  84431. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  84432. break;
  84433. }
  84434. #ifndef SQLITE_OMIT_SUBQUERY
  84435. case TK_IN: {
  84436. int destIfFalse = sqlite3VdbeMakeLabel(v);
  84437. int destIfNull = jumpIfNull ? dest : destIfFalse;
  84438. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  84439. sqlite3VdbeGoto(v, dest);
  84440. sqlite3VdbeResolveLabel(v, destIfFalse);
  84441. break;
  84442. }
  84443. #endif
  84444. default: {
  84445. if( exprAlwaysTrue(pExpr) ){
  84446. sqlite3VdbeGoto(v, dest);
  84447. }else if( exprAlwaysFalse(pExpr) ){
  84448. /* No-op */
  84449. }else{
  84450. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  84451. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  84452. VdbeCoverage(v);
  84453. testcase( regFree1==0 );
  84454. testcase( jumpIfNull==0 );
  84455. }
  84456. break;
  84457. }
  84458. }
  84459. sqlite3ReleaseTempReg(pParse, regFree1);
  84460. sqlite3ReleaseTempReg(pParse, regFree2);
  84461. }
  84462. /*
  84463. ** Generate code for a boolean expression such that a jump is made
  84464. ** to the label "dest" if the expression is false but execution
  84465. ** continues straight thru if the expression is true.
  84466. **
  84467. ** If the expression evaluates to NULL (neither true nor false) then
  84468. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  84469. ** is 0.
  84470. */
  84471. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  84472. Vdbe *v = pParse->pVdbe;
  84473. int op = 0;
  84474. int regFree1 = 0;
  84475. int regFree2 = 0;
  84476. int r1, r2;
  84477. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  84478. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  84479. if( pExpr==0 ) return;
  84480. /* The value of pExpr->op and op are related as follows:
  84481. **
  84482. ** pExpr->op op
  84483. ** --------- ----------
  84484. ** TK_ISNULL OP_NotNull
  84485. ** TK_NOTNULL OP_IsNull
  84486. ** TK_NE OP_Eq
  84487. ** TK_EQ OP_Ne
  84488. ** TK_GT OP_Le
  84489. ** TK_LE OP_Gt
  84490. ** TK_GE OP_Lt
  84491. ** TK_LT OP_Ge
  84492. **
  84493. ** For other values of pExpr->op, op is undefined and unused.
  84494. ** The value of TK_ and OP_ constants are arranged such that we
  84495. ** can compute the mapping above using the following expression.
  84496. ** Assert()s verify that the computation is correct.
  84497. */
  84498. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  84499. /* Verify correct alignment of TK_ and OP_ constants
  84500. */
  84501. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  84502. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  84503. assert( pExpr->op!=TK_NE || op==OP_Eq );
  84504. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  84505. assert( pExpr->op!=TK_LT || op==OP_Ge );
  84506. assert( pExpr->op!=TK_LE || op==OP_Gt );
  84507. assert( pExpr->op!=TK_GT || op==OP_Le );
  84508. assert( pExpr->op!=TK_GE || op==OP_Lt );
  84509. switch( pExpr->op ){
  84510. case TK_AND: {
  84511. testcase( jumpIfNull==0 );
  84512. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  84513. sqlite3ExprCachePush(pParse);
  84514. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  84515. sqlite3ExprCachePop(pParse);
  84516. break;
  84517. }
  84518. case TK_OR: {
  84519. int d2 = sqlite3VdbeMakeLabel(v);
  84520. testcase( jumpIfNull==0 );
  84521. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  84522. sqlite3ExprCachePush(pParse);
  84523. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  84524. sqlite3VdbeResolveLabel(v, d2);
  84525. sqlite3ExprCachePop(pParse);
  84526. break;
  84527. }
  84528. case TK_NOT: {
  84529. testcase( jumpIfNull==0 );
  84530. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  84531. break;
  84532. }
  84533. case TK_IS:
  84534. case TK_ISNOT:
  84535. testcase( pExpr->op==TK_IS );
  84536. testcase( pExpr->op==TK_ISNOT );
  84537. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  84538. jumpIfNull = SQLITE_NULLEQ;
  84539. /* Fall thru */
  84540. case TK_LT:
  84541. case TK_LE:
  84542. case TK_GT:
  84543. case TK_GE:
  84544. case TK_NE:
  84545. case TK_EQ: {
  84546. testcase( jumpIfNull==0 );
  84547. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  84548. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  84549. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  84550. r1, r2, dest, jumpIfNull);
  84551. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  84552. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  84553. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  84554. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  84555. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  84556. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  84557. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  84558. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  84559. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  84560. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  84561. testcase( regFree1==0 );
  84562. testcase( regFree2==0 );
  84563. break;
  84564. }
  84565. case TK_ISNULL:
  84566. case TK_NOTNULL: {
  84567. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  84568. sqlite3VdbeAddOp2(v, op, r1, dest);
  84569. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  84570. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  84571. testcase( regFree1==0 );
  84572. break;
  84573. }
  84574. case TK_BETWEEN: {
  84575. testcase( jumpIfNull==0 );
  84576. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  84577. break;
  84578. }
  84579. #ifndef SQLITE_OMIT_SUBQUERY
  84580. case TK_IN: {
  84581. if( jumpIfNull ){
  84582. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  84583. }else{
  84584. int destIfNull = sqlite3VdbeMakeLabel(v);
  84585. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  84586. sqlite3VdbeResolveLabel(v, destIfNull);
  84587. }
  84588. break;
  84589. }
  84590. #endif
  84591. default: {
  84592. if( exprAlwaysFalse(pExpr) ){
  84593. sqlite3VdbeGoto(v, dest);
  84594. }else if( exprAlwaysTrue(pExpr) ){
  84595. /* no-op */
  84596. }else{
  84597. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  84598. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  84599. VdbeCoverage(v);
  84600. testcase( regFree1==0 );
  84601. testcase( jumpIfNull==0 );
  84602. }
  84603. break;
  84604. }
  84605. }
  84606. sqlite3ReleaseTempReg(pParse, regFree1);
  84607. sqlite3ReleaseTempReg(pParse, regFree2);
  84608. }
  84609. /*
  84610. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  84611. ** code generation, and that copy is deleted after code generation. This
  84612. ** ensures that the original pExpr is unchanged.
  84613. */
  84614. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  84615. sqlite3 *db = pParse->db;
  84616. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  84617. if( db->mallocFailed==0 ){
  84618. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  84619. }
  84620. sqlite3ExprDelete(db, pCopy);
  84621. }
  84622. /*
  84623. ** Do a deep comparison of two expression trees. Return 0 if the two
  84624. ** expressions are completely identical. Return 1 if they differ only
  84625. ** by a COLLATE operator at the top level. Return 2 if there are differences
  84626. ** other than the top-level COLLATE operator.
  84627. **
  84628. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  84629. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  84630. **
  84631. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  84632. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  84633. **
  84634. ** Sometimes this routine will return 2 even if the two expressions
  84635. ** really are equivalent. If we cannot prove that the expressions are
  84636. ** identical, we return 2 just to be safe. So if this routine
  84637. ** returns 2, then you do not really know for certain if the two
  84638. ** expressions are the same. But if you get a 0 or 1 return, then you
  84639. ** can be sure the expressions are the same. In the places where
  84640. ** this routine is used, it does not hurt to get an extra 2 - that
  84641. ** just might result in some slightly slower code. But returning
  84642. ** an incorrect 0 or 1 could lead to a malfunction.
  84643. */
  84644. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  84645. u32 combinedFlags;
  84646. if( pA==0 || pB==0 ){
  84647. return pB==pA ? 0 : 2;
  84648. }
  84649. combinedFlags = pA->flags | pB->flags;
  84650. if( combinedFlags & EP_IntValue ){
  84651. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  84652. return 0;
  84653. }
  84654. return 2;
  84655. }
  84656. if( pA->op!=pB->op ){
  84657. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  84658. return 1;
  84659. }
  84660. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  84661. return 1;
  84662. }
  84663. return 2;
  84664. }
  84665. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  84666. if( pA->op==TK_FUNCTION ){
  84667. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  84668. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  84669. return pA->op==TK_COLLATE ? 1 : 2;
  84670. }
  84671. }
  84672. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  84673. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  84674. if( combinedFlags & EP_xIsSelect ) return 2;
  84675. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  84676. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  84677. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  84678. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  84679. if( pA->iColumn!=pB->iColumn ) return 2;
  84680. if( pA->iTable!=pB->iTable
  84681. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  84682. }
  84683. }
  84684. return 0;
  84685. }
  84686. /*
  84687. ** Compare two ExprList objects. Return 0 if they are identical and
  84688. ** non-zero if they differ in any way.
  84689. **
  84690. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  84691. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  84692. **
  84693. ** This routine might return non-zero for equivalent ExprLists. The
  84694. ** only consequence will be disabled optimizations. But this routine
  84695. ** must never return 0 if the two ExprList objects are different, or
  84696. ** a malfunction will result.
  84697. **
  84698. ** Two NULL pointers are considered to be the same. But a NULL pointer
  84699. ** always differs from a non-NULL pointer.
  84700. */
  84701. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  84702. int i;
  84703. if( pA==0 && pB==0 ) return 0;
  84704. if( pA==0 || pB==0 ) return 1;
  84705. if( pA->nExpr!=pB->nExpr ) return 1;
  84706. for(i=0; i<pA->nExpr; i++){
  84707. Expr *pExprA = pA->a[i].pExpr;
  84708. Expr *pExprB = pB->a[i].pExpr;
  84709. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  84710. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  84711. }
  84712. return 0;
  84713. }
  84714. /*
  84715. ** Return true if we can prove the pE2 will always be true if pE1 is
  84716. ** true. Return false if we cannot complete the proof or if pE2 might
  84717. ** be false. Examples:
  84718. **
  84719. ** pE1: x==5 pE2: x==5 Result: true
  84720. ** pE1: x>0 pE2: x==5 Result: false
  84721. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  84722. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  84723. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  84724. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  84725. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  84726. **
  84727. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  84728. ** Expr.iTable<0 then assume a table number given by iTab.
  84729. **
  84730. ** When in doubt, return false. Returning true might give a performance
  84731. ** improvement. Returning false might cause a performance reduction, but
  84732. ** it will always give the correct answer and is hence always safe.
  84733. */
  84734. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  84735. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  84736. return 1;
  84737. }
  84738. if( pE2->op==TK_OR
  84739. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  84740. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  84741. ){
  84742. return 1;
  84743. }
  84744. if( pE2->op==TK_NOTNULL
  84745. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  84746. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  84747. ){
  84748. return 1;
  84749. }
  84750. return 0;
  84751. }
  84752. /*
  84753. ** An instance of the following structure is used by the tree walker
  84754. ** to count references to table columns in the arguments of an
  84755. ** aggregate function, in order to implement the
  84756. ** sqlite3FunctionThisSrc() routine.
  84757. */
  84758. struct SrcCount {
  84759. SrcList *pSrc; /* One particular FROM clause in a nested query */
  84760. int nThis; /* Number of references to columns in pSrcList */
  84761. int nOther; /* Number of references to columns in other FROM clauses */
  84762. };
  84763. /*
  84764. ** Count the number of references to columns.
  84765. */
  84766. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  84767. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  84768. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  84769. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  84770. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  84771. ** NEVER() will need to be removed. */
  84772. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  84773. int i;
  84774. struct SrcCount *p = pWalker->u.pSrcCount;
  84775. SrcList *pSrc = p->pSrc;
  84776. int nSrc = pSrc ? pSrc->nSrc : 0;
  84777. for(i=0; i<nSrc; i++){
  84778. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  84779. }
  84780. if( i<nSrc ){
  84781. p->nThis++;
  84782. }else{
  84783. p->nOther++;
  84784. }
  84785. }
  84786. return WRC_Continue;
  84787. }
  84788. /*
  84789. ** Determine if any of the arguments to the pExpr Function reference
  84790. ** pSrcList. Return true if they do. Also return true if the function
  84791. ** has no arguments or has only constant arguments. Return false if pExpr
  84792. ** references columns but not columns of tables found in pSrcList.
  84793. */
  84794. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  84795. Walker w;
  84796. struct SrcCount cnt;
  84797. assert( pExpr->op==TK_AGG_FUNCTION );
  84798. memset(&w, 0, sizeof(w));
  84799. w.xExprCallback = exprSrcCount;
  84800. w.u.pSrcCount = &cnt;
  84801. cnt.pSrc = pSrcList;
  84802. cnt.nThis = 0;
  84803. cnt.nOther = 0;
  84804. sqlite3WalkExprList(&w, pExpr->x.pList);
  84805. return cnt.nThis>0 || cnt.nOther==0;
  84806. }
  84807. /*
  84808. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  84809. ** the new element. Return a negative number if malloc fails.
  84810. */
  84811. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  84812. int i;
  84813. pInfo->aCol = sqlite3ArrayAllocate(
  84814. db,
  84815. pInfo->aCol,
  84816. sizeof(pInfo->aCol[0]),
  84817. &pInfo->nColumn,
  84818. &i
  84819. );
  84820. return i;
  84821. }
  84822. /*
  84823. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  84824. ** the new element. Return a negative number if malloc fails.
  84825. */
  84826. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  84827. int i;
  84828. pInfo->aFunc = sqlite3ArrayAllocate(
  84829. db,
  84830. pInfo->aFunc,
  84831. sizeof(pInfo->aFunc[0]),
  84832. &pInfo->nFunc,
  84833. &i
  84834. );
  84835. return i;
  84836. }
  84837. /*
  84838. ** This is the xExprCallback for a tree walker. It is used to
  84839. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  84840. ** for additional information.
  84841. */
  84842. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  84843. int i;
  84844. NameContext *pNC = pWalker->u.pNC;
  84845. Parse *pParse = pNC->pParse;
  84846. SrcList *pSrcList = pNC->pSrcList;
  84847. AggInfo *pAggInfo = pNC->pAggInfo;
  84848. switch( pExpr->op ){
  84849. case TK_AGG_COLUMN:
  84850. case TK_COLUMN: {
  84851. testcase( pExpr->op==TK_AGG_COLUMN );
  84852. testcase( pExpr->op==TK_COLUMN );
  84853. /* Check to see if the column is in one of the tables in the FROM
  84854. ** clause of the aggregate query */
  84855. if( ALWAYS(pSrcList!=0) ){
  84856. struct SrcList_item *pItem = pSrcList->a;
  84857. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  84858. struct AggInfo_col *pCol;
  84859. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  84860. if( pExpr->iTable==pItem->iCursor ){
  84861. /* If we reach this point, it means that pExpr refers to a table
  84862. ** that is in the FROM clause of the aggregate query.
  84863. **
  84864. ** Make an entry for the column in pAggInfo->aCol[] if there
  84865. ** is not an entry there already.
  84866. */
  84867. int k;
  84868. pCol = pAggInfo->aCol;
  84869. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  84870. if( pCol->iTable==pExpr->iTable &&
  84871. pCol->iColumn==pExpr->iColumn ){
  84872. break;
  84873. }
  84874. }
  84875. if( (k>=pAggInfo->nColumn)
  84876. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  84877. ){
  84878. pCol = &pAggInfo->aCol[k];
  84879. pCol->pTab = pExpr->pTab;
  84880. pCol->iTable = pExpr->iTable;
  84881. pCol->iColumn = pExpr->iColumn;
  84882. pCol->iMem = ++pParse->nMem;
  84883. pCol->iSorterColumn = -1;
  84884. pCol->pExpr = pExpr;
  84885. if( pAggInfo->pGroupBy ){
  84886. int j, n;
  84887. ExprList *pGB = pAggInfo->pGroupBy;
  84888. struct ExprList_item *pTerm = pGB->a;
  84889. n = pGB->nExpr;
  84890. for(j=0; j<n; j++, pTerm++){
  84891. Expr *pE = pTerm->pExpr;
  84892. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  84893. pE->iColumn==pExpr->iColumn ){
  84894. pCol->iSorterColumn = j;
  84895. break;
  84896. }
  84897. }
  84898. }
  84899. if( pCol->iSorterColumn<0 ){
  84900. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  84901. }
  84902. }
  84903. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  84904. ** because it was there before or because we just created it).
  84905. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  84906. ** pAggInfo->aCol[] entry.
  84907. */
  84908. ExprSetVVAProperty(pExpr, EP_NoReduce);
  84909. pExpr->pAggInfo = pAggInfo;
  84910. pExpr->op = TK_AGG_COLUMN;
  84911. pExpr->iAgg = (i16)k;
  84912. break;
  84913. } /* endif pExpr->iTable==pItem->iCursor */
  84914. } /* end loop over pSrcList */
  84915. }
  84916. return WRC_Prune;
  84917. }
  84918. case TK_AGG_FUNCTION: {
  84919. if( (pNC->ncFlags & NC_InAggFunc)==0
  84920. && pWalker->walkerDepth==pExpr->op2
  84921. ){
  84922. /* Check to see if pExpr is a duplicate of another aggregate
  84923. ** function that is already in the pAggInfo structure
  84924. */
  84925. struct AggInfo_func *pItem = pAggInfo->aFunc;
  84926. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  84927. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  84928. break;
  84929. }
  84930. }
  84931. if( i>=pAggInfo->nFunc ){
  84932. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  84933. */
  84934. u8 enc = ENC(pParse->db);
  84935. i = addAggInfoFunc(pParse->db, pAggInfo);
  84936. if( i>=0 ){
  84937. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  84938. pItem = &pAggInfo->aFunc[i];
  84939. pItem->pExpr = pExpr;
  84940. pItem->iMem = ++pParse->nMem;
  84941. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  84942. pItem->pFunc = sqlite3FindFunction(pParse->db,
  84943. pExpr->u.zToken,
  84944. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  84945. if( pExpr->flags & EP_Distinct ){
  84946. pItem->iDistinct = pParse->nTab++;
  84947. }else{
  84948. pItem->iDistinct = -1;
  84949. }
  84950. }
  84951. }
  84952. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  84953. */
  84954. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  84955. ExprSetVVAProperty(pExpr, EP_NoReduce);
  84956. pExpr->iAgg = (i16)i;
  84957. pExpr->pAggInfo = pAggInfo;
  84958. return WRC_Prune;
  84959. }else{
  84960. return WRC_Continue;
  84961. }
  84962. }
  84963. }
  84964. return WRC_Continue;
  84965. }
  84966. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  84967. UNUSED_PARAMETER(pWalker);
  84968. UNUSED_PARAMETER(pSelect);
  84969. return WRC_Continue;
  84970. }
  84971. /*
  84972. ** Analyze the pExpr expression looking for aggregate functions and
  84973. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  84974. ** points to. Additional entries are made on the AggInfo object as
  84975. ** necessary.
  84976. **
  84977. ** This routine should only be called after the expression has been
  84978. ** analyzed by sqlite3ResolveExprNames().
  84979. */
  84980. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  84981. Walker w;
  84982. memset(&w, 0, sizeof(w));
  84983. w.xExprCallback = analyzeAggregate;
  84984. w.xSelectCallback = analyzeAggregatesInSelect;
  84985. w.u.pNC = pNC;
  84986. assert( pNC->pSrcList!=0 );
  84987. sqlite3WalkExpr(&w, pExpr);
  84988. }
  84989. /*
  84990. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  84991. ** expression list. Return the number of errors.
  84992. **
  84993. ** If an error is found, the analysis is cut short.
  84994. */
  84995. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  84996. struct ExprList_item *pItem;
  84997. int i;
  84998. if( pList ){
  84999. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  85000. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  85001. }
  85002. }
  85003. }
  85004. /*
  85005. ** Allocate a single new register for use to hold some intermediate result.
  85006. */
  85007. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  85008. if( pParse->nTempReg==0 ){
  85009. return ++pParse->nMem;
  85010. }
  85011. return pParse->aTempReg[--pParse->nTempReg];
  85012. }
  85013. /*
  85014. ** Deallocate a register, making available for reuse for some other
  85015. ** purpose.
  85016. **
  85017. ** If a register is currently being used by the column cache, then
  85018. ** the deallocation is deferred until the column cache line that uses
  85019. ** the register becomes stale.
  85020. */
  85021. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  85022. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  85023. int i;
  85024. struct yColCache *p;
  85025. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  85026. if( p->iReg==iReg ){
  85027. p->tempReg = 1;
  85028. return;
  85029. }
  85030. }
  85031. pParse->aTempReg[pParse->nTempReg++] = iReg;
  85032. }
  85033. }
  85034. /*
  85035. ** Allocate or deallocate a block of nReg consecutive registers
  85036. */
  85037. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  85038. int i, n;
  85039. i = pParse->iRangeReg;
  85040. n = pParse->nRangeReg;
  85041. if( nReg<=n ){
  85042. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  85043. pParse->iRangeReg += nReg;
  85044. pParse->nRangeReg -= nReg;
  85045. }else{
  85046. i = pParse->nMem+1;
  85047. pParse->nMem += nReg;
  85048. }
  85049. return i;
  85050. }
  85051. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  85052. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  85053. if( nReg>pParse->nRangeReg ){
  85054. pParse->nRangeReg = nReg;
  85055. pParse->iRangeReg = iReg;
  85056. }
  85057. }
  85058. /*
  85059. ** Mark all temporary registers as being unavailable for reuse.
  85060. */
  85061. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  85062. pParse->nTempReg = 0;
  85063. pParse->nRangeReg = 0;
  85064. }
  85065. /*
  85066. ** Validate that no temporary register falls within the range of
  85067. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  85068. ** statements.
  85069. */
  85070. #ifdef SQLITE_DEBUG
  85071. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  85072. int i;
  85073. if( pParse->nRangeReg>0
  85074. && pParse->iRangeReg+pParse->nRangeReg<iLast
  85075. && pParse->iRangeReg>=iFirst
  85076. ){
  85077. return 0;
  85078. }
  85079. for(i=0; i<pParse->nTempReg; i++){
  85080. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  85081. return 0;
  85082. }
  85083. }
  85084. return 1;
  85085. }
  85086. #endif /* SQLITE_DEBUG */
  85087. /************** End of expr.c ************************************************/
  85088. /************** Begin file alter.c *******************************************/
  85089. /*
  85090. ** 2005 February 15
  85091. **
  85092. ** The author disclaims copyright to this source code. In place of
  85093. ** a legal notice, here is a blessing:
  85094. **
  85095. ** May you do good and not evil.
  85096. ** May you find forgiveness for yourself and forgive others.
  85097. ** May you share freely, never taking more than you give.
  85098. **
  85099. *************************************************************************
  85100. ** This file contains C code routines that used to generate VDBE code
  85101. ** that implements the ALTER TABLE command.
  85102. */
  85103. /* #include "sqliteInt.h" */
  85104. /*
  85105. ** The code in this file only exists if we are not omitting the
  85106. ** ALTER TABLE logic from the build.
  85107. */
  85108. #ifndef SQLITE_OMIT_ALTERTABLE
  85109. /*
  85110. ** This function is used by SQL generated to implement the
  85111. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  85112. ** CREATE INDEX command. The second is a table name. The table name in
  85113. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  85114. ** argument and the result returned. Examples:
  85115. **
  85116. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  85117. ** -> 'CREATE TABLE def(a, b, c)'
  85118. **
  85119. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  85120. ** -> 'CREATE INDEX i ON def(a, b, c)'
  85121. */
  85122. static void renameTableFunc(
  85123. sqlite3_context *context,
  85124. int NotUsed,
  85125. sqlite3_value **argv
  85126. ){
  85127. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  85128. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  85129. int token;
  85130. Token tname;
  85131. unsigned char const *zCsr = zSql;
  85132. int len = 0;
  85133. char *zRet;
  85134. sqlite3 *db = sqlite3_context_db_handle(context);
  85135. UNUSED_PARAMETER(NotUsed);
  85136. /* The principle used to locate the table name in the CREATE TABLE
  85137. ** statement is that the table name is the first non-space token that
  85138. ** is immediately followed by a TK_LP or TK_USING token.
  85139. */
  85140. if( zSql ){
  85141. do {
  85142. if( !*zCsr ){
  85143. /* Ran out of input before finding an opening bracket. Return NULL. */
  85144. return;
  85145. }
  85146. /* Store the token that zCsr points to in tname. */
  85147. tname.z = (char*)zCsr;
  85148. tname.n = len;
  85149. /* Advance zCsr to the next token. Store that token type in 'token',
  85150. ** and its length in 'len' (to be used next iteration of this loop).
  85151. */
  85152. do {
  85153. zCsr += len;
  85154. len = sqlite3GetToken(zCsr, &token);
  85155. } while( token==TK_SPACE );
  85156. assert( len>0 );
  85157. } while( token!=TK_LP && token!=TK_USING );
  85158. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  85159. zSql, zTableName, tname.z+tname.n);
  85160. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  85161. }
  85162. }
  85163. /*
  85164. ** This C function implements an SQL user function that is used by SQL code
  85165. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  85166. ** of any foreign key constraints that use the table being renamed as the
  85167. ** parent table. It is passed three arguments:
  85168. **
  85169. ** 1) The complete text of the CREATE TABLE statement being modified,
  85170. ** 2) The old name of the table being renamed, and
  85171. ** 3) The new name of the table being renamed.
  85172. **
  85173. ** It returns the new CREATE TABLE statement. For example:
  85174. **
  85175. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  85176. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  85177. */
  85178. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85179. static void renameParentFunc(
  85180. sqlite3_context *context,
  85181. int NotUsed,
  85182. sqlite3_value **argv
  85183. ){
  85184. sqlite3 *db = sqlite3_context_db_handle(context);
  85185. char *zOutput = 0;
  85186. char *zResult;
  85187. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  85188. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  85189. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  85190. unsigned const char *z; /* Pointer to token */
  85191. int n; /* Length of token z */
  85192. int token; /* Type of token */
  85193. UNUSED_PARAMETER(NotUsed);
  85194. if( zInput==0 || zOld==0 ) return;
  85195. for(z=zInput; *z; z=z+n){
  85196. n = sqlite3GetToken(z, &token);
  85197. if( token==TK_REFERENCES ){
  85198. char *zParent;
  85199. do {
  85200. z += n;
  85201. n = sqlite3GetToken(z, &token);
  85202. }while( token==TK_SPACE );
  85203. if( token==TK_ILLEGAL ) break;
  85204. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  85205. if( zParent==0 ) break;
  85206. sqlite3Dequote(zParent);
  85207. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  85208. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  85209. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  85210. );
  85211. sqlite3DbFree(db, zOutput);
  85212. zOutput = zOut;
  85213. zInput = &z[n];
  85214. }
  85215. sqlite3DbFree(db, zParent);
  85216. }
  85217. }
  85218. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  85219. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  85220. sqlite3DbFree(db, zOutput);
  85221. }
  85222. #endif
  85223. #ifndef SQLITE_OMIT_TRIGGER
  85224. /* This function is used by SQL generated to implement the
  85225. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  85226. ** statement. The second is a table name. The table name in the CREATE
  85227. ** TRIGGER statement is replaced with the third argument and the result
  85228. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  85229. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  85230. */
  85231. static void renameTriggerFunc(
  85232. sqlite3_context *context,
  85233. int NotUsed,
  85234. sqlite3_value **argv
  85235. ){
  85236. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  85237. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  85238. int token;
  85239. Token tname;
  85240. int dist = 3;
  85241. unsigned char const *zCsr = zSql;
  85242. int len = 0;
  85243. char *zRet;
  85244. sqlite3 *db = sqlite3_context_db_handle(context);
  85245. UNUSED_PARAMETER(NotUsed);
  85246. /* The principle used to locate the table name in the CREATE TRIGGER
  85247. ** statement is that the table name is the first token that is immediately
  85248. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  85249. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  85250. */
  85251. if( zSql ){
  85252. do {
  85253. if( !*zCsr ){
  85254. /* Ran out of input before finding the table name. Return NULL. */
  85255. return;
  85256. }
  85257. /* Store the token that zCsr points to in tname. */
  85258. tname.z = (char*)zCsr;
  85259. tname.n = len;
  85260. /* Advance zCsr to the next token. Store that token type in 'token',
  85261. ** and its length in 'len' (to be used next iteration of this loop).
  85262. */
  85263. do {
  85264. zCsr += len;
  85265. len = sqlite3GetToken(zCsr, &token);
  85266. }while( token==TK_SPACE );
  85267. assert( len>0 );
  85268. /* Variable 'dist' stores the number of tokens read since the most
  85269. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  85270. ** token is read and 'dist' equals 2, the condition stated above
  85271. ** to be met.
  85272. **
  85273. ** Note that ON cannot be a database, table or column name, so
  85274. ** there is no need to worry about syntax like
  85275. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  85276. */
  85277. dist++;
  85278. if( token==TK_DOT || token==TK_ON ){
  85279. dist = 0;
  85280. }
  85281. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  85282. /* Variable tname now contains the token that is the old table-name
  85283. ** in the CREATE TRIGGER statement.
  85284. */
  85285. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  85286. zSql, zTableName, tname.z+tname.n);
  85287. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  85288. }
  85289. }
  85290. #endif /* !SQLITE_OMIT_TRIGGER */
  85291. /*
  85292. ** Register built-in functions used to help implement ALTER TABLE
  85293. */
  85294. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  85295. static FuncDef aAlterTableFuncs[] = {
  85296. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  85297. #ifndef SQLITE_OMIT_TRIGGER
  85298. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  85299. #endif
  85300. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85301. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  85302. #endif
  85303. };
  85304. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  85305. }
  85306. /*
  85307. ** This function is used to create the text of expressions of the form:
  85308. **
  85309. ** name=<constant1> OR name=<constant2> OR ...
  85310. **
  85311. ** If argument zWhere is NULL, then a pointer string containing the text
  85312. ** "name=<constant>" is returned, where <constant> is the quoted version
  85313. ** of the string passed as argument zConstant. The returned buffer is
  85314. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  85315. ** caller to ensure that it is eventually freed.
  85316. **
  85317. ** If argument zWhere is not NULL, then the string returned is
  85318. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  85319. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  85320. **
  85321. */
  85322. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  85323. char *zNew;
  85324. if( !zWhere ){
  85325. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  85326. }else{
  85327. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  85328. sqlite3DbFree(db, zWhere);
  85329. }
  85330. return zNew;
  85331. }
  85332. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  85333. /*
  85334. ** Generate the text of a WHERE expression which can be used to select all
  85335. ** tables that have foreign key constraints that refer to table pTab (i.e.
  85336. ** constraints for which pTab is the parent table) from the sqlite_master
  85337. ** table.
  85338. */
  85339. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  85340. FKey *p;
  85341. char *zWhere = 0;
  85342. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  85343. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  85344. }
  85345. return zWhere;
  85346. }
  85347. #endif
  85348. /*
  85349. ** Generate the text of a WHERE expression which can be used to select all
  85350. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  85351. ** table pTab has no temporary triggers, or is itself stored in the
  85352. ** temporary database, NULL is returned.
  85353. */
  85354. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  85355. Trigger *pTrig;
  85356. char *zWhere = 0;
  85357. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  85358. /* If the table is not located in the temp-db (in which case NULL is
  85359. ** returned, loop through the tables list of triggers. For each trigger
  85360. ** that is not part of the temp-db schema, add a clause to the WHERE
  85361. ** expression being built up in zWhere.
  85362. */
  85363. if( pTab->pSchema!=pTempSchema ){
  85364. sqlite3 *db = pParse->db;
  85365. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  85366. if( pTrig->pSchema==pTempSchema ){
  85367. zWhere = whereOrName(db, zWhere, pTrig->zName);
  85368. }
  85369. }
  85370. }
  85371. if( zWhere ){
  85372. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  85373. sqlite3DbFree(pParse->db, zWhere);
  85374. zWhere = zNew;
  85375. }
  85376. return zWhere;
  85377. }
  85378. /*
  85379. ** Generate code to drop and reload the internal representation of table
  85380. ** pTab from the database, including triggers and temporary triggers.
  85381. ** Argument zName is the name of the table in the database schema at
  85382. ** the time the generated code is executed. This can be different from
  85383. ** pTab->zName if this function is being called to code part of an
  85384. ** "ALTER TABLE RENAME TO" statement.
  85385. */
  85386. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  85387. Vdbe *v;
  85388. char *zWhere;
  85389. int iDb; /* Index of database containing pTab */
  85390. #ifndef SQLITE_OMIT_TRIGGER
  85391. Trigger *pTrig;
  85392. #endif
  85393. v = sqlite3GetVdbe(pParse);
  85394. if( NEVER(v==0) ) return;
  85395. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  85396. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  85397. assert( iDb>=0 );
  85398. #ifndef SQLITE_OMIT_TRIGGER
  85399. /* Drop any table triggers from the internal schema. */
  85400. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  85401. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  85402. assert( iTrigDb==iDb || iTrigDb==1 );
  85403. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  85404. }
  85405. #endif
  85406. /* Drop the table and index from the internal schema. */
  85407. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  85408. /* Reload the table, index and permanent trigger schemas. */
  85409. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  85410. if( !zWhere ) return;
  85411. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  85412. #ifndef SQLITE_OMIT_TRIGGER
  85413. /* Now, if the table is not stored in the temp database, reload any temp
  85414. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  85415. */
  85416. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  85417. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  85418. }
  85419. #endif
  85420. }
  85421. /*
  85422. ** Parameter zName is the name of a table that is about to be altered
  85423. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  85424. ** If the table is a system table, this function leaves an error message
  85425. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  85426. **
  85427. ** Or, if zName is not a system table, zero is returned.
  85428. */
  85429. static int isSystemTable(Parse *pParse, const char *zName){
  85430. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  85431. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  85432. return 1;
  85433. }
  85434. return 0;
  85435. }
  85436. /*
  85437. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  85438. ** command.
  85439. */
  85440. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  85441. Parse *pParse, /* Parser context. */
  85442. SrcList *pSrc, /* The table to rename. */
  85443. Token *pName /* The new table name. */
  85444. ){
  85445. int iDb; /* Database that contains the table */
  85446. char *zDb; /* Name of database iDb */
  85447. Table *pTab; /* Table being renamed */
  85448. char *zName = 0; /* NULL-terminated version of pName */
  85449. sqlite3 *db = pParse->db; /* Database connection */
  85450. int nTabName; /* Number of UTF-8 characters in zTabName */
  85451. const char *zTabName; /* Original name of the table */
  85452. Vdbe *v;
  85453. #ifndef SQLITE_OMIT_TRIGGER
  85454. char *zWhere = 0; /* Where clause to locate temp triggers */
  85455. #endif
  85456. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  85457. int savedDbFlags; /* Saved value of db->flags */
  85458. savedDbFlags = db->flags;
  85459. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  85460. assert( pSrc->nSrc==1 );
  85461. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  85462. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  85463. if( !pTab ) goto exit_rename_table;
  85464. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  85465. zDb = db->aDb[iDb].zName;
  85466. db->flags |= SQLITE_PreferBuiltin;
  85467. /* Get a NULL terminated version of the new table name. */
  85468. zName = sqlite3NameFromToken(db, pName);
  85469. if( !zName ) goto exit_rename_table;
  85470. /* Check that a table or index named 'zName' does not already exist
  85471. ** in database iDb. If so, this is an error.
  85472. */
  85473. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  85474. sqlite3ErrorMsg(pParse,
  85475. "there is already another table or index with this name: %s", zName);
  85476. goto exit_rename_table;
  85477. }
  85478. /* Make sure it is not a system table being altered, or a reserved name
  85479. ** that the table is being renamed to.
  85480. */
  85481. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  85482. goto exit_rename_table;
  85483. }
  85484. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  85485. exit_rename_table;
  85486. }
  85487. #ifndef SQLITE_OMIT_VIEW
  85488. if( pTab->pSelect ){
  85489. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  85490. goto exit_rename_table;
  85491. }
  85492. #endif
  85493. #ifndef SQLITE_OMIT_AUTHORIZATION
  85494. /* Invoke the authorization callback. */
  85495. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  85496. goto exit_rename_table;
  85497. }
  85498. #endif
  85499. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85500. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  85501. goto exit_rename_table;
  85502. }
  85503. if( IsVirtual(pTab) ){
  85504. pVTab = sqlite3GetVTable(db, pTab);
  85505. if( pVTab->pVtab->pModule->xRename==0 ){
  85506. pVTab = 0;
  85507. }
  85508. }
  85509. #endif
  85510. /* Begin a transaction for database iDb.
  85511. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  85512. ** schema). Open a statement transaction if the table is a virtual
  85513. ** table.
  85514. */
  85515. v = sqlite3GetVdbe(pParse);
  85516. if( v==0 ){
  85517. goto exit_rename_table;
  85518. }
  85519. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  85520. sqlite3ChangeCookie(pParse, iDb);
  85521. /* If this is a virtual table, invoke the xRename() function if
  85522. ** one is defined. The xRename() callback will modify the names
  85523. ** of any resources used by the v-table implementation (including other
  85524. ** SQLite tables) that are identified by the name of the virtual table.
  85525. */
  85526. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85527. if( pVTab ){
  85528. int i = ++pParse->nMem;
  85529. sqlite3VdbeLoadString(v, i, zName);
  85530. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  85531. sqlite3MayAbort(pParse);
  85532. }
  85533. #endif
  85534. /* figure out how many UTF-8 characters are in zName */
  85535. zTabName = pTab->zName;
  85536. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  85537. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  85538. if( db->flags&SQLITE_ForeignKeys ){
  85539. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  85540. ** statements corresponding to all child tables of foreign key constraints
  85541. ** for which the renamed table is the parent table. */
  85542. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  85543. sqlite3NestedParse(pParse,
  85544. "UPDATE \"%w\".%s SET "
  85545. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  85546. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  85547. sqlite3DbFree(db, zWhere);
  85548. }
  85549. }
  85550. #endif
  85551. /* Modify the sqlite_master table to use the new table name. */
  85552. sqlite3NestedParse(pParse,
  85553. "UPDATE %Q.%s SET "
  85554. #ifdef SQLITE_OMIT_TRIGGER
  85555. "sql = sqlite_rename_table(sql, %Q), "
  85556. #else
  85557. "sql = CASE "
  85558. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  85559. "ELSE sqlite_rename_table(sql, %Q) END, "
  85560. #endif
  85561. "tbl_name = %Q, "
  85562. "name = CASE "
  85563. "WHEN type='table' THEN %Q "
  85564. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  85565. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  85566. "ELSE name END "
  85567. "WHERE tbl_name=%Q COLLATE nocase AND "
  85568. "(type='table' OR type='index' OR type='trigger');",
  85569. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  85570. #ifndef SQLITE_OMIT_TRIGGER
  85571. zName,
  85572. #endif
  85573. zName, nTabName, zTabName
  85574. );
  85575. #ifndef SQLITE_OMIT_AUTOINCREMENT
  85576. /* If the sqlite_sequence table exists in this database, then update
  85577. ** it with the new table name.
  85578. */
  85579. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  85580. sqlite3NestedParse(pParse,
  85581. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  85582. zDb, zName, pTab->zName);
  85583. }
  85584. #endif
  85585. #ifndef SQLITE_OMIT_TRIGGER
  85586. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  85587. ** table. Don't do this if the table being ALTERed is itself located in
  85588. ** the temp database.
  85589. */
  85590. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  85591. sqlite3NestedParse(pParse,
  85592. "UPDATE sqlite_temp_master SET "
  85593. "sql = sqlite_rename_trigger(sql, %Q), "
  85594. "tbl_name = %Q "
  85595. "WHERE %s;", zName, zName, zWhere);
  85596. sqlite3DbFree(db, zWhere);
  85597. }
  85598. #endif
  85599. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  85600. if( db->flags&SQLITE_ForeignKeys ){
  85601. FKey *p;
  85602. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  85603. Table *pFrom = p->pFrom;
  85604. if( pFrom!=pTab ){
  85605. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  85606. }
  85607. }
  85608. }
  85609. #endif
  85610. /* Drop and reload the internal table schema. */
  85611. reloadTableSchema(pParse, pTab, zName);
  85612. exit_rename_table:
  85613. sqlite3SrcListDelete(db, pSrc);
  85614. sqlite3DbFree(db, zName);
  85615. db->flags = savedDbFlags;
  85616. }
  85617. /*
  85618. ** This function is called after an "ALTER TABLE ... ADD" statement
  85619. ** has been parsed. Argument pColDef contains the text of the new
  85620. ** column definition.
  85621. **
  85622. ** The Table structure pParse->pNewTable was extended to include
  85623. ** the new column during parsing.
  85624. */
  85625. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  85626. Table *pNew; /* Copy of pParse->pNewTable */
  85627. Table *pTab; /* Table being altered */
  85628. int iDb; /* Database number */
  85629. const char *zDb; /* Database name */
  85630. const char *zTab; /* Table name */
  85631. char *zCol; /* Null-terminated column definition */
  85632. Column *pCol; /* The new column */
  85633. Expr *pDflt; /* Default value for the new column */
  85634. sqlite3 *db; /* The database connection; */
  85635. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  85636. db = pParse->db;
  85637. if( pParse->nErr || db->mallocFailed ) return;
  85638. assert( v!=0 );
  85639. pNew = pParse->pNewTable;
  85640. assert( pNew );
  85641. assert( sqlite3BtreeHoldsAllMutexes(db) );
  85642. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  85643. zDb = db->aDb[iDb].zName;
  85644. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  85645. pCol = &pNew->aCol[pNew->nCol-1];
  85646. pDflt = pCol->pDflt;
  85647. pTab = sqlite3FindTable(db, zTab, zDb);
  85648. assert( pTab );
  85649. #ifndef SQLITE_OMIT_AUTHORIZATION
  85650. /* Invoke the authorization callback. */
  85651. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  85652. return;
  85653. }
  85654. #endif
  85655. /* If the default value for the new column was specified with a
  85656. ** literal NULL, then set pDflt to 0. This simplifies checking
  85657. ** for an SQL NULL default below.
  85658. */
  85659. assert( pDflt==0 || pDflt->op==TK_SPAN );
  85660. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  85661. pDflt = 0;
  85662. }
  85663. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  85664. ** If there is a NOT NULL constraint, then the default value for the
  85665. ** column must not be NULL.
  85666. */
  85667. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  85668. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  85669. return;
  85670. }
  85671. if( pNew->pIndex ){
  85672. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  85673. return;
  85674. }
  85675. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  85676. sqlite3ErrorMsg(pParse,
  85677. "Cannot add a REFERENCES column with non-NULL default value");
  85678. return;
  85679. }
  85680. if( pCol->notNull && !pDflt ){
  85681. sqlite3ErrorMsg(pParse,
  85682. "Cannot add a NOT NULL column with default value NULL");
  85683. return;
  85684. }
  85685. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  85686. ** can handle (i.e. not CURRENT_TIME etc.)
  85687. */
  85688. if( pDflt ){
  85689. sqlite3_value *pVal = 0;
  85690. int rc;
  85691. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  85692. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  85693. if( rc!=SQLITE_OK ){
  85694. assert( db->mallocFailed == 1 );
  85695. return;
  85696. }
  85697. if( !pVal ){
  85698. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  85699. return;
  85700. }
  85701. sqlite3ValueFree(pVal);
  85702. }
  85703. /* Modify the CREATE TABLE statement. */
  85704. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  85705. if( zCol ){
  85706. char *zEnd = &zCol[pColDef->n-1];
  85707. int savedDbFlags = db->flags;
  85708. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  85709. *zEnd-- = '\0';
  85710. }
  85711. db->flags |= SQLITE_PreferBuiltin;
  85712. sqlite3NestedParse(pParse,
  85713. "UPDATE \"%w\".%s SET "
  85714. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  85715. "WHERE type = 'table' AND name = %Q",
  85716. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  85717. zTab
  85718. );
  85719. sqlite3DbFree(db, zCol);
  85720. db->flags = savedDbFlags;
  85721. }
  85722. /* If the default value of the new column is NULL, then the file
  85723. ** format to 2. If the default value of the new column is not NULL,
  85724. ** the file format be 3. Back when this feature was first added
  85725. ** in 2006, we went to the trouble to upgrade the file format to the
  85726. ** minimum support values. But 10-years on, we can assume that all
  85727. ** extent versions of SQLite support file-format 4, so we always and
  85728. ** unconditionally upgrade to 4.
  85729. */
  85730. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT,
  85731. SQLITE_MAX_FILE_FORMAT);
  85732. /* Reload the schema of the modified table. */
  85733. reloadTableSchema(pParse, pTab, pTab->zName);
  85734. }
  85735. /*
  85736. ** This function is called by the parser after the table-name in
  85737. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  85738. ** pSrc is the full-name of the table being altered.
  85739. **
  85740. ** This routine makes a (partial) copy of the Table structure
  85741. ** for the table being altered and sets Parse.pNewTable to point
  85742. ** to it. Routines called by the parser as the column definition
  85743. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  85744. ** the copy. The copy of the Table structure is deleted by tokenize.c
  85745. ** after parsing is finished.
  85746. **
  85747. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  85748. ** coding the "ALTER TABLE ... ADD" statement.
  85749. */
  85750. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  85751. Table *pNew;
  85752. Table *pTab;
  85753. Vdbe *v;
  85754. int iDb;
  85755. int i;
  85756. int nAlloc;
  85757. sqlite3 *db = pParse->db;
  85758. /* Look up the table being altered. */
  85759. assert( pParse->pNewTable==0 );
  85760. assert( sqlite3BtreeHoldsAllMutexes(db) );
  85761. if( db->mallocFailed ) goto exit_begin_add_column;
  85762. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  85763. if( !pTab ) goto exit_begin_add_column;
  85764. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85765. if( IsVirtual(pTab) ){
  85766. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  85767. goto exit_begin_add_column;
  85768. }
  85769. #endif
  85770. /* Make sure this is not an attempt to ALTER a view. */
  85771. if( pTab->pSelect ){
  85772. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  85773. goto exit_begin_add_column;
  85774. }
  85775. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  85776. goto exit_begin_add_column;
  85777. }
  85778. assert( pTab->addColOffset>0 );
  85779. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85780. /* Put a copy of the Table struct in Parse.pNewTable for the
  85781. ** sqlite3AddColumn() function and friends to modify. But modify
  85782. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  85783. ** prefix, we insure that the name will not collide with an existing
  85784. ** table because user table are not allowed to have the "sqlite_"
  85785. ** prefix on their name.
  85786. */
  85787. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  85788. if( !pNew ) goto exit_begin_add_column;
  85789. pParse->pNewTable = pNew;
  85790. pNew->nRef = 1;
  85791. pNew->nCol = pTab->nCol;
  85792. assert( pNew->nCol>0 );
  85793. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  85794. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  85795. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  85796. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  85797. if( !pNew->aCol || !pNew->zName ){
  85798. assert( db->mallocFailed );
  85799. goto exit_begin_add_column;
  85800. }
  85801. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  85802. for(i=0; i<pNew->nCol; i++){
  85803. Column *pCol = &pNew->aCol[i];
  85804. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  85805. pCol->zColl = 0;
  85806. pCol->pDflt = 0;
  85807. }
  85808. pNew->pSchema = db->aDb[iDb].pSchema;
  85809. pNew->addColOffset = pTab->addColOffset;
  85810. pNew->nRef = 1;
  85811. /* Begin a transaction and increment the schema cookie. */
  85812. sqlite3BeginWriteOperation(pParse, 0, iDb);
  85813. v = sqlite3GetVdbe(pParse);
  85814. if( !v ) goto exit_begin_add_column;
  85815. sqlite3ChangeCookie(pParse, iDb);
  85816. exit_begin_add_column:
  85817. sqlite3SrcListDelete(db, pSrc);
  85818. return;
  85819. }
  85820. #endif /* SQLITE_ALTER_TABLE */
  85821. /************** End of alter.c ***********************************************/
  85822. /************** Begin file analyze.c *****************************************/
  85823. /*
  85824. ** 2005-07-08
  85825. **
  85826. ** The author disclaims copyright to this source code. In place of
  85827. ** a legal notice, here is a blessing:
  85828. **
  85829. ** May you do good and not evil.
  85830. ** May you find forgiveness for yourself and forgive others.
  85831. ** May you share freely, never taking more than you give.
  85832. **
  85833. *************************************************************************
  85834. ** This file contains code associated with the ANALYZE command.
  85835. **
  85836. ** The ANALYZE command gather statistics about the content of tables
  85837. ** and indices. These statistics are made available to the query planner
  85838. ** to help it make better decisions about how to perform queries.
  85839. **
  85840. ** The following system tables are or have been supported:
  85841. **
  85842. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  85843. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  85844. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  85845. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  85846. **
  85847. ** Additional tables might be added in future releases of SQLite.
  85848. ** The sqlite_stat2 table is not created or used unless the SQLite version
  85849. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  85850. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  85851. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  85852. ** created and used by SQLite versions 3.7.9 and later and with
  85853. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  85854. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  85855. ** version of sqlite_stat3 and is only available when compiled with
  85856. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  85857. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  85858. ** are both enabled, then STAT4 takes precedence.
  85859. **
  85860. ** For most applications, sqlite_stat1 provides all the statistics required
  85861. ** for the query planner to make good choices.
  85862. **
  85863. ** Format of sqlite_stat1:
  85864. **
  85865. ** There is normally one row per index, with the index identified by the
  85866. ** name in the idx column. The tbl column is the name of the table to
  85867. ** which the index belongs. In each such row, the stat column will be
  85868. ** a string consisting of a list of integers. The first integer in this
  85869. ** list is the number of rows in the index. (This is the same as the
  85870. ** number of rows in the table, except for partial indices.) The second
  85871. ** integer is the average number of rows in the index that have the same
  85872. ** value in the first column of the index. The third integer is the average
  85873. ** number of rows in the index that have the same value for the first two
  85874. ** columns. The N-th integer (for N>1) is the average number of rows in
  85875. ** the index which have the same value for the first N-1 columns. For
  85876. ** a K-column index, there will be K+1 integers in the stat column. If
  85877. ** the index is unique, then the last integer will be 1.
  85878. **
  85879. ** The list of integers in the stat column can optionally be followed
  85880. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  85881. ** must be separated from the last integer by a single space. If the
  85882. ** "unordered" keyword is present, then the query planner assumes that
  85883. ** the index is unordered and will not use the index for a range query.
  85884. **
  85885. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  85886. ** column contains a single integer which is the (estimated) number of
  85887. ** rows in the table identified by sqlite_stat1.tbl.
  85888. **
  85889. ** Format of sqlite_stat2:
  85890. **
  85891. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  85892. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  85893. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  85894. ** about the distribution of keys within an index. The index is identified by
  85895. ** the "idx" column and the "tbl" column is the name of the table to which
  85896. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  85897. ** table for each index.
  85898. **
  85899. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  85900. ** inclusive are samples of the left-most key value in the index taken at
  85901. ** evenly spaced points along the index. Let the number of samples be S
  85902. ** (10 in the standard build) and let C be the number of rows in the index.
  85903. ** Then the sampled rows are given by:
  85904. **
  85905. ** rownumber = (i*C*2 + C)/(S*2)
  85906. **
  85907. ** For i between 0 and S-1. Conceptually, the index space is divided into
  85908. ** S uniform buckets and the samples are the middle row from each bucket.
  85909. **
  85910. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  85911. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  85912. ** writes the sqlite_stat2 table. This version of SQLite only supports
  85913. ** sqlite_stat3.
  85914. **
  85915. ** Format for sqlite_stat3:
  85916. **
  85917. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  85918. ** sqlite_stat4 format will be described first. Further information
  85919. ** about sqlite_stat3 follows the sqlite_stat4 description.
  85920. **
  85921. ** Format for sqlite_stat4:
  85922. **
  85923. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  85924. ** to aid the query planner in choosing good indices based on the values
  85925. ** that indexed columns are compared against in the WHERE clauses of
  85926. ** queries.
  85927. **
  85928. ** The sqlite_stat4 table contains multiple entries for each index.
  85929. ** The idx column names the index and the tbl column is the table of the
  85930. ** index. If the idx and tbl columns are the same, then the sample is
  85931. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  85932. ** binary encoding of a key from the index. The nEq column is a
  85933. ** list of integers. The first integer is the approximate number
  85934. ** of entries in the index whose left-most column exactly matches
  85935. ** the left-most column of the sample. The second integer in nEq
  85936. ** is the approximate number of entries in the index where the
  85937. ** first two columns match the first two columns of the sample.
  85938. ** And so forth. nLt is another list of integers that show the approximate
  85939. ** number of entries that are strictly less than the sample. The first
  85940. ** integer in nLt contains the number of entries in the index where the
  85941. ** left-most column is less than the left-most column of the sample.
  85942. ** The K-th integer in the nLt entry is the number of index entries
  85943. ** where the first K columns are less than the first K columns of the
  85944. ** sample. The nDLt column is like nLt except that it contains the
  85945. ** number of distinct entries in the index that are less than the
  85946. ** sample.
  85947. **
  85948. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  85949. ** The ANALYZE command will typically generate sqlite_stat4 tables
  85950. ** that contain between 10 and 40 samples which are distributed across
  85951. ** the key space, though not uniformly, and which include samples with
  85952. ** large nEq values.
  85953. **
  85954. ** Format for sqlite_stat3 redux:
  85955. **
  85956. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  85957. ** looks at the left-most column of the index. The sqlite_stat3.sample
  85958. ** column contains the actual value of the left-most column instead
  85959. ** of a blob encoding of the complete index key as is found in
  85960. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  85961. ** all contain just a single integer which is the same as the first
  85962. ** integer in the equivalent columns in sqlite_stat4.
  85963. */
  85964. #ifndef SQLITE_OMIT_ANALYZE
  85965. /* #include "sqliteInt.h" */
  85966. #if defined(SQLITE_ENABLE_STAT4)
  85967. # define IsStat4 1
  85968. # define IsStat3 0
  85969. #elif defined(SQLITE_ENABLE_STAT3)
  85970. # define IsStat4 0
  85971. # define IsStat3 1
  85972. #else
  85973. # define IsStat4 0
  85974. # define IsStat3 0
  85975. # undef SQLITE_STAT4_SAMPLES
  85976. # define SQLITE_STAT4_SAMPLES 1
  85977. #endif
  85978. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  85979. /*
  85980. ** This routine generates code that opens the sqlite_statN tables.
  85981. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  85982. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  85983. ** appropriate compile-time options are provided.
  85984. **
  85985. ** If the sqlite_statN tables do not previously exist, it is created.
  85986. **
  85987. ** Argument zWhere may be a pointer to a buffer containing a table name,
  85988. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  85989. ** the sqlite_statN tables associated with the named table are deleted.
  85990. ** If zWhere==0, then code is generated to delete all stat table entries.
  85991. */
  85992. static void openStatTable(
  85993. Parse *pParse, /* Parsing context */
  85994. int iDb, /* The database we are looking in */
  85995. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  85996. const char *zWhere, /* Delete entries for this table or index */
  85997. const char *zWhereType /* Either "tbl" or "idx" */
  85998. ){
  85999. static const struct {
  86000. const char *zName;
  86001. const char *zCols;
  86002. } aTable[] = {
  86003. { "sqlite_stat1", "tbl,idx,stat" },
  86004. #if defined(SQLITE_ENABLE_STAT4)
  86005. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  86006. { "sqlite_stat3", 0 },
  86007. #elif defined(SQLITE_ENABLE_STAT3)
  86008. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  86009. { "sqlite_stat4", 0 },
  86010. #else
  86011. { "sqlite_stat3", 0 },
  86012. { "sqlite_stat4", 0 },
  86013. #endif
  86014. };
  86015. int i;
  86016. sqlite3 *db = pParse->db;
  86017. Db *pDb;
  86018. Vdbe *v = sqlite3GetVdbe(pParse);
  86019. int aRoot[ArraySize(aTable)];
  86020. u8 aCreateTbl[ArraySize(aTable)];
  86021. if( v==0 ) return;
  86022. assert( sqlite3BtreeHoldsAllMutexes(db) );
  86023. assert( sqlite3VdbeDb(v)==db );
  86024. pDb = &db->aDb[iDb];
  86025. /* Create new statistic tables if they do not exist, or clear them
  86026. ** if they do already exist.
  86027. */
  86028. for(i=0; i<ArraySize(aTable); i++){
  86029. const char *zTab = aTable[i].zName;
  86030. Table *pStat;
  86031. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  86032. if( aTable[i].zCols ){
  86033. /* The sqlite_statN table does not exist. Create it. Note that a
  86034. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  86035. ** of the new table in register pParse->regRoot. This is important
  86036. ** because the OpenWrite opcode below will be needing it. */
  86037. sqlite3NestedParse(pParse,
  86038. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  86039. );
  86040. aRoot[i] = pParse->regRoot;
  86041. aCreateTbl[i] = OPFLAG_P2ISREG;
  86042. }
  86043. }else{
  86044. /* The table already exists. If zWhere is not NULL, delete all entries
  86045. ** associated with the table zWhere. If zWhere is NULL, delete the
  86046. ** entire contents of the table. */
  86047. aRoot[i] = pStat->tnum;
  86048. aCreateTbl[i] = 0;
  86049. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  86050. if( zWhere ){
  86051. sqlite3NestedParse(pParse,
  86052. "DELETE FROM %Q.%s WHERE %s=%Q",
  86053. pDb->zName, zTab, zWhereType, zWhere
  86054. );
  86055. }else{
  86056. /* The sqlite_stat[134] table already exists. Delete all rows. */
  86057. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  86058. }
  86059. }
  86060. }
  86061. /* Open the sqlite_stat[134] tables for writing. */
  86062. for(i=0; aTable[i].zCols; i++){
  86063. assert( i<ArraySize(aTable) );
  86064. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  86065. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  86066. VdbeComment((v, aTable[i].zName));
  86067. }
  86068. }
  86069. /*
  86070. ** Recommended number of samples for sqlite_stat4
  86071. */
  86072. #ifndef SQLITE_STAT4_SAMPLES
  86073. # define SQLITE_STAT4_SAMPLES 24
  86074. #endif
  86075. /*
  86076. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  86077. ** share an instance of the following structure to hold their state
  86078. ** information.
  86079. */
  86080. typedef struct Stat4Accum Stat4Accum;
  86081. typedef struct Stat4Sample Stat4Sample;
  86082. struct Stat4Sample {
  86083. tRowcnt *anEq; /* sqlite_stat4.nEq */
  86084. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  86085. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86086. tRowcnt *anLt; /* sqlite_stat4.nLt */
  86087. union {
  86088. i64 iRowid; /* Rowid in main table of the key */
  86089. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  86090. } u;
  86091. u32 nRowid; /* Sizeof aRowid[] */
  86092. u8 isPSample; /* True if a periodic sample */
  86093. int iCol; /* If !isPSample, the reason for inclusion */
  86094. u32 iHash; /* Tiebreaker hash */
  86095. #endif
  86096. };
  86097. struct Stat4Accum {
  86098. tRowcnt nRow; /* Number of rows in the entire table */
  86099. tRowcnt nPSample; /* How often to do a periodic sample */
  86100. int nCol; /* Number of columns in index + pk/rowid */
  86101. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  86102. int mxSample; /* Maximum number of samples to accumulate */
  86103. Stat4Sample current; /* Current row as a Stat4Sample */
  86104. u32 iPrn; /* Pseudo-random number used for sampling */
  86105. Stat4Sample *aBest; /* Array of nCol best samples */
  86106. int iMin; /* Index in a[] of entry with minimum score */
  86107. int nSample; /* Current number of samples */
  86108. int iGet; /* Index of current sample accessed by stat_get() */
  86109. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  86110. sqlite3 *db; /* Database connection, for malloc() */
  86111. };
  86112. /* Reclaim memory used by a Stat4Sample
  86113. */
  86114. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86115. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  86116. assert( db!=0 );
  86117. if( p->nRowid ){
  86118. sqlite3DbFree(db, p->u.aRowid);
  86119. p->nRowid = 0;
  86120. }
  86121. }
  86122. #endif
  86123. /* Initialize the BLOB value of a ROWID
  86124. */
  86125. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86126. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  86127. assert( db!=0 );
  86128. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  86129. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  86130. if( p->u.aRowid ){
  86131. p->nRowid = n;
  86132. memcpy(p->u.aRowid, pData, n);
  86133. }else{
  86134. p->nRowid = 0;
  86135. }
  86136. }
  86137. #endif
  86138. /* Initialize the INTEGER value of a ROWID.
  86139. */
  86140. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86141. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  86142. assert( db!=0 );
  86143. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  86144. p->nRowid = 0;
  86145. p->u.iRowid = iRowid;
  86146. }
  86147. #endif
  86148. /*
  86149. ** Copy the contents of object (*pFrom) into (*pTo).
  86150. */
  86151. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86152. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  86153. pTo->isPSample = pFrom->isPSample;
  86154. pTo->iCol = pFrom->iCol;
  86155. pTo->iHash = pFrom->iHash;
  86156. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  86157. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  86158. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  86159. if( pFrom->nRowid ){
  86160. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  86161. }else{
  86162. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  86163. }
  86164. }
  86165. #endif
  86166. /*
  86167. ** Reclaim all memory of a Stat4Accum structure.
  86168. */
  86169. static void stat4Destructor(void *pOld){
  86170. Stat4Accum *p = (Stat4Accum*)pOld;
  86171. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86172. int i;
  86173. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  86174. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  86175. sampleClear(p->db, &p->current);
  86176. #endif
  86177. sqlite3DbFree(p->db, p);
  86178. }
  86179. /*
  86180. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  86181. ** are:
  86182. ** N: The number of columns in the index including the rowid/pk (note 1)
  86183. ** K: The number of columns in the index excluding the rowid/pk.
  86184. ** C: The number of rows in the index (note 2)
  86185. **
  86186. ** Note 1: In the special case of the covering index that implements a
  86187. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  86188. ** total number of columns in the table.
  86189. **
  86190. ** Note 2: C is only used for STAT3 and STAT4.
  86191. **
  86192. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  86193. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  86194. ** PRIMARY KEY of the table. The covering index that implements the
  86195. ** original WITHOUT ROWID table as N==K as a special case.
  86196. **
  86197. ** This routine allocates the Stat4Accum object in heap memory. The return
  86198. ** value is a pointer to the Stat4Accum object. The datatype of the
  86199. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  86200. ** object.
  86201. */
  86202. static void statInit(
  86203. sqlite3_context *context,
  86204. int argc,
  86205. sqlite3_value **argv
  86206. ){
  86207. Stat4Accum *p;
  86208. int nCol; /* Number of columns in index being sampled */
  86209. int nKeyCol; /* Number of key columns */
  86210. int nColUp; /* nCol rounded up for alignment */
  86211. int n; /* Bytes of space to allocate */
  86212. sqlite3 *db; /* Database connection */
  86213. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86214. int mxSample = SQLITE_STAT4_SAMPLES;
  86215. #endif
  86216. /* Decode the three function arguments */
  86217. UNUSED_PARAMETER(argc);
  86218. nCol = sqlite3_value_int(argv[0]);
  86219. assert( nCol>0 );
  86220. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  86221. nKeyCol = sqlite3_value_int(argv[1]);
  86222. assert( nKeyCol<=nCol );
  86223. assert( nKeyCol>0 );
  86224. /* Allocate the space required for the Stat4Accum object */
  86225. n = sizeof(*p)
  86226. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  86227. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  86228. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86229. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  86230. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  86231. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  86232. #endif
  86233. ;
  86234. db = sqlite3_context_db_handle(context);
  86235. p = sqlite3DbMallocZero(db, n);
  86236. if( p==0 ){
  86237. sqlite3_result_error_nomem(context);
  86238. return;
  86239. }
  86240. p->db = db;
  86241. p->nRow = 0;
  86242. p->nCol = nCol;
  86243. p->nKeyCol = nKeyCol;
  86244. p->current.anDLt = (tRowcnt*)&p[1];
  86245. p->current.anEq = &p->current.anDLt[nColUp];
  86246. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86247. {
  86248. u8 *pSpace; /* Allocated space not yet assigned */
  86249. int i; /* Used to iterate through p->aSample[] */
  86250. p->iGet = -1;
  86251. p->mxSample = mxSample;
  86252. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  86253. p->current.anLt = &p->current.anEq[nColUp];
  86254. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  86255. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  86256. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  86257. p->aBest = &p->a[mxSample];
  86258. pSpace = (u8*)(&p->a[mxSample+nCol]);
  86259. for(i=0; i<(mxSample+nCol); i++){
  86260. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  86261. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  86262. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  86263. }
  86264. assert( (pSpace - (u8*)p)==n );
  86265. for(i=0; i<nCol; i++){
  86266. p->aBest[i].iCol = i;
  86267. }
  86268. }
  86269. #endif
  86270. /* Return a pointer to the allocated object to the caller. Note that
  86271. ** only the pointer (the 2nd parameter) matters. The size of the object
  86272. ** (given by the 3rd parameter) is never used and can be any positive
  86273. ** value. */
  86274. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  86275. }
  86276. static const FuncDef statInitFuncdef = {
  86277. 2+IsStat34, /* nArg */
  86278. SQLITE_UTF8, /* funcFlags */
  86279. 0, /* pUserData */
  86280. 0, /* pNext */
  86281. statInit, /* xSFunc */
  86282. 0, /* xFinalize */
  86283. "stat_init", /* zName */
  86284. {0}
  86285. };
  86286. #ifdef SQLITE_ENABLE_STAT4
  86287. /*
  86288. ** pNew and pOld are both candidate non-periodic samples selected for
  86289. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  86290. ** considering only any trailing columns and the sample hash value, this
  86291. ** function returns true if sample pNew is to be preferred over pOld.
  86292. ** In other words, if we assume that the cardinalities of the selected
  86293. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  86294. **
  86295. ** This function assumes that for each argument sample, the contents of
  86296. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  86297. */
  86298. static int sampleIsBetterPost(
  86299. Stat4Accum *pAccum,
  86300. Stat4Sample *pNew,
  86301. Stat4Sample *pOld
  86302. ){
  86303. int nCol = pAccum->nCol;
  86304. int i;
  86305. assert( pNew->iCol==pOld->iCol );
  86306. for(i=pNew->iCol+1; i<nCol; i++){
  86307. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  86308. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  86309. }
  86310. if( pNew->iHash>pOld->iHash ) return 1;
  86311. return 0;
  86312. }
  86313. #endif
  86314. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86315. /*
  86316. ** Return true if pNew is to be preferred over pOld.
  86317. **
  86318. ** This function assumes that for each argument sample, the contents of
  86319. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  86320. */
  86321. static int sampleIsBetter(
  86322. Stat4Accum *pAccum,
  86323. Stat4Sample *pNew,
  86324. Stat4Sample *pOld
  86325. ){
  86326. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  86327. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  86328. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  86329. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  86330. if( (nEqNew>nEqOld) ) return 1;
  86331. #ifdef SQLITE_ENABLE_STAT4
  86332. if( nEqNew==nEqOld ){
  86333. if( pNew->iCol<pOld->iCol ) return 1;
  86334. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  86335. }
  86336. return 0;
  86337. #else
  86338. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  86339. #endif
  86340. }
  86341. /*
  86342. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  86343. ** remove the least desirable sample from p->a[] to make room.
  86344. */
  86345. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  86346. Stat4Sample *pSample = 0;
  86347. int i;
  86348. assert( IsStat4 || nEqZero==0 );
  86349. #ifdef SQLITE_ENABLE_STAT4
  86350. if( pNew->isPSample==0 ){
  86351. Stat4Sample *pUpgrade = 0;
  86352. assert( pNew->anEq[pNew->iCol]>0 );
  86353. /* This sample is being added because the prefix that ends in column
  86354. ** iCol occurs many times in the table. However, if we have already
  86355. ** added a sample that shares this prefix, there is no need to add
  86356. ** this one. Instead, upgrade the priority of the highest priority
  86357. ** existing sample that shares this prefix. */
  86358. for(i=p->nSample-1; i>=0; i--){
  86359. Stat4Sample *pOld = &p->a[i];
  86360. if( pOld->anEq[pNew->iCol]==0 ){
  86361. if( pOld->isPSample ) return;
  86362. assert( pOld->iCol>pNew->iCol );
  86363. assert( sampleIsBetter(p, pNew, pOld) );
  86364. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  86365. pUpgrade = pOld;
  86366. }
  86367. }
  86368. }
  86369. if( pUpgrade ){
  86370. pUpgrade->iCol = pNew->iCol;
  86371. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  86372. goto find_new_min;
  86373. }
  86374. }
  86375. #endif
  86376. /* If necessary, remove sample iMin to make room for the new sample. */
  86377. if( p->nSample>=p->mxSample ){
  86378. Stat4Sample *pMin = &p->a[p->iMin];
  86379. tRowcnt *anEq = pMin->anEq;
  86380. tRowcnt *anLt = pMin->anLt;
  86381. tRowcnt *anDLt = pMin->anDLt;
  86382. sampleClear(p->db, pMin);
  86383. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  86384. pSample = &p->a[p->nSample-1];
  86385. pSample->nRowid = 0;
  86386. pSample->anEq = anEq;
  86387. pSample->anDLt = anDLt;
  86388. pSample->anLt = anLt;
  86389. p->nSample = p->mxSample-1;
  86390. }
  86391. /* The "rows less-than" for the rowid column must be greater than that
  86392. ** for the last sample in the p->a[] array. Otherwise, the samples would
  86393. ** be out of order. */
  86394. #ifdef SQLITE_ENABLE_STAT4
  86395. assert( p->nSample==0
  86396. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  86397. #endif
  86398. /* Insert the new sample */
  86399. pSample = &p->a[p->nSample];
  86400. sampleCopy(p, pSample, pNew);
  86401. p->nSample++;
  86402. /* Zero the first nEqZero entries in the anEq[] array. */
  86403. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  86404. #ifdef SQLITE_ENABLE_STAT4
  86405. find_new_min:
  86406. #endif
  86407. if( p->nSample>=p->mxSample ){
  86408. int iMin = -1;
  86409. for(i=0; i<p->mxSample; i++){
  86410. if( p->a[i].isPSample ) continue;
  86411. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  86412. iMin = i;
  86413. }
  86414. }
  86415. assert( iMin>=0 );
  86416. p->iMin = iMin;
  86417. }
  86418. }
  86419. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  86420. /*
  86421. ** Field iChng of the index being scanned has changed. So at this point
  86422. ** p->current contains a sample that reflects the previous row of the
  86423. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  86424. ** correct at this point.
  86425. */
  86426. static void samplePushPrevious(Stat4Accum *p, int iChng){
  86427. #ifdef SQLITE_ENABLE_STAT4
  86428. int i;
  86429. /* Check if any samples from the aBest[] array should be pushed
  86430. ** into IndexSample.a[] at this point. */
  86431. for(i=(p->nCol-2); i>=iChng; i--){
  86432. Stat4Sample *pBest = &p->aBest[i];
  86433. pBest->anEq[i] = p->current.anEq[i];
  86434. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  86435. sampleInsert(p, pBest, i);
  86436. }
  86437. }
  86438. /* Update the anEq[] fields of any samples already collected. */
  86439. for(i=p->nSample-1; i>=0; i--){
  86440. int j;
  86441. for(j=iChng; j<p->nCol; j++){
  86442. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  86443. }
  86444. }
  86445. #endif
  86446. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  86447. if( iChng==0 ){
  86448. tRowcnt nLt = p->current.anLt[0];
  86449. tRowcnt nEq = p->current.anEq[0];
  86450. /* Check if this is to be a periodic sample. If so, add it. */
  86451. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  86452. p->current.isPSample = 1;
  86453. sampleInsert(p, &p->current, 0);
  86454. p->current.isPSample = 0;
  86455. }else
  86456. /* Or if it is a non-periodic sample. Add it in this case too. */
  86457. if( p->nSample<p->mxSample
  86458. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  86459. ){
  86460. sampleInsert(p, &p->current, 0);
  86461. }
  86462. }
  86463. #endif
  86464. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  86465. UNUSED_PARAMETER( p );
  86466. UNUSED_PARAMETER( iChng );
  86467. #endif
  86468. }
  86469. /*
  86470. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  86471. ** Arguments:
  86472. **
  86473. ** P Pointer to the Stat4Accum object created by stat_init()
  86474. ** C Index of left-most column to differ from previous row
  86475. ** R Rowid for the current row. Might be a key record for
  86476. ** WITHOUT ROWID tables.
  86477. **
  86478. ** This SQL function always returns NULL. It's purpose it to accumulate
  86479. ** statistical data and/or samples in the Stat4Accum object about the
  86480. ** index being analyzed. The stat_get() SQL function will later be used to
  86481. ** extract relevant information for constructing the sqlite_statN tables.
  86482. **
  86483. ** The R parameter is only used for STAT3 and STAT4
  86484. */
  86485. static void statPush(
  86486. sqlite3_context *context,
  86487. int argc,
  86488. sqlite3_value **argv
  86489. ){
  86490. int i;
  86491. /* The three function arguments */
  86492. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  86493. int iChng = sqlite3_value_int(argv[1]);
  86494. UNUSED_PARAMETER( argc );
  86495. UNUSED_PARAMETER( context );
  86496. assert( p->nCol>0 );
  86497. assert( iChng<p->nCol );
  86498. if( p->nRow==0 ){
  86499. /* This is the first call to this function. Do initialization. */
  86500. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  86501. }else{
  86502. /* Second and subsequent calls get processed here */
  86503. samplePushPrevious(p, iChng);
  86504. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  86505. ** to the current row of the index. */
  86506. for(i=0; i<iChng; i++){
  86507. p->current.anEq[i]++;
  86508. }
  86509. for(i=iChng; i<p->nCol; i++){
  86510. p->current.anDLt[i]++;
  86511. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86512. p->current.anLt[i] += p->current.anEq[i];
  86513. #endif
  86514. p->current.anEq[i] = 1;
  86515. }
  86516. }
  86517. p->nRow++;
  86518. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86519. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  86520. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  86521. }else{
  86522. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  86523. sqlite3_value_blob(argv[2]));
  86524. }
  86525. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  86526. #endif
  86527. #ifdef SQLITE_ENABLE_STAT4
  86528. {
  86529. tRowcnt nLt = p->current.anLt[p->nCol-1];
  86530. /* Check if this is to be a periodic sample. If so, add it. */
  86531. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  86532. p->current.isPSample = 1;
  86533. p->current.iCol = 0;
  86534. sampleInsert(p, &p->current, p->nCol-1);
  86535. p->current.isPSample = 0;
  86536. }
  86537. /* Update the aBest[] array. */
  86538. for(i=0; i<(p->nCol-1); i++){
  86539. p->current.iCol = i;
  86540. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  86541. sampleCopy(p, &p->aBest[i], &p->current);
  86542. }
  86543. }
  86544. }
  86545. #endif
  86546. }
  86547. static const FuncDef statPushFuncdef = {
  86548. 2+IsStat34, /* nArg */
  86549. SQLITE_UTF8, /* funcFlags */
  86550. 0, /* pUserData */
  86551. 0, /* pNext */
  86552. statPush, /* xSFunc */
  86553. 0, /* xFinalize */
  86554. "stat_push", /* zName */
  86555. {0}
  86556. };
  86557. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  86558. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  86559. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  86560. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  86561. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  86562. /*
  86563. ** Implementation of the stat_get(P,J) SQL function. This routine is
  86564. ** used to query statistical information that has been gathered into
  86565. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  86566. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  86567. ** The content to returned is determined by the parameter J
  86568. ** which is one of the STAT_GET_xxxx values defined above.
  86569. **
  86570. ** If neither STAT3 nor STAT4 are enabled, then J is always
  86571. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  86572. ** a one-parameter function, stat_get(P), that always returns the
  86573. ** stat1 table entry information.
  86574. */
  86575. static void statGet(
  86576. sqlite3_context *context,
  86577. int argc,
  86578. sqlite3_value **argv
  86579. ){
  86580. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  86581. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86582. /* STAT3 and STAT4 have a parameter on this routine. */
  86583. int eCall = sqlite3_value_int(argv[1]);
  86584. assert( argc==2 );
  86585. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  86586. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  86587. || eCall==STAT_GET_NDLT
  86588. );
  86589. if( eCall==STAT_GET_STAT1 )
  86590. #else
  86591. assert( argc==1 );
  86592. #endif
  86593. {
  86594. /* Return the value to store in the "stat" column of the sqlite_stat1
  86595. ** table for this index.
  86596. **
  86597. ** The value is a string composed of a list of integers describing
  86598. ** the index. The first integer in the list is the total number of
  86599. ** entries in the index. There is one additional integer in the list
  86600. ** for each indexed column. This additional integer is an estimate of
  86601. ** the number of rows matched by a stabbing query on the index using
  86602. ** a key with the corresponding number of fields. In other words,
  86603. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  86604. ** "100 10 2", then SQLite estimates that:
  86605. **
  86606. ** * the index contains 100 rows,
  86607. ** * "WHERE a=?" matches 10 rows, and
  86608. ** * "WHERE a=? AND b=?" matches 2 rows.
  86609. **
  86610. ** If D is the count of distinct values and K is the total number of
  86611. ** rows, then each estimate is computed as:
  86612. **
  86613. ** I = (K+D-1)/D
  86614. */
  86615. char *z;
  86616. int i;
  86617. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  86618. if( zRet==0 ){
  86619. sqlite3_result_error_nomem(context);
  86620. return;
  86621. }
  86622. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  86623. z = zRet + sqlite3Strlen30(zRet);
  86624. for(i=0; i<p->nKeyCol; i++){
  86625. u64 nDistinct = p->current.anDLt[i] + 1;
  86626. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  86627. sqlite3_snprintf(24, z, " %llu", iVal);
  86628. z += sqlite3Strlen30(z);
  86629. assert( p->current.anEq[i] );
  86630. }
  86631. assert( z[0]=='\0' && z>zRet );
  86632. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  86633. }
  86634. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86635. else if( eCall==STAT_GET_ROWID ){
  86636. if( p->iGet<0 ){
  86637. samplePushPrevious(p, 0);
  86638. p->iGet = 0;
  86639. }
  86640. if( p->iGet<p->nSample ){
  86641. Stat4Sample *pS = p->a + p->iGet;
  86642. if( pS->nRowid==0 ){
  86643. sqlite3_result_int64(context, pS->u.iRowid);
  86644. }else{
  86645. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  86646. SQLITE_TRANSIENT);
  86647. }
  86648. }
  86649. }else{
  86650. tRowcnt *aCnt = 0;
  86651. assert( p->iGet<p->nSample );
  86652. switch( eCall ){
  86653. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  86654. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  86655. default: {
  86656. aCnt = p->a[p->iGet].anDLt;
  86657. p->iGet++;
  86658. break;
  86659. }
  86660. }
  86661. if( IsStat3 ){
  86662. sqlite3_result_int64(context, (i64)aCnt[0]);
  86663. }else{
  86664. char *zRet = sqlite3MallocZero(p->nCol * 25);
  86665. if( zRet==0 ){
  86666. sqlite3_result_error_nomem(context);
  86667. }else{
  86668. int i;
  86669. char *z = zRet;
  86670. for(i=0; i<p->nCol; i++){
  86671. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  86672. z += sqlite3Strlen30(z);
  86673. }
  86674. assert( z[0]=='\0' && z>zRet );
  86675. z[-1] = '\0';
  86676. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  86677. }
  86678. }
  86679. }
  86680. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  86681. #ifndef SQLITE_DEBUG
  86682. UNUSED_PARAMETER( argc );
  86683. #endif
  86684. }
  86685. static const FuncDef statGetFuncdef = {
  86686. 1+IsStat34, /* nArg */
  86687. SQLITE_UTF8, /* funcFlags */
  86688. 0, /* pUserData */
  86689. 0, /* pNext */
  86690. statGet, /* xSFunc */
  86691. 0, /* xFinalize */
  86692. "stat_get", /* zName */
  86693. {0}
  86694. };
  86695. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  86696. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  86697. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86698. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  86699. #elif SQLITE_DEBUG
  86700. assert( iParam==STAT_GET_STAT1 );
  86701. #else
  86702. UNUSED_PARAMETER( iParam );
  86703. #endif
  86704. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  86705. (char*)&statGetFuncdef, P4_FUNCDEF);
  86706. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  86707. }
  86708. /*
  86709. ** Generate code to do an analysis of all indices associated with
  86710. ** a single table.
  86711. */
  86712. static void analyzeOneTable(
  86713. Parse *pParse, /* Parser context */
  86714. Table *pTab, /* Table whose indices are to be analyzed */
  86715. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  86716. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  86717. int iMem, /* Available memory locations begin here */
  86718. int iTab /* Next available cursor */
  86719. ){
  86720. sqlite3 *db = pParse->db; /* Database handle */
  86721. Index *pIdx; /* An index to being analyzed */
  86722. int iIdxCur; /* Cursor open on index being analyzed */
  86723. int iTabCur; /* Table cursor */
  86724. Vdbe *v; /* The virtual machine being built up */
  86725. int i; /* Loop counter */
  86726. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  86727. int iDb; /* Index of database containing pTab */
  86728. u8 needTableCnt = 1; /* True to count the table */
  86729. int regNewRowid = iMem++; /* Rowid for the inserted record */
  86730. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  86731. int regChng = iMem++; /* Index of changed index field */
  86732. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86733. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  86734. #endif
  86735. int regTemp = iMem++; /* Temporary use register */
  86736. int regTabname = iMem++; /* Register containing table name */
  86737. int regIdxname = iMem++; /* Register containing index name */
  86738. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  86739. int regPrev = iMem; /* MUST BE LAST (see below) */
  86740. pParse->nMem = MAX(pParse->nMem, iMem);
  86741. v = sqlite3GetVdbe(pParse);
  86742. if( v==0 || NEVER(pTab==0) ){
  86743. return;
  86744. }
  86745. if( pTab->tnum==0 ){
  86746. /* Do not gather statistics on views or virtual tables */
  86747. return;
  86748. }
  86749. if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
  86750. /* Do not gather statistics on system tables */
  86751. return;
  86752. }
  86753. assert( sqlite3BtreeHoldsAllMutexes(db) );
  86754. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  86755. assert( iDb>=0 );
  86756. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86757. #ifndef SQLITE_OMIT_AUTHORIZATION
  86758. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  86759. db->aDb[iDb].zName ) ){
  86760. return;
  86761. }
  86762. #endif
  86763. /* Establish a read-lock on the table at the shared-cache level.
  86764. ** Open a read-only cursor on the table. Also allocate a cursor number
  86765. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  86766. ** this time though. */
  86767. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  86768. iTabCur = iTab++;
  86769. iIdxCur = iTab++;
  86770. pParse->nTab = MAX(pParse->nTab, iTab);
  86771. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  86772. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  86773. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86774. int nCol; /* Number of columns in pIdx. "N" */
  86775. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  86776. int addrNextRow; /* Address of "next_row:" */
  86777. const char *zIdxName; /* Name of the index */
  86778. int nColTest; /* Number of columns to test for changes */
  86779. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  86780. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  86781. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  86782. nCol = pIdx->nKeyCol;
  86783. zIdxName = pTab->zName;
  86784. nColTest = nCol - 1;
  86785. }else{
  86786. nCol = pIdx->nColumn;
  86787. zIdxName = pIdx->zName;
  86788. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  86789. }
  86790. /* Populate the register containing the index name. */
  86791. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  86792. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  86793. /*
  86794. ** Pseudo-code for loop that calls stat_push():
  86795. **
  86796. ** Rewind csr
  86797. ** if eof(csr) goto end_of_scan;
  86798. ** regChng = 0
  86799. ** goto chng_addr_0;
  86800. **
  86801. ** next_row:
  86802. ** regChng = 0
  86803. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  86804. ** regChng = 1
  86805. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  86806. ** ...
  86807. ** regChng = N
  86808. ** goto chng_addr_N
  86809. **
  86810. ** chng_addr_0:
  86811. ** regPrev(0) = idx(0)
  86812. ** chng_addr_1:
  86813. ** regPrev(1) = idx(1)
  86814. ** ...
  86815. **
  86816. ** endDistinctTest:
  86817. ** regRowid = idx(rowid)
  86818. ** stat_push(P, regChng, regRowid)
  86819. ** Next csr
  86820. ** if !eof(csr) goto next_row;
  86821. **
  86822. ** end_of_scan:
  86823. */
  86824. /* Make sure there are enough memory cells allocated to accommodate
  86825. ** the regPrev array and a trailing rowid (the rowid slot is required
  86826. ** when building a record to insert into the sample column of
  86827. ** the sqlite_stat4 table. */
  86828. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  86829. /* Open a read-only cursor on the index being analyzed. */
  86830. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  86831. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  86832. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  86833. VdbeComment((v, "%s", pIdx->zName));
  86834. /* Invoke the stat_init() function. The arguments are:
  86835. **
  86836. ** (1) the number of columns in the index including the rowid
  86837. ** (or for a WITHOUT ROWID table, the number of PK columns),
  86838. ** (2) the number of columns in the key without the rowid/pk
  86839. ** (3) the number of rows in the index,
  86840. **
  86841. **
  86842. ** The third argument is only used for STAT3 and STAT4
  86843. */
  86844. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86845. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  86846. #endif
  86847. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  86848. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  86849. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  86850. (char*)&statInitFuncdef, P4_FUNCDEF);
  86851. sqlite3VdbeChangeP5(v, 2+IsStat34);
  86852. /* Implementation of the following:
  86853. **
  86854. ** Rewind csr
  86855. ** if eof(csr) goto end_of_scan;
  86856. ** regChng = 0
  86857. ** goto next_push_0;
  86858. **
  86859. */
  86860. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  86861. VdbeCoverage(v);
  86862. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  86863. addrNextRow = sqlite3VdbeCurrentAddr(v);
  86864. if( nColTest>0 ){
  86865. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  86866. int *aGotoChng; /* Array of jump instruction addresses */
  86867. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  86868. if( aGotoChng==0 ) continue;
  86869. /*
  86870. ** next_row:
  86871. ** regChng = 0
  86872. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  86873. ** regChng = 1
  86874. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  86875. ** ...
  86876. ** regChng = N
  86877. ** goto endDistinctTest
  86878. */
  86879. sqlite3VdbeAddOp0(v, OP_Goto);
  86880. addrNextRow = sqlite3VdbeCurrentAddr(v);
  86881. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  86882. /* For a single-column UNIQUE index, once we have found a non-NULL
  86883. ** row, we know that all the rest will be distinct, so skip
  86884. ** subsequent distinctness tests. */
  86885. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  86886. VdbeCoverage(v);
  86887. }
  86888. for(i=0; i<nColTest; i++){
  86889. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  86890. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  86891. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  86892. aGotoChng[i] =
  86893. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  86894. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  86895. VdbeCoverage(v);
  86896. }
  86897. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  86898. sqlite3VdbeGoto(v, endDistinctTest);
  86899. /*
  86900. ** chng_addr_0:
  86901. ** regPrev(0) = idx(0)
  86902. ** chng_addr_1:
  86903. ** regPrev(1) = idx(1)
  86904. ** ...
  86905. */
  86906. sqlite3VdbeJumpHere(v, addrNextRow-1);
  86907. for(i=0; i<nColTest; i++){
  86908. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  86909. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  86910. }
  86911. sqlite3VdbeResolveLabel(v, endDistinctTest);
  86912. sqlite3DbFree(db, aGotoChng);
  86913. }
  86914. /*
  86915. ** chng_addr_N:
  86916. ** regRowid = idx(rowid) // STAT34 only
  86917. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  86918. ** Next csr
  86919. ** if !eof(csr) goto next_row;
  86920. */
  86921. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86922. assert( regRowid==(regStat4+2) );
  86923. if( HasRowid(pTab) ){
  86924. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  86925. }else{
  86926. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  86927. int j, k, regKey;
  86928. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  86929. for(j=0; j<pPk->nKeyCol; j++){
  86930. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  86931. assert( k>=0 && k<pTab->nCol );
  86932. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  86933. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  86934. }
  86935. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  86936. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  86937. }
  86938. #endif
  86939. assert( regChng==(regStat4+1) );
  86940. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  86941. (char*)&statPushFuncdef, P4_FUNCDEF);
  86942. sqlite3VdbeChangeP5(v, 2+IsStat34);
  86943. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  86944. /* Add the entry to the stat1 table. */
  86945. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  86946. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  86947. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  86948. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  86949. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  86950. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  86951. /* Add the entries to the stat3 or stat4 table. */
  86952. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86953. {
  86954. int regEq = regStat1;
  86955. int regLt = regStat1+1;
  86956. int regDLt = regStat1+2;
  86957. int regSample = regStat1+3;
  86958. int regCol = regStat1+4;
  86959. int regSampleRowid = regCol + nCol;
  86960. int addrNext;
  86961. int addrIsNull;
  86962. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  86963. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  86964. addrNext = sqlite3VdbeCurrentAddr(v);
  86965. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  86966. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  86967. VdbeCoverage(v);
  86968. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  86969. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  86970. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  86971. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  86972. /* We know that the regSampleRowid row exists because it was read by
  86973. ** the previous loop. Thus the not-found jump of seekOp will never
  86974. ** be taken */
  86975. VdbeCoverageNeverTaken(v);
  86976. #ifdef SQLITE_ENABLE_STAT3
  86977. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  86978. #else
  86979. for(i=0; i<nCol; i++){
  86980. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  86981. }
  86982. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  86983. #endif
  86984. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  86985. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  86986. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  86987. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  86988. sqlite3VdbeJumpHere(v, addrIsNull);
  86989. }
  86990. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  86991. /* End of analysis */
  86992. sqlite3VdbeJumpHere(v, addrRewind);
  86993. }
  86994. /* Create a single sqlite_stat1 entry containing NULL as the index
  86995. ** name and the row count as the content.
  86996. */
  86997. if( pOnlyIdx==0 && needTableCnt ){
  86998. VdbeComment((v, "%s", pTab->zName));
  86999. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  87000. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  87001. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  87002. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  87003. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  87004. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  87005. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  87006. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  87007. sqlite3VdbeJumpHere(v, jZeroRows);
  87008. }
  87009. }
  87010. /*
  87011. ** Generate code that will cause the most recent index analysis to
  87012. ** be loaded into internal hash tables where is can be used.
  87013. */
  87014. static void loadAnalysis(Parse *pParse, int iDb){
  87015. Vdbe *v = sqlite3GetVdbe(pParse);
  87016. if( v ){
  87017. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  87018. }
  87019. }
  87020. /*
  87021. ** Generate code that will do an analysis of an entire database
  87022. */
  87023. static void analyzeDatabase(Parse *pParse, int iDb){
  87024. sqlite3 *db = pParse->db;
  87025. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  87026. HashElem *k;
  87027. int iStatCur;
  87028. int iMem;
  87029. int iTab;
  87030. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87031. iStatCur = pParse->nTab;
  87032. pParse->nTab += 3;
  87033. openStatTable(pParse, iDb, iStatCur, 0, 0);
  87034. iMem = pParse->nMem+1;
  87035. iTab = pParse->nTab;
  87036. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87037. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  87038. Table *pTab = (Table*)sqliteHashData(k);
  87039. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  87040. }
  87041. loadAnalysis(pParse, iDb);
  87042. }
  87043. /*
  87044. ** Generate code that will do an analysis of a single table in
  87045. ** a database. If pOnlyIdx is not NULL then it is a single index
  87046. ** in pTab that should be analyzed.
  87047. */
  87048. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  87049. int iDb;
  87050. int iStatCur;
  87051. assert( pTab!=0 );
  87052. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  87053. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  87054. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87055. iStatCur = pParse->nTab;
  87056. pParse->nTab += 3;
  87057. if( pOnlyIdx ){
  87058. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  87059. }else{
  87060. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  87061. }
  87062. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  87063. loadAnalysis(pParse, iDb);
  87064. }
  87065. /*
  87066. ** Generate code for the ANALYZE command. The parser calls this routine
  87067. ** when it recognizes an ANALYZE command.
  87068. **
  87069. ** ANALYZE -- 1
  87070. ** ANALYZE <database> -- 2
  87071. ** ANALYZE ?<database>.?<tablename> -- 3
  87072. **
  87073. ** Form 1 causes all indices in all attached databases to be analyzed.
  87074. ** Form 2 analyzes all indices the single database named.
  87075. ** Form 3 analyzes all indices associated with the named table.
  87076. */
  87077. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  87078. sqlite3 *db = pParse->db;
  87079. int iDb;
  87080. int i;
  87081. char *z, *zDb;
  87082. Table *pTab;
  87083. Index *pIdx;
  87084. Token *pTableName;
  87085. Vdbe *v;
  87086. /* Read the database schema. If an error occurs, leave an error message
  87087. ** and code in pParse and return NULL. */
  87088. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  87089. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  87090. return;
  87091. }
  87092. assert( pName2!=0 || pName1==0 );
  87093. if( pName1==0 ){
  87094. /* Form 1: Analyze everything */
  87095. for(i=0; i<db->nDb; i++){
  87096. if( i==1 ) continue; /* Do not analyze the TEMP database */
  87097. analyzeDatabase(pParse, i);
  87098. }
  87099. }else if( pName2->n==0 ){
  87100. /* Form 2: Analyze the database or table named */
  87101. iDb = sqlite3FindDb(db, pName1);
  87102. if( iDb>=0 ){
  87103. analyzeDatabase(pParse, iDb);
  87104. }else{
  87105. z = sqlite3NameFromToken(db, pName1);
  87106. if( z ){
  87107. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  87108. analyzeTable(pParse, pIdx->pTable, pIdx);
  87109. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  87110. analyzeTable(pParse, pTab, 0);
  87111. }
  87112. sqlite3DbFree(db, z);
  87113. }
  87114. }
  87115. }else{
  87116. /* Form 3: Analyze the fully qualified table name */
  87117. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  87118. if( iDb>=0 ){
  87119. zDb = db->aDb[iDb].zName;
  87120. z = sqlite3NameFromToken(db, pTableName);
  87121. if( z ){
  87122. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  87123. analyzeTable(pParse, pIdx->pTable, pIdx);
  87124. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  87125. analyzeTable(pParse, pTab, 0);
  87126. }
  87127. sqlite3DbFree(db, z);
  87128. }
  87129. }
  87130. }
  87131. v = sqlite3GetVdbe(pParse);
  87132. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  87133. }
  87134. /*
  87135. ** Used to pass information from the analyzer reader through to the
  87136. ** callback routine.
  87137. */
  87138. typedef struct analysisInfo analysisInfo;
  87139. struct analysisInfo {
  87140. sqlite3 *db;
  87141. const char *zDatabase;
  87142. };
  87143. /*
  87144. ** The first argument points to a nul-terminated string containing a
  87145. ** list of space separated integers. Read the first nOut of these into
  87146. ** the array aOut[].
  87147. */
  87148. static void decodeIntArray(
  87149. char *zIntArray, /* String containing int array to decode */
  87150. int nOut, /* Number of slots in aOut[] */
  87151. tRowcnt *aOut, /* Store integers here */
  87152. LogEst *aLog, /* Or, if aOut==0, here */
  87153. Index *pIndex /* Handle extra flags for this index, if not NULL */
  87154. ){
  87155. char *z = zIntArray;
  87156. int c;
  87157. int i;
  87158. tRowcnt v;
  87159. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87160. if( z==0 ) z = "";
  87161. #else
  87162. assert( z!=0 );
  87163. #endif
  87164. for(i=0; *z && i<nOut; i++){
  87165. v = 0;
  87166. while( (c=z[0])>='0' && c<='9' ){
  87167. v = v*10 + c - '0';
  87168. z++;
  87169. }
  87170. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87171. if( aOut ) aOut[i] = v;
  87172. if( aLog ) aLog[i] = sqlite3LogEst(v);
  87173. #else
  87174. assert( aOut==0 );
  87175. UNUSED_PARAMETER(aOut);
  87176. assert( aLog!=0 );
  87177. aLog[i] = sqlite3LogEst(v);
  87178. #endif
  87179. if( *z==' ' ) z++;
  87180. }
  87181. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  87182. assert( pIndex!=0 ); {
  87183. #else
  87184. if( pIndex ){
  87185. #endif
  87186. pIndex->bUnordered = 0;
  87187. pIndex->noSkipScan = 0;
  87188. while( z[0] ){
  87189. if( sqlite3_strglob("unordered*", z)==0 ){
  87190. pIndex->bUnordered = 1;
  87191. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  87192. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  87193. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  87194. pIndex->noSkipScan = 1;
  87195. }
  87196. #ifdef SQLITE_ENABLE_COSTMULT
  87197. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  87198. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  87199. }
  87200. #endif
  87201. while( z[0]!=0 && z[0]!=' ' ) z++;
  87202. while( z[0]==' ' ) z++;
  87203. }
  87204. }
  87205. }
  87206. /*
  87207. ** This callback is invoked once for each index when reading the
  87208. ** sqlite_stat1 table.
  87209. **
  87210. ** argv[0] = name of the table
  87211. ** argv[1] = name of the index (might be NULL)
  87212. ** argv[2] = results of analysis - on integer for each column
  87213. **
  87214. ** Entries for which argv[1]==NULL simply record the number of rows in
  87215. ** the table.
  87216. */
  87217. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  87218. analysisInfo *pInfo = (analysisInfo*)pData;
  87219. Index *pIndex;
  87220. Table *pTable;
  87221. const char *z;
  87222. assert( argc==3 );
  87223. UNUSED_PARAMETER2(NotUsed, argc);
  87224. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  87225. return 0;
  87226. }
  87227. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  87228. if( pTable==0 ){
  87229. return 0;
  87230. }
  87231. if( argv[1]==0 ){
  87232. pIndex = 0;
  87233. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  87234. pIndex = sqlite3PrimaryKeyIndex(pTable);
  87235. }else{
  87236. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  87237. }
  87238. z = argv[2];
  87239. if( pIndex ){
  87240. tRowcnt *aiRowEst = 0;
  87241. int nCol = pIndex->nKeyCol+1;
  87242. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87243. /* Index.aiRowEst may already be set here if there are duplicate
  87244. ** sqlite_stat1 entries for this index. In that case just clobber
  87245. ** the old data with the new instead of allocating a new array. */
  87246. if( pIndex->aiRowEst==0 ){
  87247. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  87248. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  87249. }
  87250. aiRowEst = pIndex->aiRowEst;
  87251. #endif
  87252. pIndex->bUnordered = 0;
  87253. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  87254. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  87255. }else{
  87256. Index fakeIdx;
  87257. fakeIdx.szIdxRow = pTable->szTabRow;
  87258. #ifdef SQLITE_ENABLE_COSTMULT
  87259. fakeIdx.pTable = pTable;
  87260. #endif
  87261. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  87262. pTable->szTabRow = fakeIdx.szIdxRow;
  87263. }
  87264. return 0;
  87265. }
  87266. /*
  87267. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  87268. ** and its contents.
  87269. */
  87270. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  87271. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87272. if( pIdx->aSample ){
  87273. int j;
  87274. for(j=0; j<pIdx->nSample; j++){
  87275. IndexSample *p = &pIdx->aSample[j];
  87276. sqlite3DbFree(db, p->p);
  87277. }
  87278. sqlite3DbFree(db, pIdx->aSample);
  87279. }
  87280. if( db && db->pnBytesFreed==0 ){
  87281. pIdx->nSample = 0;
  87282. pIdx->aSample = 0;
  87283. }
  87284. #else
  87285. UNUSED_PARAMETER(db);
  87286. UNUSED_PARAMETER(pIdx);
  87287. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  87288. }
  87289. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87290. /*
  87291. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  87292. ** stored in pIdx->aSample[].
  87293. */
  87294. static void initAvgEq(Index *pIdx){
  87295. if( pIdx ){
  87296. IndexSample *aSample = pIdx->aSample;
  87297. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  87298. int iCol;
  87299. int nCol = 1;
  87300. if( pIdx->nSampleCol>1 ){
  87301. /* If this is stat4 data, then calculate aAvgEq[] values for all
  87302. ** sample columns except the last. The last is always set to 1, as
  87303. ** once the trailing PK fields are considered all index keys are
  87304. ** unique. */
  87305. nCol = pIdx->nSampleCol-1;
  87306. pIdx->aAvgEq[nCol] = 1;
  87307. }
  87308. for(iCol=0; iCol<nCol; iCol++){
  87309. int nSample = pIdx->nSample;
  87310. int i; /* Used to iterate through samples */
  87311. tRowcnt sumEq = 0; /* Sum of the nEq values */
  87312. tRowcnt avgEq = 0;
  87313. tRowcnt nRow; /* Number of rows in index */
  87314. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  87315. i64 nDist100; /* Number of distinct values in index */
  87316. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  87317. nRow = pFinal->anLt[iCol];
  87318. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  87319. nSample--;
  87320. }else{
  87321. nRow = pIdx->aiRowEst[0];
  87322. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  87323. }
  87324. pIdx->nRowEst0 = nRow;
  87325. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  87326. ** occur in the stat4 table for this index. Set sumEq to the sum of
  87327. ** the nEq values for column iCol for the same set (adding the value
  87328. ** only once where there exist duplicate prefixes). */
  87329. for(i=0; i<nSample; i++){
  87330. if( i==(pIdx->nSample-1)
  87331. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  87332. ){
  87333. sumEq += aSample[i].anEq[iCol];
  87334. nSum100 += 100;
  87335. }
  87336. }
  87337. if( nDist100>nSum100 ){
  87338. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  87339. }
  87340. if( avgEq==0 ) avgEq = 1;
  87341. pIdx->aAvgEq[iCol] = avgEq;
  87342. }
  87343. }
  87344. }
  87345. /*
  87346. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  87347. ** is supplied instead, find the PRIMARY KEY index for that table.
  87348. */
  87349. static Index *findIndexOrPrimaryKey(
  87350. sqlite3 *db,
  87351. const char *zName,
  87352. const char *zDb
  87353. ){
  87354. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  87355. if( pIdx==0 ){
  87356. Table *pTab = sqlite3FindTable(db, zName, zDb);
  87357. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  87358. }
  87359. return pIdx;
  87360. }
  87361. /*
  87362. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  87363. ** into the relevant Index.aSample[] arrays.
  87364. **
  87365. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  87366. ** data equivalent to the following (statements are different for stat3,
  87367. ** see the caller of this function for details):
  87368. **
  87369. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  87370. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  87371. **
  87372. ** where %Q is replaced with the database name before the SQL is executed.
  87373. */
  87374. static int loadStatTbl(
  87375. sqlite3 *db, /* Database handle */
  87376. int bStat3, /* Assume single column records only */
  87377. const char *zSql1, /* SQL statement 1 (see above) */
  87378. const char *zSql2, /* SQL statement 2 (see above) */
  87379. const char *zDb /* Database name (e.g. "main") */
  87380. ){
  87381. int rc; /* Result codes from subroutines */
  87382. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  87383. char *zSql; /* Text of the SQL statement */
  87384. Index *pPrevIdx = 0; /* Previous index in the loop */
  87385. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  87386. assert( db->lookaside.bDisable );
  87387. zSql = sqlite3MPrintf(db, zSql1, zDb);
  87388. if( !zSql ){
  87389. return SQLITE_NOMEM_BKPT;
  87390. }
  87391. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  87392. sqlite3DbFree(db, zSql);
  87393. if( rc ) return rc;
  87394. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  87395. int nIdxCol = 1; /* Number of columns in stat4 records */
  87396. char *zIndex; /* Index name */
  87397. Index *pIdx; /* Pointer to the index object */
  87398. int nSample; /* Number of samples */
  87399. int nByte; /* Bytes of space required */
  87400. int i; /* Bytes of space required */
  87401. tRowcnt *pSpace;
  87402. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  87403. if( zIndex==0 ) continue;
  87404. nSample = sqlite3_column_int(pStmt, 1);
  87405. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  87406. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  87407. /* Index.nSample is non-zero at this point if data has already been
  87408. ** loaded from the stat4 table. In this case ignore stat3 data. */
  87409. if( pIdx==0 || pIdx->nSample ) continue;
  87410. if( bStat3==0 ){
  87411. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  87412. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  87413. nIdxCol = pIdx->nKeyCol;
  87414. }else{
  87415. nIdxCol = pIdx->nColumn;
  87416. }
  87417. }
  87418. pIdx->nSampleCol = nIdxCol;
  87419. nByte = sizeof(IndexSample) * nSample;
  87420. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  87421. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  87422. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  87423. if( pIdx->aSample==0 ){
  87424. sqlite3_finalize(pStmt);
  87425. return SQLITE_NOMEM_BKPT;
  87426. }
  87427. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  87428. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  87429. for(i=0; i<nSample; i++){
  87430. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  87431. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  87432. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  87433. }
  87434. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  87435. }
  87436. rc = sqlite3_finalize(pStmt);
  87437. if( rc ) return rc;
  87438. zSql = sqlite3MPrintf(db, zSql2, zDb);
  87439. if( !zSql ){
  87440. return SQLITE_NOMEM_BKPT;
  87441. }
  87442. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  87443. sqlite3DbFree(db, zSql);
  87444. if( rc ) return rc;
  87445. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  87446. char *zIndex; /* Index name */
  87447. Index *pIdx; /* Pointer to the index object */
  87448. int nCol = 1; /* Number of columns in index */
  87449. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  87450. if( zIndex==0 ) continue;
  87451. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  87452. if( pIdx==0 ) continue;
  87453. /* This next condition is true if data has already been loaded from
  87454. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  87455. nCol = pIdx->nSampleCol;
  87456. if( bStat3 && nCol>1 ) continue;
  87457. if( pIdx!=pPrevIdx ){
  87458. initAvgEq(pPrevIdx);
  87459. pPrevIdx = pIdx;
  87460. }
  87461. pSample = &pIdx->aSample[pIdx->nSample];
  87462. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  87463. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  87464. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  87465. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  87466. ** This is in case the sample record is corrupted. In that case, the
  87467. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  87468. ** end of the allocated buffer before it realizes it is dealing with
  87469. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  87470. ** a buffer overread. */
  87471. pSample->n = sqlite3_column_bytes(pStmt, 4);
  87472. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  87473. if( pSample->p==0 ){
  87474. sqlite3_finalize(pStmt);
  87475. return SQLITE_NOMEM_BKPT;
  87476. }
  87477. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  87478. pIdx->nSample++;
  87479. }
  87480. rc = sqlite3_finalize(pStmt);
  87481. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  87482. return rc;
  87483. }
  87484. /*
  87485. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  87486. ** the Index.aSample[] arrays of all indices.
  87487. */
  87488. static int loadStat4(sqlite3 *db, const char *zDb){
  87489. int rc = SQLITE_OK; /* Result codes from subroutines */
  87490. assert( db->lookaside.bDisable );
  87491. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  87492. rc = loadStatTbl(db, 0,
  87493. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  87494. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  87495. zDb
  87496. );
  87497. }
  87498. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  87499. rc = loadStatTbl(db, 1,
  87500. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  87501. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  87502. zDb
  87503. );
  87504. }
  87505. return rc;
  87506. }
  87507. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  87508. /*
  87509. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  87510. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  87511. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  87512. ** Index.aSample[] arrays.
  87513. **
  87514. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  87515. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  87516. ** during compilation and the sqlite_stat3/4 table is present, no data is
  87517. ** read from it.
  87518. **
  87519. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  87520. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  87521. ** returned. However, in this case, data is read from the sqlite_stat1
  87522. ** table (if it is present) before returning.
  87523. **
  87524. ** If an OOM error occurs, this function always sets db->mallocFailed.
  87525. ** This means if the caller does not care about other errors, the return
  87526. ** code may be ignored.
  87527. */
  87528. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  87529. analysisInfo sInfo;
  87530. HashElem *i;
  87531. char *zSql;
  87532. int rc;
  87533. assert( iDb>=0 && iDb<db->nDb );
  87534. assert( db->aDb[iDb].pBt!=0 );
  87535. /* Clear any prior statistics */
  87536. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87537. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  87538. Index *pIdx = sqliteHashData(i);
  87539. sqlite3DefaultRowEst(pIdx);
  87540. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87541. sqlite3DeleteIndexSamples(db, pIdx);
  87542. pIdx->aSample = 0;
  87543. #endif
  87544. }
  87545. /* Check to make sure the sqlite_stat1 table exists */
  87546. sInfo.db = db;
  87547. sInfo.zDatabase = db->aDb[iDb].zName;
  87548. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  87549. return SQLITE_ERROR;
  87550. }
  87551. /* Load new statistics out of the sqlite_stat1 table */
  87552. zSql = sqlite3MPrintf(db,
  87553. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  87554. if( zSql==0 ){
  87555. rc = SQLITE_NOMEM_BKPT;
  87556. }else{
  87557. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  87558. sqlite3DbFree(db, zSql);
  87559. }
  87560. /* Load the statistics from the sqlite_stat4 table. */
  87561. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  87562. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  87563. db->lookaside.bDisable++;
  87564. rc = loadStat4(db, sInfo.zDatabase);
  87565. db->lookaside.bDisable--;
  87566. }
  87567. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  87568. Index *pIdx = sqliteHashData(i);
  87569. sqlite3_free(pIdx->aiRowEst);
  87570. pIdx->aiRowEst = 0;
  87571. }
  87572. #endif
  87573. if( rc==SQLITE_NOMEM ){
  87574. sqlite3OomFault(db);
  87575. }
  87576. return rc;
  87577. }
  87578. #endif /* SQLITE_OMIT_ANALYZE */
  87579. /************** End of analyze.c *********************************************/
  87580. /************** Begin file attach.c ******************************************/
  87581. /*
  87582. ** 2003 April 6
  87583. **
  87584. ** The author disclaims copyright to this source code. In place of
  87585. ** a legal notice, here is a blessing:
  87586. **
  87587. ** May you do good and not evil.
  87588. ** May you find forgiveness for yourself and forgive others.
  87589. ** May you share freely, never taking more than you give.
  87590. **
  87591. *************************************************************************
  87592. ** This file contains code used to implement the ATTACH and DETACH commands.
  87593. */
  87594. /* #include "sqliteInt.h" */
  87595. #ifndef SQLITE_OMIT_ATTACH
  87596. /*
  87597. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  87598. ** is slightly different from resolving a normal SQL expression, because simple
  87599. ** identifiers are treated as strings, not possible column names or aliases.
  87600. **
  87601. ** i.e. if the parser sees:
  87602. **
  87603. ** ATTACH DATABASE abc AS def
  87604. **
  87605. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  87606. ** looking for columns of the same name.
  87607. **
  87608. ** This only applies to the root node of pExpr, so the statement:
  87609. **
  87610. ** ATTACH DATABASE abc||def AS 'db2'
  87611. **
  87612. ** will fail because neither abc or def can be resolved.
  87613. */
  87614. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  87615. {
  87616. int rc = SQLITE_OK;
  87617. if( pExpr ){
  87618. if( pExpr->op!=TK_ID ){
  87619. rc = sqlite3ResolveExprNames(pName, pExpr);
  87620. }else{
  87621. pExpr->op = TK_STRING;
  87622. }
  87623. }
  87624. return rc;
  87625. }
  87626. /*
  87627. ** An SQL user-function registered to do the work of an ATTACH statement. The
  87628. ** three arguments to the function come directly from an attach statement:
  87629. **
  87630. ** ATTACH DATABASE x AS y KEY z
  87631. **
  87632. ** SELECT sqlite_attach(x, y, z)
  87633. **
  87634. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  87635. ** third argument.
  87636. */
  87637. static void attachFunc(
  87638. sqlite3_context *context,
  87639. int NotUsed,
  87640. sqlite3_value **argv
  87641. ){
  87642. int i;
  87643. int rc = 0;
  87644. sqlite3 *db = sqlite3_context_db_handle(context);
  87645. const char *zName;
  87646. const char *zFile;
  87647. char *zPath = 0;
  87648. char *zErr = 0;
  87649. unsigned int flags;
  87650. Db *aNew;
  87651. char *zErrDyn = 0;
  87652. sqlite3_vfs *pVfs;
  87653. UNUSED_PARAMETER(NotUsed);
  87654. zFile = (const char *)sqlite3_value_text(argv[0]);
  87655. zName = (const char *)sqlite3_value_text(argv[1]);
  87656. if( zFile==0 ) zFile = "";
  87657. if( zName==0 ) zName = "";
  87658. /* Check for the following errors:
  87659. **
  87660. ** * Too many attached databases,
  87661. ** * Transaction currently open
  87662. ** * Specified database name already being used.
  87663. */
  87664. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  87665. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  87666. db->aLimit[SQLITE_LIMIT_ATTACHED]
  87667. );
  87668. goto attach_error;
  87669. }
  87670. if( !db->autoCommit ){
  87671. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  87672. goto attach_error;
  87673. }
  87674. for(i=0; i<db->nDb; i++){
  87675. char *z = db->aDb[i].zName;
  87676. assert( z && zName );
  87677. if( sqlite3StrICmp(z, zName)==0 ){
  87678. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  87679. goto attach_error;
  87680. }
  87681. }
  87682. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  87683. ** hash tables.
  87684. */
  87685. if( db->aDb==db->aDbStatic ){
  87686. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  87687. if( aNew==0 ) return;
  87688. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  87689. }else{
  87690. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  87691. if( aNew==0 ) return;
  87692. }
  87693. db->aDb = aNew;
  87694. aNew = &db->aDb[db->nDb];
  87695. memset(aNew, 0, sizeof(*aNew));
  87696. /* Open the database file. If the btree is successfully opened, use
  87697. ** it to obtain the database schema. At this point the schema may
  87698. ** or may not be initialized.
  87699. */
  87700. flags = db->openFlags;
  87701. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  87702. if( rc!=SQLITE_OK ){
  87703. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  87704. sqlite3_result_error(context, zErr, -1);
  87705. sqlite3_free(zErr);
  87706. return;
  87707. }
  87708. assert( pVfs );
  87709. flags |= SQLITE_OPEN_MAIN_DB;
  87710. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  87711. sqlite3_free( zPath );
  87712. db->nDb++;
  87713. if( rc==SQLITE_CONSTRAINT ){
  87714. rc = SQLITE_ERROR;
  87715. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  87716. }else if( rc==SQLITE_OK ){
  87717. Pager *pPager;
  87718. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  87719. if( !aNew->pSchema ){
  87720. rc = SQLITE_NOMEM_BKPT;
  87721. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  87722. zErrDyn = sqlite3MPrintf(db,
  87723. "attached databases must use the same text encoding as main database");
  87724. rc = SQLITE_ERROR;
  87725. }
  87726. sqlite3BtreeEnter(aNew->pBt);
  87727. pPager = sqlite3BtreePager(aNew->pBt);
  87728. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  87729. sqlite3BtreeSecureDelete(aNew->pBt,
  87730. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  87731. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87732. sqlite3BtreeSetPagerFlags(aNew->pBt,
  87733. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  87734. #endif
  87735. sqlite3BtreeLeave(aNew->pBt);
  87736. }
  87737. aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  87738. aNew->zName = sqlite3DbStrDup(db, zName);
  87739. if( rc==SQLITE_OK && aNew->zName==0 ){
  87740. rc = SQLITE_NOMEM_BKPT;
  87741. }
  87742. #ifdef SQLITE_HAS_CODEC
  87743. if( rc==SQLITE_OK ){
  87744. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  87745. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  87746. int nKey;
  87747. char *zKey;
  87748. int t = sqlite3_value_type(argv[2]);
  87749. switch( t ){
  87750. case SQLITE_INTEGER:
  87751. case SQLITE_FLOAT:
  87752. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  87753. rc = SQLITE_ERROR;
  87754. break;
  87755. case SQLITE_TEXT:
  87756. case SQLITE_BLOB:
  87757. nKey = sqlite3_value_bytes(argv[2]);
  87758. zKey = (char *)sqlite3_value_blob(argv[2]);
  87759. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  87760. break;
  87761. case SQLITE_NULL:
  87762. /* No key specified. Use the key from the main database */
  87763. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  87764. if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  87765. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  87766. }
  87767. break;
  87768. }
  87769. }
  87770. #endif
  87771. /* If the file was opened successfully, read the schema for the new database.
  87772. ** If this fails, or if opening the file failed, then close the file and
  87773. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  87774. ** we found it.
  87775. */
  87776. if( rc==SQLITE_OK ){
  87777. sqlite3BtreeEnterAll(db);
  87778. rc = sqlite3Init(db, &zErrDyn);
  87779. sqlite3BtreeLeaveAll(db);
  87780. }
  87781. #ifdef SQLITE_USER_AUTHENTICATION
  87782. if( rc==SQLITE_OK ){
  87783. u8 newAuth = 0;
  87784. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  87785. if( newAuth<db->auth.authLevel ){
  87786. rc = SQLITE_AUTH_USER;
  87787. }
  87788. }
  87789. #endif
  87790. if( rc ){
  87791. int iDb = db->nDb - 1;
  87792. assert( iDb>=2 );
  87793. if( db->aDb[iDb].pBt ){
  87794. sqlite3BtreeClose(db->aDb[iDb].pBt);
  87795. db->aDb[iDb].pBt = 0;
  87796. db->aDb[iDb].pSchema = 0;
  87797. }
  87798. sqlite3ResetAllSchemasOfConnection(db);
  87799. db->nDb = iDb;
  87800. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  87801. sqlite3OomFault(db);
  87802. sqlite3DbFree(db, zErrDyn);
  87803. zErrDyn = sqlite3MPrintf(db, "out of memory");
  87804. }else if( zErrDyn==0 ){
  87805. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  87806. }
  87807. goto attach_error;
  87808. }
  87809. return;
  87810. attach_error:
  87811. /* Return an error if we get here */
  87812. if( zErrDyn ){
  87813. sqlite3_result_error(context, zErrDyn, -1);
  87814. sqlite3DbFree(db, zErrDyn);
  87815. }
  87816. if( rc ) sqlite3_result_error_code(context, rc);
  87817. }
  87818. /*
  87819. ** An SQL user-function registered to do the work of an DETACH statement. The
  87820. ** three arguments to the function come directly from a detach statement:
  87821. **
  87822. ** DETACH DATABASE x
  87823. **
  87824. ** SELECT sqlite_detach(x)
  87825. */
  87826. static void detachFunc(
  87827. sqlite3_context *context,
  87828. int NotUsed,
  87829. sqlite3_value **argv
  87830. ){
  87831. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  87832. sqlite3 *db = sqlite3_context_db_handle(context);
  87833. int i;
  87834. Db *pDb = 0;
  87835. char zErr[128];
  87836. UNUSED_PARAMETER(NotUsed);
  87837. if( zName==0 ) zName = "";
  87838. for(i=0; i<db->nDb; i++){
  87839. pDb = &db->aDb[i];
  87840. if( pDb->pBt==0 ) continue;
  87841. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  87842. }
  87843. if( i>=db->nDb ){
  87844. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  87845. goto detach_error;
  87846. }
  87847. if( i<2 ){
  87848. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  87849. goto detach_error;
  87850. }
  87851. if( !db->autoCommit ){
  87852. sqlite3_snprintf(sizeof(zErr), zErr,
  87853. "cannot DETACH database within transaction");
  87854. goto detach_error;
  87855. }
  87856. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  87857. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  87858. goto detach_error;
  87859. }
  87860. sqlite3BtreeClose(pDb->pBt);
  87861. pDb->pBt = 0;
  87862. pDb->pSchema = 0;
  87863. sqlite3CollapseDatabaseArray(db);
  87864. return;
  87865. detach_error:
  87866. sqlite3_result_error(context, zErr, -1);
  87867. }
  87868. /*
  87869. ** This procedure generates VDBE code for a single invocation of either the
  87870. ** sqlite_detach() or sqlite_attach() SQL user functions.
  87871. */
  87872. static void codeAttach(
  87873. Parse *pParse, /* The parser context */
  87874. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  87875. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  87876. Expr *pAuthArg, /* Expression to pass to authorization callback */
  87877. Expr *pFilename, /* Name of database file */
  87878. Expr *pDbname, /* Name of the database to use internally */
  87879. Expr *pKey /* Database key for encryption extension */
  87880. ){
  87881. int rc;
  87882. NameContext sName;
  87883. Vdbe *v;
  87884. sqlite3* db = pParse->db;
  87885. int regArgs;
  87886. memset(&sName, 0, sizeof(NameContext));
  87887. sName.pParse = pParse;
  87888. if(
  87889. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  87890. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  87891. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  87892. ){
  87893. goto attach_end;
  87894. }
  87895. #ifndef SQLITE_OMIT_AUTHORIZATION
  87896. if( pAuthArg ){
  87897. char *zAuthArg;
  87898. if( pAuthArg->op==TK_STRING ){
  87899. zAuthArg = pAuthArg->u.zToken;
  87900. }else{
  87901. zAuthArg = 0;
  87902. }
  87903. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  87904. if(rc!=SQLITE_OK ){
  87905. goto attach_end;
  87906. }
  87907. }
  87908. #endif /* SQLITE_OMIT_AUTHORIZATION */
  87909. v = sqlite3GetVdbe(pParse);
  87910. regArgs = sqlite3GetTempRange(pParse, 4);
  87911. sqlite3ExprCode(pParse, pFilename, regArgs);
  87912. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  87913. sqlite3ExprCode(pParse, pKey, regArgs+2);
  87914. assert( v || db->mallocFailed );
  87915. if( v ){
  87916. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  87917. (char *)pFunc, P4_FUNCDEF);
  87918. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  87919. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  87920. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  87921. ** statement only). For DETACH, set it to false (expire all existing
  87922. ** statements).
  87923. */
  87924. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  87925. }
  87926. attach_end:
  87927. sqlite3ExprDelete(db, pFilename);
  87928. sqlite3ExprDelete(db, pDbname);
  87929. sqlite3ExprDelete(db, pKey);
  87930. }
  87931. /*
  87932. ** Called by the parser to compile a DETACH statement.
  87933. **
  87934. ** DETACH pDbname
  87935. */
  87936. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  87937. static const FuncDef detach_func = {
  87938. 1, /* nArg */
  87939. SQLITE_UTF8, /* funcFlags */
  87940. 0, /* pUserData */
  87941. 0, /* pNext */
  87942. detachFunc, /* xSFunc */
  87943. 0, /* xFinalize */
  87944. "sqlite_detach", /* zName */
  87945. {0}
  87946. };
  87947. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  87948. }
  87949. /*
  87950. ** Called by the parser to compile an ATTACH statement.
  87951. **
  87952. ** ATTACH p AS pDbname KEY pKey
  87953. */
  87954. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  87955. static const FuncDef attach_func = {
  87956. 3, /* nArg */
  87957. SQLITE_UTF8, /* funcFlags */
  87958. 0, /* pUserData */
  87959. 0, /* pNext */
  87960. attachFunc, /* xSFunc */
  87961. 0, /* xFinalize */
  87962. "sqlite_attach", /* zName */
  87963. {0}
  87964. };
  87965. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  87966. }
  87967. #endif /* SQLITE_OMIT_ATTACH */
  87968. /*
  87969. ** Initialize a DbFixer structure. This routine must be called prior
  87970. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  87971. */
  87972. SQLITE_PRIVATE void sqlite3FixInit(
  87973. DbFixer *pFix, /* The fixer to be initialized */
  87974. Parse *pParse, /* Error messages will be written here */
  87975. int iDb, /* This is the database that must be used */
  87976. const char *zType, /* "view", "trigger", or "index" */
  87977. const Token *pName /* Name of the view, trigger, or index */
  87978. ){
  87979. sqlite3 *db;
  87980. db = pParse->db;
  87981. assert( db->nDb>iDb );
  87982. pFix->pParse = pParse;
  87983. pFix->zDb = db->aDb[iDb].zName;
  87984. pFix->pSchema = db->aDb[iDb].pSchema;
  87985. pFix->zType = zType;
  87986. pFix->pName = pName;
  87987. pFix->bVarOnly = (iDb==1);
  87988. }
  87989. /*
  87990. ** The following set of routines walk through the parse tree and assign
  87991. ** a specific database to all table references where the database name
  87992. ** was left unspecified in the original SQL statement. The pFix structure
  87993. ** must have been initialized by a prior call to sqlite3FixInit().
  87994. **
  87995. ** These routines are used to make sure that an index, trigger, or
  87996. ** view in one database does not refer to objects in a different database.
  87997. ** (Exception: indices, triggers, and views in the TEMP database are
  87998. ** allowed to refer to anything.) If a reference is explicitly made
  87999. ** to an object in a different database, an error message is added to
  88000. ** pParse->zErrMsg and these routines return non-zero. If everything
  88001. ** checks out, these routines return 0.
  88002. */
  88003. SQLITE_PRIVATE int sqlite3FixSrcList(
  88004. DbFixer *pFix, /* Context of the fixation */
  88005. SrcList *pList /* The Source list to check and modify */
  88006. ){
  88007. int i;
  88008. const char *zDb;
  88009. struct SrcList_item *pItem;
  88010. if( NEVER(pList==0) ) return 0;
  88011. zDb = pFix->zDb;
  88012. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  88013. if( pFix->bVarOnly==0 ){
  88014. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  88015. sqlite3ErrorMsg(pFix->pParse,
  88016. "%s %T cannot reference objects in database %s",
  88017. pFix->zType, pFix->pName, pItem->zDatabase);
  88018. return 1;
  88019. }
  88020. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  88021. pItem->zDatabase = 0;
  88022. pItem->pSchema = pFix->pSchema;
  88023. }
  88024. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  88025. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  88026. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  88027. #endif
  88028. }
  88029. return 0;
  88030. }
  88031. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  88032. SQLITE_PRIVATE int sqlite3FixSelect(
  88033. DbFixer *pFix, /* Context of the fixation */
  88034. Select *pSelect /* The SELECT statement to be fixed to one database */
  88035. ){
  88036. while( pSelect ){
  88037. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  88038. return 1;
  88039. }
  88040. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  88041. return 1;
  88042. }
  88043. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  88044. return 1;
  88045. }
  88046. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  88047. return 1;
  88048. }
  88049. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  88050. return 1;
  88051. }
  88052. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  88053. return 1;
  88054. }
  88055. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  88056. return 1;
  88057. }
  88058. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  88059. return 1;
  88060. }
  88061. pSelect = pSelect->pPrior;
  88062. }
  88063. return 0;
  88064. }
  88065. SQLITE_PRIVATE int sqlite3FixExpr(
  88066. DbFixer *pFix, /* Context of the fixation */
  88067. Expr *pExpr /* The expression to be fixed to one database */
  88068. ){
  88069. while( pExpr ){
  88070. if( pExpr->op==TK_VARIABLE ){
  88071. if( pFix->pParse->db->init.busy ){
  88072. pExpr->op = TK_NULL;
  88073. }else{
  88074. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  88075. return 1;
  88076. }
  88077. }
  88078. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  88079. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  88080. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  88081. }else{
  88082. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  88083. }
  88084. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  88085. return 1;
  88086. }
  88087. pExpr = pExpr->pLeft;
  88088. }
  88089. return 0;
  88090. }
  88091. SQLITE_PRIVATE int sqlite3FixExprList(
  88092. DbFixer *pFix, /* Context of the fixation */
  88093. ExprList *pList /* The expression to be fixed to one database */
  88094. ){
  88095. int i;
  88096. struct ExprList_item *pItem;
  88097. if( pList==0 ) return 0;
  88098. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  88099. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  88100. return 1;
  88101. }
  88102. }
  88103. return 0;
  88104. }
  88105. #endif
  88106. #ifndef SQLITE_OMIT_TRIGGER
  88107. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  88108. DbFixer *pFix, /* Context of the fixation */
  88109. TriggerStep *pStep /* The trigger step be fixed to one database */
  88110. ){
  88111. while( pStep ){
  88112. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  88113. return 1;
  88114. }
  88115. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  88116. return 1;
  88117. }
  88118. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  88119. return 1;
  88120. }
  88121. pStep = pStep->pNext;
  88122. }
  88123. return 0;
  88124. }
  88125. #endif
  88126. /************** End of attach.c **********************************************/
  88127. /************** Begin file auth.c ********************************************/
  88128. /*
  88129. ** 2003 January 11
  88130. **
  88131. ** The author disclaims copyright to this source code. In place of
  88132. ** a legal notice, here is a blessing:
  88133. **
  88134. ** May you do good and not evil.
  88135. ** May you find forgiveness for yourself and forgive others.
  88136. ** May you share freely, never taking more than you give.
  88137. **
  88138. *************************************************************************
  88139. ** This file contains code used to implement the sqlite3_set_authorizer()
  88140. ** API. This facility is an optional feature of the library. Embedded
  88141. ** systems that do not need this facility may omit it by recompiling
  88142. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  88143. */
  88144. /* #include "sqliteInt.h" */
  88145. /*
  88146. ** All of the code in this file may be omitted by defining a single
  88147. ** macro.
  88148. */
  88149. #ifndef SQLITE_OMIT_AUTHORIZATION
  88150. /*
  88151. ** Set or clear the access authorization function.
  88152. **
  88153. ** The access authorization function is be called during the compilation
  88154. ** phase to verify that the user has read and/or write access permission on
  88155. ** various fields of the database. The first argument to the auth function
  88156. ** is a copy of the 3rd argument to this routine. The second argument
  88157. ** to the auth function is one of these constants:
  88158. **
  88159. ** SQLITE_CREATE_INDEX
  88160. ** SQLITE_CREATE_TABLE
  88161. ** SQLITE_CREATE_TEMP_INDEX
  88162. ** SQLITE_CREATE_TEMP_TABLE
  88163. ** SQLITE_CREATE_TEMP_TRIGGER
  88164. ** SQLITE_CREATE_TEMP_VIEW
  88165. ** SQLITE_CREATE_TRIGGER
  88166. ** SQLITE_CREATE_VIEW
  88167. ** SQLITE_DELETE
  88168. ** SQLITE_DROP_INDEX
  88169. ** SQLITE_DROP_TABLE
  88170. ** SQLITE_DROP_TEMP_INDEX
  88171. ** SQLITE_DROP_TEMP_TABLE
  88172. ** SQLITE_DROP_TEMP_TRIGGER
  88173. ** SQLITE_DROP_TEMP_VIEW
  88174. ** SQLITE_DROP_TRIGGER
  88175. ** SQLITE_DROP_VIEW
  88176. ** SQLITE_INSERT
  88177. ** SQLITE_PRAGMA
  88178. ** SQLITE_READ
  88179. ** SQLITE_SELECT
  88180. ** SQLITE_TRANSACTION
  88181. ** SQLITE_UPDATE
  88182. **
  88183. ** The third and fourth arguments to the auth function are the name of
  88184. ** the table and the column that are being accessed. The auth function
  88185. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  88186. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  88187. ** means that the SQL statement will never-run - the sqlite3_exec() call
  88188. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  88189. ** should run but attempts to read the specified column will return NULL
  88190. ** and attempts to write the column will be ignored.
  88191. **
  88192. ** Setting the auth function to NULL disables this hook. The default
  88193. ** setting of the auth function is NULL.
  88194. */
  88195. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  88196. sqlite3 *db,
  88197. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  88198. void *pArg
  88199. ){
  88200. #ifdef SQLITE_ENABLE_API_ARMOR
  88201. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  88202. #endif
  88203. sqlite3_mutex_enter(db->mutex);
  88204. db->xAuth = (sqlite3_xauth)xAuth;
  88205. db->pAuthArg = pArg;
  88206. sqlite3ExpirePreparedStatements(db);
  88207. sqlite3_mutex_leave(db->mutex);
  88208. return SQLITE_OK;
  88209. }
  88210. /*
  88211. ** Write an error message into pParse->zErrMsg that explains that the
  88212. ** user-supplied authorization function returned an illegal value.
  88213. */
  88214. static void sqliteAuthBadReturnCode(Parse *pParse){
  88215. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  88216. pParse->rc = SQLITE_ERROR;
  88217. }
  88218. /*
  88219. ** Invoke the authorization callback for permission to read column zCol from
  88220. ** table zTab in database zDb. This function assumes that an authorization
  88221. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  88222. **
  88223. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  88224. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  88225. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  88226. */
  88227. SQLITE_PRIVATE int sqlite3AuthReadCol(
  88228. Parse *pParse, /* The parser context */
  88229. const char *zTab, /* Table name */
  88230. const char *zCol, /* Column name */
  88231. int iDb /* Index of containing database. */
  88232. ){
  88233. sqlite3 *db = pParse->db; /* Database handle */
  88234. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  88235. int rc; /* Auth callback return code */
  88236. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  88237. #ifdef SQLITE_USER_AUTHENTICATION
  88238. ,db->auth.zAuthUser
  88239. #endif
  88240. );
  88241. if( rc==SQLITE_DENY ){
  88242. if( db->nDb>2 || iDb!=0 ){
  88243. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  88244. }else{
  88245. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  88246. }
  88247. pParse->rc = SQLITE_AUTH;
  88248. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  88249. sqliteAuthBadReturnCode(pParse);
  88250. }
  88251. return rc;
  88252. }
  88253. /*
  88254. ** The pExpr should be a TK_COLUMN expression. The table referred to
  88255. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  88256. ** Check to see if it is OK to read this particular column.
  88257. **
  88258. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  88259. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  88260. ** then generate an error.
  88261. */
  88262. SQLITE_PRIVATE void sqlite3AuthRead(
  88263. Parse *pParse, /* The parser context */
  88264. Expr *pExpr, /* The expression to check authorization on */
  88265. Schema *pSchema, /* The schema of the expression */
  88266. SrcList *pTabList /* All table that pExpr might refer to */
  88267. ){
  88268. sqlite3 *db = pParse->db;
  88269. Table *pTab = 0; /* The table being read */
  88270. const char *zCol; /* Name of the column of the table */
  88271. int iSrc; /* Index in pTabList->a[] of table being read */
  88272. int iDb; /* The index of the database the expression refers to */
  88273. int iCol; /* Index of column in table */
  88274. if( db->xAuth==0 ) return;
  88275. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  88276. if( iDb<0 ){
  88277. /* An attempt to read a column out of a subquery or other
  88278. ** temporary table. */
  88279. return;
  88280. }
  88281. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  88282. if( pExpr->op==TK_TRIGGER ){
  88283. pTab = pParse->pTriggerTab;
  88284. }else{
  88285. assert( pTabList );
  88286. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  88287. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  88288. pTab = pTabList->a[iSrc].pTab;
  88289. break;
  88290. }
  88291. }
  88292. }
  88293. iCol = pExpr->iColumn;
  88294. if( NEVER(pTab==0) ) return;
  88295. if( iCol>=0 ){
  88296. assert( iCol<pTab->nCol );
  88297. zCol = pTab->aCol[iCol].zName;
  88298. }else if( pTab->iPKey>=0 ){
  88299. assert( pTab->iPKey<pTab->nCol );
  88300. zCol = pTab->aCol[pTab->iPKey].zName;
  88301. }else{
  88302. zCol = "ROWID";
  88303. }
  88304. assert( iDb>=0 && iDb<db->nDb );
  88305. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  88306. pExpr->op = TK_NULL;
  88307. }
  88308. }
  88309. /*
  88310. ** Do an authorization check using the code and arguments given. Return
  88311. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  88312. ** is returned, then the error count and error message in pParse are
  88313. ** modified appropriately.
  88314. */
  88315. SQLITE_PRIVATE int sqlite3AuthCheck(
  88316. Parse *pParse,
  88317. int code,
  88318. const char *zArg1,
  88319. const char *zArg2,
  88320. const char *zArg3
  88321. ){
  88322. sqlite3 *db = pParse->db;
  88323. int rc;
  88324. /* Don't do any authorization checks if the database is initialising
  88325. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  88326. */
  88327. if( db->init.busy || IN_DECLARE_VTAB ){
  88328. return SQLITE_OK;
  88329. }
  88330. if( db->xAuth==0 ){
  88331. return SQLITE_OK;
  88332. }
  88333. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  88334. #ifdef SQLITE_USER_AUTHENTICATION
  88335. ,db->auth.zAuthUser
  88336. #endif
  88337. );
  88338. if( rc==SQLITE_DENY ){
  88339. sqlite3ErrorMsg(pParse, "not authorized");
  88340. pParse->rc = SQLITE_AUTH;
  88341. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  88342. rc = SQLITE_DENY;
  88343. sqliteAuthBadReturnCode(pParse);
  88344. }
  88345. return rc;
  88346. }
  88347. /*
  88348. ** Push an authorization context. After this routine is called, the
  88349. ** zArg3 argument to authorization callbacks will be zContext until
  88350. ** popped. Or if pParse==0, this routine is a no-op.
  88351. */
  88352. SQLITE_PRIVATE void sqlite3AuthContextPush(
  88353. Parse *pParse,
  88354. AuthContext *pContext,
  88355. const char *zContext
  88356. ){
  88357. assert( pParse );
  88358. pContext->pParse = pParse;
  88359. pContext->zAuthContext = pParse->zAuthContext;
  88360. pParse->zAuthContext = zContext;
  88361. }
  88362. /*
  88363. ** Pop an authorization context that was previously pushed
  88364. ** by sqlite3AuthContextPush
  88365. */
  88366. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  88367. if( pContext->pParse ){
  88368. pContext->pParse->zAuthContext = pContext->zAuthContext;
  88369. pContext->pParse = 0;
  88370. }
  88371. }
  88372. #endif /* SQLITE_OMIT_AUTHORIZATION */
  88373. /************** End of auth.c ************************************************/
  88374. /************** Begin file build.c *******************************************/
  88375. /*
  88376. ** 2001 September 15
  88377. **
  88378. ** The author disclaims copyright to this source code. In place of
  88379. ** a legal notice, here is a blessing:
  88380. **
  88381. ** May you do good and not evil.
  88382. ** May you find forgiveness for yourself and forgive others.
  88383. ** May you share freely, never taking more than you give.
  88384. **
  88385. *************************************************************************
  88386. ** This file contains C code routines that are called by the SQLite parser
  88387. ** when syntax rules are reduced. The routines in this file handle the
  88388. ** following kinds of SQL syntax:
  88389. **
  88390. ** CREATE TABLE
  88391. ** DROP TABLE
  88392. ** CREATE INDEX
  88393. ** DROP INDEX
  88394. ** creating ID lists
  88395. ** BEGIN TRANSACTION
  88396. ** COMMIT
  88397. ** ROLLBACK
  88398. */
  88399. /* #include "sqliteInt.h" */
  88400. #ifndef SQLITE_OMIT_SHARED_CACHE
  88401. /*
  88402. ** The TableLock structure is only used by the sqlite3TableLock() and
  88403. ** codeTableLocks() functions.
  88404. */
  88405. struct TableLock {
  88406. int iDb; /* The database containing the table to be locked */
  88407. int iTab; /* The root page of the table to be locked */
  88408. u8 isWriteLock; /* True for write lock. False for a read lock */
  88409. const char *zName; /* Name of the table */
  88410. };
  88411. /*
  88412. ** Record the fact that we want to lock a table at run-time.
  88413. **
  88414. ** The table to be locked has root page iTab and is found in database iDb.
  88415. ** A read or a write lock can be taken depending on isWritelock.
  88416. **
  88417. ** This routine just records the fact that the lock is desired. The
  88418. ** code to make the lock occur is generated by a later call to
  88419. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  88420. */
  88421. SQLITE_PRIVATE void sqlite3TableLock(
  88422. Parse *pParse, /* Parsing context */
  88423. int iDb, /* Index of the database containing the table to lock */
  88424. int iTab, /* Root page number of the table to be locked */
  88425. u8 isWriteLock, /* True for a write lock */
  88426. const char *zName /* Name of the table to be locked */
  88427. ){
  88428. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88429. int i;
  88430. int nBytes;
  88431. TableLock *p;
  88432. assert( iDb>=0 );
  88433. for(i=0; i<pToplevel->nTableLock; i++){
  88434. p = &pToplevel->aTableLock[i];
  88435. if( p->iDb==iDb && p->iTab==iTab ){
  88436. p->isWriteLock = (p->isWriteLock || isWriteLock);
  88437. return;
  88438. }
  88439. }
  88440. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  88441. pToplevel->aTableLock =
  88442. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  88443. if( pToplevel->aTableLock ){
  88444. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  88445. p->iDb = iDb;
  88446. p->iTab = iTab;
  88447. p->isWriteLock = isWriteLock;
  88448. p->zName = zName;
  88449. }else{
  88450. pToplevel->nTableLock = 0;
  88451. sqlite3OomFault(pToplevel->db);
  88452. }
  88453. }
  88454. /*
  88455. ** Code an OP_TableLock instruction for each table locked by the
  88456. ** statement (configured by calls to sqlite3TableLock()).
  88457. */
  88458. static void codeTableLocks(Parse *pParse){
  88459. int i;
  88460. Vdbe *pVdbe;
  88461. pVdbe = sqlite3GetVdbe(pParse);
  88462. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  88463. for(i=0; i<pParse->nTableLock; i++){
  88464. TableLock *p = &pParse->aTableLock[i];
  88465. int p1 = p->iDb;
  88466. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  88467. p->zName, P4_STATIC);
  88468. }
  88469. }
  88470. #else
  88471. #define codeTableLocks(x)
  88472. #endif
  88473. /*
  88474. ** Return TRUE if the given yDbMask object is empty - if it contains no
  88475. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  88476. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  88477. */
  88478. #if SQLITE_MAX_ATTACHED>30
  88479. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  88480. int i;
  88481. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  88482. return 1;
  88483. }
  88484. #endif
  88485. /*
  88486. ** This routine is called after a single SQL statement has been
  88487. ** parsed and a VDBE program to execute that statement has been
  88488. ** prepared. This routine puts the finishing touches on the
  88489. ** VDBE program and resets the pParse structure for the next
  88490. ** parse.
  88491. **
  88492. ** Note that if an error occurred, it might be the case that
  88493. ** no VDBE code was generated.
  88494. */
  88495. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  88496. sqlite3 *db;
  88497. Vdbe *v;
  88498. assert( pParse->pToplevel==0 );
  88499. db = pParse->db;
  88500. if( pParse->nested ) return;
  88501. if( db->mallocFailed || pParse->nErr ){
  88502. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  88503. return;
  88504. }
  88505. /* Begin by generating some termination code at the end of the
  88506. ** vdbe program
  88507. */
  88508. v = sqlite3GetVdbe(pParse);
  88509. assert( !pParse->isMultiWrite
  88510. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  88511. if( v ){
  88512. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  88513. sqlite3VdbeAddOp0(v, OP_Halt);
  88514. #if SQLITE_USER_AUTHENTICATION
  88515. if( pParse->nTableLock>0 && db->init.busy==0 ){
  88516. sqlite3UserAuthInit(db);
  88517. if( db->auth.authLevel<UAUTH_User ){
  88518. pParse->rc = SQLITE_AUTH_USER;
  88519. sqlite3ErrorMsg(pParse, "user not authenticated");
  88520. return;
  88521. }
  88522. }
  88523. #endif
  88524. /* The cookie mask contains one bit for each database file open.
  88525. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  88526. ** set for each database that is used. Generate code to start a
  88527. ** transaction on each used database and to verify the schema cookie
  88528. ** on each used database.
  88529. */
  88530. if( db->mallocFailed==0
  88531. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  88532. ){
  88533. int iDb, i;
  88534. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  88535. sqlite3VdbeJumpHere(v, 0);
  88536. for(iDb=0; iDb<db->nDb; iDb++){
  88537. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  88538. sqlite3VdbeUsesBtree(v, iDb);
  88539. sqlite3VdbeAddOp4Int(v,
  88540. OP_Transaction, /* Opcode */
  88541. iDb, /* P1 */
  88542. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  88543. pParse->cookieValue[iDb], /* P3 */
  88544. db->aDb[iDb].pSchema->iGeneration /* P4 */
  88545. );
  88546. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  88547. VdbeComment((v,
  88548. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  88549. }
  88550. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88551. for(i=0; i<pParse->nVtabLock; i++){
  88552. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  88553. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  88554. }
  88555. pParse->nVtabLock = 0;
  88556. #endif
  88557. /* Once all the cookies have been verified and transactions opened,
  88558. ** obtain the required table-locks. This is a no-op unless the
  88559. ** shared-cache feature is enabled.
  88560. */
  88561. codeTableLocks(pParse);
  88562. /* Initialize any AUTOINCREMENT data structures required.
  88563. */
  88564. sqlite3AutoincrementBegin(pParse);
  88565. /* Code constant expressions that where factored out of inner loops */
  88566. if( pParse->pConstExpr ){
  88567. ExprList *pEL = pParse->pConstExpr;
  88568. pParse->okConstFactor = 0;
  88569. for(i=0; i<pEL->nExpr; i++){
  88570. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  88571. }
  88572. }
  88573. /* Finally, jump back to the beginning of the executable code. */
  88574. sqlite3VdbeGoto(v, 1);
  88575. }
  88576. }
  88577. /* Get the VDBE program ready for execution
  88578. */
  88579. if( v && pParse->nErr==0 && !db->mallocFailed ){
  88580. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  88581. /* A minimum of one cursor is required if autoincrement is used
  88582. * See ticket [a696379c1f08866] */
  88583. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  88584. sqlite3VdbeMakeReady(v, pParse);
  88585. pParse->rc = SQLITE_DONE;
  88586. }else{
  88587. pParse->rc = SQLITE_ERROR;
  88588. }
  88589. /* We are done with this Parse object. There is no need to de-initialize it */
  88590. #if 0
  88591. pParse->colNamesSet = 0;
  88592. pParse->nTab = 0;
  88593. pParse->nMem = 0;
  88594. pParse->nSet = 0;
  88595. pParse->nVar = 0;
  88596. DbMaskZero(pParse->cookieMask);
  88597. #endif
  88598. }
  88599. /*
  88600. ** Run the parser and code generator recursively in order to generate
  88601. ** code for the SQL statement given onto the end of the pParse context
  88602. ** currently under construction. When the parser is run recursively
  88603. ** this way, the final OP_Halt is not appended and other initialization
  88604. ** and finalization steps are omitted because those are handling by the
  88605. ** outermost parser.
  88606. **
  88607. ** Not everything is nestable. This facility is designed to permit
  88608. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  88609. ** care if you decide to try to use this routine for some other purposes.
  88610. */
  88611. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  88612. va_list ap;
  88613. char *zSql;
  88614. char *zErrMsg = 0;
  88615. sqlite3 *db = pParse->db;
  88616. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  88617. char saveBuf[SAVE_SZ];
  88618. if( pParse->nErr ) return;
  88619. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  88620. va_start(ap, zFormat);
  88621. zSql = sqlite3VMPrintf(db, zFormat, ap);
  88622. va_end(ap);
  88623. if( zSql==0 ){
  88624. return; /* A malloc must have failed */
  88625. }
  88626. pParse->nested++;
  88627. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  88628. memset(&pParse->nVar, 0, SAVE_SZ);
  88629. sqlite3RunParser(pParse, zSql, &zErrMsg);
  88630. sqlite3DbFree(db, zErrMsg);
  88631. sqlite3DbFree(db, zSql);
  88632. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  88633. pParse->nested--;
  88634. }
  88635. #if SQLITE_USER_AUTHENTICATION
  88636. /*
  88637. ** Return TRUE if zTable is the name of the system table that stores the
  88638. ** list of users and their access credentials.
  88639. */
  88640. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  88641. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  88642. }
  88643. #endif
  88644. /*
  88645. ** Locate the in-memory structure that describes a particular database
  88646. ** table given the name of that table and (optionally) the name of the
  88647. ** database containing the table. Return NULL if not found.
  88648. **
  88649. ** If zDatabase is 0, all databases are searched for the table and the
  88650. ** first matching table is returned. (No checking for duplicate table
  88651. ** names is done.) The search order is TEMP first, then MAIN, then any
  88652. ** auxiliary databases added using the ATTACH command.
  88653. **
  88654. ** See also sqlite3LocateTable().
  88655. */
  88656. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  88657. Table *p = 0;
  88658. int i;
  88659. /* All mutexes are required for schema access. Make sure we hold them. */
  88660. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  88661. #if SQLITE_USER_AUTHENTICATION
  88662. /* Only the admin user is allowed to know that the sqlite_user table
  88663. ** exists */
  88664. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  88665. return 0;
  88666. }
  88667. #endif
  88668. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  88669. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  88670. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  88671. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  88672. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  88673. if( p ) break;
  88674. }
  88675. return p;
  88676. }
  88677. /*
  88678. ** Locate the in-memory structure that describes a particular database
  88679. ** table given the name of that table and (optionally) the name of the
  88680. ** database containing the table. Return NULL if not found. Also leave an
  88681. ** error message in pParse->zErrMsg.
  88682. **
  88683. ** The difference between this routine and sqlite3FindTable() is that this
  88684. ** routine leaves an error message in pParse->zErrMsg where
  88685. ** sqlite3FindTable() does not.
  88686. */
  88687. SQLITE_PRIVATE Table *sqlite3LocateTable(
  88688. Parse *pParse, /* context in which to report errors */
  88689. int isView, /* True if looking for a VIEW rather than a TABLE */
  88690. const char *zName, /* Name of the table we are looking for */
  88691. const char *zDbase /* Name of the database. Might be NULL */
  88692. ){
  88693. Table *p;
  88694. /* Read the database schema. If an error occurs, leave an error message
  88695. ** and code in pParse and return NULL. */
  88696. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88697. return 0;
  88698. }
  88699. p = sqlite3FindTable(pParse->db, zName, zDbase);
  88700. if( p==0 ){
  88701. const char *zMsg = isView ? "no such view" : "no such table";
  88702. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88703. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  88704. /* If zName is the not the name of a table in the schema created using
  88705. ** CREATE, then check to see if it is the name of an virtual table that
  88706. ** can be an eponymous virtual table. */
  88707. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  88708. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  88709. return pMod->pEpoTab;
  88710. }
  88711. }
  88712. #endif
  88713. if( zDbase ){
  88714. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  88715. }else{
  88716. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  88717. }
  88718. pParse->checkSchema = 1;
  88719. }
  88720. return p;
  88721. }
  88722. /*
  88723. ** Locate the table identified by *p.
  88724. **
  88725. ** This is a wrapper around sqlite3LocateTable(). The difference between
  88726. ** sqlite3LocateTable() and this function is that this function restricts
  88727. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  88728. ** non-NULL if it is part of a view or trigger program definition. See
  88729. ** sqlite3FixSrcList() for details.
  88730. */
  88731. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  88732. Parse *pParse,
  88733. int isView,
  88734. struct SrcList_item *p
  88735. ){
  88736. const char *zDb;
  88737. assert( p->pSchema==0 || p->zDatabase==0 );
  88738. if( p->pSchema ){
  88739. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  88740. zDb = pParse->db->aDb[iDb].zName;
  88741. }else{
  88742. zDb = p->zDatabase;
  88743. }
  88744. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  88745. }
  88746. /*
  88747. ** Locate the in-memory structure that describes
  88748. ** a particular index given the name of that index
  88749. ** and the name of the database that contains the index.
  88750. ** Return NULL if not found.
  88751. **
  88752. ** If zDatabase is 0, all databases are searched for the
  88753. ** table and the first matching index is returned. (No checking
  88754. ** for duplicate index names is done.) The search order is
  88755. ** TEMP first, then MAIN, then any auxiliary databases added
  88756. ** using the ATTACH command.
  88757. */
  88758. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  88759. Index *p = 0;
  88760. int i;
  88761. /* All mutexes are required for schema access. Make sure we hold them. */
  88762. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  88763. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  88764. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  88765. Schema *pSchema = db->aDb[j].pSchema;
  88766. assert( pSchema );
  88767. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  88768. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  88769. p = sqlite3HashFind(&pSchema->idxHash, zName);
  88770. if( p ) break;
  88771. }
  88772. return p;
  88773. }
  88774. /*
  88775. ** Reclaim the memory used by an index
  88776. */
  88777. static void freeIndex(sqlite3 *db, Index *p){
  88778. #ifndef SQLITE_OMIT_ANALYZE
  88779. sqlite3DeleteIndexSamples(db, p);
  88780. #endif
  88781. sqlite3ExprDelete(db, p->pPartIdxWhere);
  88782. sqlite3ExprListDelete(db, p->aColExpr);
  88783. sqlite3DbFree(db, p->zColAff);
  88784. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  88785. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  88786. sqlite3_free(p->aiRowEst);
  88787. #endif
  88788. sqlite3DbFree(db, p);
  88789. }
  88790. /*
  88791. ** For the index called zIdxName which is found in the database iDb,
  88792. ** unlike that index from its Table then remove the index from
  88793. ** the index hash table and free all memory structures associated
  88794. ** with the index.
  88795. */
  88796. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  88797. Index *pIndex;
  88798. Hash *pHash;
  88799. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88800. pHash = &db->aDb[iDb].pSchema->idxHash;
  88801. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  88802. if( ALWAYS(pIndex) ){
  88803. if( pIndex->pTable->pIndex==pIndex ){
  88804. pIndex->pTable->pIndex = pIndex->pNext;
  88805. }else{
  88806. Index *p;
  88807. /* Justification of ALWAYS(); The index must be on the list of
  88808. ** indices. */
  88809. p = pIndex->pTable->pIndex;
  88810. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  88811. if( ALWAYS(p && p->pNext==pIndex) ){
  88812. p->pNext = pIndex->pNext;
  88813. }
  88814. }
  88815. freeIndex(db, pIndex);
  88816. }
  88817. db->flags |= SQLITE_InternChanges;
  88818. }
  88819. /*
  88820. ** Look through the list of open database files in db->aDb[] and if
  88821. ** any have been closed, remove them from the list. Reallocate the
  88822. ** db->aDb[] structure to a smaller size, if possible.
  88823. **
  88824. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  88825. ** are never candidates for being collapsed.
  88826. */
  88827. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  88828. int i, j;
  88829. for(i=j=2; i<db->nDb; i++){
  88830. struct Db *pDb = &db->aDb[i];
  88831. if( pDb->pBt==0 ){
  88832. sqlite3DbFree(db, pDb->zName);
  88833. pDb->zName = 0;
  88834. continue;
  88835. }
  88836. if( j<i ){
  88837. db->aDb[j] = db->aDb[i];
  88838. }
  88839. j++;
  88840. }
  88841. db->nDb = j;
  88842. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  88843. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  88844. sqlite3DbFree(db, db->aDb);
  88845. db->aDb = db->aDbStatic;
  88846. }
  88847. }
  88848. /*
  88849. ** Reset the schema for the database at index iDb. Also reset the
  88850. ** TEMP schema.
  88851. */
  88852. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  88853. Db *pDb;
  88854. assert( iDb<db->nDb );
  88855. /* Case 1: Reset the single schema identified by iDb */
  88856. pDb = &db->aDb[iDb];
  88857. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88858. assert( pDb->pSchema!=0 );
  88859. sqlite3SchemaClear(pDb->pSchema);
  88860. /* If any database other than TEMP is reset, then also reset TEMP
  88861. ** since TEMP might be holding triggers that reference tables in the
  88862. ** other database.
  88863. */
  88864. if( iDb!=1 ){
  88865. pDb = &db->aDb[1];
  88866. assert( pDb->pSchema!=0 );
  88867. sqlite3SchemaClear(pDb->pSchema);
  88868. }
  88869. return;
  88870. }
  88871. /*
  88872. ** Erase all schema information from all attached databases (including
  88873. ** "main" and "temp") for a single database connection.
  88874. */
  88875. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  88876. int i;
  88877. sqlite3BtreeEnterAll(db);
  88878. for(i=0; i<db->nDb; i++){
  88879. Db *pDb = &db->aDb[i];
  88880. if( pDb->pSchema ){
  88881. sqlite3SchemaClear(pDb->pSchema);
  88882. }
  88883. }
  88884. db->flags &= ~SQLITE_InternChanges;
  88885. sqlite3VtabUnlockList(db);
  88886. sqlite3BtreeLeaveAll(db);
  88887. sqlite3CollapseDatabaseArray(db);
  88888. }
  88889. /*
  88890. ** This routine is called when a commit occurs.
  88891. */
  88892. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  88893. db->flags &= ~SQLITE_InternChanges;
  88894. }
  88895. /*
  88896. ** Delete memory allocated for the column names of a table or view (the
  88897. ** Table.aCol[] array).
  88898. */
  88899. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  88900. int i;
  88901. Column *pCol;
  88902. assert( pTable!=0 );
  88903. if( (pCol = pTable->aCol)!=0 ){
  88904. for(i=0; i<pTable->nCol; i++, pCol++){
  88905. sqlite3DbFree(db, pCol->zName);
  88906. sqlite3ExprDelete(db, pCol->pDflt);
  88907. sqlite3DbFree(db, pCol->zColl);
  88908. }
  88909. sqlite3DbFree(db, pTable->aCol);
  88910. }
  88911. }
  88912. /*
  88913. ** Remove the memory data structures associated with the given
  88914. ** Table. No changes are made to disk by this routine.
  88915. **
  88916. ** This routine just deletes the data structure. It does not unlink
  88917. ** the table data structure from the hash table. But it does destroy
  88918. ** memory structures of the indices and foreign keys associated with
  88919. ** the table.
  88920. **
  88921. ** The db parameter is optional. It is needed if the Table object
  88922. ** contains lookaside memory. (Table objects in the schema do not use
  88923. ** lookaside memory, but some ephemeral Table objects do.) Or the
  88924. ** db parameter can be used with db->pnBytesFreed to measure the memory
  88925. ** used by the Table object.
  88926. */
  88927. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  88928. Index *pIndex, *pNext;
  88929. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  88930. assert( !pTable || pTable->nRef>0 );
  88931. /* Do not delete the table until the reference count reaches zero. */
  88932. if( !pTable ) return;
  88933. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  88934. /* Record the number of outstanding lookaside allocations in schema Tables
  88935. ** prior to doing any free() operations. Since schema Tables do not use
  88936. ** lookaside, this number should not change. */
  88937. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  88938. db->lookaside.nOut : 0 );
  88939. /* Delete all indices associated with this table. */
  88940. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  88941. pNext = pIndex->pNext;
  88942. assert( pIndex->pSchema==pTable->pSchema );
  88943. if( !db || db->pnBytesFreed==0 ){
  88944. char *zName = pIndex->zName;
  88945. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  88946. &pIndex->pSchema->idxHash, zName, 0
  88947. );
  88948. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  88949. assert( pOld==pIndex || pOld==0 );
  88950. }
  88951. freeIndex(db, pIndex);
  88952. }
  88953. /* Delete any foreign keys attached to this table. */
  88954. sqlite3FkDelete(db, pTable);
  88955. /* Delete the Table structure itself.
  88956. */
  88957. sqlite3DeleteColumnNames(db, pTable);
  88958. sqlite3DbFree(db, pTable->zName);
  88959. sqlite3DbFree(db, pTable->zColAff);
  88960. sqlite3SelectDelete(db, pTable->pSelect);
  88961. sqlite3ExprListDelete(db, pTable->pCheck);
  88962. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88963. sqlite3VtabClear(db, pTable);
  88964. #endif
  88965. sqlite3DbFree(db, pTable);
  88966. /* Verify that no lookaside memory was used by schema tables */
  88967. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  88968. }
  88969. /*
  88970. ** Unlink the given table from the hash tables and the delete the
  88971. ** table structure with all its indices and foreign keys.
  88972. */
  88973. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  88974. Table *p;
  88975. Db *pDb;
  88976. assert( db!=0 );
  88977. assert( iDb>=0 && iDb<db->nDb );
  88978. assert( zTabName );
  88979. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88980. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  88981. pDb = &db->aDb[iDb];
  88982. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  88983. sqlite3DeleteTable(db, p);
  88984. db->flags |= SQLITE_InternChanges;
  88985. }
  88986. /*
  88987. ** Given a token, return a string that consists of the text of that
  88988. ** token. Space to hold the returned string
  88989. ** is obtained from sqliteMalloc() and must be freed by the calling
  88990. ** function.
  88991. **
  88992. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  88993. ** surround the body of the token are removed.
  88994. **
  88995. ** Tokens are often just pointers into the original SQL text and so
  88996. ** are not \000 terminated and are not persistent. The returned string
  88997. ** is \000 terminated and is persistent.
  88998. */
  88999. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  89000. char *zName;
  89001. if( pName ){
  89002. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  89003. sqlite3Dequote(zName);
  89004. }else{
  89005. zName = 0;
  89006. }
  89007. return zName;
  89008. }
  89009. /*
  89010. ** Open the sqlite_master table stored in database number iDb for
  89011. ** writing. The table is opened using cursor 0.
  89012. */
  89013. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  89014. Vdbe *v = sqlite3GetVdbe(p);
  89015. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  89016. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  89017. if( p->nTab==0 ){
  89018. p->nTab = 1;
  89019. }
  89020. }
  89021. /*
  89022. ** Parameter zName points to a nul-terminated buffer containing the name
  89023. ** of a database ("main", "temp" or the name of an attached db). This
  89024. ** function returns the index of the named database in db->aDb[], or
  89025. ** -1 if the named db cannot be found.
  89026. */
  89027. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  89028. int i = -1; /* Database number */
  89029. if( zName ){
  89030. Db *pDb;
  89031. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  89032. if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
  89033. }
  89034. }
  89035. return i;
  89036. }
  89037. /*
  89038. ** The token *pName contains the name of a database (either "main" or
  89039. ** "temp" or the name of an attached db). This routine returns the
  89040. ** index of the named database in db->aDb[], or -1 if the named db
  89041. ** does not exist.
  89042. */
  89043. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  89044. int i; /* Database number */
  89045. char *zName; /* Name we are searching for */
  89046. zName = sqlite3NameFromToken(db, pName);
  89047. i = sqlite3FindDbName(db, zName);
  89048. sqlite3DbFree(db, zName);
  89049. return i;
  89050. }
  89051. /* The table or view or trigger name is passed to this routine via tokens
  89052. ** pName1 and pName2. If the table name was fully qualified, for example:
  89053. **
  89054. ** CREATE TABLE xxx.yyy (...);
  89055. **
  89056. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  89057. ** the table name is not fully qualified, i.e.:
  89058. **
  89059. ** CREATE TABLE yyy(...);
  89060. **
  89061. ** Then pName1 is set to "yyy" and pName2 is "".
  89062. **
  89063. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  89064. ** pName2) that stores the unqualified table name. The index of the
  89065. ** database "xxx" is returned.
  89066. */
  89067. SQLITE_PRIVATE int sqlite3TwoPartName(
  89068. Parse *pParse, /* Parsing and code generating context */
  89069. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  89070. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  89071. Token **pUnqual /* Write the unqualified object name here */
  89072. ){
  89073. int iDb; /* Database holding the object */
  89074. sqlite3 *db = pParse->db;
  89075. assert( pName2!=0 );
  89076. if( pName2->n>0 ){
  89077. if( db->init.busy ) {
  89078. sqlite3ErrorMsg(pParse, "corrupt database");
  89079. return -1;
  89080. }
  89081. *pUnqual = pName2;
  89082. iDb = sqlite3FindDb(db, pName1);
  89083. if( iDb<0 ){
  89084. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  89085. return -1;
  89086. }
  89087. }else{
  89088. assert( db->init.iDb==0 || db->init.busy );
  89089. iDb = db->init.iDb;
  89090. *pUnqual = pName1;
  89091. }
  89092. return iDb;
  89093. }
  89094. /*
  89095. ** This routine is used to check if the UTF-8 string zName is a legal
  89096. ** unqualified name for a new schema object (table, index, view or
  89097. ** trigger). All names are legal except those that begin with the string
  89098. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  89099. ** is reserved for internal use.
  89100. */
  89101. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  89102. if( !pParse->db->init.busy && pParse->nested==0
  89103. && (pParse->db->flags & SQLITE_WriteSchema)==0
  89104. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  89105. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  89106. return SQLITE_ERROR;
  89107. }
  89108. return SQLITE_OK;
  89109. }
  89110. /*
  89111. ** Return the PRIMARY KEY index of a table
  89112. */
  89113. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  89114. Index *p;
  89115. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  89116. return p;
  89117. }
  89118. /*
  89119. ** Return the column of index pIdx that corresponds to table
  89120. ** column iCol. Return -1 if not found.
  89121. */
  89122. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  89123. int i;
  89124. for(i=0; i<pIdx->nColumn; i++){
  89125. if( iCol==pIdx->aiColumn[i] ) return i;
  89126. }
  89127. return -1;
  89128. }
  89129. /*
  89130. ** Begin constructing a new table representation in memory. This is
  89131. ** the first of several action routines that get called in response
  89132. ** to a CREATE TABLE statement. In particular, this routine is called
  89133. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  89134. ** flag is true if the table should be stored in the auxiliary database
  89135. ** file instead of in the main database file. This is normally the case
  89136. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  89137. ** CREATE and TABLE.
  89138. **
  89139. ** The new table record is initialized and put in pParse->pNewTable.
  89140. ** As more of the CREATE TABLE statement is parsed, additional action
  89141. ** routines will be called to add more information to this record.
  89142. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  89143. ** is called to complete the construction of the new table record.
  89144. */
  89145. SQLITE_PRIVATE void sqlite3StartTable(
  89146. Parse *pParse, /* Parser context */
  89147. Token *pName1, /* First part of the name of the table or view */
  89148. Token *pName2, /* Second part of the name of the table or view */
  89149. int isTemp, /* True if this is a TEMP table */
  89150. int isView, /* True if this is a VIEW */
  89151. int isVirtual, /* True if this is a VIRTUAL table */
  89152. int noErr /* Do nothing if table already exists */
  89153. ){
  89154. Table *pTable;
  89155. char *zName = 0; /* The name of the new table */
  89156. sqlite3 *db = pParse->db;
  89157. Vdbe *v;
  89158. int iDb; /* Database number to create the table in */
  89159. Token *pName; /* Unqualified name of the table to create */
  89160. if( db->init.busy && db->init.newTnum==1 ){
  89161. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  89162. iDb = db->init.iDb;
  89163. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  89164. pName = pName1;
  89165. }else{
  89166. /* The common case */
  89167. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  89168. if( iDb<0 ) return;
  89169. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  89170. /* If creating a temp table, the name may not be qualified. Unless
  89171. ** the database name is "temp" anyway. */
  89172. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  89173. return;
  89174. }
  89175. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  89176. zName = sqlite3NameFromToken(db, pName);
  89177. }
  89178. pParse->sNameToken = *pName;
  89179. if( zName==0 ) return;
  89180. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  89181. goto begin_table_error;
  89182. }
  89183. if( db->init.iDb==1 ) isTemp = 1;
  89184. #ifndef SQLITE_OMIT_AUTHORIZATION
  89185. assert( isTemp==0 || isTemp==1 );
  89186. assert( isView==0 || isView==1 );
  89187. {
  89188. static const u8 aCode[] = {
  89189. SQLITE_CREATE_TABLE,
  89190. SQLITE_CREATE_TEMP_TABLE,
  89191. SQLITE_CREATE_VIEW,
  89192. SQLITE_CREATE_TEMP_VIEW
  89193. };
  89194. char *zDb = db->aDb[iDb].zName;
  89195. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  89196. goto begin_table_error;
  89197. }
  89198. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  89199. zName, 0, zDb) ){
  89200. goto begin_table_error;
  89201. }
  89202. }
  89203. #endif
  89204. /* Make sure the new table name does not collide with an existing
  89205. ** index or table name in the same database. Issue an error message if
  89206. ** it does. The exception is if the statement being parsed was passed
  89207. ** to an sqlite3_declare_vtab() call. In that case only the column names
  89208. ** and types will be used, so there is no need to test for namespace
  89209. ** collisions.
  89210. */
  89211. if( !IN_DECLARE_VTAB ){
  89212. char *zDb = db->aDb[iDb].zName;
  89213. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  89214. goto begin_table_error;
  89215. }
  89216. pTable = sqlite3FindTable(db, zName, zDb);
  89217. if( pTable ){
  89218. if( !noErr ){
  89219. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  89220. }else{
  89221. assert( !db->init.busy || CORRUPT_DB );
  89222. sqlite3CodeVerifySchema(pParse, iDb);
  89223. }
  89224. goto begin_table_error;
  89225. }
  89226. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  89227. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  89228. goto begin_table_error;
  89229. }
  89230. }
  89231. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  89232. if( pTable==0 ){
  89233. assert( db->mallocFailed );
  89234. pParse->rc = SQLITE_NOMEM_BKPT;
  89235. pParse->nErr++;
  89236. goto begin_table_error;
  89237. }
  89238. pTable->zName = zName;
  89239. pTable->iPKey = -1;
  89240. pTable->pSchema = db->aDb[iDb].pSchema;
  89241. pTable->nRef = 1;
  89242. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  89243. assert( pParse->pNewTable==0 );
  89244. pParse->pNewTable = pTable;
  89245. /* If this is the magic sqlite_sequence table used by autoincrement,
  89246. ** then record a pointer to this table in the main database structure
  89247. ** so that INSERT can find the table easily.
  89248. */
  89249. #ifndef SQLITE_OMIT_AUTOINCREMENT
  89250. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  89251. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89252. pTable->pSchema->pSeqTab = pTable;
  89253. }
  89254. #endif
  89255. /* Begin generating the code that will insert the table record into
  89256. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  89257. ** and allocate the record number for the table entry now. Before any
  89258. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  89259. ** indices to be created and the table record must come before the
  89260. ** indices. Hence, the record number for the table must be allocated
  89261. ** now.
  89262. */
  89263. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  89264. int addr1;
  89265. int fileFormat;
  89266. int reg1, reg2, reg3;
  89267. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  89268. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  89269. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89270. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89271. if( isVirtual ){
  89272. sqlite3VdbeAddOp0(v, OP_VBegin);
  89273. }
  89274. #endif
  89275. /* If the file format and encoding in the database have not been set,
  89276. ** set them now.
  89277. */
  89278. reg1 = pParse->regRowid = ++pParse->nMem;
  89279. reg2 = pParse->regRoot = ++pParse->nMem;
  89280. reg3 = ++pParse->nMem;
  89281. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  89282. sqlite3VdbeUsesBtree(v, iDb);
  89283. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  89284. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  89285. 1 : SQLITE_MAX_FILE_FORMAT;
  89286. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  89287. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  89288. sqlite3VdbeJumpHere(v, addr1);
  89289. /* This just creates a place-holder record in the sqlite_master table.
  89290. ** The record created does not contain anything yet. It will be replaced
  89291. ** by the real entry in code generated at sqlite3EndTable().
  89292. **
  89293. ** The rowid for the new entry is left in register pParse->regRowid.
  89294. ** The root page number of the new table is left in reg pParse->regRoot.
  89295. ** The rowid and root page number values are needed by the code that
  89296. ** sqlite3EndTable will generate.
  89297. */
  89298. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  89299. if( isView || isVirtual ){
  89300. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  89301. }else
  89302. #endif
  89303. {
  89304. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  89305. }
  89306. sqlite3OpenMasterTable(pParse, iDb);
  89307. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  89308. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  89309. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  89310. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  89311. sqlite3VdbeAddOp0(v, OP_Close);
  89312. }
  89313. /* Normal (non-error) return. */
  89314. return;
  89315. /* If an error occurs, we jump here */
  89316. begin_table_error:
  89317. sqlite3DbFree(db, zName);
  89318. return;
  89319. }
  89320. /* Set properties of a table column based on the (magical)
  89321. ** name of the column.
  89322. */
  89323. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  89324. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  89325. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  89326. pCol->colFlags |= COLFLAG_HIDDEN;
  89327. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  89328. pTab->tabFlags |= TF_OOOHidden;
  89329. }
  89330. }
  89331. #endif
  89332. /*
  89333. ** Add a new column to the table currently being constructed.
  89334. **
  89335. ** The parser calls this routine once for each column declaration
  89336. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  89337. ** first to get things going. Then this routine is called for each
  89338. ** column.
  89339. */
  89340. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  89341. Table *p;
  89342. int i;
  89343. char *z;
  89344. char *zType;
  89345. Column *pCol;
  89346. sqlite3 *db = pParse->db;
  89347. if( (p = pParse->pNewTable)==0 ) return;
  89348. #if SQLITE_MAX_COLUMN
  89349. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  89350. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  89351. return;
  89352. }
  89353. #endif
  89354. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  89355. if( z==0 ) return;
  89356. memcpy(z, pName->z, pName->n);
  89357. z[pName->n] = 0;
  89358. sqlite3Dequote(z);
  89359. for(i=0; i<p->nCol; i++){
  89360. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  89361. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  89362. sqlite3DbFree(db, z);
  89363. return;
  89364. }
  89365. }
  89366. if( (p->nCol & 0x7)==0 ){
  89367. Column *aNew;
  89368. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  89369. if( aNew==0 ){
  89370. sqlite3DbFree(db, z);
  89371. return;
  89372. }
  89373. p->aCol = aNew;
  89374. }
  89375. pCol = &p->aCol[p->nCol];
  89376. memset(pCol, 0, sizeof(p->aCol[0]));
  89377. pCol->zName = z;
  89378. sqlite3ColumnPropertiesFromName(p, pCol);
  89379. if( pType->n==0 ){
  89380. /* If there is no type specified, columns have the default affinity
  89381. ** 'BLOB'. */
  89382. pCol->affinity = SQLITE_AFF_BLOB;
  89383. pCol->szEst = 1;
  89384. }else{
  89385. zType = z + sqlite3Strlen30(z) + 1;
  89386. memcpy(zType, pType->z, pType->n);
  89387. zType[pType->n] = 0;
  89388. pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
  89389. pCol->colFlags |= COLFLAG_HASTYPE;
  89390. }
  89391. p->nCol++;
  89392. pParse->constraintName.n = 0;
  89393. }
  89394. /*
  89395. ** This routine is called by the parser while in the middle of
  89396. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  89397. ** been seen on a column. This routine sets the notNull flag on
  89398. ** the column currently under construction.
  89399. */
  89400. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  89401. Table *p;
  89402. p = pParse->pNewTable;
  89403. if( p==0 || NEVER(p->nCol<1) ) return;
  89404. p->aCol[p->nCol-1].notNull = (u8)onError;
  89405. }
  89406. /*
  89407. ** Scan the column type name zType (length nType) and return the
  89408. ** associated affinity type.
  89409. **
  89410. ** This routine does a case-independent search of zType for the
  89411. ** substrings in the following table. If one of the substrings is
  89412. ** found, the corresponding affinity is returned. If zType contains
  89413. ** more than one of the substrings, entries toward the top of
  89414. ** the table take priority. For example, if zType is 'BLOBINT',
  89415. ** SQLITE_AFF_INTEGER is returned.
  89416. **
  89417. ** Substring | Affinity
  89418. ** --------------------------------
  89419. ** 'INT' | SQLITE_AFF_INTEGER
  89420. ** 'CHAR' | SQLITE_AFF_TEXT
  89421. ** 'CLOB' | SQLITE_AFF_TEXT
  89422. ** 'TEXT' | SQLITE_AFF_TEXT
  89423. ** 'BLOB' | SQLITE_AFF_BLOB
  89424. ** 'REAL' | SQLITE_AFF_REAL
  89425. ** 'FLOA' | SQLITE_AFF_REAL
  89426. ** 'DOUB' | SQLITE_AFF_REAL
  89427. **
  89428. ** If none of the substrings in the above table are found,
  89429. ** SQLITE_AFF_NUMERIC is returned.
  89430. */
  89431. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  89432. u32 h = 0;
  89433. char aff = SQLITE_AFF_NUMERIC;
  89434. const char *zChar = 0;
  89435. assert( zIn!=0 );
  89436. while( zIn[0] ){
  89437. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  89438. zIn++;
  89439. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  89440. aff = SQLITE_AFF_TEXT;
  89441. zChar = zIn;
  89442. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  89443. aff = SQLITE_AFF_TEXT;
  89444. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  89445. aff = SQLITE_AFF_TEXT;
  89446. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  89447. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  89448. aff = SQLITE_AFF_BLOB;
  89449. if( zIn[0]=='(' ) zChar = zIn;
  89450. #ifndef SQLITE_OMIT_FLOATING_POINT
  89451. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  89452. && aff==SQLITE_AFF_NUMERIC ){
  89453. aff = SQLITE_AFF_REAL;
  89454. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  89455. && aff==SQLITE_AFF_NUMERIC ){
  89456. aff = SQLITE_AFF_REAL;
  89457. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  89458. && aff==SQLITE_AFF_NUMERIC ){
  89459. aff = SQLITE_AFF_REAL;
  89460. #endif
  89461. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  89462. aff = SQLITE_AFF_INTEGER;
  89463. break;
  89464. }
  89465. }
  89466. /* If pszEst is not NULL, store an estimate of the field size. The
  89467. ** estimate is scaled so that the size of an integer is 1. */
  89468. if( pszEst ){
  89469. *pszEst = 1; /* default size is approx 4 bytes */
  89470. if( aff<SQLITE_AFF_NUMERIC ){
  89471. if( zChar ){
  89472. while( zChar[0] ){
  89473. if( sqlite3Isdigit(zChar[0]) ){
  89474. int v = 0;
  89475. sqlite3GetInt32(zChar, &v);
  89476. v = v/4 + 1;
  89477. if( v>255 ) v = 255;
  89478. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  89479. break;
  89480. }
  89481. zChar++;
  89482. }
  89483. }else{
  89484. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  89485. }
  89486. }
  89487. }
  89488. return aff;
  89489. }
  89490. /*
  89491. ** The expression is the default value for the most recently added column
  89492. ** of the table currently under construction.
  89493. **
  89494. ** Default value expressions must be constant. Raise an exception if this
  89495. ** is not the case.
  89496. **
  89497. ** This routine is called by the parser while in the middle of
  89498. ** parsing a CREATE TABLE statement.
  89499. */
  89500. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  89501. Table *p;
  89502. Column *pCol;
  89503. sqlite3 *db = pParse->db;
  89504. p = pParse->pNewTable;
  89505. if( p!=0 ){
  89506. pCol = &(p->aCol[p->nCol-1]);
  89507. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  89508. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  89509. pCol->zName);
  89510. }else{
  89511. /* A copy of pExpr is used instead of the original, as pExpr contains
  89512. ** tokens that point to volatile memory. The 'span' of the expression
  89513. ** is required by pragma table_info.
  89514. */
  89515. Expr x;
  89516. sqlite3ExprDelete(db, pCol->pDflt);
  89517. memset(&x, 0, sizeof(x));
  89518. x.op = TK_SPAN;
  89519. x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  89520. (int)(pSpan->zEnd - pSpan->zStart));
  89521. x.pLeft = pSpan->pExpr;
  89522. x.flags = EP_Skip;
  89523. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  89524. sqlite3DbFree(db, x.u.zToken);
  89525. }
  89526. }
  89527. sqlite3ExprDelete(db, pSpan->pExpr);
  89528. }
  89529. /*
  89530. ** Backwards Compatibility Hack:
  89531. **
  89532. ** Historical versions of SQLite accepted strings as column names in
  89533. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  89534. **
  89535. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  89536. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  89537. **
  89538. ** This is goofy. But to preserve backwards compatibility we continue to
  89539. ** accept it. This routine does the necessary conversion. It converts
  89540. ** the expression given in its argument from a TK_STRING into a TK_ID
  89541. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  89542. ** If the epxression is anything other than TK_STRING, the expression is
  89543. ** unchanged.
  89544. */
  89545. static void sqlite3StringToId(Expr *p){
  89546. if( p->op==TK_STRING ){
  89547. p->op = TK_ID;
  89548. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  89549. p->pLeft->op = TK_ID;
  89550. }
  89551. }
  89552. /*
  89553. ** Designate the PRIMARY KEY for the table. pList is a list of names
  89554. ** of columns that form the primary key. If pList is NULL, then the
  89555. ** most recently added column of the table is the primary key.
  89556. **
  89557. ** A table can have at most one primary key. If the table already has
  89558. ** a primary key (and this is the second primary key) then create an
  89559. ** error.
  89560. **
  89561. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  89562. ** then we will try to use that column as the rowid. Set the Table.iPKey
  89563. ** field of the table under construction to be the index of the
  89564. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  89565. ** no INTEGER PRIMARY KEY.
  89566. **
  89567. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  89568. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  89569. */
  89570. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  89571. Parse *pParse, /* Parsing context */
  89572. ExprList *pList, /* List of field names to be indexed */
  89573. int onError, /* What to do with a uniqueness conflict */
  89574. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  89575. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  89576. ){
  89577. Table *pTab = pParse->pNewTable;
  89578. Column *pCol = 0;
  89579. int iCol = -1, i;
  89580. int nTerm;
  89581. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  89582. if( pTab->tabFlags & TF_HasPrimaryKey ){
  89583. sqlite3ErrorMsg(pParse,
  89584. "table \"%s\" has more than one primary key", pTab->zName);
  89585. goto primary_key_exit;
  89586. }
  89587. pTab->tabFlags |= TF_HasPrimaryKey;
  89588. if( pList==0 ){
  89589. iCol = pTab->nCol - 1;
  89590. pCol = &pTab->aCol[iCol];
  89591. pCol->colFlags |= COLFLAG_PRIMKEY;
  89592. nTerm = 1;
  89593. }else{
  89594. nTerm = pList->nExpr;
  89595. for(i=0; i<nTerm; i++){
  89596. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  89597. assert( pCExpr!=0 );
  89598. sqlite3StringToId(pCExpr);
  89599. if( pCExpr->op==TK_ID ){
  89600. const char *zCName = pCExpr->u.zToken;
  89601. for(iCol=0; iCol<pTab->nCol; iCol++){
  89602. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  89603. pCol = &pTab->aCol[iCol];
  89604. pCol->colFlags |= COLFLAG_PRIMKEY;
  89605. break;
  89606. }
  89607. }
  89608. }
  89609. }
  89610. }
  89611. if( nTerm==1
  89612. && pCol
  89613. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  89614. && sortOrder!=SQLITE_SO_DESC
  89615. ){
  89616. pTab->iPKey = iCol;
  89617. pTab->keyConf = (u8)onError;
  89618. assert( autoInc==0 || autoInc==1 );
  89619. pTab->tabFlags |= autoInc*TF_Autoincrement;
  89620. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  89621. }else if( autoInc ){
  89622. #ifndef SQLITE_OMIT_AUTOINCREMENT
  89623. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  89624. "INTEGER PRIMARY KEY");
  89625. #endif
  89626. }else{
  89627. Index *p;
  89628. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  89629. 0, sortOrder, 0);
  89630. if( p ){
  89631. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  89632. }
  89633. pList = 0;
  89634. }
  89635. primary_key_exit:
  89636. sqlite3ExprListDelete(pParse->db, pList);
  89637. return;
  89638. }
  89639. /*
  89640. ** Add a new CHECK constraint to the table currently under construction.
  89641. */
  89642. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  89643. Parse *pParse, /* Parsing context */
  89644. Expr *pCheckExpr /* The check expression */
  89645. ){
  89646. #ifndef SQLITE_OMIT_CHECK
  89647. Table *pTab = pParse->pNewTable;
  89648. sqlite3 *db = pParse->db;
  89649. if( pTab && !IN_DECLARE_VTAB
  89650. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  89651. ){
  89652. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  89653. if( pParse->constraintName.n ){
  89654. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  89655. }
  89656. }else
  89657. #endif
  89658. {
  89659. sqlite3ExprDelete(pParse->db, pCheckExpr);
  89660. }
  89661. }
  89662. /*
  89663. ** Set the collation function of the most recently parsed table column
  89664. ** to the CollSeq given.
  89665. */
  89666. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  89667. Table *p;
  89668. int i;
  89669. char *zColl; /* Dequoted name of collation sequence */
  89670. sqlite3 *db;
  89671. if( (p = pParse->pNewTable)==0 ) return;
  89672. i = p->nCol-1;
  89673. db = pParse->db;
  89674. zColl = sqlite3NameFromToken(db, pToken);
  89675. if( !zColl ) return;
  89676. if( sqlite3LocateCollSeq(pParse, zColl) ){
  89677. Index *pIdx;
  89678. sqlite3DbFree(db, p->aCol[i].zColl);
  89679. p->aCol[i].zColl = zColl;
  89680. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  89681. ** then an index may have been created on this column before the
  89682. ** collation type was added. Correct this if it is the case.
  89683. */
  89684. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  89685. assert( pIdx->nKeyCol==1 );
  89686. if( pIdx->aiColumn[0]==i ){
  89687. pIdx->azColl[0] = p->aCol[i].zColl;
  89688. }
  89689. }
  89690. }else{
  89691. sqlite3DbFree(db, zColl);
  89692. }
  89693. }
  89694. /*
  89695. ** This function returns the collation sequence for database native text
  89696. ** encoding identified by the string zName, length nName.
  89697. **
  89698. ** If the requested collation sequence is not available, or not available
  89699. ** in the database native encoding, the collation factory is invoked to
  89700. ** request it. If the collation factory does not supply such a sequence,
  89701. ** and the sequence is available in another text encoding, then that is
  89702. ** returned instead.
  89703. **
  89704. ** If no versions of the requested collations sequence are available, or
  89705. ** another error occurs, NULL is returned and an error message written into
  89706. ** pParse.
  89707. **
  89708. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  89709. ** invokes the collation factory if the named collation cannot be found
  89710. ** and generates an error message.
  89711. **
  89712. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  89713. */
  89714. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  89715. sqlite3 *db = pParse->db;
  89716. u8 enc = ENC(db);
  89717. u8 initbusy = db->init.busy;
  89718. CollSeq *pColl;
  89719. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  89720. if( !initbusy && (!pColl || !pColl->xCmp) ){
  89721. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  89722. }
  89723. return pColl;
  89724. }
  89725. /*
  89726. ** Generate code that will increment the schema cookie.
  89727. **
  89728. ** The schema cookie is used to determine when the schema for the
  89729. ** database changes. After each schema change, the cookie value
  89730. ** changes. When a process first reads the schema it records the
  89731. ** cookie. Thereafter, whenever it goes to access the database,
  89732. ** it checks the cookie to make sure the schema has not changed
  89733. ** since it was last read.
  89734. **
  89735. ** This plan is not completely bullet-proof. It is possible for
  89736. ** the schema to change multiple times and for the cookie to be
  89737. ** set back to prior value. But schema changes are infrequent
  89738. ** and the probability of hitting the same cookie value is only
  89739. ** 1 chance in 2^32. So we're safe enough.
  89740. */
  89741. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  89742. sqlite3 *db = pParse->db;
  89743. Vdbe *v = pParse->pVdbe;
  89744. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89745. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  89746. db->aDb[iDb].pSchema->schema_cookie+1);
  89747. }
  89748. /*
  89749. ** Measure the number of characters needed to output the given
  89750. ** identifier. The number returned includes any quotes used
  89751. ** but does not include the null terminator.
  89752. **
  89753. ** The estimate is conservative. It might be larger that what is
  89754. ** really needed.
  89755. */
  89756. static int identLength(const char *z){
  89757. int n;
  89758. for(n=0; *z; n++, z++){
  89759. if( *z=='"' ){ n++; }
  89760. }
  89761. return n + 2;
  89762. }
  89763. /*
  89764. ** The first parameter is a pointer to an output buffer. The second
  89765. ** parameter is a pointer to an integer that contains the offset at
  89766. ** which to write into the output buffer. This function copies the
  89767. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  89768. ** to the specified offset in the buffer and updates *pIdx to refer
  89769. ** to the first byte after the last byte written before returning.
  89770. **
  89771. ** If the string zSignedIdent consists entirely of alpha-numeric
  89772. ** characters, does not begin with a digit and is not an SQL keyword,
  89773. ** then it is copied to the output buffer exactly as it is. Otherwise,
  89774. ** it is quoted using double-quotes.
  89775. */
  89776. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  89777. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  89778. int i, j, needQuote;
  89779. i = *pIdx;
  89780. for(j=0; zIdent[j]; j++){
  89781. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  89782. }
  89783. needQuote = sqlite3Isdigit(zIdent[0])
  89784. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  89785. || zIdent[j]!=0
  89786. || j==0;
  89787. if( needQuote ) z[i++] = '"';
  89788. for(j=0; zIdent[j]; j++){
  89789. z[i++] = zIdent[j];
  89790. if( zIdent[j]=='"' ) z[i++] = '"';
  89791. }
  89792. if( needQuote ) z[i++] = '"';
  89793. z[i] = 0;
  89794. *pIdx = i;
  89795. }
  89796. /*
  89797. ** Generate a CREATE TABLE statement appropriate for the given
  89798. ** table. Memory to hold the text of the statement is obtained
  89799. ** from sqliteMalloc() and must be freed by the calling function.
  89800. */
  89801. static char *createTableStmt(sqlite3 *db, Table *p){
  89802. int i, k, n;
  89803. char *zStmt;
  89804. char *zSep, *zSep2, *zEnd;
  89805. Column *pCol;
  89806. n = 0;
  89807. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  89808. n += identLength(pCol->zName) + 5;
  89809. }
  89810. n += identLength(p->zName);
  89811. if( n<50 ){
  89812. zSep = "";
  89813. zSep2 = ",";
  89814. zEnd = ")";
  89815. }else{
  89816. zSep = "\n ";
  89817. zSep2 = ",\n ";
  89818. zEnd = "\n)";
  89819. }
  89820. n += 35 + 6*p->nCol;
  89821. zStmt = sqlite3DbMallocRaw(0, n);
  89822. if( zStmt==0 ){
  89823. sqlite3OomFault(db);
  89824. return 0;
  89825. }
  89826. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  89827. k = sqlite3Strlen30(zStmt);
  89828. identPut(zStmt, &k, p->zName);
  89829. zStmt[k++] = '(';
  89830. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  89831. static const char * const azType[] = {
  89832. /* SQLITE_AFF_BLOB */ "",
  89833. /* SQLITE_AFF_TEXT */ " TEXT",
  89834. /* SQLITE_AFF_NUMERIC */ " NUM",
  89835. /* SQLITE_AFF_INTEGER */ " INT",
  89836. /* SQLITE_AFF_REAL */ " REAL"
  89837. };
  89838. int len;
  89839. const char *zType;
  89840. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  89841. k += sqlite3Strlen30(&zStmt[k]);
  89842. zSep = zSep2;
  89843. identPut(zStmt, &k, pCol->zName);
  89844. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  89845. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  89846. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  89847. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  89848. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  89849. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  89850. testcase( pCol->affinity==SQLITE_AFF_REAL );
  89851. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  89852. len = sqlite3Strlen30(zType);
  89853. assert( pCol->affinity==SQLITE_AFF_BLOB
  89854. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  89855. memcpy(&zStmt[k], zType, len);
  89856. k += len;
  89857. assert( k<=n );
  89858. }
  89859. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  89860. return zStmt;
  89861. }
  89862. /*
  89863. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  89864. ** on success and SQLITE_NOMEM on an OOM error.
  89865. */
  89866. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  89867. char *zExtra;
  89868. int nByte;
  89869. if( pIdx->nColumn>=N ) return SQLITE_OK;
  89870. assert( pIdx->isResized==0 );
  89871. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  89872. zExtra = sqlite3DbMallocZero(db, nByte);
  89873. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  89874. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  89875. pIdx->azColl = (const char**)zExtra;
  89876. zExtra += sizeof(char*)*N;
  89877. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  89878. pIdx->aiColumn = (i16*)zExtra;
  89879. zExtra += sizeof(i16)*N;
  89880. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  89881. pIdx->aSortOrder = (u8*)zExtra;
  89882. pIdx->nColumn = N;
  89883. pIdx->isResized = 1;
  89884. return SQLITE_OK;
  89885. }
  89886. /*
  89887. ** Estimate the total row width for a table.
  89888. */
  89889. static void estimateTableWidth(Table *pTab){
  89890. unsigned wTable = 0;
  89891. const Column *pTabCol;
  89892. int i;
  89893. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  89894. wTable += pTabCol->szEst;
  89895. }
  89896. if( pTab->iPKey<0 ) wTable++;
  89897. pTab->szTabRow = sqlite3LogEst(wTable*4);
  89898. }
  89899. /*
  89900. ** Estimate the average size of a row for an index.
  89901. */
  89902. static void estimateIndexWidth(Index *pIdx){
  89903. unsigned wIndex = 0;
  89904. int i;
  89905. const Column *aCol = pIdx->pTable->aCol;
  89906. for(i=0; i<pIdx->nColumn; i++){
  89907. i16 x = pIdx->aiColumn[i];
  89908. assert( x<pIdx->pTable->nCol );
  89909. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  89910. }
  89911. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  89912. }
  89913. /* Return true if value x is found any of the first nCol entries of aiCol[]
  89914. */
  89915. static int hasColumn(const i16 *aiCol, int nCol, int x){
  89916. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  89917. return 0;
  89918. }
  89919. /*
  89920. ** This routine runs at the end of parsing a CREATE TABLE statement that
  89921. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  89922. ** internal schema data structures and the generated VDBE code so that they
  89923. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  89924. ** Changes include:
  89925. **
  89926. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  89927. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  89928. ** data storage is a covering index btree.
  89929. ** (2) Bypass the creation of the sqlite_master table entry
  89930. ** for the PRIMARY KEY as the primary key index is now
  89931. ** identified by the sqlite_master table entry of the table itself.
  89932. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  89933. ** schema to the rootpage from the main table.
  89934. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  89935. ** (5) Add all table columns to the PRIMARY KEY Index object
  89936. ** so that the PRIMARY KEY is a covering index. The surplus
  89937. ** columns are part of KeyInfo.nXField and are not used for
  89938. ** sorting or lookup or uniqueness checks.
  89939. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  89940. ** indices with the PRIMARY KEY columns.
  89941. */
  89942. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  89943. Index *pIdx;
  89944. Index *pPk;
  89945. int nPk;
  89946. int i, j;
  89947. sqlite3 *db = pParse->db;
  89948. Vdbe *v = pParse->pVdbe;
  89949. /* Convert the OP_CreateTable opcode that would normally create the
  89950. ** root-page for the table into an OP_CreateIndex opcode. The index
  89951. ** created will become the PRIMARY KEY index.
  89952. */
  89953. if( pParse->addrCrTab ){
  89954. assert( v );
  89955. sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
  89956. }
  89957. /* Locate the PRIMARY KEY index. Or, if this table was originally
  89958. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  89959. */
  89960. if( pTab->iPKey>=0 ){
  89961. ExprList *pList;
  89962. Token ipkToken;
  89963. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  89964. pList = sqlite3ExprListAppend(pParse, 0,
  89965. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  89966. if( pList==0 ) return;
  89967. pList->a[0].sortOrder = pParse->iPkSortOrder;
  89968. assert( pParse->pNewTable==pTab );
  89969. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  89970. if( pPk==0 ) return;
  89971. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  89972. pTab->iPKey = -1;
  89973. }else{
  89974. pPk = sqlite3PrimaryKeyIndex(pTab);
  89975. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  89976. ** table entry. This is only required if currently generating VDBE
  89977. ** code for a CREATE TABLE (not when parsing one as part of reading
  89978. ** a database schema). */
  89979. if( v ){
  89980. assert( db->init.busy==0 );
  89981. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  89982. }
  89983. /*
  89984. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  89985. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  89986. ** code assumes the PRIMARY KEY contains no repeated columns.
  89987. */
  89988. for(i=j=1; i<pPk->nKeyCol; i++){
  89989. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  89990. pPk->nColumn--;
  89991. }else{
  89992. pPk->aiColumn[j++] = pPk->aiColumn[i];
  89993. }
  89994. }
  89995. pPk->nKeyCol = j;
  89996. }
  89997. pPk->isCovering = 1;
  89998. assert( pPk!=0 );
  89999. nPk = pPk->nKeyCol;
  90000. /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
  90001. ** do not enforce this for imposter tables.) */
  90002. if( !db->init.imposterTable ){
  90003. for(i=0; i<nPk; i++){
  90004. pTab->aCol[pPk->aiColumn[i]].notNull = OE_Abort;
  90005. }
  90006. pPk->uniqNotNull = 1;
  90007. }
  90008. /* The root page of the PRIMARY KEY is the table root page */
  90009. pPk->tnum = pTab->tnum;
  90010. /* Update the in-memory representation of all UNIQUE indices by converting
  90011. ** the final rowid column into one or more columns of the PRIMARY KEY.
  90012. */
  90013. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90014. int n;
  90015. if( IsPrimaryKeyIndex(pIdx) ) continue;
  90016. for(i=n=0; i<nPk; i++){
  90017. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  90018. }
  90019. if( n==0 ){
  90020. /* This index is a superset of the primary key */
  90021. pIdx->nColumn = pIdx->nKeyCol;
  90022. continue;
  90023. }
  90024. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  90025. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  90026. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  90027. pIdx->aiColumn[j] = pPk->aiColumn[i];
  90028. pIdx->azColl[j] = pPk->azColl[i];
  90029. j++;
  90030. }
  90031. }
  90032. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  90033. assert( pIdx->nColumn>=j );
  90034. }
  90035. /* Add all table columns to the PRIMARY KEY index
  90036. */
  90037. if( nPk<pTab->nCol ){
  90038. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  90039. for(i=0, j=nPk; i<pTab->nCol; i++){
  90040. if( !hasColumn(pPk->aiColumn, j, i) ){
  90041. assert( j<pPk->nColumn );
  90042. pPk->aiColumn[j] = i;
  90043. pPk->azColl[j] = sqlite3StrBINARY;
  90044. j++;
  90045. }
  90046. }
  90047. assert( pPk->nColumn==j );
  90048. assert( pTab->nCol==j );
  90049. }else{
  90050. pPk->nColumn = pTab->nCol;
  90051. }
  90052. }
  90053. /*
  90054. ** This routine is called to report the final ")" that terminates
  90055. ** a CREATE TABLE statement.
  90056. **
  90057. ** The table structure that other action routines have been building
  90058. ** is added to the internal hash tables, assuming no errors have
  90059. ** occurred.
  90060. **
  90061. ** An entry for the table is made in the master table on disk, unless
  90062. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  90063. ** it means we are reading the sqlite_master table because we just
  90064. ** connected to the database or because the sqlite_master table has
  90065. ** recently changed, so the entry for this table already exists in
  90066. ** the sqlite_master table. We do not want to create it again.
  90067. **
  90068. ** If the pSelect argument is not NULL, it means that this routine
  90069. ** was called to create a table generated from a
  90070. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  90071. ** the new table will match the result set of the SELECT.
  90072. */
  90073. SQLITE_PRIVATE void sqlite3EndTable(
  90074. Parse *pParse, /* Parse context */
  90075. Token *pCons, /* The ',' token after the last column defn. */
  90076. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  90077. u8 tabOpts, /* Extra table options. Usually 0. */
  90078. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  90079. ){
  90080. Table *p; /* The new table */
  90081. sqlite3 *db = pParse->db; /* The database connection */
  90082. int iDb; /* Database in which the table lives */
  90083. Index *pIdx; /* An implied index of the table */
  90084. if( pEnd==0 && pSelect==0 ){
  90085. return;
  90086. }
  90087. assert( !db->mallocFailed );
  90088. p = pParse->pNewTable;
  90089. if( p==0 ) return;
  90090. assert( !db->init.busy || !pSelect );
  90091. /* If the db->init.busy is 1 it means we are reading the SQL off the
  90092. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  90093. ** So do not write to the disk again. Extract the root page number
  90094. ** for the table from the db->init.newTnum field. (The page number
  90095. ** should have been put there by the sqliteOpenCb routine.)
  90096. **
  90097. ** If the root page number is 1, that means this is the sqlite_master
  90098. ** table itself. So mark it read-only.
  90099. */
  90100. if( db->init.busy ){
  90101. p->tnum = db->init.newTnum;
  90102. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  90103. }
  90104. /* Special processing for WITHOUT ROWID Tables */
  90105. if( tabOpts & TF_WithoutRowid ){
  90106. if( (p->tabFlags & TF_Autoincrement) ){
  90107. sqlite3ErrorMsg(pParse,
  90108. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  90109. return;
  90110. }
  90111. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  90112. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  90113. }else{
  90114. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  90115. convertToWithoutRowidTable(pParse, p);
  90116. }
  90117. }
  90118. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  90119. #ifndef SQLITE_OMIT_CHECK
  90120. /* Resolve names in all CHECK constraint expressions.
  90121. */
  90122. if( p->pCheck ){
  90123. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  90124. }
  90125. #endif /* !defined(SQLITE_OMIT_CHECK) */
  90126. /* Estimate the average row size for the table and for all implied indices */
  90127. estimateTableWidth(p);
  90128. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  90129. estimateIndexWidth(pIdx);
  90130. }
  90131. /* If not initializing, then create a record for the new table
  90132. ** in the SQLITE_MASTER table of the database.
  90133. **
  90134. ** If this is a TEMPORARY table, write the entry into the auxiliary
  90135. ** file instead of into the main database file.
  90136. */
  90137. if( !db->init.busy ){
  90138. int n;
  90139. Vdbe *v;
  90140. char *zType; /* "view" or "table" */
  90141. char *zType2; /* "VIEW" or "TABLE" */
  90142. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  90143. v = sqlite3GetVdbe(pParse);
  90144. if( NEVER(v==0) ) return;
  90145. sqlite3VdbeAddOp1(v, OP_Close, 0);
  90146. /*
  90147. ** Initialize zType for the new view or table.
  90148. */
  90149. if( p->pSelect==0 ){
  90150. /* A regular table */
  90151. zType = "table";
  90152. zType2 = "TABLE";
  90153. #ifndef SQLITE_OMIT_VIEW
  90154. }else{
  90155. /* A view */
  90156. zType = "view";
  90157. zType2 = "VIEW";
  90158. #endif
  90159. }
  90160. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  90161. ** statement to populate the new table. The root-page number for the
  90162. ** new table is in register pParse->regRoot.
  90163. **
  90164. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  90165. ** suitable state to query for the column names and types to be used
  90166. ** by the new table.
  90167. **
  90168. ** A shared-cache write-lock is not required to write to the new table,
  90169. ** as a schema-lock must have already been obtained to create it. Since
  90170. ** a schema-lock excludes all other database users, the write-lock would
  90171. ** be redundant.
  90172. */
  90173. if( pSelect ){
  90174. SelectDest dest; /* Where the SELECT should store results */
  90175. int regYield; /* Register holding co-routine entry-point */
  90176. int addrTop; /* Top of the co-routine */
  90177. int regRec; /* A record to be insert into the new table */
  90178. int regRowid; /* Rowid of the next row to insert */
  90179. int addrInsLoop; /* Top of the loop for inserting rows */
  90180. Table *pSelTab; /* A table that describes the SELECT results */
  90181. regYield = ++pParse->nMem;
  90182. regRec = ++pParse->nMem;
  90183. regRowid = ++pParse->nMem;
  90184. assert(pParse->nTab==1);
  90185. sqlite3MayAbort(pParse);
  90186. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  90187. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  90188. pParse->nTab = 2;
  90189. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  90190. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  90191. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  90192. sqlite3Select(pParse, pSelect, &dest);
  90193. sqlite3VdbeEndCoroutine(v, regYield);
  90194. sqlite3VdbeJumpHere(v, addrTop - 1);
  90195. if( pParse->nErr ) return;
  90196. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  90197. if( pSelTab==0 ) return;
  90198. assert( p->aCol==0 );
  90199. p->nCol = pSelTab->nCol;
  90200. p->aCol = pSelTab->aCol;
  90201. pSelTab->nCol = 0;
  90202. pSelTab->aCol = 0;
  90203. sqlite3DeleteTable(db, pSelTab);
  90204. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  90205. VdbeCoverage(v);
  90206. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  90207. sqlite3TableAffinity(v, p, 0);
  90208. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  90209. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  90210. sqlite3VdbeGoto(v, addrInsLoop);
  90211. sqlite3VdbeJumpHere(v, addrInsLoop);
  90212. sqlite3VdbeAddOp1(v, OP_Close, 1);
  90213. }
  90214. /* Compute the complete text of the CREATE statement */
  90215. if( pSelect ){
  90216. zStmt = createTableStmt(db, p);
  90217. }else{
  90218. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  90219. n = (int)(pEnd2->z - pParse->sNameToken.z);
  90220. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  90221. zStmt = sqlite3MPrintf(db,
  90222. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  90223. );
  90224. }
  90225. /* A slot for the record has already been allocated in the
  90226. ** SQLITE_MASTER table. We just need to update that slot with all
  90227. ** the information we've collected.
  90228. */
  90229. sqlite3NestedParse(pParse,
  90230. "UPDATE %Q.%s "
  90231. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  90232. "WHERE rowid=#%d",
  90233. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  90234. zType,
  90235. p->zName,
  90236. p->zName,
  90237. pParse->regRoot,
  90238. zStmt,
  90239. pParse->regRowid
  90240. );
  90241. sqlite3DbFree(db, zStmt);
  90242. sqlite3ChangeCookie(pParse, iDb);
  90243. #ifndef SQLITE_OMIT_AUTOINCREMENT
  90244. /* Check to see if we need to create an sqlite_sequence table for
  90245. ** keeping track of autoincrement keys.
  90246. */
  90247. if( p->tabFlags & TF_Autoincrement ){
  90248. Db *pDb = &db->aDb[iDb];
  90249. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90250. if( pDb->pSchema->pSeqTab==0 ){
  90251. sqlite3NestedParse(pParse,
  90252. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  90253. pDb->zName
  90254. );
  90255. }
  90256. }
  90257. #endif
  90258. /* Reparse everything to update our internal data structures */
  90259. sqlite3VdbeAddParseSchemaOp(v, iDb,
  90260. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  90261. }
  90262. /* Add the table to the in-memory representation of the database.
  90263. */
  90264. if( db->init.busy ){
  90265. Table *pOld;
  90266. Schema *pSchema = p->pSchema;
  90267. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90268. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  90269. if( pOld ){
  90270. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  90271. sqlite3OomFault(db);
  90272. return;
  90273. }
  90274. pParse->pNewTable = 0;
  90275. db->flags |= SQLITE_InternChanges;
  90276. #ifndef SQLITE_OMIT_ALTERTABLE
  90277. if( !p->pSelect ){
  90278. const char *zName = (const char *)pParse->sNameToken.z;
  90279. int nName;
  90280. assert( !pSelect && pCons && pEnd );
  90281. if( pCons->z==0 ){
  90282. pCons = pEnd;
  90283. }
  90284. nName = (int)((const char *)pCons->z - zName);
  90285. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  90286. }
  90287. #endif
  90288. }
  90289. }
  90290. #ifndef SQLITE_OMIT_VIEW
  90291. /*
  90292. ** The parser calls this routine in order to create a new VIEW
  90293. */
  90294. SQLITE_PRIVATE void sqlite3CreateView(
  90295. Parse *pParse, /* The parsing context */
  90296. Token *pBegin, /* The CREATE token that begins the statement */
  90297. Token *pName1, /* The token that holds the name of the view */
  90298. Token *pName2, /* The token that holds the name of the view */
  90299. ExprList *pCNames, /* Optional list of view column names */
  90300. Select *pSelect, /* A SELECT statement that will become the new view */
  90301. int isTemp, /* TRUE for a TEMPORARY view */
  90302. int noErr /* Suppress error messages if VIEW already exists */
  90303. ){
  90304. Table *p;
  90305. int n;
  90306. const char *z;
  90307. Token sEnd;
  90308. DbFixer sFix;
  90309. Token *pName = 0;
  90310. int iDb;
  90311. sqlite3 *db = pParse->db;
  90312. if( pParse->nVar>0 ){
  90313. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  90314. goto create_view_fail;
  90315. }
  90316. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  90317. p = pParse->pNewTable;
  90318. if( p==0 || pParse->nErr ) goto create_view_fail;
  90319. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  90320. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  90321. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  90322. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  90323. /* Make a copy of the entire SELECT statement that defines the view.
  90324. ** This will force all the Expr.token.z values to be dynamically
  90325. ** allocated rather than point to the input string - which means that
  90326. ** they will persist after the current sqlite3_exec() call returns.
  90327. */
  90328. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  90329. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  90330. if( db->mallocFailed ) goto create_view_fail;
  90331. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  90332. ** the end.
  90333. */
  90334. sEnd = pParse->sLastToken;
  90335. assert( sEnd.z[0]!=0 );
  90336. if( sEnd.z[0]!=';' ){
  90337. sEnd.z += sEnd.n;
  90338. }
  90339. sEnd.n = 0;
  90340. n = (int)(sEnd.z - pBegin->z);
  90341. assert( n>0 );
  90342. z = pBegin->z;
  90343. while( sqlite3Isspace(z[n-1]) ){ n--; }
  90344. sEnd.z = &z[n-1];
  90345. sEnd.n = 1;
  90346. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  90347. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  90348. create_view_fail:
  90349. sqlite3SelectDelete(db, pSelect);
  90350. sqlite3ExprListDelete(db, pCNames);
  90351. return;
  90352. }
  90353. #endif /* SQLITE_OMIT_VIEW */
  90354. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  90355. /*
  90356. ** The Table structure pTable is really a VIEW. Fill in the names of
  90357. ** the columns of the view in the pTable structure. Return the number
  90358. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  90359. */
  90360. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  90361. Table *pSelTab; /* A fake table from which we get the result set */
  90362. Select *pSel; /* Copy of the SELECT that implements the view */
  90363. int nErr = 0; /* Number of errors encountered */
  90364. int n; /* Temporarily holds the number of cursors assigned */
  90365. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  90366. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  90367. assert( pTable );
  90368. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90369. if( sqlite3VtabCallConnect(pParse, pTable) ){
  90370. return SQLITE_ERROR;
  90371. }
  90372. if( IsVirtual(pTable) ) return 0;
  90373. #endif
  90374. #ifndef SQLITE_OMIT_VIEW
  90375. /* A positive nCol means the columns names for this view are
  90376. ** already known.
  90377. */
  90378. if( pTable->nCol>0 ) return 0;
  90379. /* A negative nCol is a special marker meaning that we are currently
  90380. ** trying to compute the column names. If we enter this routine with
  90381. ** a negative nCol, it means two or more views form a loop, like this:
  90382. **
  90383. ** CREATE VIEW one AS SELECT * FROM two;
  90384. ** CREATE VIEW two AS SELECT * FROM one;
  90385. **
  90386. ** Actually, the error above is now caught prior to reaching this point.
  90387. ** But the following test is still important as it does come up
  90388. ** in the following:
  90389. **
  90390. ** CREATE TABLE main.ex1(a);
  90391. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  90392. ** SELECT * FROM temp.ex1;
  90393. */
  90394. if( pTable->nCol<0 ){
  90395. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  90396. return 1;
  90397. }
  90398. assert( pTable->nCol>=0 );
  90399. /* If we get this far, it means we need to compute the table names.
  90400. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  90401. ** "*" elements in the results set of the view and will assign cursors
  90402. ** to the elements of the FROM clause. But we do not want these changes
  90403. ** to be permanent. So the computation is done on a copy of the SELECT
  90404. ** statement that defines the view.
  90405. */
  90406. assert( pTable->pSelect );
  90407. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  90408. if( pSel ){
  90409. n = pParse->nTab;
  90410. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  90411. pTable->nCol = -1;
  90412. db->lookaside.bDisable++;
  90413. #ifndef SQLITE_OMIT_AUTHORIZATION
  90414. xAuth = db->xAuth;
  90415. db->xAuth = 0;
  90416. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  90417. db->xAuth = xAuth;
  90418. #else
  90419. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  90420. #endif
  90421. pParse->nTab = n;
  90422. if( pTable->pCheck ){
  90423. /* CREATE VIEW name(arglist) AS ...
  90424. ** The names of the columns in the table are taken from
  90425. ** arglist which is stored in pTable->pCheck. The pCheck field
  90426. ** normally holds CHECK constraints on an ordinary table, but for
  90427. ** a VIEW it holds the list of column names.
  90428. */
  90429. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  90430. &pTable->nCol, &pTable->aCol);
  90431. if( db->mallocFailed==0
  90432. && pParse->nErr==0
  90433. && pTable->nCol==pSel->pEList->nExpr
  90434. ){
  90435. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  90436. }
  90437. }else if( pSelTab ){
  90438. /* CREATE VIEW name AS... without an argument list. Construct
  90439. ** the column names from the SELECT statement that defines the view.
  90440. */
  90441. assert( pTable->aCol==0 );
  90442. pTable->nCol = pSelTab->nCol;
  90443. pTable->aCol = pSelTab->aCol;
  90444. pSelTab->nCol = 0;
  90445. pSelTab->aCol = 0;
  90446. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  90447. }else{
  90448. pTable->nCol = 0;
  90449. nErr++;
  90450. }
  90451. if( pSelTab ) sqlite3DeleteTable(db, pSelTab);
  90452. sqlite3SelectDelete(db, pSel);
  90453. db->lookaside.bDisable--;
  90454. } else {
  90455. nErr++;
  90456. }
  90457. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  90458. #endif /* SQLITE_OMIT_VIEW */
  90459. return nErr;
  90460. }
  90461. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  90462. #ifndef SQLITE_OMIT_VIEW
  90463. /*
  90464. ** Clear the column names from every VIEW in database idx.
  90465. */
  90466. static void sqliteViewResetAll(sqlite3 *db, int idx){
  90467. HashElem *i;
  90468. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  90469. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  90470. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  90471. Table *pTab = sqliteHashData(i);
  90472. if( pTab->pSelect ){
  90473. sqlite3DeleteColumnNames(db, pTab);
  90474. pTab->aCol = 0;
  90475. pTab->nCol = 0;
  90476. }
  90477. }
  90478. DbClearProperty(db, idx, DB_UnresetViews);
  90479. }
  90480. #else
  90481. # define sqliteViewResetAll(A,B)
  90482. #endif /* SQLITE_OMIT_VIEW */
  90483. /*
  90484. ** This function is called by the VDBE to adjust the internal schema
  90485. ** used by SQLite when the btree layer moves a table root page. The
  90486. ** root-page of a table or index in database iDb has changed from iFrom
  90487. ** to iTo.
  90488. **
  90489. ** Ticket #1728: The symbol table might still contain information
  90490. ** on tables and/or indices that are the process of being deleted.
  90491. ** If you are unlucky, one of those deleted indices or tables might
  90492. ** have the same rootpage number as the real table or index that is
  90493. ** being moved. So we cannot stop searching after the first match
  90494. ** because the first match might be for one of the deleted indices
  90495. ** or tables and not the table/index that is actually being moved.
  90496. ** We must continue looping until all tables and indices with
  90497. ** rootpage==iFrom have been converted to have a rootpage of iTo
  90498. ** in order to be certain that we got the right one.
  90499. */
  90500. #ifndef SQLITE_OMIT_AUTOVACUUM
  90501. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  90502. HashElem *pElem;
  90503. Hash *pHash;
  90504. Db *pDb;
  90505. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90506. pDb = &db->aDb[iDb];
  90507. pHash = &pDb->pSchema->tblHash;
  90508. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  90509. Table *pTab = sqliteHashData(pElem);
  90510. if( pTab->tnum==iFrom ){
  90511. pTab->tnum = iTo;
  90512. }
  90513. }
  90514. pHash = &pDb->pSchema->idxHash;
  90515. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  90516. Index *pIdx = sqliteHashData(pElem);
  90517. if( pIdx->tnum==iFrom ){
  90518. pIdx->tnum = iTo;
  90519. }
  90520. }
  90521. }
  90522. #endif
  90523. /*
  90524. ** Write code to erase the table with root-page iTable from database iDb.
  90525. ** Also write code to modify the sqlite_master table and internal schema
  90526. ** if a root-page of another table is moved by the btree-layer whilst
  90527. ** erasing iTable (this can happen with an auto-vacuum database).
  90528. */
  90529. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  90530. Vdbe *v = sqlite3GetVdbe(pParse);
  90531. int r1 = sqlite3GetTempReg(pParse);
  90532. assert( iTable>1 );
  90533. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  90534. sqlite3MayAbort(pParse);
  90535. #ifndef SQLITE_OMIT_AUTOVACUUM
  90536. /* OP_Destroy stores an in integer r1. If this integer
  90537. ** is non-zero, then it is the root page number of a table moved to
  90538. ** location iTable. The following code modifies the sqlite_master table to
  90539. ** reflect this.
  90540. **
  90541. ** The "#NNN" in the SQL is a special constant that means whatever value
  90542. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  90543. ** token for additional information.
  90544. */
  90545. sqlite3NestedParse(pParse,
  90546. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  90547. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  90548. #endif
  90549. sqlite3ReleaseTempReg(pParse, r1);
  90550. }
  90551. /*
  90552. ** Write VDBE code to erase table pTab and all associated indices on disk.
  90553. ** Code to update the sqlite_master tables and internal schema definitions
  90554. ** in case a root-page belonging to another table is moved by the btree layer
  90555. ** is also added (this can happen with an auto-vacuum database).
  90556. */
  90557. static void destroyTable(Parse *pParse, Table *pTab){
  90558. #ifdef SQLITE_OMIT_AUTOVACUUM
  90559. Index *pIdx;
  90560. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90561. destroyRootPage(pParse, pTab->tnum, iDb);
  90562. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90563. destroyRootPage(pParse, pIdx->tnum, iDb);
  90564. }
  90565. #else
  90566. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  90567. ** is not defined), then it is important to call OP_Destroy on the
  90568. ** table and index root-pages in order, starting with the numerically
  90569. ** largest root-page number. This guarantees that none of the root-pages
  90570. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  90571. ** following were coded:
  90572. **
  90573. ** OP_Destroy 4 0
  90574. ** ...
  90575. ** OP_Destroy 5 0
  90576. **
  90577. ** and root page 5 happened to be the largest root-page number in the
  90578. ** database, then root page 5 would be moved to page 4 by the
  90579. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  90580. ** a free-list page.
  90581. */
  90582. int iTab = pTab->tnum;
  90583. int iDestroyed = 0;
  90584. while( 1 ){
  90585. Index *pIdx;
  90586. int iLargest = 0;
  90587. if( iDestroyed==0 || iTab<iDestroyed ){
  90588. iLargest = iTab;
  90589. }
  90590. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90591. int iIdx = pIdx->tnum;
  90592. assert( pIdx->pSchema==pTab->pSchema );
  90593. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  90594. iLargest = iIdx;
  90595. }
  90596. }
  90597. if( iLargest==0 ){
  90598. return;
  90599. }else{
  90600. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90601. assert( iDb>=0 && iDb<pParse->db->nDb );
  90602. destroyRootPage(pParse, iLargest, iDb);
  90603. iDestroyed = iLargest;
  90604. }
  90605. }
  90606. #endif
  90607. }
  90608. /*
  90609. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  90610. ** after a DROP INDEX or DROP TABLE command.
  90611. */
  90612. static void sqlite3ClearStatTables(
  90613. Parse *pParse, /* The parsing context */
  90614. int iDb, /* The database number */
  90615. const char *zType, /* "idx" or "tbl" */
  90616. const char *zName /* Name of index or table */
  90617. ){
  90618. int i;
  90619. const char *zDbName = pParse->db->aDb[iDb].zName;
  90620. for(i=1; i<=4; i++){
  90621. char zTab[24];
  90622. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  90623. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  90624. sqlite3NestedParse(pParse,
  90625. "DELETE FROM %Q.%s WHERE %s=%Q",
  90626. zDbName, zTab, zType, zName
  90627. );
  90628. }
  90629. }
  90630. }
  90631. /*
  90632. ** Generate code to drop a table.
  90633. */
  90634. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  90635. Vdbe *v;
  90636. sqlite3 *db = pParse->db;
  90637. Trigger *pTrigger;
  90638. Db *pDb = &db->aDb[iDb];
  90639. v = sqlite3GetVdbe(pParse);
  90640. assert( v!=0 );
  90641. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90642. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90643. if( IsVirtual(pTab) ){
  90644. sqlite3VdbeAddOp0(v, OP_VBegin);
  90645. }
  90646. #endif
  90647. /* Drop all triggers associated with the table being dropped. Code
  90648. ** is generated to remove entries from sqlite_master and/or
  90649. ** sqlite_temp_master if required.
  90650. */
  90651. pTrigger = sqlite3TriggerList(pParse, pTab);
  90652. while( pTrigger ){
  90653. assert( pTrigger->pSchema==pTab->pSchema ||
  90654. pTrigger->pSchema==db->aDb[1].pSchema );
  90655. sqlite3DropTriggerPtr(pParse, pTrigger);
  90656. pTrigger = pTrigger->pNext;
  90657. }
  90658. #ifndef SQLITE_OMIT_AUTOINCREMENT
  90659. /* Remove any entries of the sqlite_sequence table associated with
  90660. ** the table being dropped. This is done before the table is dropped
  90661. ** at the btree level, in case the sqlite_sequence table needs to
  90662. ** move as a result of the drop (can happen in auto-vacuum mode).
  90663. */
  90664. if( pTab->tabFlags & TF_Autoincrement ){
  90665. sqlite3NestedParse(pParse,
  90666. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  90667. pDb->zName, pTab->zName
  90668. );
  90669. }
  90670. #endif
  90671. /* Drop all SQLITE_MASTER table and index entries that refer to the
  90672. ** table. The program name loops through the master table and deletes
  90673. ** every row that refers to a table of the same name as the one being
  90674. ** dropped. Triggers are handled separately because a trigger can be
  90675. ** created in the temp database that refers to a table in another
  90676. ** database.
  90677. */
  90678. sqlite3NestedParse(pParse,
  90679. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  90680. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  90681. if( !isView && !IsVirtual(pTab) ){
  90682. destroyTable(pParse, pTab);
  90683. }
  90684. /* Remove the table entry from SQLite's internal schema and modify
  90685. ** the schema cookie.
  90686. */
  90687. if( IsVirtual(pTab) ){
  90688. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  90689. }
  90690. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  90691. sqlite3ChangeCookie(pParse, iDb);
  90692. sqliteViewResetAll(db, iDb);
  90693. }
  90694. /*
  90695. ** This routine is called to do the work of a DROP TABLE statement.
  90696. ** pName is the name of the table to be dropped.
  90697. */
  90698. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  90699. Table *pTab;
  90700. Vdbe *v;
  90701. sqlite3 *db = pParse->db;
  90702. int iDb;
  90703. if( db->mallocFailed ){
  90704. goto exit_drop_table;
  90705. }
  90706. assert( pParse->nErr==0 );
  90707. assert( pName->nSrc==1 );
  90708. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  90709. if( noErr ) db->suppressErr++;
  90710. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  90711. if( noErr ) db->suppressErr--;
  90712. if( pTab==0 ){
  90713. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  90714. goto exit_drop_table;
  90715. }
  90716. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90717. assert( iDb>=0 && iDb<db->nDb );
  90718. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  90719. ** it is initialized.
  90720. */
  90721. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  90722. goto exit_drop_table;
  90723. }
  90724. #ifndef SQLITE_OMIT_AUTHORIZATION
  90725. {
  90726. int code;
  90727. const char *zTab = SCHEMA_TABLE(iDb);
  90728. const char *zDb = db->aDb[iDb].zName;
  90729. const char *zArg2 = 0;
  90730. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  90731. goto exit_drop_table;
  90732. }
  90733. if( isView ){
  90734. if( !OMIT_TEMPDB && iDb==1 ){
  90735. code = SQLITE_DROP_TEMP_VIEW;
  90736. }else{
  90737. code = SQLITE_DROP_VIEW;
  90738. }
  90739. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90740. }else if( IsVirtual(pTab) ){
  90741. code = SQLITE_DROP_VTABLE;
  90742. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  90743. #endif
  90744. }else{
  90745. if( !OMIT_TEMPDB && iDb==1 ){
  90746. code = SQLITE_DROP_TEMP_TABLE;
  90747. }else{
  90748. code = SQLITE_DROP_TABLE;
  90749. }
  90750. }
  90751. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  90752. goto exit_drop_table;
  90753. }
  90754. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  90755. goto exit_drop_table;
  90756. }
  90757. }
  90758. #endif
  90759. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  90760. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  90761. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  90762. goto exit_drop_table;
  90763. }
  90764. #ifndef SQLITE_OMIT_VIEW
  90765. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  90766. ** on a table.
  90767. */
  90768. if( isView && pTab->pSelect==0 ){
  90769. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  90770. goto exit_drop_table;
  90771. }
  90772. if( !isView && pTab->pSelect ){
  90773. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  90774. goto exit_drop_table;
  90775. }
  90776. #endif
  90777. /* Generate code to remove the table from the master table
  90778. ** on disk.
  90779. */
  90780. v = sqlite3GetVdbe(pParse);
  90781. if( v ){
  90782. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90783. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  90784. sqlite3FkDropTable(pParse, pName, pTab);
  90785. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  90786. }
  90787. exit_drop_table:
  90788. sqlite3SrcListDelete(db, pName);
  90789. }
  90790. /*
  90791. ** This routine is called to create a new foreign key on the table
  90792. ** currently under construction. pFromCol determines which columns
  90793. ** in the current table point to the foreign key. If pFromCol==0 then
  90794. ** connect the key to the last column inserted. pTo is the name of
  90795. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  90796. ** of tables in the parent pTo table. flags contains all
  90797. ** information about the conflict resolution algorithms specified
  90798. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  90799. **
  90800. ** An FKey structure is created and added to the table currently
  90801. ** under construction in the pParse->pNewTable field.
  90802. **
  90803. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  90804. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  90805. */
  90806. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  90807. Parse *pParse, /* Parsing context */
  90808. ExprList *pFromCol, /* Columns in this table that point to other table */
  90809. Token *pTo, /* Name of the other table */
  90810. ExprList *pToCol, /* Columns in the other table */
  90811. int flags /* Conflict resolution algorithms. */
  90812. ){
  90813. sqlite3 *db = pParse->db;
  90814. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90815. FKey *pFKey = 0;
  90816. FKey *pNextTo;
  90817. Table *p = pParse->pNewTable;
  90818. int nByte;
  90819. int i;
  90820. int nCol;
  90821. char *z;
  90822. assert( pTo!=0 );
  90823. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  90824. if( pFromCol==0 ){
  90825. int iCol = p->nCol-1;
  90826. if( NEVER(iCol<0) ) goto fk_end;
  90827. if( pToCol && pToCol->nExpr!=1 ){
  90828. sqlite3ErrorMsg(pParse, "foreign key on %s"
  90829. " should reference only one column of table %T",
  90830. p->aCol[iCol].zName, pTo);
  90831. goto fk_end;
  90832. }
  90833. nCol = 1;
  90834. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  90835. sqlite3ErrorMsg(pParse,
  90836. "number of columns in foreign key does not match the number of "
  90837. "columns in the referenced table");
  90838. goto fk_end;
  90839. }else{
  90840. nCol = pFromCol->nExpr;
  90841. }
  90842. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  90843. if( pToCol ){
  90844. for(i=0; i<pToCol->nExpr; i++){
  90845. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  90846. }
  90847. }
  90848. pFKey = sqlite3DbMallocZero(db, nByte );
  90849. if( pFKey==0 ){
  90850. goto fk_end;
  90851. }
  90852. pFKey->pFrom = p;
  90853. pFKey->pNextFrom = p->pFKey;
  90854. z = (char*)&pFKey->aCol[nCol];
  90855. pFKey->zTo = z;
  90856. memcpy(z, pTo->z, pTo->n);
  90857. z[pTo->n] = 0;
  90858. sqlite3Dequote(z);
  90859. z += pTo->n+1;
  90860. pFKey->nCol = nCol;
  90861. if( pFromCol==0 ){
  90862. pFKey->aCol[0].iFrom = p->nCol-1;
  90863. }else{
  90864. for(i=0; i<nCol; i++){
  90865. int j;
  90866. for(j=0; j<p->nCol; j++){
  90867. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  90868. pFKey->aCol[i].iFrom = j;
  90869. break;
  90870. }
  90871. }
  90872. if( j>=p->nCol ){
  90873. sqlite3ErrorMsg(pParse,
  90874. "unknown column \"%s\" in foreign key definition",
  90875. pFromCol->a[i].zName);
  90876. goto fk_end;
  90877. }
  90878. }
  90879. }
  90880. if( pToCol ){
  90881. for(i=0; i<nCol; i++){
  90882. int n = sqlite3Strlen30(pToCol->a[i].zName);
  90883. pFKey->aCol[i].zCol = z;
  90884. memcpy(z, pToCol->a[i].zName, n);
  90885. z[n] = 0;
  90886. z += n+1;
  90887. }
  90888. }
  90889. pFKey->isDeferred = 0;
  90890. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  90891. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  90892. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  90893. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  90894. pFKey->zTo, (void *)pFKey
  90895. );
  90896. if( pNextTo==pFKey ){
  90897. sqlite3OomFault(db);
  90898. goto fk_end;
  90899. }
  90900. if( pNextTo ){
  90901. assert( pNextTo->pPrevTo==0 );
  90902. pFKey->pNextTo = pNextTo;
  90903. pNextTo->pPrevTo = pFKey;
  90904. }
  90905. /* Link the foreign key to the table as the last step.
  90906. */
  90907. p->pFKey = pFKey;
  90908. pFKey = 0;
  90909. fk_end:
  90910. sqlite3DbFree(db, pFKey);
  90911. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  90912. sqlite3ExprListDelete(db, pFromCol);
  90913. sqlite3ExprListDelete(db, pToCol);
  90914. }
  90915. /*
  90916. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  90917. ** clause is seen as part of a foreign key definition. The isDeferred
  90918. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  90919. ** The behavior of the most recently created foreign key is adjusted
  90920. ** accordingly.
  90921. */
  90922. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  90923. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90924. Table *pTab;
  90925. FKey *pFKey;
  90926. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  90927. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  90928. pFKey->isDeferred = (u8)isDeferred;
  90929. #endif
  90930. }
  90931. /*
  90932. ** Generate code that will erase and refill index *pIdx. This is
  90933. ** used to initialize a newly created index or to recompute the
  90934. ** content of an index in response to a REINDEX command.
  90935. **
  90936. ** if memRootPage is not negative, it means that the index is newly
  90937. ** created. The register specified by memRootPage contains the
  90938. ** root page number of the index. If memRootPage is negative, then
  90939. ** the index already exists and must be cleared before being refilled and
  90940. ** the root page number of the index is taken from pIndex->tnum.
  90941. */
  90942. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  90943. Table *pTab = pIndex->pTable; /* The table that is indexed */
  90944. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  90945. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  90946. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  90947. int addr1; /* Address of top of loop */
  90948. int addr2; /* Address to jump to for next iteration */
  90949. int tnum; /* Root page of index */
  90950. int iPartIdxLabel; /* Jump to this label to skip a row */
  90951. Vdbe *v; /* Generate code into this virtual machine */
  90952. KeyInfo *pKey; /* KeyInfo for index */
  90953. int regRecord; /* Register holding assembled index record */
  90954. sqlite3 *db = pParse->db; /* The database connection */
  90955. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  90956. #ifndef SQLITE_OMIT_AUTHORIZATION
  90957. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  90958. db->aDb[iDb].zName ) ){
  90959. return;
  90960. }
  90961. #endif
  90962. /* Require a write-lock on the table to perform this operation */
  90963. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  90964. v = sqlite3GetVdbe(pParse);
  90965. if( v==0 ) return;
  90966. if( memRootPage>=0 ){
  90967. tnum = memRootPage;
  90968. }else{
  90969. tnum = pIndex->tnum;
  90970. }
  90971. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  90972. /* Open the sorter cursor if we are to use one. */
  90973. iSorter = pParse->nTab++;
  90974. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  90975. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  90976. /* Open the table. Loop through all rows of the table, inserting index
  90977. ** records into the sorter. */
  90978. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  90979. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  90980. regRecord = sqlite3GetTempReg(pParse);
  90981. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  90982. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  90983. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  90984. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  90985. sqlite3VdbeJumpHere(v, addr1);
  90986. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  90987. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  90988. (char *)pKey, P4_KEYINFO);
  90989. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  90990. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  90991. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  90992. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  90993. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  90994. sqlite3VdbeGoto(v, j2);
  90995. addr2 = sqlite3VdbeCurrentAddr(v);
  90996. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  90997. pIndex->nKeyCol); VdbeCoverage(v);
  90998. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  90999. }else{
  91000. addr2 = sqlite3VdbeCurrentAddr(v);
  91001. }
  91002. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  91003. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  91004. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
  91005. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  91006. sqlite3ReleaseTempReg(pParse, regRecord);
  91007. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  91008. sqlite3VdbeJumpHere(v, addr1);
  91009. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  91010. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  91011. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  91012. }
  91013. /*
  91014. ** Allocate heap space to hold an Index object with nCol columns.
  91015. **
  91016. ** Increase the allocation size to provide an extra nExtra bytes
  91017. ** of 8-byte aligned space after the Index object and return a
  91018. ** pointer to this extra space in *ppExtra.
  91019. */
  91020. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  91021. sqlite3 *db, /* Database connection */
  91022. i16 nCol, /* Total number of columns in the index */
  91023. int nExtra, /* Number of bytes of extra space to alloc */
  91024. char **ppExtra /* Pointer to the "extra" space */
  91025. ){
  91026. Index *p; /* Allocated index object */
  91027. int nByte; /* Bytes of space for Index object + arrays */
  91028. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  91029. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  91030. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  91031. sizeof(i16)*nCol + /* Index.aiColumn */
  91032. sizeof(u8)*nCol); /* Index.aSortOrder */
  91033. p = sqlite3DbMallocZero(db, nByte + nExtra);
  91034. if( p ){
  91035. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  91036. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  91037. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  91038. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  91039. p->aSortOrder = (u8*)pExtra;
  91040. p->nColumn = nCol;
  91041. p->nKeyCol = nCol - 1;
  91042. *ppExtra = ((char*)p) + nByte;
  91043. }
  91044. return p;
  91045. }
  91046. /*
  91047. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  91048. ** and pTblList is the name of the table that is to be indexed. Both will
  91049. ** be NULL for a primary key or an index that is created to satisfy a
  91050. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  91051. ** as the table to be indexed. pParse->pNewTable is a table that is
  91052. ** currently being constructed by a CREATE TABLE statement.
  91053. **
  91054. ** pList is a list of columns to be indexed. pList will be NULL if this
  91055. ** is a primary key or unique-constraint on the most recent column added
  91056. ** to the table currently under construction.
  91057. **
  91058. ** If the index is created successfully, return a pointer to the new Index
  91059. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  91060. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  91061. */
  91062. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  91063. Parse *pParse, /* All information about this parse */
  91064. Token *pName1, /* First part of index name. May be NULL */
  91065. Token *pName2, /* Second part of index name. May be NULL */
  91066. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  91067. ExprList *pList, /* A list of columns to be indexed */
  91068. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  91069. Token *pStart, /* The CREATE token that begins this statement */
  91070. Expr *pPIWhere, /* WHERE clause for partial indices */
  91071. int sortOrder, /* Sort order of primary key when pList==NULL */
  91072. int ifNotExist /* Omit error if index already exists */
  91073. ){
  91074. Index *pRet = 0; /* Pointer to return */
  91075. Table *pTab = 0; /* Table to be indexed */
  91076. Index *pIndex = 0; /* The index to be created */
  91077. char *zName = 0; /* Name of the index */
  91078. int nName; /* Number of characters in zName */
  91079. int i, j;
  91080. DbFixer sFix; /* For assigning database names to pTable */
  91081. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  91082. sqlite3 *db = pParse->db;
  91083. Db *pDb; /* The specific table containing the indexed database */
  91084. int iDb; /* Index of the database that is being written */
  91085. Token *pName = 0; /* Unqualified name of the index to create */
  91086. struct ExprList_item *pListItem; /* For looping over pList */
  91087. int nExtra = 0; /* Space allocated for zExtra[] */
  91088. int nExtraCol; /* Number of extra columns needed */
  91089. char *zExtra = 0; /* Extra space after the Index object */
  91090. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  91091. if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
  91092. goto exit_create_index;
  91093. }
  91094. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  91095. goto exit_create_index;
  91096. }
  91097. /*
  91098. ** Find the table that is to be indexed. Return early if not found.
  91099. */
  91100. if( pTblName!=0 ){
  91101. /* Use the two-part index name to determine the database
  91102. ** to search for the table. 'Fix' the table name to this db
  91103. ** before looking up the table.
  91104. */
  91105. assert( pName1 && pName2 );
  91106. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  91107. if( iDb<0 ) goto exit_create_index;
  91108. assert( pName && pName->z );
  91109. #ifndef SQLITE_OMIT_TEMPDB
  91110. /* If the index name was unqualified, check if the table
  91111. ** is a temp table. If so, set the database to 1. Do not do this
  91112. ** if initialising a database schema.
  91113. */
  91114. if( !db->init.busy ){
  91115. pTab = sqlite3SrcListLookup(pParse, pTblName);
  91116. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  91117. iDb = 1;
  91118. }
  91119. }
  91120. #endif
  91121. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  91122. if( sqlite3FixSrcList(&sFix, pTblName) ){
  91123. /* Because the parser constructs pTblName from a single identifier,
  91124. ** sqlite3FixSrcList can never fail. */
  91125. assert(0);
  91126. }
  91127. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  91128. assert( db->mallocFailed==0 || pTab==0 );
  91129. if( pTab==0 ) goto exit_create_index;
  91130. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  91131. sqlite3ErrorMsg(pParse,
  91132. "cannot create a TEMP index on non-TEMP table \"%s\"",
  91133. pTab->zName);
  91134. goto exit_create_index;
  91135. }
  91136. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  91137. }else{
  91138. assert( pName==0 );
  91139. assert( pStart==0 );
  91140. pTab = pParse->pNewTable;
  91141. if( !pTab ) goto exit_create_index;
  91142. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91143. }
  91144. pDb = &db->aDb[iDb];
  91145. assert( pTab!=0 );
  91146. assert( pParse->nErr==0 );
  91147. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  91148. && db->init.busy==0
  91149. #if SQLITE_USER_AUTHENTICATION
  91150. && sqlite3UserAuthTable(pTab->zName)==0
  91151. #endif
  91152. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  91153. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  91154. goto exit_create_index;
  91155. }
  91156. #ifndef SQLITE_OMIT_VIEW
  91157. if( pTab->pSelect ){
  91158. sqlite3ErrorMsg(pParse, "views may not be indexed");
  91159. goto exit_create_index;
  91160. }
  91161. #endif
  91162. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91163. if( IsVirtual(pTab) ){
  91164. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  91165. goto exit_create_index;
  91166. }
  91167. #endif
  91168. /*
  91169. ** Find the name of the index. Make sure there is not already another
  91170. ** index or table with the same name.
  91171. **
  91172. ** Exception: If we are reading the names of permanent indices from the
  91173. ** sqlite_master table (because some other process changed the schema) and
  91174. ** one of the index names collides with the name of a temporary table or
  91175. ** index, then we will continue to process this index.
  91176. **
  91177. ** If pName==0 it means that we are
  91178. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  91179. ** own name.
  91180. */
  91181. if( pName ){
  91182. zName = sqlite3NameFromToken(db, pName);
  91183. if( zName==0 ) goto exit_create_index;
  91184. assert( pName->z!=0 );
  91185. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  91186. goto exit_create_index;
  91187. }
  91188. if( !db->init.busy ){
  91189. if( sqlite3FindTable(db, zName, 0)!=0 ){
  91190. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  91191. goto exit_create_index;
  91192. }
  91193. }
  91194. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  91195. if( !ifNotExist ){
  91196. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  91197. }else{
  91198. assert( !db->init.busy );
  91199. sqlite3CodeVerifySchema(pParse, iDb);
  91200. }
  91201. goto exit_create_index;
  91202. }
  91203. }else{
  91204. int n;
  91205. Index *pLoop;
  91206. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  91207. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  91208. if( zName==0 ){
  91209. goto exit_create_index;
  91210. }
  91211. }
  91212. /* Check for authorization to create an index.
  91213. */
  91214. #ifndef SQLITE_OMIT_AUTHORIZATION
  91215. {
  91216. const char *zDb = pDb->zName;
  91217. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  91218. goto exit_create_index;
  91219. }
  91220. i = SQLITE_CREATE_INDEX;
  91221. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  91222. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  91223. goto exit_create_index;
  91224. }
  91225. }
  91226. #endif
  91227. /* If pList==0, it means this routine was called to make a primary
  91228. ** key out of the last column added to the table under construction.
  91229. ** So create a fake list to simulate this.
  91230. */
  91231. if( pList==0 ){
  91232. Token prevCol;
  91233. sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
  91234. pList = sqlite3ExprListAppend(pParse, 0,
  91235. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  91236. if( pList==0 ) goto exit_create_index;
  91237. assert( pList->nExpr==1 );
  91238. sqlite3ExprListSetSortOrder(pList, sortOrder);
  91239. }else{
  91240. sqlite3ExprListCheckLength(pParse, pList, "index");
  91241. }
  91242. /* Figure out how many bytes of space are required to store explicitly
  91243. ** specified collation sequence names.
  91244. */
  91245. for(i=0; i<pList->nExpr; i++){
  91246. Expr *pExpr = pList->a[i].pExpr;
  91247. assert( pExpr!=0 );
  91248. if( pExpr->op==TK_COLLATE ){
  91249. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  91250. }
  91251. }
  91252. /*
  91253. ** Allocate the index structure.
  91254. */
  91255. nName = sqlite3Strlen30(zName);
  91256. nExtraCol = pPk ? pPk->nKeyCol : 1;
  91257. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  91258. nName + nExtra + 1, &zExtra);
  91259. if( db->mallocFailed ){
  91260. goto exit_create_index;
  91261. }
  91262. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  91263. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  91264. pIndex->zName = zExtra;
  91265. zExtra += nName + 1;
  91266. memcpy(pIndex->zName, zName, nName+1);
  91267. pIndex->pTable = pTab;
  91268. pIndex->onError = (u8)onError;
  91269. pIndex->uniqNotNull = onError!=OE_None;
  91270. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  91271. pIndex->pSchema = db->aDb[iDb].pSchema;
  91272. pIndex->nKeyCol = pList->nExpr;
  91273. if( pPIWhere ){
  91274. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  91275. pIndex->pPartIdxWhere = pPIWhere;
  91276. pPIWhere = 0;
  91277. }
  91278. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  91279. /* Check to see if we should honor DESC requests on index columns
  91280. */
  91281. if( pDb->pSchema->file_format>=4 ){
  91282. sortOrderMask = -1; /* Honor DESC */
  91283. }else{
  91284. sortOrderMask = 0; /* Ignore DESC */
  91285. }
  91286. /* Analyze the list of expressions that form the terms of the index and
  91287. ** report any errors. In the common case where the expression is exactly
  91288. ** a table column, store that column in aiColumn[]. For general expressions,
  91289. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  91290. **
  91291. ** TODO: Issue a warning if two or more columns of the index are identical.
  91292. ** TODO: Issue a warning if the table primary key is used as part of the
  91293. ** index key.
  91294. */
  91295. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  91296. Expr *pCExpr; /* The i-th index expression */
  91297. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  91298. const char *zColl; /* Collation sequence name */
  91299. sqlite3StringToId(pListItem->pExpr);
  91300. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  91301. if( pParse->nErr ) goto exit_create_index;
  91302. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  91303. if( pCExpr->op!=TK_COLUMN ){
  91304. if( pTab==pParse->pNewTable ){
  91305. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  91306. "UNIQUE constraints");
  91307. goto exit_create_index;
  91308. }
  91309. if( pIndex->aColExpr==0 ){
  91310. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  91311. pIndex->aColExpr = pCopy;
  91312. if( !db->mallocFailed ){
  91313. assert( pCopy!=0 );
  91314. pListItem = &pCopy->a[i];
  91315. }
  91316. }
  91317. j = XN_EXPR;
  91318. pIndex->aiColumn[i] = XN_EXPR;
  91319. pIndex->uniqNotNull = 0;
  91320. }else{
  91321. j = pCExpr->iColumn;
  91322. assert( j<=0x7fff );
  91323. if( j<0 ){
  91324. j = pTab->iPKey;
  91325. }else if( pTab->aCol[j].notNull==0 ){
  91326. pIndex->uniqNotNull = 0;
  91327. }
  91328. pIndex->aiColumn[i] = (i16)j;
  91329. }
  91330. zColl = 0;
  91331. if( pListItem->pExpr->op==TK_COLLATE ){
  91332. int nColl;
  91333. zColl = pListItem->pExpr->u.zToken;
  91334. nColl = sqlite3Strlen30(zColl) + 1;
  91335. assert( nExtra>=nColl );
  91336. memcpy(zExtra, zColl, nColl);
  91337. zColl = zExtra;
  91338. zExtra += nColl;
  91339. nExtra -= nColl;
  91340. }else if( j>=0 ){
  91341. zColl = pTab->aCol[j].zColl;
  91342. }
  91343. if( !zColl ) zColl = sqlite3StrBINARY;
  91344. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  91345. goto exit_create_index;
  91346. }
  91347. pIndex->azColl[i] = zColl;
  91348. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  91349. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  91350. }
  91351. /* Append the table key to the end of the index. For WITHOUT ROWID
  91352. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  91353. ** normal tables (when pPk==0) this will be the rowid.
  91354. */
  91355. if( pPk ){
  91356. for(j=0; j<pPk->nKeyCol; j++){
  91357. int x = pPk->aiColumn[j];
  91358. assert( x>=0 );
  91359. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  91360. pIndex->nColumn--;
  91361. }else{
  91362. pIndex->aiColumn[i] = x;
  91363. pIndex->azColl[i] = pPk->azColl[j];
  91364. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  91365. i++;
  91366. }
  91367. }
  91368. assert( i==pIndex->nColumn );
  91369. }else{
  91370. pIndex->aiColumn[i] = XN_ROWID;
  91371. pIndex->azColl[i] = sqlite3StrBINARY;
  91372. }
  91373. sqlite3DefaultRowEst(pIndex);
  91374. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  91375. /* If this index contains every column of its table, then mark
  91376. ** it as a covering index */
  91377. assert( HasRowid(pTab)
  91378. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  91379. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  91380. pIndex->isCovering = 1;
  91381. for(j=0; j<pTab->nCol; j++){
  91382. if( j==pTab->iPKey ) continue;
  91383. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  91384. pIndex->isCovering = 0;
  91385. break;
  91386. }
  91387. }
  91388. if( pTab==pParse->pNewTable ){
  91389. /* This routine has been called to create an automatic index as a
  91390. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  91391. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  91392. ** i.e. one of:
  91393. **
  91394. ** CREATE TABLE t(x PRIMARY KEY, y);
  91395. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  91396. **
  91397. ** Either way, check to see if the table already has such an index. If
  91398. ** so, don't bother creating this one. This only applies to
  91399. ** automatically created indices. Users can do as they wish with
  91400. ** explicit indices.
  91401. **
  91402. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  91403. ** (and thus suppressing the second one) even if they have different
  91404. ** sort orders.
  91405. **
  91406. ** If there are different collating sequences or if the columns of
  91407. ** the constraint occur in different orders, then the constraints are
  91408. ** considered distinct and both result in separate indices.
  91409. */
  91410. Index *pIdx;
  91411. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  91412. int k;
  91413. assert( IsUniqueIndex(pIdx) );
  91414. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  91415. assert( IsUniqueIndex(pIndex) );
  91416. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  91417. for(k=0; k<pIdx->nKeyCol; k++){
  91418. const char *z1;
  91419. const char *z2;
  91420. assert( pIdx->aiColumn[k]>=0 );
  91421. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  91422. z1 = pIdx->azColl[k];
  91423. z2 = pIndex->azColl[k];
  91424. if( sqlite3StrICmp(z1, z2) ) break;
  91425. }
  91426. if( k==pIdx->nKeyCol ){
  91427. if( pIdx->onError!=pIndex->onError ){
  91428. /* This constraint creates the same index as a previous
  91429. ** constraint specified somewhere in the CREATE TABLE statement.
  91430. ** However the ON CONFLICT clauses are different. If both this
  91431. ** constraint and the previous equivalent constraint have explicit
  91432. ** ON CONFLICT clauses this is an error. Otherwise, use the
  91433. ** explicitly specified behavior for the index.
  91434. */
  91435. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  91436. sqlite3ErrorMsg(pParse,
  91437. "conflicting ON CONFLICT clauses specified", 0);
  91438. }
  91439. if( pIdx->onError==OE_Default ){
  91440. pIdx->onError = pIndex->onError;
  91441. }
  91442. }
  91443. pRet = pIdx;
  91444. goto exit_create_index;
  91445. }
  91446. }
  91447. }
  91448. /* Link the new Index structure to its table and to the other
  91449. ** in-memory database structures.
  91450. */
  91451. assert( pParse->nErr==0 );
  91452. if( db->init.busy ){
  91453. Index *p;
  91454. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  91455. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  91456. pIndex->zName, pIndex);
  91457. if( p ){
  91458. assert( p==pIndex ); /* Malloc must have failed */
  91459. sqlite3OomFault(db);
  91460. goto exit_create_index;
  91461. }
  91462. db->flags |= SQLITE_InternChanges;
  91463. if( pTblName!=0 ){
  91464. pIndex->tnum = db->init.newTnum;
  91465. }
  91466. }
  91467. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  91468. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  91469. ** emit code to allocate the index rootpage on disk and make an entry for
  91470. ** the index in the sqlite_master table and populate the index with
  91471. ** content. But, do not do this if we are simply reading the sqlite_master
  91472. ** table to parse the schema, or if this index is the PRIMARY KEY index
  91473. ** of a WITHOUT ROWID table.
  91474. **
  91475. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  91476. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  91477. ** has just been created, it contains no data and the index initialization
  91478. ** step can be skipped.
  91479. */
  91480. else if( HasRowid(pTab) || pTblName!=0 ){
  91481. Vdbe *v;
  91482. char *zStmt;
  91483. int iMem = ++pParse->nMem;
  91484. v = sqlite3GetVdbe(pParse);
  91485. if( v==0 ) goto exit_create_index;
  91486. sqlite3BeginWriteOperation(pParse, 1, iDb);
  91487. /* Create the rootpage for the index using CreateIndex. But before
  91488. ** doing so, code a Noop instruction and store its address in
  91489. ** Index.tnum. This is required in case this index is actually a
  91490. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  91491. ** that case the convertToWithoutRowidTable() routine will replace
  91492. ** the Noop with a Goto to jump over the VDBE code generated below. */
  91493. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  91494. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  91495. /* Gather the complete text of the CREATE INDEX statement into
  91496. ** the zStmt variable
  91497. */
  91498. if( pStart ){
  91499. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  91500. if( pName->z[n-1]==';' ) n--;
  91501. /* A named index with an explicit CREATE INDEX statement */
  91502. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  91503. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  91504. }else{
  91505. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  91506. /* zStmt = sqlite3MPrintf(""); */
  91507. zStmt = 0;
  91508. }
  91509. /* Add an entry in sqlite_master for this index
  91510. */
  91511. sqlite3NestedParse(pParse,
  91512. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  91513. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  91514. pIndex->zName,
  91515. pTab->zName,
  91516. iMem,
  91517. zStmt
  91518. );
  91519. sqlite3DbFree(db, zStmt);
  91520. /* Fill the index with data and reparse the schema. Code an OP_Expire
  91521. ** to invalidate all pre-compiled statements.
  91522. */
  91523. if( pTblName ){
  91524. sqlite3RefillIndex(pParse, pIndex, iMem);
  91525. sqlite3ChangeCookie(pParse, iDb);
  91526. sqlite3VdbeAddParseSchemaOp(v, iDb,
  91527. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  91528. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  91529. }
  91530. sqlite3VdbeJumpHere(v, pIndex->tnum);
  91531. }
  91532. /* When adding an index to the list of indices for a table, make
  91533. ** sure all indices labeled OE_Replace come after all those labeled
  91534. ** OE_Ignore. This is necessary for the correct constraint check
  91535. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  91536. ** UPDATE and INSERT statements.
  91537. */
  91538. if( db->init.busy || pTblName==0 ){
  91539. if( onError!=OE_Replace || pTab->pIndex==0
  91540. || pTab->pIndex->onError==OE_Replace){
  91541. pIndex->pNext = pTab->pIndex;
  91542. pTab->pIndex = pIndex;
  91543. }else{
  91544. Index *pOther = pTab->pIndex;
  91545. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  91546. pOther = pOther->pNext;
  91547. }
  91548. pIndex->pNext = pOther->pNext;
  91549. pOther->pNext = pIndex;
  91550. }
  91551. pRet = pIndex;
  91552. pIndex = 0;
  91553. }
  91554. /* Clean up before exiting */
  91555. exit_create_index:
  91556. if( pIndex ) freeIndex(db, pIndex);
  91557. sqlite3ExprDelete(db, pPIWhere);
  91558. sqlite3ExprListDelete(db, pList);
  91559. sqlite3SrcListDelete(db, pTblName);
  91560. sqlite3DbFree(db, zName);
  91561. return pRet;
  91562. }
  91563. /*
  91564. ** Fill the Index.aiRowEst[] array with default information - information
  91565. ** to be used when we have not run the ANALYZE command.
  91566. **
  91567. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  91568. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  91569. ** number of rows in the table that match any particular value of the
  91570. ** first column of the index. aiRowEst[2] is an estimate of the number
  91571. ** of rows that match any particular combination of the first 2 columns
  91572. ** of the index. And so forth. It must always be the case that
  91573. *
  91574. ** aiRowEst[N]<=aiRowEst[N-1]
  91575. ** aiRowEst[N]>=1
  91576. **
  91577. ** Apart from that, we have little to go on besides intuition as to
  91578. ** how aiRowEst[] should be initialized. The numbers generated here
  91579. ** are based on typical values found in actual indices.
  91580. */
  91581. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  91582. /* 10, 9, 8, 7, 6 */
  91583. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  91584. LogEst *a = pIdx->aiRowLogEst;
  91585. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  91586. int i;
  91587. /* Set the first entry (number of rows in the index) to the estimated
  91588. ** number of rows in the table. Or 10, if the estimated number of rows
  91589. ** in the table is less than that. */
  91590. a[0] = pIdx->pTable->nRowLogEst;
  91591. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  91592. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  91593. ** 6 and each subsequent value (if any) is 5. */
  91594. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  91595. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  91596. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  91597. }
  91598. assert( 0==sqlite3LogEst(1) );
  91599. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  91600. }
  91601. /*
  91602. ** This routine will drop an existing named index. This routine
  91603. ** implements the DROP INDEX statement.
  91604. */
  91605. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  91606. Index *pIndex;
  91607. Vdbe *v;
  91608. sqlite3 *db = pParse->db;
  91609. int iDb;
  91610. assert( pParse->nErr==0 ); /* Never called with prior errors */
  91611. if( db->mallocFailed ){
  91612. goto exit_drop_index;
  91613. }
  91614. assert( pName->nSrc==1 );
  91615. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  91616. goto exit_drop_index;
  91617. }
  91618. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  91619. if( pIndex==0 ){
  91620. if( !ifExists ){
  91621. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  91622. }else{
  91623. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  91624. }
  91625. pParse->checkSchema = 1;
  91626. goto exit_drop_index;
  91627. }
  91628. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  91629. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  91630. "or PRIMARY KEY constraint cannot be dropped", 0);
  91631. goto exit_drop_index;
  91632. }
  91633. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  91634. #ifndef SQLITE_OMIT_AUTHORIZATION
  91635. {
  91636. int code = SQLITE_DROP_INDEX;
  91637. Table *pTab = pIndex->pTable;
  91638. const char *zDb = db->aDb[iDb].zName;
  91639. const char *zTab = SCHEMA_TABLE(iDb);
  91640. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  91641. goto exit_drop_index;
  91642. }
  91643. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  91644. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  91645. goto exit_drop_index;
  91646. }
  91647. }
  91648. #endif
  91649. /* Generate code to remove the index and from the master table */
  91650. v = sqlite3GetVdbe(pParse);
  91651. if( v ){
  91652. sqlite3BeginWriteOperation(pParse, 1, iDb);
  91653. sqlite3NestedParse(pParse,
  91654. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  91655. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  91656. );
  91657. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  91658. sqlite3ChangeCookie(pParse, iDb);
  91659. destroyRootPage(pParse, pIndex->tnum, iDb);
  91660. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  91661. }
  91662. exit_drop_index:
  91663. sqlite3SrcListDelete(db, pName);
  91664. }
  91665. /*
  91666. ** pArray is a pointer to an array of objects. Each object in the
  91667. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  91668. ** to extend the array so that there is space for a new object at the end.
  91669. **
  91670. ** When this function is called, *pnEntry contains the current size of
  91671. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  91672. ** in total).
  91673. **
  91674. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  91675. ** space allocated for the new object is zeroed, *pnEntry updated to
  91676. ** reflect the new size of the array and a pointer to the new allocation
  91677. ** returned. *pIdx is set to the index of the new array entry in this case.
  91678. **
  91679. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  91680. ** unchanged and a copy of pArray returned.
  91681. */
  91682. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  91683. sqlite3 *db, /* Connection to notify of malloc failures */
  91684. void *pArray, /* Array of objects. Might be reallocated */
  91685. int szEntry, /* Size of each object in the array */
  91686. int *pnEntry, /* Number of objects currently in use */
  91687. int *pIdx /* Write the index of a new slot here */
  91688. ){
  91689. char *z;
  91690. int n = *pnEntry;
  91691. if( (n & (n-1))==0 ){
  91692. int sz = (n==0) ? 1 : 2*n;
  91693. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  91694. if( pNew==0 ){
  91695. *pIdx = -1;
  91696. return pArray;
  91697. }
  91698. pArray = pNew;
  91699. }
  91700. z = (char*)pArray;
  91701. memset(&z[n * szEntry], 0, szEntry);
  91702. *pIdx = n;
  91703. ++*pnEntry;
  91704. return pArray;
  91705. }
  91706. /*
  91707. ** Append a new element to the given IdList. Create a new IdList if
  91708. ** need be.
  91709. **
  91710. ** A new IdList is returned, or NULL if malloc() fails.
  91711. */
  91712. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  91713. int i;
  91714. if( pList==0 ){
  91715. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  91716. if( pList==0 ) return 0;
  91717. }
  91718. pList->a = sqlite3ArrayAllocate(
  91719. db,
  91720. pList->a,
  91721. sizeof(pList->a[0]),
  91722. &pList->nId,
  91723. &i
  91724. );
  91725. if( i<0 ){
  91726. sqlite3IdListDelete(db, pList);
  91727. return 0;
  91728. }
  91729. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  91730. return pList;
  91731. }
  91732. /*
  91733. ** Delete an IdList.
  91734. */
  91735. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  91736. int i;
  91737. if( pList==0 ) return;
  91738. for(i=0; i<pList->nId; i++){
  91739. sqlite3DbFree(db, pList->a[i].zName);
  91740. }
  91741. sqlite3DbFree(db, pList->a);
  91742. sqlite3DbFree(db, pList);
  91743. }
  91744. /*
  91745. ** Return the index in pList of the identifier named zId. Return -1
  91746. ** if not found.
  91747. */
  91748. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  91749. int i;
  91750. if( pList==0 ) return -1;
  91751. for(i=0; i<pList->nId; i++){
  91752. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  91753. }
  91754. return -1;
  91755. }
  91756. /*
  91757. ** Expand the space allocated for the given SrcList object by
  91758. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  91759. ** New slots are zeroed.
  91760. **
  91761. ** For example, suppose a SrcList initially contains two entries: A,B.
  91762. ** To append 3 new entries onto the end, do this:
  91763. **
  91764. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  91765. **
  91766. ** After the call above it would contain: A, B, nil, nil, nil.
  91767. ** If the iStart argument had been 1 instead of 2, then the result
  91768. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  91769. ** the iStart value would be 0. The result then would
  91770. ** be: nil, nil, nil, A, B.
  91771. **
  91772. ** If a memory allocation fails the SrcList is unchanged. The
  91773. ** db->mallocFailed flag will be set to true.
  91774. */
  91775. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  91776. sqlite3 *db, /* Database connection to notify of OOM errors */
  91777. SrcList *pSrc, /* The SrcList to be enlarged */
  91778. int nExtra, /* Number of new slots to add to pSrc->a[] */
  91779. int iStart /* Index in pSrc->a[] of first new slot */
  91780. ){
  91781. int i;
  91782. /* Sanity checking on calling parameters */
  91783. assert( iStart>=0 );
  91784. assert( nExtra>=1 );
  91785. assert( pSrc!=0 );
  91786. assert( iStart<=pSrc->nSrc );
  91787. /* Allocate additional space if needed */
  91788. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  91789. SrcList *pNew;
  91790. int nAlloc = pSrc->nSrc+nExtra;
  91791. int nGot;
  91792. pNew = sqlite3DbRealloc(db, pSrc,
  91793. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  91794. if( pNew==0 ){
  91795. assert( db->mallocFailed );
  91796. return pSrc;
  91797. }
  91798. pSrc = pNew;
  91799. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  91800. pSrc->nAlloc = nGot;
  91801. }
  91802. /* Move existing slots that come after the newly inserted slots
  91803. ** out of the way */
  91804. for(i=pSrc->nSrc-1; i>=iStart; i--){
  91805. pSrc->a[i+nExtra] = pSrc->a[i];
  91806. }
  91807. pSrc->nSrc += nExtra;
  91808. /* Zero the newly allocated slots */
  91809. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  91810. for(i=iStart; i<iStart+nExtra; i++){
  91811. pSrc->a[i].iCursor = -1;
  91812. }
  91813. /* Return a pointer to the enlarged SrcList */
  91814. return pSrc;
  91815. }
  91816. /*
  91817. ** Append a new table name to the given SrcList. Create a new SrcList if
  91818. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  91819. **
  91820. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  91821. ** SrcList might be the same as the SrcList that was input or it might be
  91822. ** a new one. If an OOM error does occurs, then the prior value of pList
  91823. ** that is input to this routine is automatically freed.
  91824. **
  91825. ** If pDatabase is not null, it means that the table has an optional
  91826. ** database name prefix. Like this: "database.table". The pDatabase
  91827. ** points to the table name and the pTable points to the database name.
  91828. ** The SrcList.a[].zName field is filled with the table name which might
  91829. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  91830. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  91831. ** or with NULL if no database is specified.
  91832. **
  91833. ** In other words, if call like this:
  91834. **
  91835. ** sqlite3SrcListAppend(D,A,B,0);
  91836. **
  91837. ** Then B is a table name and the database name is unspecified. If called
  91838. ** like this:
  91839. **
  91840. ** sqlite3SrcListAppend(D,A,B,C);
  91841. **
  91842. ** Then C is the table name and B is the database name. If C is defined
  91843. ** then so is B. In other words, we never have a case where:
  91844. **
  91845. ** sqlite3SrcListAppend(D,A,0,C);
  91846. **
  91847. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  91848. ** before being added to the SrcList.
  91849. */
  91850. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  91851. sqlite3 *db, /* Connection to notify of malloc failures */
  91852. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  91853. Token *pTable, /* Table to append */
  91854. Token *pDatabase /* Database of the table */
  91855. ){
  91856. struct SrcList_item *pItem;
  91857. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  91858. assert( db!=0 );
  91859. if( pList==0 ){
  91860. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  91861. if( pList==0 ) return 0;
  91862. pList->nAlloc = 1;
  91863. pList->nSrc = 0;
  91864. }
  91865. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  91866. if( db->mallocFailed ){
  91867. sqlite3SrcListDelete(db, pList);
  91868. return 0;
  91869. }
  91870. pItem = &pList->a[pList->nSrc-1];
  91871. if( pDatabase && pDatabase->z==0 ){
  91872. pDatabase = 0;
  91873. }
  91874. if( pDatabase ){
  91875. Token *pTemp = pDatabase;
  91876. pDatabase = pTable;
  91877. pTable = pTemp;
  91878. }
  91879. pItem->zName = sqlite3NameFromToken(db, pTable);
  91880. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  91881. return pList;
  91882. }
  91883. /*
  91884. ** Assign VdbeCursor index numbers to all tables in a SrcList
  91885. */
  91886. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  91887. int i;
  91888. struct SrcList_item *pItem;
  91889. assert(pList || pParse->db->mallocFailed );
  91890. if( pList ){
  91891. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  91892. if( pItem->iCursor>=0 ) break;
  91893. pItem->iCursor = pParse->nTab++;
  91894. if( pItem->pSelect ){
  91895. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  91896. }
  91897. }
  91898. }
  91899. }
  91900. /*
  91901. ** Delete an entire SrcList including all its substructure.
  91902. */
  91903. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  91904. int i;
  91905. struct SrcList_item *pItem;
  91906. if( pList==0 ) return;
  91907. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  91908. sqlite3DbFree(db, pItem->zDatabase);
  91909. sqlite3DbFree(db, pItem->zName);
  91910. sqlite3DbFree(db, pItem->zAlias);
  91911. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  91912. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  91913. sqlite3DeleteTable(db, pItem->pTab);
  91914. sqlite3SelectDelete(db, pItem->pSelect);
  91915. sqlite3ExprDelete(db, pItem->pOn);
  91916. sqlite3IdListDelete(db, pItem->pUsing);
  91917. }
  91918. sqlite3DbFree(db, pList);
  91919. }
  91920. /*
  91921. ** This routine is called by the parser to add a new term to the
  91922. ** end of a growing FROM clause. The "p" parameter is the part of
  91923. ** the FROM clause that has already been constructed. "p" is NULL
  91924. ** if this is the first term of the FROM clause. pTable and pDatabase
  91925. ** are the name of the table and database named in the FROM clause term.
  91926. ** pDatabase is NULL if the database name qualifier is missing - the
  91927. ** usual case. If the term has an alias, then pAlias points to the
  91928. ** alias token. If the term is a subquery, then pSubquery is the
  91929. ** SELECT statement that the subquery encodes. The pTable and
  91930. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  91931. ** parameters are the content of the ON and USING clauses.
  91932. **
  91933. ** Return a new SrcList which encodes is the FROM with the new
  91934. ** term added.
  91935. */
  91936. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  91937. Parse *pParse, /* Parsing context */
  91938. SrcList *p, /* The left part of the FROM clause already seen */
  91939. Token *pTable, /* Name of the table to add to the FROM clause */
  91940. Token *pDatabase, /* Name of the database containing pTable */
  91941. Token *pAlias, /* The right-hand side of the AS subexpression */
  91942. Select *pSubquery, /* A subquery used in place of a table name */
  91943. Expr *pOn, /* The ON clause of a join */
  91944. IdList *pUsing /* The USING clause of a join */
  91945. ){
  91946. struct SrcList_item *pItem;
  91947. sqlite3 *db = pParse->db;
  91948. if( !p && (pOn || pUsing) ){
  91949. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  91950. (pOn ? "ON" : "USING")
  91951. );
  91952. goto append_from_error;
  91953. }
  91954. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  91955. if( p==0 || NEVER(p->nSrc==0) ){
  91956. goto append_from_error;
  91957. }
  91958. pItem = &p->a[p->nSrc-1];
  91959. assert( pAlias!=0 );
  91960. if( pAlias->n ){
  91961. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  91962. }
  91963. pItem->pSelect = pSubquery;
  91964. pItem->pOn = pOn;
  91965. pItem->pUsing = pUsing;
  91966. return p;
  91967. append_from_error:
  91968. assert( p==0 );
  91969. sqlite3ExprDelete(db, pOn);
  91970. sqlite3IdListDelete(db, pUsing);
  91971. sqlite3SelectDelete(db, pSubquery);
  91972. return 0;
  91973. }
  91974. /*
  91975. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  91976. ** element of the source-list passed as the second argument.
  91977. */
  91978. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  91979. assert( pIndexedBy!=0 );
  91980. if( p && ALWAYS(p->nSrc>0) ){
  91981. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  91982. assert( pItem->fg.notIndexed==0 );
  91983. assert( pItem->fg.isIndexedBy==0 );
  91984. assert( pItem->fg.isTabFunc==0 );
  91985. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  91986. /* A "NOT INDEXED" clause was supplied. See parse.y
  91987. ** construct "indexed_opt" for details. */
  91988. pItem->fg.notIndexed = 1;
  91989. }else{
  91990. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  91991. pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
  91992. }
  91993. }
  91994. }
  91995. /*
  91996. ** Add the list of function arguments to the SrcList entry for a
  91997. ** table-valued-function.
  91998. */
  91999. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  92000. if( p ){
  92001. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  92002. assert( pItem->fg.notIndexed==0 );
  92003. assert( pItem->fg.isIndexedBy==0 );
  92004. assert( pItem->fg.isTabFunc==0 );
  92005. pItem->u1.pFuncArg = pList;
  92006. pItem->fg.isTabFunc = 1;
  92007. }else{
  92008. sqlite3ExprListDelete(pParse->db, pList);
  92009. }
  92010. }
  92011. /*
  92012. ** When building up a FROM clause in the parser, the join operator
  92013. ** is initially attached to the left operand. But the code generator
  92014. ** expects the join operator to be on the right operand. This routine
  92015. ** Shifts all join operators from left to right for an entire FROM
  92016. ** clause.
  92017. **
  92018. ** Example: Suppose the join is like this:
  92019. **
  92020. ** A natural cross join B
  92021. **
  92022. ** The operator is "natural cross join". The A and B operands are stored
  92023. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  92024. ** operator with A. This routine shifts that operator over to B.
  92025. */
  92026. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  92027. if( p ){
  92028. int i;
  92029. for(i=p->nSrc-1; i>0; i--){
  92030. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  92031. }
  92032. p->a[0].fg.jointype = 0;
  92033. }
  92034. }
  92035. /*
  92036. ** Generate VDBE code for a BEGIN statement.
  92037. */
  92038. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  92039. sqlite3 *db;
  92040. Vdbe *v;
  92041. int i;
  92042. assert( pParse!=0 );
  92043. db = pParse->db;
  92044. assert( db!=0 );
  92045. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  92046. return;
  92047. }
  92048. v = sqlite3GetVdbe(pParse);
  92049. if( !v ) return;
  92050. if( type!=TK_DEFERRED ){
  92051. for(i=0; i<db->nDb; i++){
  92052. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  92053. sqlite3VdbeUsesBtree(v, i);
  92054. }
  92055. }
  92056. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  92057. }
  92058. /*
  92059. ** Generate VDBE code for a COMMIT statement.
  92060. */
  92061. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  92062. Vdbe *v;
  92063. assert( pParse!=0 );
  92064. assert( pParse->db!=0 );
  92065. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  92066. return;
  92067. }
  92068. v = sqlite3GetVdbe(pParse);
  92069. if( v ){
  92070. sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
  92071. }
  92072. }
  92073. /*
  92074. ** Generate VDBE code for a ROLLBACK statement.
  92075. */
  92076. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  92077. Vdbe *v;
  92078. assert( pParse!=0 );
  92079. assert( pParse->db!=0 );
  92080. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  92081. return;
  92082. }
  92083. v = sqlite3GetVdbe(pParse);
  92084. if( v ){
  92085. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  92086. }
  92087. }
  92088. /*
  92089. ** This function is called by the parser when it parses a command to create,
  92090. ** release or rollback an SQL savepoint.
  92091. */
  92092. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  92093. char *zName = sqlite3NameFromToken(pParse->db, pName);
  92094. if( zName ){
  92095. Vdbe *v = sqlite3GetVdbe(pParse);
  92096. #ifndef SQLITE_OMIT_AUTHORIZATION
  92097. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  92098. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  92099. #endif
  92100. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  92101. sqlite3DbFree(pParse->db, zName);
  92102. return;
  92103. }
  92104. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  92105. }
  92106. }
  92107. /*
  92108. ** Make sure the TEMP database is open and available for use. Return
  92109. ** the number of errors. Leave any error messages in the pParse structure.
  92110. */
  92111. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  92112. sqlite3 *db = pParse->db;
  92113. if( db->aDb[1].pBt==0 && !pParse->explain ){
  92114. int rc;
  92115. Btree *pBt;
  92116. static const int flags =
  92117. SQLITE_OPEN_READWRITE |
  92118. SQLITE_OPEN_CREATE |
  92119. SQLITE_OPEN_EXCLUSIVE |
  92120. SQLITE_OPEN_DELETEONCLOSE |
  92121. SQLITE_OPEN_TEMP_DB;
  92122. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  92123. if( rc!=SQLITE_OK ){
  92124. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  92125. "file for storing temporary tables");
  92126. pParse->rc = rc;
  92127. return 1;
  92128. }
  92129. db->aDb[1].pBt = pBt;
  92130. assert( db->aDb[1].pSchema );
  92131. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  92132. sqlite3OomFault(db);
  92133. return 1;
  92134. }
  92135. }
  92136. return 0;
  92137. }
  92138. /*
  92139. ** Record the fact that the schema cookie will need to be verified
  92140. ** for database iDb. The code to actually verify the schema cookie
  92141. ** will occur at the end of the top-level VDBE and will be generated
  92142. ** later, by sqlite3FinishCoding().
  92143. */
  92144. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  92145. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  92146. sqlite3 *db = pToplevel->db;
  92147. assert( iDb>=0 && iDb<db->nDb );
  92148. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  92149. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  92150. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92151. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  92152. DbMaskSet(pToplevel->cookieMask, iDb);
  92153. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  92154. if( !OMIT_TEMPDB && iDb==1 ){
  92155. sqlite3OpenTempDatabase(pToplevel);
  92156. }
  92157. }
  92158. }
  92159. /*
  92160. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  92161. ** attached database. Otherwise, invoke it for the database named zDb only.
  92162. */
  92163. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  92164. sqlite3 *db = pParse->db;
  92165. int i;
  92166. for(i=0; i<db->nDb; i++){
  92167. Db *pDb = &db->aDb[i];
  92168. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  92169. sqlite3CodeVerifySchema(pParse, i);
  92170. }
  92171. }
  92172. }
  92173. /*
  92174. ** Generate VDBE code that prepares for doing an operation that
  92175. ** might change the database.
  92176. **
  92177. ** This routine starts a new transaction if we are not already within
  92178. ** a transaction. If we are already within a transaction, then a checkpoint
  92179. ** is set if the setStatement parameter is true. A checkpoint should
  92180. ** be set for operations that might fail (due to a constraint) part of
  92181. ** the way through and which will need to undo some writes without having to
  92182. ** rollback the whole transaction. For operations where all constraints
  92183. ** can be checked before any changes are made to the database, it is never
  92184. ** necessary to undo a write and the checkpoint should not be set.
  92185. */
  92186. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  92187. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  92188. sqlite3CodeVerifySchema(pParse, iDb);
  92189. DbMaskSet(pToplevel->writeMask, iDb);
  92190. pToplevel->isMultiWrite |= setStatement;
  92191. }
  92192. /*
  92193. ** Indicate that the statement currently under construction might write
  92194. ** more than one entry (example: deleting one row then inserting another,
  92195. ** inserting multiple rows in a table, or inserting a row and index entries.)
  92196. ** If an abort occurs after some of these writes have completed, then it will
  92197. ** be necessary to undo the completed writes.
  92198. */
  92199. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  92200. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  92201. pToplevel->isMultiWrite = 1;
  92202. }
  92203. /*
  92204. ** The code generator calls this routine if is discovers that it is
  92205. ** possible to abort a statement prior to completion. In order to
  92206. ** perform this abort without corrupting the database, we need to make
  92207. ** sure that the statement is protected by a statement transaction.
  92208. **
  92209. ** Technically, we only need to set the mayAbort flag if the
  92210. ** isMultiWrite flag was previously set. There is a time dependency
  92211. ** such that the abort must occur after the multiwrite. This makes
  92212. ** some statements involving the REPLACE conflict resolution algorithm
  92213. ** go a little faster. But taking advantage of this time dependency
  92214. ** makes it more difficult to prove that the code is correct (in
  92215. ** particular, it prevents us from writing an effective
  92216. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  92217. ** to take the safe route and skip the optimization.
  92218. */
  92219. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  92220. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  92221. pToplevel->mayAbort = 1;
  92222. }
  92223. /*
  92224. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  92225. ** error. The onError parameter determines which (if any) of the statement
  92226. ** and/or current transaction is rolled back.
  92227. */
  92228. SQLITE_PRIVATE void sqlite3HaltConstraint(
  92229. Parse *pParse, /* Parsing context */
  92230. int errCode, /* extended error code */
  92231. int onError, /* Constraint type */
  92232. char *p4, /* Error message */
  92233. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  92234. u8 p5Errmsg /* P5_ErrMsg type */
  92235. ){
  92236. Vdbe *v = sqlite3GetVdbe(pParse);
  92237. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  92238. if( onError==OE_Abort ){
  92239. sqlite3MayAbort(pParse);
  92240. }
  92241. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  92242. sqlite3VdbeChangeP5(v, p5Errmsg);
  92243. }
  92244. /*
  92245. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  92246. */
  92247. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  92248. Parse *pParse, /* Parsing context */
  92249. int onError, /* Constraint type */
  92250. Index *pIdx /* The index that triggers the constraint */
  92251. ){
  92252. char *zErr;
  92253. int j;
  92254. StrAccum errMsg;
  92255. Table *pTab = pIdx->pTable;
  92256. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  92257. if( pIdx->aColExpr ){
  92258. sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
  92259. }else{
  92260. for(j=0; j<pIdx->nKeyCol; j++){
  92261. char *zCol;
  92262. assert( pIdx->aiColumn[j]>=0 );
  92263. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  92264. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  92265. sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
  92266. }
  92267. }
  92268. zErr = sqlite3StrAccumFinish(&errMsg);
  92269. sqlite3HaltConstraint(pParse,
  92270. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  92271. : SQLITE_CONSTRAINT_UNIQUE,
  92272. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  92273. }
  92274. /*
  92275. ** Code an OP_Halt due to non-unique rowid.
  92276. */
  92277. SQLITE_PRIVATE void sqlite3RowidConstraint(
  92278. Parse *pParse, /* Parsing context */
  92279. int onError, /* Conflict resolution algorithm */
  92280. Table *pTab /* The table with the non-unique rowid */
  92281. ){
  92282. char *zMsg;
  92283. int rc;
  92284. if( pTab->iPKey>=0 ){
  92285. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  92286. pTab->aCol[pTab->iPKey].zName);
  92287. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  92288. }else{
  92289. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  92290. rc = SQLITE_CONSTRAINT_ROWID;
  92291. }
  92292. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  92293. P5_ConstraintUnique);
  92294. }
  92295. /*
  92296. ** Check to see if pIndex uses the collating sequence pColl. Return
  92297. ** true if it does and false if it does not.
  92298. */
  92299. #ifndef SQLITE_OMIT_REINDEX
  92300. static int collationMatch(const char *zColl, Index *pIndex){
  92301. int i;
  92302. assert( zColl!=0 );
  92303. for(i=0; i<pIndex->nColumn; i++){
  92304. const char *z = pIndex->azColl[i];
  92305. assert( z!=0 || pIndex->aiColumn[i]<0 );
  92306. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  92307. return 1;
  92308. }
  92309. }
  92310. return 0;
  92311. }
  92312. #endif
  92313. /*
  92314. ** Recompute all indices of pTab that use the collating sequence pColl.
  92315. ** If pColl==0 then recompute all indices of pTab.
  92316. */
  92317. #ifndef SQLITE_OMIT_REINDEX
  92318. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  92319. Index *pIndex; /* An index associated with pTab */
  92320. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  92321. if( zColl==0 || collationMatch(zColl, pIndex) ){
  92322. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  92323. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92324. sqlite3RefillIndex(pParse, pIndex, -1);
  92325. }
  92326. }
  92327. }
  92328. #endif
  92329. /*
  92330. ** Recompute all indices of all tables in all databases where the
  92331. ** indices use the collating sequence pColl. If pColl==0 then recompute
  92332. ** all indices everywhere.
  92333. */
  92334. #ifndef SQLITE_OMIT_REINDEX
  92335. static void reindexDatabases(Parse *pParse, char const *zColl){
  92336. Db *pDb; /* A single database */
  92337. int iDb; /* The database index number */
  92338. sqlite3 *db = pParse->db; /* The database connection */
  92339. HashElem *k; /* For looping over tables in pDb */
  92340. Table *pTab; /* A table in the database */
  92341. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  92342. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  92343. assert( pDb!=0 );
  92344. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  92345. pTab = (Table*)sqliteHashData(k);
  92346. reindexTable(pParse, pTab, zColl);
  92347. }
  92348. }
  92349. }
  92350. #endif
  92351. /*
  92352. ** Generate code for the REINDEX command.
  92353. **
  92354. ** REINDEX -- 1
  92355. ** REINDEX <collation> -- 2
  92356. ** REINDEX ?<database>.?<tablename> -- 3
  92357. ** REINDEX ?<database>.?<indexname> -- 4
  92358. **
  92359. ** Form 1 causes all indices in all attached databases to be rebuilt.
  92360. ** Form 2 rebuilds all indices in all databases that use the named
  92361. ** collating function. Forms 3 and 4 rebuild the named index or all
  92362. ** indices associated with the named table.
  92363. */
  92364. #ifndef SQLITE_OMIT_REINDEX
  92365. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  92366. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  92367. char *z; /* Name of a table or index */
  92368. const char *zDb; /* Name of the database */
  92369. Table *pTab; /* A table in the database */
  92370. Index *pIndex; /* An index associated with pTab */
  92371. int iDb; /* The database index number */
  92372. sqlite3 *db = pParse->db; /* The database connection */
  92373. Token *pObjName; /* Name of the table or index to be reindexed */
  92374. /* Read the database schema. If an error occurs, leave an error message
  92375. ** and code in pParse and return NULL. */
  92376. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  92377. return;
  92378. }
  92379. if( pName1==0 ){
  92380. reindexDatabases(pParse, 0);
  92381. return;
  92382. }else if( NEVER(pName2==0) || pName2->z==0 ){
  92383. char *zColl;
  92384. assert( pName1->z );
  92385. zColl = sqlite3NameFromToken(pParse->db, pName1);
  92386. if( !zColl ) return;
  92387. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  92388. if( pColl ){
  92389. reindexDatabases(pParse, zColl);
  92390. sqlite3DbFree(db, zColl);
  92391. return;
  92392. }
  92393. sqlite3DbFree(db, zColl);
  92394. }
  92395. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  92396. if( iDb<0 ) return;
  92397. z = sqlite3NameFromToken(db, pObjName);
  92398. if( z==0 ) return;
  92399. zDb = db->aDb[iDb].zName;
  92400. pTab = sqlite3FindTable(db, z, zDb);
  92401. if( pTab ){
  92402. reindexTable(pParse, pTab, 0);
  92403. sqlite3DbFree(db, z);
  92404. return;
  92405. }
  92406. pIndex = sqlite3FindIndex(db, z, zDb);
  92407. sqlite3DbFree(db, z);
  92408. if( pIndex ){
  92409. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92410. sqlite3RefillIndex(pParse, pIndex, -1);
  92411. return;
  92412. }
  92413. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  92414. }
  92415. #endif
  92416. /*
  92417. ** Return a KeyInfo structure that is appropriate for the given Index.
  92418. **
  92419. ** The KeyInfo structure for an index is cached in the Index object.
  92420. ** So there might be multiple references to the returned pointer. The
  92421. ** caller should not try to modify the KeyInfo object.
  92422. **
  92423. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  92424. ** when it has finished using it.
  92425. */
  92426. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  92427. int i;
  92428. int nCol = pIdx->nColumn;
  92429. int nKey = pIdx->nKeyCol;
  92430. KeyInfo *pKey;
  92431. if( pParse->nErr ) return 0;
  92432. if( pIdx->uniqNotNull ){
  92433. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  92434. }else{
  92435. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  92436. }
  92437. if( pKey ){
  92438. assert( sqlite3KeyInfoIsWriteable(pKey) );
  92439. for(i=0; i<nCol; i++){
  92440. const char *zColl = pIdx->azColl[i];
  92441. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  92442. sqlite3LocateCollSeq(pParse, zColl);
  92443. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  92444. }
  92445. if( pParse->nErr ){
  92446. sqlite3KeyInfoUnref(pKey);
  92447. pKey = 0;
  92448. }
  92449. }
  92450. return pKey;
  92451. }
  92452. #ifndef SQLITE_OMIT_CTE
  92453. /*
  92454. ** This routine is invoked once per CTE by the parser while parsing a
  92455. ** WITH clause.
  92456. */
  92457. SQLITE_PRIVATE With *sqlite3WithAdd(
  92458. Parse *pParse, /* Parsing context */
  92459. With *pWith, /* Existing WITH clause, or NULL */
  92460. Token *pName, /* Name of the common-table */
  92461. ExprList *pArglist, /* Optional column name list for the table */
  92462. Select *pQuery /* Query used to initialize the table */
  92463. ){
  92464. sqlite3 *db = pParse->db;
  92465. With *pNew;
  92466. char *zName;
  92467. /* Check that the CTE name is unique within this WITH clause. If
  92468. ** not, store an error in the Parse structure. */
  92469. zName = sqlite3NameFromToken(pParse->db, pName);
  92470. if( zName && pWith ){
  92471. int i;
  92472. for(i=0; i<pWith->nCte; i++){
  92473. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  92474. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  92475. }
  92476. }
  92477. }
  92478. if( pWith ){
  92479. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  92480. pNew = sqlite3DbRealloc(db, pWith, nByte);
  92481. }else{
  92482. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  92483. }
  92484. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  92485. if( db->mallocFailed ){
  92486. sqlite3ExprListDelete(db, pArglist);
  92487. sqlite3SelectDelete(db, pQuery);
  92488. sqlite3DbFree(db, zName);
  92489. pNew = pWith;
  92490. }else{
  92491. pNew->a[pNew->nCte].pSelect = pQuery;
  92492. pNew->a[pNew->nCte].pCols = pArglist;
  92493. pNew->a[pNew->nCte].zName = zName;
  92494. pNew->a[pNew->nCte].zCteErr = 0;
  92495. pNew->nCte++;
  92496. }
  92497. return pNew;
  92498. }
  92499. /*
  92500. ** Free the contents of the With object passed as the second argument.
  92501. */
  92502. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  92503. if( pWith ){
  92504. int i;
  92505. for(i=0; i<pWith->nCte; i++){
  92506. struct Cte *pCte = &pWith->a[i];
  92507. sqlite3ExprListDelete(db, pCte->pCols);
  92508. sqlite3SelectDelete(db, pCte->pSelect);
  92509. sqlite3DbFree(db, pCte->zName);
  92510. }
  92511. sqlite3DbFree(db, pWith);
  92512. }
  92513. }
  92514. #endif /* !defined(SQLITE_OMIT_CTE) */
  92515. /************** End of build.c ***********************************************/
  92516. /************** Begin file callback.c ****************************************/
  92517. /*
  92518. ** 2005 May 23
  92519. **
  92520. ** The author disclaims copyright to this source code. In place of
  92521. ** a legal notice, here is a blessing:
  92522. **
  92523. ** May you do good and not evil.
  92524. ** May you find forgiveness for yourself and forgive others.
  92525. ** May you share freely, never taking more than you give.
  92526. **
  92527. *************************************************************************
  92528. **
  92529. ** This file contains functions used to access the internal hash tables
  92530. ** of user defined functions and collation sequences.
  92531. */
  92532. /* #include "sqliteInt.h" */
  92533. /*
  92534. ** Invoke the 'collation needed' callback to request a collation sequence
  92535. ** in the encoding enc of name zName, length nName.
  92536. */
  92537. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  92538. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  92539. if( db->xCollNeeded ){
  92540. char *zExternal = sqlite3DbStrDup(db, zName);
  92541. if( !zExternal ) return;
  92542. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  92543. sqlite3DbFree(db, zExternal);
  92544. }
  92545. #ifndef SQLITE_OMIT_UTF16
  92546. if( db->xCollNeeded16 ){
  92547. char const *zExternal;
  92548. sqlite3_value *pTmp = sqlite3ValueNew(db);
  92549. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  92550. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  92551. if( zExternal ){
  92552. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  92553. }
  92554. sqlite3ValueFree(pTmp);
  92555. }
  92556. #endif
  92557. }
  92558. /*
  92559. ** This routine is called if the collation factory fails to deliver a
  92560. ** collation function in the best encoding but there may be other versions
  92561. ** of this collation function (for other text encodings) available. Use one
  92562. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  92563. ** possible.
  92564. */
  92565. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  92566. CollSeq *pColl2;
  92567. char *z = pColl->zName;
  92568. int i;
  92569. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  92570. for(i=0; i<3; i++){
  92571. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  92572. if( pColl2->xCmp!=0 ){
  92573. memcpy(pColl, pColl2, sizeof(CollSeq));
  92574. pColl->xDel = 0; /* Do not copy the destructor */
  92575. return SQLITE_OK;
  92576. }
  92577. }
  92578. return SQLITE_ERROR;
  92579. }
  92580. /*
  92581. ** This function is responsible for invoking the collation factory callback
  92582. ** or substituting a collation sequence of a different encoding when the
  92583. ** requested collation sequence is not available in the desired encoding.
  92584. **
  92585. ** If it is not NULL, then pColl must point to the database native encoding
  92586. ** collation sequence with name zName, length nName.
  92587. **
  92588. ** The return value is either the collation sequence to be used in database
  92589. ** db for collation type name zName, length nName, or NULL, if no collation
  92590. ** sequence can be found. If no collation is found, leave an error message.
  92591. **
  92592. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  92593. */
  92594. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  92595. Parse *pParse, /* Parsing context */
  92596. u8 enc, /* The desired encoding for the collating sequence */
  92597. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  92598. const char *zName /* Collating sequence name */
  92599. ){
  92600. CollSeq *p;
  92601. sqlite3 *db = pParse->db;
  92602. p = pColl;
  92603. if( !p ){
  92604. p = sqlite3FindCollSeq(db, enc, zName, 0);
  92605. }
  92606. if( !p || !p->xCmp ){
  92607. /* No collation sequence of this type for this encoding is registered.
  92608. ** Call the collation factory to see if it can supply us with one.
  92609. */
  92610. callCollNeeded(db, enc, zName);
  92611. p = sqlite3FindCollSeq(db, enc, zName, 0);
  92612. }
  92613. if( p && !p->xCmp && synthCollSeq(db, p) ){
  92614. p = 0;
  92615. }
  92616. assert( !p || p->xCmp );
  92617. if( p==0 ){
  92618. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  92619. }
  92620. return p;
  92621. }
  92622. /*
  92623. ** This routine is called on a collation sequence before it is used to
  92624. ** check that it is defined. An undefined collation sequence exists when
  92625. ** a database is loaded that contains references to collation sequences
  92626. ** that have not been defined by sqlite3_create_collation() etc.
  92627. **
  92628. ** If required, this routine calls the 'collation needed' callback to
  92629. ** request a definition of the collating sequence. If this doesn't work,
  92630. ** an equivalent collating sequence that uses a text encoding different
  92631. ** from the main database is substituted, if one is available.
  92632. */
  92633. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  92634. if( pColl ){
  92635. const char *zName = pColl->zName;
  92636. sqlite3 *db = pParse->db;
  92637. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  92638. if( !p ){
  92639. return SQLITE_ERROR;
  92640. }
  92641. assert( p==pColl );
  92642. }
  92643. return SQLITE_OK;
  92644. }
  92645. /*
  92646. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  92647. ** specified by zName and nName is not found and parameter 'create' is
  92648. ** true, then create a new entry. Otherwise return NULL.
  92649. **
  92650. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  92651. ** array of three CollSeq structures. The first is the collation sequence
  92652. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  92653. **
  92654. ** Stored immediately after the three collation sequences is a copy of
  92655. ** the collation sequence name. A pointer to this string is stored in
  92656. ** each collation sequence structure.
  92657. */
  92658. static CollSeq *findCollSeqEntry(
  92659. sqlite3 *db, /* Database connection */
  92660. const char *zName, /* Name of the collating sequence */
  92661. int create /* Create a new entry if true */
  92662. ){
  92663. CollSeq *pColl;
  92664. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  92665. if( 0==pColl && create ){
  92666. int nName = sqlite3Strlen30(zName);
  92667. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  92668. if( pColl ){
  92669. CollSeq *pDel = 0;
  92670. pColl[0].zName = (char*)&pColl[3];
  92671. pColl[0].enc = SQLITE_UTF8;
  92672. pColl[1].zName = (char*)&pColl[3];
  92673. pColl[1].enc = SQLITE_UTF16LE;
  92674. pColl[2].zName = (char*)&pColl[3];
  92675. pColl[2].enc = SQLITE_UTF16BE;
  92676. memcpy(pColl[0].zName, zName, nName);
  92677. pColl[0].zName[nName] = 0;
  92678. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  92679. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  92680. ** return the pColl pointer to be deleted (because it wasn't added
  92681. ** to the hash table).
  92682. */
  92683. assert( pDel==0 || pDel==pColl );
  92684. if( pDel!=0 ){
  92685. sqlite3OomFault(db);
  92686. sqlite3DbFree(db, pDel);
  92687. pColl = 0;
  92688. }
  92689. }
  92690. }
  92691. return pColl;
  92692. }
  92693. /*
  92694. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  92695. ** Return the CollSeq* pointer for the collation sequence named zName
  92696. ** for the encoding 'enc' from the database 'db'.
  92697. **
  92698. ** If the entry specified is not found and 'create' is true, then create a
  92699. ** new entry. Otherwise return NULL.
  92700. **
  92701. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  92702. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  92703. ** if necessary and generates an error message if the collating sequence
  92704. ** cannot be found.
  92705. **
  92706. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  92707. */
  92708. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  92709. sqlite3 *db,
  92710. u8 enc,
  92711. const char *zName,
  92712. int create
  92713. ){
  92714. CollSeq *pColl;
  92715. if( zName ){
  92716. pColl = findCollSeqEntry(db, zName, create);
  92717. }else{
  92718. pColl = db->pDfltColl;
  92719. }
  92720. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  92721. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  92722. if( pColl ) pColl += enc-1;
  92723. return pColl;
  92724. }
  92725. /* During the search for the best function definition, this procedure
  92726. ** is called to test how well the function passed as the first argument
  92727. ** matches the request for a function with nArg arguments in a system
  92728. ** that uses encoding enc. The value returned indicates how well the
  92729. ** request is matched. A higher value indicates a better match.
  92730. **
  92731. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  92732. ** is also -1. In other words, we are searching for a function that
  92733. ** takes a variable number of arguments.
  92734. **
  92735. ** If nArg is -2 that means that we are searching for any function
  92736. ** regardless of the number of arguments it uses, so return a positive
  92737. ** match score for any
  92738. **
  92739. ** The returned value is always between 0 and 6, as follows:
  92740. **
  92741. ** 0: Not a match.
  92742. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  92743. ** 2: UTF16 byte order change required and function takes any number of args.
  92744. ** 3: encoding matches and function takes any number of arguments
  92745. ** 4: UTF8/16 conversion required - argument count matches exactly
  92746. ** 5: UTF16 byte order conversion required - argument count matches exactly
  92747. ** 6: Perfect match: encoding and argument count match exactly.
  92748. **
  92749. ** If nArg==(-2) then any function with a non-null xSFunc is
  92750. ** a perfect match and any function with xSFunc NULL is
  92751. ** a non-match.
  92752. */
  92753. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  92754. static int matchQuality(
  92755. FuncDef *p, /* The function we are evaluating for match quality */
  92756. int nArg, /* Desired number of arguments. (-1)==any */
  92757. u8 enc /* Desired text encoding */
  92758. ){
  92759. int match;
  92760. /* nArg of -2 is a special case */
  92761. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  92762. /* Wrong number of arguments means "no match" */
  92763. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  92764. /* Give a better score to a function with a specific number of arguments
  92765. ** than to function that accepts any number of arguments. */
  92766. if( p->nArg==nArg ){
  92767. match = 4;
  92768. }else{
  92769. match = 1;
  92770. }
  92771. /* Bonus points if the text encoding matches */
  92772. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  92773. match += 2; /* Exact encoding match */
  92774. }else if( (enc & p->funcFlags & 2)!=0 ){
  92775. match += 1; /* Both are UTF16, but with different byte orders */
  92776. }
  92777. return match;
  92778. }
  92779. /*
  92780. ** Search a FuncDefHash for a function with the given name. Return
  92781. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  92782. */
  92783. static FuncDef *functionSearch(
  92784. int h, /* Hash of the name */
  92785. const char *zFunc /* Name of function */
  92786. ){
  92787. FuncDef *p;
  92788. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  92789. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  92790. return p;
  92791. }
  92792. }
  92793. return 0;
  92794. }
  92795. /*
  92796. ** Insert a new FuncDef into a FuncDefHash hash table.
  92797. */
  92798. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  92799. FuncDef *aDef, /* List of global functions to be inserted */
  92800. int nDef /* Length of the apDef[] list */
  92801. ){
  92802. int i;
  92803. for(i=0; i<nDef; i++){
  92804. FuncDef *pOther;
  92805. const char *zName = aDef[i].zName;
  92806. int nName = sqlite3Strlen30(zName);
  92807. int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  92808. pOther = functionSearch(h, zName);
  92809. if( pOther ){
  92810. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  92811. aDef[i].pNext = pOther->pNext;
  92812. pOther->pNext = &aDef[i];
  92813. }else{
  92814. aDef[i].pNext = 0;
  92815. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  92816. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  92817. }
  92818. }
  92819. }
  92820. /*
  92821. ** Locate a user function given a name, a number of arguments and a flag
  92822. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  92823. ** pointer to the FuncDef structure that defines that function, or return
  92824. ** NULL if the function does not exist.
  92825. **
  92826. ** If the createFlag argument is true, then a new (blank) FuncDef
  92827. ** structure is created and liked into the "db" structure if a
  92828. ** no matching function previously existed.
  92829. **
  92830. ** If nArg is -2, then the first valid function found is returned. A
  92831. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  92832. ** case is used to see if zName is a valid function name for some number
  92833. ** of arguments. If nArg is -2, then createFlag must be 0.
  92834. **
  92835. ** If createFlag is false, then a function with the required name and
  92836. ** number of arguments may be returned even if the eTextRep flag does not
  92837. ** match that requested.
  92838. */
  92839. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  92840. sqlite3 *db, /* An open database */
  92841. const char *zName, /* Name of the function. zero-terminated */
  92842. int nArg, /* Number of arguments. -1 means any number */
  92843. u8 enc, /* Preferred text encoding */
  92844. u8 createFlag /* Create new entry if true and does not otherwise exist */
  92845. ){
  92846. FuncDef *p; /* Iterator variable */
  92847. FuncDef *pBest = 0; /* Best match found so far */
  92848. int bestScore = 0; /* Score of best match */
  92849. int h; /* Hash value */
  92850. int nName; /* Length of the name */
  92851. assert( nArg>=(-2) );
  92852. assert( nArg>=(-1) || createFlag==0 );
  92853. nName = sqlite3Strlen30(zName);
  92854. /* First search for a match amongst the application-defined functions.
  92855. */
  92856. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  92857. while( p ){
  92858. int score = matchQuality(p, nArg, enc);
  92859. if( score>bestScore ){
  92860. pBest = p;
  92861. bestScore = score;
  92862. }
  92863. p = p->pNext;
  92864. }
  92865. /* If no match is found, search the built-in functions.
  92866. **
  92867. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  92868. ** functions even if a prior app-defined function was found. And give
  92869. ** priority to built-in functions.
  92870. **
  92871. ** Except, if createFlag is true, that means that we are trying to
  92872. ** install a new function. Whatever FuncDef structure is returned it will
  92873. ** have fields overwritten with new information appropriate for the
  92874. ** new function. But the FuncDefs for built-in functions are read-only.
  92875. ** So we must not search for built-ins when creating a new function.
  92876. */
  92877. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  92878. bestScore = 0;
  92879. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  92880. p = functionSearch(h, zName);
  92881. while( p ){
  92882. int score = matchQuality(p, nArg, enc);
  92883. if( score>bestScore ){
  92884. pBest = p;
  92885. bestScore = score;
  92886. }
  92887. p = p->pNext;
  92888. }
  92889. }
  92890. /* If the createFlag parameter is true and the search did not reveal an
  92891. ** exact match for the name, number of arguments and encoding, then add a
  92892. ** new entry to the hash table and return it.
  92893. */
  92894. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  92895. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  92896. FuncDef *pOther;
  92897. pBest->zName = (const char*)&pBest[1];
  92898. pBest->nArg = (u16)nArg;
  92899. pBest->funcFlags = enc;
  92900. memcpy((char*)&pBest[1], zName, nName+1);
  92901. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  92902. if( pOther==pBest ){
  92903. sqlite3DbFree(db, pBest);
  92904. sqlite3OomFault(db);
  92905. return 0;
  92906. }else{
  92907. pBest->pNext = pOther;
  92908. }
  92909. }
  92910. if( pBest && (pBest->xSFunc || createFlag) ){
  92911. return pBest;
  92912. }
  92913. return 0;
  92914. }
  92915. /*
  92916. ** Free all resources held by the schema structure. The void* argument points
  92917. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  92918. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  92919. ** of the schema hash tables).
  92920. **
  92921. ** The Schema.cache_size variable is not cleared.
  92922. */
  92923. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  92924. Hash temp1;
  92925. Hash temp2;
  92926. HashElem *pElem;
  92927. Schema *pSchema = (Schema *)p;
  92928. temp1 = pSchema->tblHash;
  92929. temp2 = pSchema->trigHash;
  92930. sqlite3HashInit(&pSchema->trigHash);
  92931. sqlite3HashClear(&pSchema->idxHash);
  92932. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  92933. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  92934. }
  92935. sqlite3HashClear(&temp2);
  92936. sqlite3HashInit(&pSchema->tblHash);
  92937. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  92938. Table *pTab = sqliteHashData(pElem);
  92939. sqlite3DeleteTable(0, pTab);
  92940. }
  92941. sqlite3HashClear(&temp1);
  92942. sqlite3HashClear(&pSchema->fkeyHash);
  92943. pSchema->pSeqTab = 0;
  92944. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  92945. pSchema->iGeneration++;
  92946. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  92947. }
  92948. }
  92949. /*
  92950. ** Find and return the schema associated with a BTree. Create
  92951. ** a new one if necessary.
  92952. */
  92953. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  92954. Schema * p;
  92955. if( pBt ){
  92956. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  92957. }else{
  92958. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  92959. }
  92960. if( !p ){
  92961. sqlite3OomFault(db);
  92962. }else if ( 0==p->file_format ){
  92963. sqlite3HashInit(&p->tblHash);
  92964. sqlite3HashInit(&p->idxHash);
  92965. sqlite3HashInit(&p->trigHash);
  92966. sqlite3HashInit(&p->fkeyHash);
  92967. p->enc = SQLITE_UTF8;
  92968. }
  92969. return p;
  92970. }
  92971. /************** End of callback.c ********************************************/
  92972. /************** Begin file delete.c ******************************************/
  92973. /*
  92974. ** 2001 September 15
  92975. **
  92976. ** The author disclaims copyright to this source code. In place of
  92977. ** a legal notice, here is a blessing:
  92978. **
  92979. ** May you do good and not evil.
  92980. ** May you find forgiveness for yourself and forgive others.
  92981. ** May you share freely, never taking more than you give.
  92982. **
  92983. *************************************************************************
  92984. ** This file contains C code routines that are called by the parser
  92985. ** in order to generate code for DELETE FROM statements.
  92986. */
  92987. /* #include "sqliteInt.h" */
  92988. /*
  92989. ** While a SrcList can in general represent multiple tables and subqueries
  92990. ** (as in the FROM clause of a SELECT statement) in this case it contains
  92991. ** the name of a single table, as one might find in an INSERT, DELETE,
  92992. ** or UPDATE statement. Look up that table in the symbol table and
  92993. ** return a pointer. Set an error message and return NULL if the table
  92994. ** name is not found or if any other error occurs.
  92995. **
  92996. ** The following fields are initialized appropriate in pSrc:
  92997. **
  92998. ** pSrc->a[0].pTab Pointer to the Table object
  92999. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  93000. **
  93001. */
  93002. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  93003. struct SrcList_item *pItem = pSrc->a;
  93004. Table *pTab;
  93005. assert( pItem && pSrc->nSrc==1 );
  93006. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  93007. sqlite3DeleteTable(pParse->db, pItem->pTab);
  93008. pItem->pTab = pTab;
  93009. if( pTab ){
  93010. pTab->nRef++;
  93011. }
  93012. if( sqlite3IndexedByLookup(pParse, pItem) ){
  93013. pTab = 0;
  93014. }
  93015. return pTab;
  93016. }
  93017. /*
  93018. ** Check to make sure the given table is writable. If it is not
  93019. ** writable, generate an error message and return 1. If it is
  93020. ** writable return 0;
  93021. */
  93022. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  93023. /* A table is not writable under the following circumstances:
  93024. **
  93025. ** 1) It is a virtual table and no implementation of the xUpdate method
  93026. ** has been provided, or
  93027. ** 2) It is a system table (i.e. sqlite_master), this call is not
  93028. ** part of a nested parse and writable_schema pragma has not
  93029. ** been specified.
  93030. **
  93031. ** In either case leave an error message in pParse and return non-zero.
  93032. */
  93033. if( ( IsVirtual(pTab)
  93034. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  93035. || ( (pTab->tabFlags & TF_Readonly)!=0
  93036. && (pParse->db->flags & SQLITE_WriteSchema)==0
  93037. && pParse->nested==0 )
  93038. ){
  93039. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  93040. return 1;
  93041. }
  93042. #ifndef SQLITE_OMIT_VIEW
  93043. if( !viewOk && pTab->pSelect ){
  93044. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  93045. return 1;
  93046. }
  93047. #endif
  93048. return 0;
  93049. }
  93050. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  93051. /*
  93052. ** Evaluate a view and store its result in an ephemeral table. The
  93053. ** pWhere argument is an optional WHERE clause that restricts the
  93054. ** set of rows in the view that are to be added to the ephemeral table.
  93055. */
  93056. SQLITE_PRIVATE void sqlite3MaterializeView(
  93057. Parse *pParse, /* Parsing context */
  93058. Table *pView, /* View definition */
  93059. Expr *pWhere, /* Optional WHERE clause to be added */
  93060. int iCur /* Cursor number for ephemeral table */
  93061. ){
  93062. SelectDest dest;
  93063. Select *pSel;
  93064. SrcList *pFrom;
  93065. sqlite3 *db = pParse->db;
  93066. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  93067. pWhere = sqlite3ExprDup(db, pWhere, 0);
  93068. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  93069. if( pFrom ){
  93070. assert( pFrom->nSrc==1 );
  93071. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  93072. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  93073. assert( pFrom->a[0].pOn==0 );
  93074. assert( pFrom->a[0].pUsing==0 );
  93075. }
  93076. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
  93077. SF_IncludeHidden, 0, 0);
  93078. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  93079. sqlite3Select(pParse, pSel, &dest);
  93080. sqlite3SelectDelete(db, pSel);
  93081. }
  93082. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  93083. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  93084. /*
  93085. ** Generate an expression tree to implement the WHERE, ORDER BY,
  93086. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  93087. **
  93088. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  93089. ** \__________________________/
  93090. ** pLimitWhere (pInClause)
  93091. */
  93092. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  93093. Parse *pParse, /* The parser context */
  93094. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  93095. Expr *pWhere, /* The WHERE clause. May be null */
  93096. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  93097. Expr *pLimit, /* The LIMIT clause. May be null */
  93098. Expr *pOffset, /* The OFFSET clause. May be null */
  93099. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  93100. ){
  93101. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  93102. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  93103. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  93104. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  93105. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  93106. Select *pSelect = NULL; /* Complete SELECT tree */
  93107. /* Check that there isn't an ORDER BY without a LIMIT clause.
  93108. */
  93109. if( pOrderBy && (pLimit == 0) ) {
  93110. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  93111. goto limit_where_cleanup_2;
  93112. }
  93113. /* We only need to generate a select expression if there
  93114. ** is a limit/offset term to enforce.
  93115. */
  93116. if( pLimit == 0 ) {
  93117. /* if pLimit is null, pOffset will always be null as well. */
  93118. assert( pOffset == 0 );
  93119. return pWhere;
  93120. }
  93121. /* Generate a select expression tree to enforce the limit/offset
  93122. ** term for the DELETE or UPDATE statement. For example:
  93123. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  93124. ** becomes:
  93125. ** DELETE FROM table_a WHERE rowid IN (
  93126. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  93127. ** );
  93128. */
  93129. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  93130. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  93131. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  93132. if( pEList == 0 ) goto limit_where_cleanup_2;
  93133. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  93134. ** and the SELECT subtree. */
  93135. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  93136. if( pSelectSrc == 0 ) {
  93137. sqlite3ExprListDelete(pParse->db, pEList);
  93138. goto limit_where_cleanup_2;
  93139. }
  93140. /* generate the SELECT expression tree. */
  93141. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  93142. pOrderBy,0,pLimit,pOffset);
  93143. if( pSelect == 0 ) return 0;
  93144. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  93145. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  93146. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  93147. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  93148. if( pInClause == 0 ) goto limit_where_cleanup_1;
  93149. pInClause->x.pSelect = pSelect;
  93150. pInClause->flags |= EP_xIsSelect;
  93151. sqlite3ExprSetHeightAndFlags(pParse, pInClause);
  93152. return pInClause;
  93153. /* something went wrong. clean up anything allocated. */
  93154. limit_where_cleanup_1:
  93155. sqlite3SelectDelete(pParse->db, pSelect);
  93156. return 0;
  93157. limit_where_cleanup_2:
  93158. sqlite3ExprDelete(pParse->db, pWhere);
  93159. sqlite3ExprListDelete(pParse->db, pOrderBy);
  93160. sqlite3ExprDelete(pParse->db, pLimit);
  93161. sqlite3ExprDelete(pParse->db, pOffset);
  93162. return 0;
  93163. }
  93164. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  93165. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  93166. /*
  93167. ** Generate code for a DELETE FROM statement.
  93168. **
  93169. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  93170. ** \________/ \________________/
  93171. ** pTabList pWhere
  93172. */
  93173. SQLITE_PRIVATE void sqlite3DeleteFrom(
  93174. Parse *pParse, /* The parser context */
  93175. SrcList *pTabList, /* The table from which we should delete things */
  93176. Expr *pWhere /* The WHERE clause. May be null */
  93177. ){
  93178. Vdbe *v; /* The virtual database engine */
  93179. Table *pTab; /* The table from which records will be deleted */
  93180. const char *zDb; /* Name of database holding pTab */
  93181. int i; /* Loop counter */
  93182. WhereInfo *pWInfo; /* Information about the WHERE clause */
  93183. Index *pIdx; /* For looping over indices of the table */
  93184. int iTabCur; /* Cursor number for the table */
  93185. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  93186. int iIdxCur = 0; /* Cursor number of the first index */
  93187. int nIdx; /* Number of indices */
  93188. sqlite3 *db; /* Main database structure */
  93189. AuthContext sContext; /* Authorization context */
  93190. NameContext sNC; /* Name context to resolve expressions in */
  93191. int iDb; /* Database number */
  93192. int memCnt = -1; /* Memory cell used for change counting */
  93193. int rcauth; /* Value returned by authorization callback */
  93194. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  93195. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  93196. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  93197. Index *pPk; /* The PRIMARY KEY index on the table */
  93198. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  93199. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  93200. int iKey; /* Memory cell holding key of row to be deleted */
  93201. i16 nKey; /* Number of memory cells in the row key */
  93202. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  93203. int iRowSet = 0; /* Register for rowset of rows to delete */
  93204. int addrBypass = 0; /* Address of jump over the delete logic */
  93205. int addrLoop = 0; /* Top of the delete loop */
  93206. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  93207. #ifndef SQLITE_OMIT_TRIGGER
  93208. int isView; /* True if attempting to delete from a view */
  93209. Trigger *pTrigger; /* List of table triggers, if required */
  93210. int bComplex; /* True if there are either triggers or FKs */
  93211. #endif
  93212. memset(&sContext, 0, sizeof(sContext));
  93213. db = pParse->db;
  93214. if( pParse->nErr || db->mallocFailed ){
  93215. goto delete_from_cleanup;
  93216. }
  93217. assert( pTabList->nSrc==1 );
  93218. /* Locate the table which we want to delete. This table has to be
  93219. ** put in an SrcList structure because some of the subroutines we
  93220. ** will be calling are designed to work with multiple tables and expect
  93221. ** an SrcList* parameter instead of just a Table* parameter.
  93222. */
  93223. pTab = sqlite3SrcListLookup(pParse, pTabList);
  93224. if( pTab==0 ) goto delete_from_cleanup;
  93225. /* Figure out if we have any triggers and if the table being
  93226. ** deleted from is a view
  93227. */
  93228. #ifndef SQLITE_OMIT_TRIGGER
  93229. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  93230. isView = pTab->pSelect!=0;
  93231. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  93232. #else
  93233. # define pTrigger 0
  93234. # define isView 0
  93235. # define bComplex 0
  93236. #endif
  93237. #ifdef SQLITE_OMIT_VIEW
  93238. # undef isView
  93239. # define isView 0
  93240. #endif
  93241. /* If pTab is really a view, make sure it has been initialized.
  93242. */
  93243. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  93244. goto delete_from_cleanup;
  93245. }
  93246. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  93247. goto delete_from_cleanup;
  93248. }
  93249. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  93250. assert( iDb<db->nDb );
  93251. zDb = db->aDb[iDb].zName;
  93252. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  93253. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  93254. if( rcauth==SQLITE_DENY ){
  93255. goto delete_from_cleanup;
  93256. }
  93257. assert(!isView || pTrigger);
  93258. /* Assign cursor numbers to the table and all its indices.
  93259. */
  93260. assert( pTabList->nSrc==1 );
  93261. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  93262. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  93263. pParse->nTab++;
  93264. }
  93265. /* Start the view context
  93266. */
  93267. if( isView ){
  93268. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  93269. }
  93270. /* Begin generating code.
  93271. */
  93272. v = sqlite3GetVdbe(pParse);
  93273. if( v==0 ){
  93274. goto delete_from_cleanup;
  93275. }
  93276. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  93277. sqlite3BeginWriteOperation(pParse, 1, iDb);
  93278. /* If we are trying to delete from a view, realize that view into
  93279. ** an ephemeral table.
  93280. */
  93281. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  93282. if( isView ){
  93283. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  93284. iDataCur = iIdxCur = iTabCur;
  93285. }
  93286. #endif
  93287. /* Resolve the column names in the WHERE clause.
  93288. */
  93289. memset(&sNC, 0, sizeof(sNC));
  93290. sNC.pParse = pParse;
  93291. sNC.pSrcList = pTabList;
  93292. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  93293. goto delete_from_cleanup;
  93294. }
  93295. /* Initialize the counter of the number of rows deleted, if
  93296. ** we are counting rows.
  93297. */
  93298. if( db->flags & SQLITE_CountRows ){
  93299. memCnt = ++pParse->nMem;
  93300. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  93301. }
  93302. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  93303. /* Special case: A DELETE without a WHERE clause deletes everything.
  93304. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  93305. ** this optimization caused the row change count (the value returned by
  93306. ** API function sqlite3_count_changes) to be set incorrectly. */
  93307. if( rcauth==SQLITE_OK
  93308. && pWhere==0
  93309. && !bComplex
  93310. && !IsVirtual(pTab)
  93311. ){
  93312. assert( !isView );
  93313. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  93314. if( HasRowid(pTab) ){
  93315. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  93316. pTab->zName, P4_STATIC);
  93317. }
  93318. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  93319. assert( pIdx->pSchema==pTab->pSchema );
  93320. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  93321. }
  93322. }else
  93323. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  93324. {
  93325. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
  93326. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  93327. if( HasRowid(pTab) ){
  93328. /* For a rowid table, initialize the RowSet to an empty set */
  93329. pPk = 0;
  93330. nPk = 1;
  93331. iRowSet = ++pParse->nMem;
  93332. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  93333. }else{
  93334. /* For a WITHOUT ROWID table, create an ephemeral table used to
  93335. ** hold all primary keys for rows to be deleted. */
  93336. pPk = sqlite3PrimaryKeyIndex(pTab);
  93337. assert( pPk!=0 );
  93338. nPk = pPk->nKeyCol;
  93339. iPk = pParse->nMem+1;
  93340. pParse->nMem += nPk;
  93341. iEphCur = pParse->nTab++;
  93342. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  93343. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  93344. }
  93345. /* Construct a query to find the rowid or primary key for every row
  93346. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  93347. ** to indicate the strategy used to implement this delete:
  93348. **
  93349. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  93350. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  93351. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  93352. */
  93353. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  93354. if( pWInfo==0 ) goto delete_from_cleanup;
  93355. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  93356. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  93357. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  93358. /* Keep track of the number of rows to be deleted */
  93359. if( db->flags & SQLITE_CountRows ){
  93360. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  93361. }
  93362. /* Extract the rowid or primary key for the current row */
  93363. if( pPk ){
  93364. for(i=0; i<nPk; i++){
  93365. assert( pPk->aiColumn[i]>=0 );
  93366. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  93367. pPk->aiColumn[i], iPk+i);
  93368. }
  93369. iKey = iPk;
  93370. }else{
  93371. iKey = pParse->nMem + 1;
  93372. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  93373. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  93374. }
  93375. if( eOnePass!=ONEPASS_OFF ){
  93376. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  93377. ** one, so just keep it in its register(s) and fall through to the
  93378. ** delete code. */
  93379. nKey = nPk; /* OP_Found will use an unpacked key */
  93380. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  93381. if( aToOpen==0 ){
  93382. sqlite3WhereEnd(pWInfo);
  93383. goto delete_from_cleanup;
  93384. }
  93385. memset(aToOpen, 1, nIdx+1);
  93386. aToOpen[nIdx+1] = 0;
  93387. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  93388. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  93389. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  93390. }else{
  93391. if( pPk ){
  93392. /* Add the PK key for this row to the temporary table */
  93393. iKey = ++pParse->nMem;
  93394. nKey = 0; /* Zero tells OP_Found to use a composite key */
  93395. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  93396. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  93397. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  93398. }else{
  93399. /* Add the rowid of the row to be deleted to the RowSet */
  93400. nKey = 1; /* OP_Seek always uses a single rowid */
  93401. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  93402. }
  93403. }
  93404. /* If this DELETE cannot use the ONEPASS strategy, this is the
  93405. ** end of the WHERE loop */
  93406. if( eOnePass!=ONEPASS_OFF ){
  93407. addrBypass = sqlite3VdbeMakeLabel(v);
  93408. }else{
  93409. sqlite3WhereEnd(pWInfo);
  93410. }
  93411. /* Unless this is a view, open cursors for the table we are
  93412. ** deleting from and all its indices. If this is a view, then the
  93413. ** only effect this statement has is to fire the INSTEAD OF
  93414. ** triggers.
  93415. */
  93416. if( !isView ){
  93417. int iAddrOnce = 0;
  93418. if( eOnePass==ONEPASS_MULTI ){
  93419. iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  93420. }
  93421. testcase( IsVirtual(pTab) );
  93422. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  93423. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  93424. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  93425. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  93426. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  93427. }
  93428. /* Set up a loop over the rowids/primary-keys that were found in the
  93429. ** where-clause loop above.
  93430. */
  93431. if( eOnePass!=ONEPASS_OFF ){
  93432. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  93433. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  93434. assert( pPk!=0 || pTab->pSelect!=0 );
  93435. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  93436. VdbeCoverage(v);
  93437. }
  93438. }else if( pPk ){
  93439. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  93440. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  93441. assert( nKey==0 ); /* OP_Found will use a composite key */
  93442. }else{
  93443. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  93444. VdbeCoverage(v);
  93445. assert( nKey==1 );
  93446. }
  93447. /* Delete the row */
  93448. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93449. if( IsVirtual(pTab) ){
  93450. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  93451. sqlite3VtabMakeWritable(pParse, pTab);
  93452. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  93453. sqlite3VdbeChangeP5(v, OE_Abort);
  93454. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  93455. sqlite3MayAbort(pParse);
  93456. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  93457. pParse->isMultiWrite = 0;
  93458. }
  93459. }else
  93460. #endif
  93461. {
  93462. int count = (pParse->nested==0); /* True to count changes */
  93463. int iIdxNoSeek = -1;
  93464. if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
  93465. iIdxNoSeek = aiCurOnePass[1];
  93466. }
  93467. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  93468. iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
  93469. }
  93470. /* End of the loop over all rowids/primary-keys. */
  93471. if( eOnePass!=ONEPASS_OFF ){
  93472. sqlite3VdbeResolveLabel(v, addrBypass);
  93473. sqlite3WhereEnd(pWInfo);
  93474. }else if( pPk ){
  93475. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  93476. sqlite3VdbeJumpHere(v, addrLoop);
  93477. }else{
  93478. sqlite3VdbeGoto(v, addrLoop);
  93479. sqlite3VdbeJumpHere(v, addrLoop);
  93480. }
  93481. /* Close the cursors open on the table and its indexes. */
  93482. if( !isView && !IsVirtual(pTab) ){
  93483. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  93484. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  93485. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  93486. }
  93487. }
  93488. } /* End non-truncate path */
  93489. /* Update the sqlite_sequence table by storing the content of the
  93490. ** maximum rowid counter values recorded while inserting into
  93491. ** autoincrement tables.
  93492. */
  93493. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  93494. sqlite3AutoincrementEnd(pParse);
  93495. }
  93496. /* Return the number of rows that were deleted. If this routine is
  93497. ** generating code because of a call to sqlite3NestedParse(), do not
  93498. ** invoke the callback function.
  93499. */
  93500. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  93501. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  93502. sqlite3VdbeSetNumCols(v, 1);
  93503. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  93504. }
  93505. delete_from_cleanup:
  93506. sqlite3AuthContextPop(&sContext);
  93507. sqlite3SrcListDelete(db, pTabList);
  93508. sqlite3ExprDelete(db, pWhere);
  93509. sqlite3DbFree(db, aToOpen);
  93510. return;
  93511. }
  93512. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  93513. ** they may interfere with compilation of other functions in this file
  93514. ** (or in another file, if this file becomes part of the amalgamation). */
  93515. #ifdef isView
  93516. #undef isView
  93517. #endif
  93518. #ifdef pTrigger
  93519. #undef pTrigger
  93520. #endif
  93521. /*
  93522. ** This routine generates VDBE code that causes a single row of a
  93523. ** single table to be deleted. Both the original table entry and
  93524. ** all indices are removed.
  93525. **
  93526. ** Preconditions:
  93527. **
  93528. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  93529. ** store for the table. (This will be either the table itself,
  93530. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  93531. ** of a WITHOUT ROWID table.)
  93532. **
  93533. ** 2. Read/write cursors for all indices of pTab must be open as
  93534. ** cursor number iIdxCur+i for the i-th index.
  93535. **
  93536. ** 3. The primary key for the row to be deleted must be stored in a
  93537. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  93538. ** that a search record formed from OP_MakeRecord is contained in the
  93539. ** single memory location iPk.
  93540. **
  93541. ** eMode:
  93542. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  93543. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  93544. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  93545. ** then this function must seek iDataCur to the entry identified by iPk
  93546. ** and nPk before reading from it.
  93547. **
  93548. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  93549. ** of a ONEPASS delete that affects multiple rows. In this case, if
  93550. ** iIdxNoSeek is a valid cursor number (>=0), then its position should
  93551. ** be preserved following the delete operation. Or, if iIdxNoSeek is not
  93552. ** a valid cursor number, the position of iDataCur should be preserved
  93553. ** instead.
  93554. **
  93555. ** iIdxNoSeek:
  93556. ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
  93557. ** index cursor (from within array of cursors starting at iIdxCur) that
  93558. ** already points to the index entry to be deleted.
  93559. */
  93560. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  93561. Parse *pParse, /* Parsing context */
  93562. Table *pTab, /* Table containing the row to be deleted */
  93563. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  93564. int iDataCur, /* Cursor from which column data is extracted */
  93565. int iIdxCur, /* First index cursor */
  93566. int iPk, /* First memory cell containing the PRIMARY KEY */
  93567. i16 nPk, /* Number of PRIMARY KEY memory cells */
  93568. u8 count, /* If non-zero, increment the row change counter */
  93569. u8 onconf, /* Default ON CONFLICT policy for triggers */
  93570. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  93571. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  93572. ){
  93573. Vdbe *v = pParse->pVdbe; /* Vdbe */
  93574. int iOld = 0; /* First register in OLD.* array */
  93575. int iLabel; /* Label resolved to end of generated code */
  93576. u8 opSeek; /* Seek opcode */
  93577. /* Vdbe is guaranteed to have been allocated by this stage. */
  93578. assert( v );
  93579. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  93580. iDataCur, iIdxCur, iPk, (int)nPk));
  93581. /* Seek cursor iCur to the row to delete. If this row no longer exists
  93582. ** (this can happen if a trigger program has already deleted it), do
  93583. ** not attempt to delete it or fire any DELETE triggers. */
  93584. iLabel = sqlite3VdbeMakeLabel(v);
  93585. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  93586. if( eMode==ONEPASS_OFF ){
  93587. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  93588. VdbeCoverageIf(v, opSeek==OP_NotExists);
  93589. VdbeCoverageIf(v, opSeek==OP_NotFound);
  93590. }
  93591. /* If there are any triggers to fire, allocate a range of registers to
  93592. ** use for the old.* references in the triggers. */
  93593. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  93594. u32 mask; /* Mask of OLD.* columns in use */
  93595. int iCol; /* Iterator used while populating OLD.* */
  93596. int addrStart; /* Start of BEFORE trigger programs */
  93597. /* TODO: Could use temporary registers here. Also could attempt to
  93598. ** avoid copying the contents of the rowid register. */
  93599. mask = sqlite3TriggerColmask(
  93600. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  93601. );
  93602. mask |= sqlite3FkOldmask(pParse, pTab);
  93603. iOld = pParse->nMem+1;
  93604. pParse->nMem += (1 + pTab->nCol);
  93605. /* Populate the OLD.* pseudo-table register array. These values will be
  93606. ** used by any BEFORE and AFTER triggers that exist. */
  93607. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  93608. for(iCol=0; iCol<pTab->nCol; iCol++){
  93609. testcase( mask!=0xffffffff && iCol==31 );
  93610. testcase( mask!=0xffffffff && iCol==32 );
  93611. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  93612. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  93613. }
  93614. }
  93615. /* Invoke BEFORE DELETE trigger programs. */
  93616. addrStart = sqlite3VdbeCurrentAddr(v);
  93617. sqlite3CodeRowTrigger(pParse, pTrigger,
  93618. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  93619. );
  93620. /* If any BEFORE triggers were coded, then seek the cursor to the
  93621. ** row to be deleted again. It may be that the BEFORE triggers moved
  93622. ** the cursor or of already deleted the row that the cursor was
  93623. ** pointing to.
  93624. */
  93625. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  93626. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  93627. VdbeCoverageIf(v, opSeek==OP_NotExists);
  93628. VdbeCoverageIf(v, opSeek==OP_NotFound);
  93629. }
  93630. /* Do FK processing. This call checks that any FK constraints that
  93631. ** refer to this table (i.e. constraints attached to other tables)
  93632. ** are not violated by deleting this row. */
  93633. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  93634. }
  93635. /* Delete the index and table entries. Skip this step if pTab is really
  93636. ** a view (in which case the only effect of the DELETE statement is to
  93637. ** fire the INSTEAD OF triggers). */
  93638. if( pTab->pSelect==0 ){
  93639. u8 p5 = 0;
  93640. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  93641. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  93642. if( count ){
  93643. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  93644. }
  93645. if( eMode!=ONEPASS_OFF ){
  93646. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  93647. }
  93648. if( iIdxNoSeek>=0 ){
  93649. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  93650. }
  93651. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  93652. sqlite3VdbeChangeP5(v, p5);
  93653. }
  93654. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  93655. ** handle rows (possibly in other tables) that refer via a foreign key
  93656. ** to the row just deleted. */
  93657. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  93658. /* Invoke AFTER DELETE trigger programs. */
  93659. sqlite3CodeRowTrigger(pParse, pTrigger,
  93660. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  93661. );
  93662. /* Jump here if the row had already been deleted before any BEFORE
  93663. ** trigger programs were invoked. Or if a trigger program throws a
  93664. ** RAISE(IGNORE) exception. */
  93665. sqlite3VdbeResolveLabel(v, iLabel);
  93666. VdbeModuleComment((v, "END: GenRowDel()"));
  93667. }
  93668. /*
  93669. ** This routine generates VDBE code that causes the deletion of all
  93670. ** index entries associated with a single row of a single table, pTab
  93671. **
  93672. ** Preconditions:
  93673. **
  93674. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  93675. ** btree for the table pTab. (This will be either the table itself
  93676. ** for rowid tables or to the primary key index for WITHOUT ROWID
  93677. ** tables.)
  93678. **
  93679. ** 2. Read/write cursors for all indices of pTab must be open as
  93680. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  93681. ** index is the 0-th index.)
  93682. **
  93683. ** 3. The "iDataCur" cursor must be already be positioned on the row
  93684. ** that is to be deleted.
  93685. */
  93686. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  93687. Parse *pParse, /* Parsing and code generating context */
  93688. Table *pTab, /* Table containing the row to be deleted */
  93689. int iDataCur, /* Cursor of table holding data. */
  93690. int iIdxCur, /* First index cursor */
  93691. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  93692. int iIdxNoSeek /* Do not delete from this cursor */
  93693. ){
  93694. int i; /* Index loop counter */
  93695. int r1 = -1; /* Register holding an index key */
  93696. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  93697. Index *pIdx; /* Current index */
  93698. Index *pPrior = 0; /* Prior index */
  93699. Vdbe *v; /* The prepared statement under construction */
  93700. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  93701. v = pParse->pVdbe;
  93702. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  93703. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  93704. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  93705. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  93706. if( pIdx==pPk ) continue;
  93707. if( iIdxCur+i==iIdxNoSeek ) continue;
  93708. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  93709. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  93710. &iPartIdxLabel, pPrior, r1);
  93711. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  93712. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  93713. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  93714. pPrior = pIdx;
  93715. }
  93716. }
  93717. /*
  93718. ** Generate code that will assemble an index key and stores it in register
  93719. ** regOut. The key with be for index pIdx which is an index on pTab.
  93720. ** iCur is the index of a cursor open on the pTab table and pointing to
  93721. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  93722. ** iCur must be the cursor of the PRIMARY KEY index.
  93723. **
  93724. ** Return a register number which is the first in a block of
  93725. ** registers that holds the elements of the index key. The
  93726. ** block of registers has already been deallocated by the time
  93727. ** this routine returns.
  93728. **
  93729. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  93730. ** to that label if pIdx is a partial index that should be skipped.
  93731. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  93732. ** A partial index should be skipped if its WHERE clause evaluates
  93733. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  93734. ** will be set to zero which is an empty label that is ignored by
  93735. ** sqlite3ResolvePartIdxLabel().
  93736. **
  93737. ** The pPrior and regPrior parameters are used to implement a cache to
  93738. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  93739. ** a pointer to a different index for which an index key has just been
  93740. ** computed into register regPrior. If the current pIdx index is generating
  93741. ** its key into the same sequence of registers and if pPrior and pIdx share
  93742. ** a column in common, then the register corresponding to that column already
  93743. ** holds the correct value and the loading of that register is skipped.
  93744. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  93745. ** on a table with multiple indices, and especially with the ROWID or
  93746. ** PRIMARY KEY columns of the index.
  93747. */
  93748. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  93749. Parse *pParse, /* Parsing context */
  93750. Index *pIdx, /* The index for which to generate a key */
  93751. int iDataCur, /* Cursor number from which to take column data */
  93752. int regOut, /* Put the new key into this register if not 0 */
  93753. int prefixOnly, /* Compute only a unique prefix of the key */
  93754. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  93755. Index *pPrior, /* Previously generated index key */
  93756. int regPrior /* Register holding previous generated key */
  93757. ){
  93758. Vdbe *v = pParse->pVdbe;
  93759. int j;
  93760. int regBase;
  93761. int nCol;
  93762. if( piPartIdxLabel ){
  93763. if( pIdx->pPartIdxWhere ){
  93764. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  93765. pParse->iSelfTab = iDataCur;
  93766. sqlite3ExprCachePush(pParse);
  93767. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  93768. SQLITE_JUMPIFNULL);
  93769. }else{
  93770. *piPartIdxLabel = 0;
  93771. }
  93772. }
  93773. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  93774. regBase = sqlite3GetTempRange(pParse, nCol);
  93775. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  93776. for(j=0; j<nCol; j++){
  93777. if( pPrior
  93778. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  93779. && pPrior->aiColumn[j]!=XN_EXPR
  93780. ){
  93781. /* This column was already computed by the previous index */
  93782. continue;
  93783. }
  93784. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  93785. /* If the column affinity is REAL but the number is an integer, then it
  93786. ** might be stored in the table as an integer (using a compact
  93787. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  93788. ** But we are getting ready to store this value back into an index, where
  93789. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  93790. ** opcode if it is present */
  93791. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  93792. }
  93793. if( regOut ){
  93794. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  93795. }
  93796. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  93797. return regBase;
  93798. }
  93799. /*
  93800. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  93801. ** because it was a partial index, then this routine should be called to
  93802. ** resolve that label.
  93803. */
  93804. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  93805. if( iLabel ){
  93806. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  93807. sqlite3ExprCachePop(pParse);
  93808. }
  93809. }
  93810. /************** End of delete.c **********************************************/
  93811. /************** Begin file func.c ********************************************/
  93812. /*
  93813. ** 2002 February 23
  93814. **
  93815. ** The author disclaims copyright to this source code. In place of
  93816. ** a legal notice, here is a blessing:
  93817. **
  93818. ** May you do good and not evil.
  93819. ** May you find forgiveness for yourself and forgive others.
  93820. ** May you share freely, never taking more than you give.
  93821. **
  93822. *************************************************************************
  93823. ** This file contains the C-language implementations for many of the SQL
  93824. ** functions of SQLite. (Some function, and in particular the date and
  93825. ** time functions, are implemented separately.)
  93826. */
  93827. /* #include "sqliteInt.h" */
  93828. /* #include <stdlib.h> */
  93829. /* #include <assert.h> */
  93830. /* #include "vdbeInt.h" */
  93831. /*
  93832. ** Return the collating function associated with a function.
  93833. */
  93834. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  93835. VdbeOp *pOp;
  93836. assert( context->pVdbe!=0 );
  93837. pOp = &context->pVdbe->aOp[context->iOp-1];
  93838. assert( pOp->opcode==OP_CollSeq );
  93839. assert( pOp->p4type==P4_COLLSEQ );
  93840. return pOp->p4.pColl;
  93841. }
  93842. /*
  93843. ** Indicate that the accumulator load should be skipped on this
  93844. ** iteration of the aggregate loop.
  93845. */
  93846. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  93847. context->skipFlag = 1;
  93848. }
  93849. /*
  93850. ** Implementation of the non-aggregate min() and max() functions
  93851. */
  93852. static void minmaxFunc(
  93853. sqlite3_context *context,
  93854. int argc,
  93855. sqlite3_value **argv
  93856. ){
  93857. int i;
  93858. int mask; /* 0 for min() or 0xffffffff for max() */
  93859. int iBest;
  93860. CollSeq *pColl;
  93861. assert( argc>1 );
  93862. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  93863. pColl = sqlite3GetFuncCollSeq(context);
  93864. assert( pColl );
  93865. assert( mask==-1 || mask==0 );
  93866. iBest = 0;
  93867. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  93868. for(i=1; i<argc; i++){
  93869. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  93870. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  93871. testcase( mask==0 );
  93872. iBest = i;
  93873. }
  93874. }
  93875. sqlite3_result_value(context, argv[iBest]);
  93876. }
  93877. /*
  93878. ** Return the type of the argument.
  93879. */
  93880. static void typeofFunc(
  93881. sqlite3_context *context,
  93882. int NotUsed,
  93883. sqlite3_value **argv
  93884. ){
  93885. const char *z = 0;
  93886. UNUSED_PARAMETER(NotUsed);
  93887. switch( sqlite3_value_type(argv[0]) ){
  93888. case SQLITE_INTEGER: z = "integer"; break;
  93889. case SQLITE_TEXT: z = "text"; break;
  93890. case SQLITE_FLOAT: z = "real"; break;
  93891. case SQLITE_BLOB: z = "blob"; break;
  93892. default: z = "null"; break;
  93893. }
  93894. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  93895. }
  93896. /*
  93897. ** Implementation of the length() function
  93898. */
  93899. static void lengthFunc(
  93900. sqlite3_context *context,
  93901. int argc,
  93902. sqlite3_value **argv
  93903. ){
  93904. int len;
  93905. assert( argc==1 );
  93906. UNUSED_PARAMETER(argc);
  93907. switch( sqlite3_value_type(argv[0]) ){
  93908. case SQLITE_BLOB:
  93909. case SQLITE_INTEGER:
  93910. case SQLITE_FLOAT: {
  93911. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  93912. break;
  93913. }
  93914. case SQLITE_TEXT: {
  93915. const unsigned char *z = sqlite3_value_text(argv[0]);
  93916. if( z==0 ) return;
  93917. len = 0;
  93918. while( *z ){
  93919. len++;
  93920. SQLITE_SKIP_UTF8(z);
  93921. }
  93922. sqlite3_result_int(context, len);
  93923. break;
  93924. }
  93925. default: {
  93926. sqlite3_result_null(context);
  93927. break;
  93928. }
  93929. }
  93930. }
  93931. /*
  93932. ** Implementation of the abs() function.
  93933. **
  93934. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  93935. ** the numeric argument X.
  93936. */
  93937. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  93938. assert( argc==1 );
  93939. UNUSED_PARAMETER(argc);
  93940. switch( sqlite3_value_type(argv[0]) ){
  93941. case SQLITE_INTEGER: {
  93942. i64 iVal = sqlite3_value_int64(argv[0]);
  93943. if( iVal<0 ){
  93944. if( iVal==SMALLEST_INT64 ){
  93945. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  93946. ** then abs(X) throws an integer overflow error since there is no
  93947. ** equivalent positive 64-bit two complement value. */
  93948. sqlite3_result_error(context, "integer overflow", -1);
  93949. return;
  93950. }
  93951. iVal = -iVal;
  93952. }
  93953. sqlite3_result_int64(context, iVal);
  93954. break;
  93955. }
  93956. case SQLITE_NULL: {
  93957. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  93958. sqlite3_result_null(context);
  93959. break;
  93960. }
  93961. default: {
  93962. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  93963. ** something that can be converted into a number, we have:
  93964. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  93965. ** that cannot be converted to a numeric value.
  93966. */
  93967. double rVal = sqlite3_value_double(argv[0]);
  93968. if( rVal<0 ) rVal = -rVal;
  93969. sqlite3_result_double(context, rVal);
  93970. break;
  93971. }
  93972. }
  93973. }
  93974. /*
  93975. ** Implementation of the instr() function.
  93976. **
  93977. ** instr(haystack,needle) finds the first occurrence of needle
  93978. ** in haystack and returns the number of previous characters plus 1,
  93979. ** or 0 if needle does not occur within haystack.
  93980. **
  93981. ** If both haystack and needle are BLOBs, then the result is one more than
  93982. ** the number of bytes in haystack prior to the first occurrence of needle,
  93983. ** or 0 if needle never occurs in haystack.
  93984. */
  93985. static void instrFunc(
  93986. sqlite3_context *context,
  93987. int argc,
  93988. sqlite3_value **argv
  93989. ){
  93990. const unsigned char *zHaystack;
  93991. const unsigned char *zNeedle;
  93992. int nHaystack;
  93993. int nNeedle;
  93994. int typeHaystack, typeNeedle;
  93995. int N = 1;
  93996. int isText;
  93997. UNUSED_PARAMETER(argc);
  93998. typeHaystack = sqlite3_value_type(argv[0]);
  93999. typeNeedle = sqlite3_value_type(argv[1]);
  94000. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  94001. nHaystack = sqlite3_value_bytes(argv[0]);
  94002. nNeedle = sqlite3_value_bytes(argv[1]);
  94003. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  94004. zHaystack = sqlite3_value_blob(argv[0]);
  94005. zNeedle = sqlite3_value_blob(argv[1]);
  94006. isText = 0;
  94007. }else{
  94008. zHaystack = sqlite3_value_text(argv[0]);
  94009. zNeedle = sqlite3_value_text(argv[1]);
  94010. isText = 1;
  94011. }
  94012. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  94013. N++;
  94014. do{
  94015. nHaystack--;
  94016. zHaystack++;
  94017. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  94018. }
  94019. if( nNeedle>nHaystack ) N = 0;
  94020. sqlite3_result_int(context, N);
  94021. }
  94022. /*
  94023. ** Implementation of the printf() function.
  94024. */
  94025. static void printfFunc(
  94026. sqlite3_context *context,
  94027. int argc,
  94028. sqlite3_value **argv
  94029. ){
  94030. PrintfArguments x;
  94031. StrAccum str;
  94032. const char *zFormat;
  94033. int n;
  94034. sqlite3 *db = sqlite3_context_db_handle(context);
  94035. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  94036. x.nArg = argc-1;
  94037. x.nUsed = 0;
  94038. x.apArg = argv+1;
  94039. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  94040. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  94041. sqlite3XPrintf(&str, zFormat, &x);
  94042. n = str.nChar;
  94043. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  94044. SQLITE_DYNAMIC);
  94045. }
  94046. }
  94047. /*
  94048. ** Implementation of the substr() function.
  94049. **
  94050. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  94051. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  94052. ** of x. If x is text, then we actually count UTF-8 characters.
  94053. ** If x is a blob, then we count bytes.
  94054. **
  94055. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  94056. **
  94057. ** If p2 is negative, return the p2 characters preceding p1.
  94058. */
  94059. static void substrFunc(
  94060. sqlite3_context *context,
  94061. int argc,
  94062. sqlite3_value **argv
  94063. ){
  94064. const unsigned char *z;
  94065. const unsigned char *z2;
  94066. int len;
  94067. int p0type;
  94068. i64 p1, p2;
  94069. int negP2 = 0;
  94070. assert( argc==3 || argc==2 );
  94071. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  94072. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  94073. ){
  94074. return;
  94075. }
  94076. p0type = sqlite3_value_type(argv[0]);
  94077. p1 = sqlite3_value_int(argv[1]);
  94078. if( p0type==SQLITE_BLOB ){
  94079. len = sqlite3_value_bytes(argv[0]);
  94080. z = sqlite3_value_blob(argv[0]);
  94081. if( z==0 ) return;
  94082. assert( len==sqlite3_value_bytes(argv[0]) );
  94083. }else{
  94084. z = sqlite3_value_text(argv[0]);
  94085. if( z==0 ) return;
  94086. len = 0;
  94087. if( p1<0 ){
  94088. for(z2=z; *z2; len++){
  94089. SQLITE_SKIP_UTF8(z2);
  94090. }
  94091. }
  94092. }
  94093. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  94094. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  94095. ** as substr(X,1,N) - it returns the first N characters of X. This
  94096. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  94097. ** from 2009-02-02 for compatibility of applications that exploited the
  94098. ** old buggy behavior. */
  94099. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  94100. #endif
  94101. if( argc==3 ){
  94102. p2 = sqlite3_value_int(argv[2]);
  94103. if( p2<0 ){
  94104. p2 = -p2;
  94105. negP2 = 1;
  94106. }
  94107. }else{
  94108. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  94109. }
  94110. if( p1<0 ){
  94111. p1 += len;
  94112. if( p1<0 ){
  94113. p2 += p1;
  94114. if( p2<0 ) p2 = 0;
  94115. p1 = 0;
  94116. }
  94117. }else if( p1>0 ){
  94118. p1--;
  94119. }else if( p2>0 ){
  94120. p2--;
  94121. }
  94122. if( negP2 ){
  94123. p1 -= p2;
  94124. if( p1<0 ){
  94125. p2 += p1;
  94126. p1 = 0;
  94127. }
  94128. }
  94129. assert( p1>=0 && p2>=0 );
  94130. if( p0type!=SQLITE_BLOB ){
  94131. while( *z && p1 ){
  94132. SQLITE_SKIP_UTF8(z);
  94133. p1--;
  94134. }
  94135. for(z2=z; *z2 && p2; p2--){
  94136. SQLITE_SKIP_UTF8(z2);
  94137. }
  94138. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  94139. SQLITE_UTF8);
  94140. }else{
  94141. if( p1+p2>len ){
  94142. p2 = len-p1;
  94143. if( p2<0 ) p2 = 0;
  94144. }
  94145. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  94146. }
  94147. }
  94148. /*
  94149. ** Implementation of the round() function
  94150. */
  94151. #ifndef SQLITE_OMIT_FLOATING_POINT
  94152. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  94153. int n = 0;
  94154. double r;
  94155. char *zBuf;
  94156. assert( argc==1 || argc==2 );
  94157. if( argc==2 ){
  94158. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  94159. n = sqlite3_value_int(argv[1]);
  94160. if( n>30 ) n = 30;
  94161. if( n<0 ) n = 0;
  94162. }
  94163. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  94164. r = sqlite3_value_double(argv[0]);
  94165. /* If Y==0 and X will fit in a 64-bit int,
  94166. ** handle the rounding directly,
  94167. ** otherwise use printf.
  94168. */
  94169. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  94170. r = (double)((sqlite_int64)(r+0.5));
  94171. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  94172. r = -(double)((sqlite_int64)((-r)+0.5));
  94173. }else{
  94174. zBuf = sqlite3_mprintf("%.*f",n,r);
  94175. if( zBuf==0 ){
  94176. sqlite3_result_error_nomem(context);
  94177. return;
  94178. }
  94179. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  94180. sqlite3_free(zBuf);
  94181. }
  94182. sqlite3_result_double(context, r);
  94183. }
  94184. #endif
  94185. /*
  94186. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  94187. ** allocation fails, call sqlite3_result_error_nomem() to notify
  94188. ** the database handle that malloc() has failed and return NULL.
  94189. ** If nByte is larger than the maximum string or blob length, then
  94190. ** raise an SQLITE_TOOBIG exception and return NULL.
  94191. */
  94192. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  94193. char *z;
  94194. sqlite3 *db = sqlite3_context_db_handle(context);
  94195. assert( nByte>0 );
  94196. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  94197. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  94198. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  94199. sqlite3_result_error_toobig(context);
  94200. z = 0;
  94201. }else{
  94202. z = sqlite3Malloc(nByte);
  94203. if( !z ){
  94204. sqlite3_result_error_nomem(context);
  94205. }
  94206. }
  94207. return z;
  94208. }
  94209. /*
  94210. ** Implementation of the upper() and lower() SQL functions.
  94211. */
  94212. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  94213. char *z1;
  94214. const char *z2;
  94215. int i, n;
  94216. UNUSED_PARAMETER(argc);
  94217. z2 = (char*)sqlite3_value_text(argv[0]);
  94218. n = sqlite3_value_bytes(argv[0]);
  94219. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  94220. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  94221. if( z2 ){
  94222. z1 = contextMalloc(context, ((i64)n)+1);
  94223. if( z1 ){
  94224. for(i=0; i<n; i++){
  94225. z1[i] = (char)sqlite3Toupper(z2[i]);
  94226. }
  94227. sqlite3_result_text(context, z1, n, sqlite3_free);
  94228. }
  94229. }
  94230. }
  94231. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  94232. char *z1;
  94233. const char *z2;
  94234. int i, n;
  94235. UNUSED_PARAMETER(argc);
  94236. z2 = (char*)sqlite3_value_text(argv[0]);
  94237. n = sqlite3_value_bytes(argv[0]);
  94238. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  94239. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  94240. if( z2 ){
  94241. z1 = contextMalloc(context, ((i64)n)+1);
  94242. if( z1 ){
  94243. for(i=0; i<n; i++){
  94244. z1[i] = sqlite3Tolower(z2[i]);
  94245. }
  94246. sqlite3_result_text(context, z1, n, sqlite3_free);
  94247. }
  94248. }
  94249. }
  94250. /*
  94251. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  94252. ** as VDBE code so that unused argument values do not have to be computed.
  94253. ** However, we still need some kind of function implementation for this
  94254. ** routines in the function table. The noopFunc macro provides this.
  94255. ** noopFunc will never be called so it doesn't matter what the implementation
  94256. ** is. We might as well use the "version()" function as a substitute.
  94257. */
  94258. #define noopFunc versionFunc /* Substitute function - never called */
  94259. /*
  94260. ** Implementation of random(). Return a random integer.
  94261. */
  94262. static void randomFunc(
  94263. sqlite3_context *context,
  94264. int NotUsed,
  94265. sqlite3_value **NotUsed2
  94266. ){
  94267. sqlite_int64 r;
  94268. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  94269. sqlite3_randomness(sizeof(r), &r);
  94270. if( r<0 ){
  94271. /* We need to prevent a random number of 0x8000000000000000
  94272. ** (or -9223372036854775808) since when you do abs() of that
  94273. ** number of you get the same value back again. To do this
  94274. ** in a way that is testable, mask the sign bit off of negative
  94275. ** values, resulting in a positive value. Then take the
  94276. ** 2s complement of that positive value. The end result can
  94277. ** therefore be no less than -9223372036854775807.
  94278. */
  94279. r = -(r & LARGEST_INT64);
  94280. }
  94281. sqlite3_result_int64(context, r);
  94282. }
  94283. /*
  94284. ** Implementation of randomblob(N). Return a random blob
  94285. ** that is N bytes long.
  94286. */
  94287. static void randomBlob(
  94288. sqlite3_context *context,
  94289. int argc,
  94290. sqlite3_value **argv
  94291. ){
  94292. int n;
  94293. unsigned char *p;
  94294. assert( argc==1 );
  94295. UNUSED_PARAMETER(argc);
  94296. n = sqlite3_value_int(argv[0]);
  94297. if( n<1 ){
  94298. n = 1;
  94299. }
  94300. p = contextMalloc(context, n);
  94301. if( p ){
  94302. sqlite3_randomness(n, p);
  94303. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  94304. }
  94305. }
  94306. /*
  94307. ** Implementation of the last_insert_rowid() SQL function. The return
  94308. ** value is the same as the sqlite3_last_insert_rowid() API function.
  94309. */
  94310. static void last_insert_rowid(
  94311. sqlite3_context *context,
  94312. int NotUsed,
  94313. sqlite3_value **NotUsed2
  94314. ){
  94315. sqlite3 *db = sqlite3_context_db_handle(context);
  94316. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  94317. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  94318. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  94319. ** function. */
  94320. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  94321. }
  94322. /*
  94323. ** Implementation of the changes() SQL function.
  94324. **
  94325. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  94326. ** around the sqlite3_changes() C/C++ function and hence follows the same
  94327. ** rules for counting changes.
  94328. */
  94329. static void changes(
  94330. sqlite3_context *context,
  94331. int NotUsed,
  94332. sqlite3_value **NotUsed2
  94333. ){
  94334. sqlite3 *db = sqlite3_context_db_handle(context);
  94335. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  94336. sqlite3_result_int(context, sqlite3_changes(db));
  94337. }
  94338. /*
  94339. ** Implementation of the total_changes() SQL function. The return value is
  94340. ** the same as the sqlite3_total_changes() API function.
  94341. */
  94342. static void total_changes(
  94343. sqlite3_context *context,
  94344. int NotUsed,
  94345. sqlite3_value **NotUsed2
  94346. ){
  94347. sqlite3 *db = sqlite3_context_db_handle(context);
  94348. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  94349. /* IMP: R-52756-41993 This function is a wrapper around the
  94350. ** sqlite3_total_changes() C/C++ interface. */
  94351. sqlite3_result_int(context, sqlite3_total_changes(db));
  94352. }
  94353. /*
  94354. ** A structure defining how to do GLOB-style comparisons.
  94355. */
  94356. struct compareInfo {
  94357. u8 matchAll; /* "*" or "%" */
  94358. u8 matchOne; /* "?" or "_" */
  94359. u8 matchSet; /* "[" or 0 */
  94360. u8 noCase; /* true to ignore case differences */
  94361. };
  94362. /*
  94363. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  94364. ** character is exactly one byte in size. Also, provde the Utf8Read()
  94365. ** macro for fast reading of the next character in the common case where
  94366. ** the next character is ASCII.
  94367. */
  94368. #if defined(SQLITE_EBCDIC)
  94369. # define sqlite3Utf8Read(A) (*((*A)++))
  94370. # define Utf8Read(A) (*(A++))
  94371. #else
  94372. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  94373. #endif
  94374. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  94375. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  94376. ** case. Thus 'a' LIKE 'A' would be true. */
  94377. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  94378. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  94379. ** is case sensitive causing 'a' LIKE 'A' to be false */
  94380. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  94381. /*
  94382. ** Compare two UTF-8 strings for equality where the first string can
  94383. ** potentially be a "glob" or "like" expression. Return true (1) if they
  94384. ** are the same and false (0) if they are different.
  94385. **
  94386. ** Globbing rules:
  94387. **
  94388. ** '*' Matches any sequence of zero or more characters.
  94389. **
  94390. ** '?' Matches exactly one character.
  94391. **
  94392. ** [...] Matches one character from the enclosed list of
  94393. ** characters.
  94394. **
  94395. ** [^...] Matches one character not in the enclosed list.
  94396. **
  94397. ** With the [...] and [^...] matching, a ']' character can be included
  94398. ** in the list by making it the first character after '[' or '^'. A
  94399. ** range of characters can be specified using '-'. Example:
  94400. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  94401. ** it the last character in the list.
  94402. **
  94403. ** Like matching rules:
  94404. **
  94405. ** '%' Matches any sequence of zero or more characters
  94406. **
  94407. *** '_' Matches any one character
  94408. **
  94409. ** Ec Where E is the "esc" character and c is any other
  94410. ** character, including '%', '_', and esc, match exactly c.
  94411. **
  94412. ** The comments within this routine usually assume glob matching.
  94413. **
  94414. ** This routine is usually quick, but can be N**2 in the worst case.
  94415. */
  94416. static int patternCompare(
  94417. const u8 *zPattern, /* The glob pattern */
  94418. const u8 *zString, /* The string to compare against the glob */
  94419. const struct compareInfo *pInfo, /* Information about how to do the compare */
  94420. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  94421. ){
  94422. u32 c, c2; /* Next pattern and input string chars */
  94423. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  94424. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  94425. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  94426. const u8 *zEscaped = 0; /* One past the last escaped input char */
  94427. while( (c = Utf8Read(zPattern))!=0 ){
  94428. if( c==matchAll ){ /* Match "*" */
  94429. /* Skip over multiple "*" characters in the pattern. If there
  94430. ** are also "?" characters, skip those as well, but consume a
  94431. ** single character of the input string for each "?" skipped */
  94432. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  94433. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  94434. return 0;
  94435. }
  94436. }
  94437. if( c==0 ){
  94438. return 1; /* "*" at the end of the pattern matches */
  94439. }else if( c==matchOther ){
  94440. if( pInfo->matchSet==0 ){
  94441. c = sqlite3Utf8Read(&zPattern);
  94442. if( c==0 ) return 0;
  94443. }else{
  94444. /* "[...]" immediately follows the "*". We have to do a slow
  94445. ** recursive search in this case, but it is an unusual case. */
  94446. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  94447. while( *zString
  94448. && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
  94449. SQLITE_SKIP_UTF8(zString);
  94450. }
  94451. return *zString!=0;
  94452. }
  94453. }
  94454. /* At this point variable c contains the first character of the
  94455. ** pattern string past the "*". Search in the input string for the
  94456. ** first matching character and recursively contine the match from
  94457. ** that point.
  94458. **
  94459. ** For a case-insensitive search, set variable cx to be the same as
  94460. ** c but in the other case and search the input string for either
  94461. ** c or cx.
  94462. */
  94463. if( c<=0x80 ){
  94464. u32 cx;
  94465. if( noCase ){
  94466. cx = sqlite3Toupper(c);
  94467. c = sqlite3Tolower(c);
  94468. }else{
  94469. cx = c;
  94470. }
  94471. while( (c2 = *(zString++))!=0 ){
  94472. if( c2!=c && c2!=cx ) continue;
  94473. if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
  94474. }
  94475. }else{
  94476. while( (c2 = Utf8Read(zString))!=0 ){
  94477. if( c2!=c ) continue;
  94478. if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
  94479. }
  94480. }
  94481. return 0;
  94482. }
  94483. if( c==matchOther ){
  94484. if( pInfo->matchSet==0 ){
  94485. c = sqlite3Utf8Read(&zPattern);
  94486. if( c==0 ) return 0;
  94487. zEscaped = zPattern;
  94488. }else{
  94489. u32 prior_c = 0;
  94490. int seen = 0;
  94491. int invert = 0;
  94492. c = sqlite3Utf8Read(&zString);
  94493. if( c==0 ) return 0;
  94494. c2 = sqlite3Utf8Read(&zPattern);
  94495. if( c2=='^' ){
  94496. invert = 1;
  94497. c2 = sqlite3Utf8Read(&zPattern);
  94498. }
  94499. if( c2==']' ){
  94500. if( c==']' ) seen = 1;
  94501. c2 = sqlite3Utf8Read(&zPattern);
  94502. }
  94503. while( c2 && c2!=']' ){
  94504. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  94505. c2 = sqlite3Utf8Read(&zPattern);
  94506. if( c>=prior_c && c<=c2 ) seen = 1;
  94507. prior_c = 0;
  94508. }else{
  94509. if( c==c2 ){
  94510. seen = 1;
  94511. }
  94512. prior_c = c2;
  94513. }
  94514. c2 = sqlite3Utf8Read(&zPattern);
  94515. }
  94516. if( c2==0 || (seen ^ invert)==0 ){
  94517. return 0;
  94518. }
  94519. continue;
  94520. }
  94521. }
  94522. c2 = Utf8Read(zString);
  94523. if( c==c2 ) continue;
  94524. if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  94525. continue;
  94526. }
  94527. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  94528. return 0;
  94529. }
  94530. return *zString==0;
  94531. }
  94532. /*
  94533. ** The sqlite3_strglob() interface.
  94534. */
  94535. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
  94536. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
  94537. }
  94538. /*
  94539. ** The sqlite3_strlike() interface.
  94540. */
  94541. SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  94542. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
  94543. }
  94544. /*
  94545. ** Count the number of times that the LIKE operator (or GLOB which is
  94546. ** just a variation of LIKE) gets called. This is used for testing
  94547. ** only.
  94548. */
  94549. #ifdef SQLITE_TEST
  94550. SQLITE_API int sqlite3_like_count = 0;
  94551. #endif
  94552. /*
  94553. ** Implementation of the like() SQL function. This function implements
  94554. ** the build-in LIKE operator. The first argument to the function is the
  94555. ** pattern and the second argument is the string. So, the SQL statements:
  94556. **
  94557. ** A LIKE B
  94558. **
  94559. ** is implemented as like(B,A).
  94560. **
  94561. ** This same function (with a different compareInfo structure) computes
  94562. ** the GLOB operator.
  94563. */
  94564. static void likeFunc(
  94565. sqlite3_context *context,
  94566. int argc,
  94567. sqlite3_value **argv
  94568. ){
  94569. const unsigned char *zA, *zB;
  94570. u32 escape;
  94571. int nPat;
  94572. sqlite3 *db = sqlite3_context_db_handle(context);
  94573. struct compareInfo *pInfo = sqlite3_user_data(context);
  94574. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  94575. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  94576. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  94577. ){
  94578. #ifdef SQLITE_TEST
  94579. sqlite3_like_count++;
  94580. #endif
  94581. sqlite3_result_int(context, 0);
  94582. return;
  94583. }
  94584. #endif
  94585. zB = sqlite3_value_text(argv[0]);
  94586. zA = sqlite3_value_text(argv[1]);
  94587. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  94588. ** of deep recursion and N*N behavior in patternCompare().
  94589. */
  94590. nPat = sqlite3_value_bytes(argv[0]);
  94591. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  94592. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  94593. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  94594. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  94595. return;
  94596. }
  94597. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  94598. if( argc==3 ){
  94599. /* The escape character string must consist of a single UTF-8 character.
  94600. ** Otherwise, return an error.
  94601. */
  94602. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  94603. if( zEsc==0 ) return;
  94604. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  94605. sqlite3_result_error(context,
  94606. "ESCAPE expression must be a single character", -1);
  94607. return;
  94608. }
  94609. escape = sqlite3Utf8Read(&zEsc);
  94610. }else{
  94611. escape = pInfo->matchSet;
  94612. }
  94613. if( zA && zB ){
  94614. #ifdef SQLITE_TEST
  94615. sqlite3_like_count++;
  94616. #endif
  94617. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  94618. }
  94619. }
  94620. /*
  94621. ** Implementation of the NULLIF(x,y) function. The result is the first
  94622. ** argument if the arguments are different. The result is NULL if the
  94623. ** arguments are equal to each other.
  94624. */
  94625. static void nullifFunc(
  94626. sqlite3_context *context,
  94627. int NotUsed,
  94628. sqlite3_value **argv
  94629. ){
  94630. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  94631. UNUSED_PARAMETER(NotUsed);
  94632. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  94633. sqlite3_result_value(context, argv[0]);
  94634. }
  94635. }
  94636. /*
  94637. ** Implementation of the sqlite_version() function. The result is the version
  94638. ** of the SQLite library that is running.
  94639. */
  94640. static void versionFunc(
  94641. sqlite3_context *context,
  94642. int NotUsed,
  94643. sqlite3_value **NotUsed2
  94644. ){
  94645. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  94646. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  94647. ** sqlite3_libversion() C-interface. */
  94648. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  94649. }
  94650. /*
  94651. ** Implementation of the sqlite_source_id() function. The result is a string
  94652. ** that identifies the particular version of the source code used to build
  94653. ** SQLite.
  94654. */
  94655. static void sourceidFunc(
  94656. sqlite3_context *context,
  94657. int NotUsed,
  94658. sqlite3_value **NotUsed2
  94659. ){
  94660. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  94661. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  94662. ** sqlite3_sourceid() C interface. */
  94663. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  94664. }
  94665. /*
  94666. ** Implementation of the sqlite_log() function. This is a wrapper around
  94667. ** sqlite3_log(). The return value is NULL. The function exists purely for
  94668. ** its side-effects.
  94669. */
  94670. static void errlogFunc(
  94671. sqlite3_context *context,
  94672. int argc,
  94673. sqlite3_value **argv
  94674. ){
  94675. UNUSED_PARAMETER(argc);
  94676. UNUSED_PARAMETER(context);
  94677. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  94678. }
  94679. /*
  94680. ** Implementation of the sqlite_compileoption_used() function.
  94681. ** The result is an integer that identifies if the compiler option
  94682. ** was used to build SQLite.
  94683. */
  94684. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  94685. static void compileoptionusedFunc(
  94686. sqlite3_context *context,
  94687. int argc,
  94688. sqlite3_value **argv
  94689. ){
  94690. const char *zOptName;
  94691. assert( argc==1 );
  94692. UNUSED_PARAMETER(argc);
  94693. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  94694. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  94695. ** function.
  94696. */
  94697. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  94698. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  94699. }
  94700. }
  94701. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  94702. /*
  94703. ** Implementation of the sqlite_compileoption_get() function.
  94704. ** The result is a string that identifies the compiler options
  94705. ** used to build SQLite.
  94706. */
  94707. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  94708. static void compileoptiongetFunc(
  94709. sqlite3_context *context,
  94710. int argc,
  94711. sqlite3_value **argv
  94712. ){
  94713. int n;
  94714. assert( argc==1 );
  94715. UNUSED_PARAMETER(argc);
  94716. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  94717. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  94718. */
  94719. n = sqlite3_value_int(argv[0]);
  94720. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  94721. }
  94722. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  94723. /* Array for converting from half-bytes (nybbles) into ASCII hex
  94724. ** digits. */
  94725. static const char hexdigits[] = {
  94726. '0', '1', '2', '3', '4', '5', '6', '7',
  94727. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  94728. };
  94729. /*
  94730. ** Implementation of the QUOTE() function. This function takes a single
  94731. ** argument. If the argument is numeric, the return value is the same as
  94732. ** the argument. If the argument is NULL, the return value is the string
  94733. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  94734. ** single-quote escapes.
  94735. */
  94736. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  94737. assert( argc==1 );
  94738. UNUSED_PARAMETER(argc);
  94739. switch( sqlite3_value_type(argv[0]) ){
  94740. case SQLITE_FLOAT: {
  94741. double r1, r2;
  94742. char zBuf[50];
  94743. r1 = sqlite3_value_double(argv[0]);
  94744. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  94745. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  94746. if( r1!=r2 ){
  94747. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  94748. }
  94749. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  94750. break;
  94751. }
  94752. case SQLITE_INTEGER: {
  94753. sqlite3_result_value(context, argv[0]);
  94754. break;
  94755. }
  94756. case SQLITE_BLOB: {
  94757. char *zText = 0;
  94758. char const *zBlob = sqlite3_value_blob(argv[0]);
  94759. int nBlob = sqlite3_value_bytes(argv[0]);
  94760. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  94761. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  94762. if( zText ){
  94763. int i;
  94764. for(i=0; i<nBlob; i++){
  94765. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  94766. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  94767. }
  94768. zText[(nBlob*2)+2] = '\'';
  94769. zText[(nBlob*2)+3] = '\0';
  94770. zText[0] = 'X';
  94771. zText[1] = '\'';
  94772. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  94773. sqlite3_free(zText);
  94774. }
  94775. break;
  94776. }
  94777. case SQLITE_TEXT: {
  94778. int i,j;
  94779. u64 n;
  94780. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  94781. char *z;
  94782. if( zArg==0 ) return;
  94783. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  94784. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  94785. if( z ){
  94786. z[0] = '\'';
  94787. for(i=0, j=1; zArg[i]; i++){
  94788. z[j++] = zArg[i];
  94789. if( zArg[i]=='\'' ){
  94790. z[j++] = '\'';
  94791. }
  94792. }
  94793. z[j++] = '\'';
  94794. z[j] = 0;
  94795. sqlite3_result_text(context, z, j, sqlite3_free);
  94796. }
  94797. break;
  94798. }
  94799. default: {
  94800. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  94801. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  94802. break;
  94803. }
  94804. }
  94805. }
  94806. /*
  94807. ** The unicode() function. Return the integer unicode code-point value
  94808. ** for the first character of the input string.
  94809. */
  94810. static void unicodeFunc(
  94811. sqlite3_context *context,
  94812. int argc,
  94813. sqlite3_value **argv
  94814. ){
  94815. const unsigned char *z = sqlite3_value_text(argv[0]);
  94816. (void)argc;
  94817. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  94818. }
  94819. /*
  94820. ** The char() function takes zero or more arguments, each of which is
  94821. ** an integer. It constructs a string where each character of the string
  94822. ** is the unicode character for the corresponding integer argument.
  94823. */
  94824. static void charFunc(
  94825. sqlite3_context *context,
  94826. int argc,
  94827. sqlite3_value **argv
  94828. ){
  94829. unsigned char *z, *zOut;
  94830. int i;
  94831. zOut = z = sqlite3_malloc64( argc*4+1 );
  94832. if( z==0 ){
  94833. sqlite3_result_error_nomem(context);
  94834. return;
  94835. }
  94836. for(i=0; i<argc; i++){
  94837. sqlite3_int64 x;
  94838. unsigned c;
  94839. x = sqlite3_value_int64(argv[i]);
  94840. if( x<0 || x>0x10ffff ) x = 0xfffd;
  94841. c = (unsigned)(x & 0x1fffff);
  94842. if( c<0x00080 ){
  94843. *zOut++ = (u8)(c&0xFF);
  94844. }else if( c<0x00800 ){
  94845. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  94846. *zOut++ = 0x80 + (u8)(c & 0x3F);
  94847. }else if( c<0x10000 ){
  94848. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  94849. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  94850. *zOut++ = 0x80 + (u8)(c & 0x3F);
  94851. }else{
  94852. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  94853. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  94854. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  94855. *zOut++ = 0x80 + (u8)(c & 0x3F);
  94856. } \
  94857. }
  94858. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  94859. }
  94860. /*
  94861. ** The hex() function. Interpret the argument as a blob. Return
  94862. ** a hexadecimal rendering as text.
  94863. */
  94864. static void hexFunc(
  94865. sqlite3_context *context,
  94866. int argc,
  94867. sqlite3_value **argv
  94868. ){
  94869. int i, n;
  94870. const unsigned char *pBlob;
  94871. char *zHex, *z;
  94872. assert( argc==1 );
  94873. UNUSED_PARAMETER(argc);
  94874. pBlob = sqlite3_value_blob(argv[0]);
  94875. n = sqlite3_value_bytes(argv[0]);
  94876. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  94877. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  94878. if( zHex ){
  94879. for(i=0; i<n; i++, pBlob++){
  94880. unsigned char c = *pBlob;
  94881. *(z++) = hexdigits[(c>>4)&0xf];
  94882. *(z++) = hexdigits[c&0xf];
  94883. }
  94884. *z = 0;
  94885. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  94886. }
  94887. }
  94888. /*
  94889. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  94890. */
  94891. static void zeroblobFunc(
  94892. sqlite3_context *context,
  94893. int argc,
  94894. sqlite3_value **argv
  94895. ){
  94896. i64 n;
  94897. int rc;
  94898. assert( argc==1 );
  94899. UNUSED_PARAMETER(argc);
  94900. n = sqlite3_value_int64(argv[0]);
  94901. if( n<0 ) n = 0;
  94902. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  94903. if( rc ){
  94904. sqlite3_result_error_code(context, rc);
  94905. }
  94906. }
  94907. /*
  94908. ** The replace() function. Three arguments are all strings: call
  94909. ** them A, B, and C. The result is also a string which is derived
  94910. ** from A by replacing every occurrence of B with C. The match
  94911. ** must be exact. Collating sequences are not used.
  94912. */
  94913. static void replaceFunc(
  94914. sqlite3_context *context,
  94915. int argc,
  94916. sqlite3_value **argv
  94917. ){
  94918. const unsigned char *zStr; /* The input string A */
  94919. const unsigned char *zPattern; /* The pattern string B */
  94920. const unsigned char *zRep; /* The replacement string C */
  94921. unsigned char *zOut; /* The output */
  94922. int nStr; /* Size of zStr */
  94923. int nPattern; /* Size of zPattern */
  94924. int nRep; /* Size of zRep */
  94925. i64 nOut; /* Maximum size of zOut */
  94926. int loopLimit; /* Last zStr[] that might match zPattern[] */
  94927. int i, j; /* Loop counters */
  94928. assert( argc==3 );
  94929. UNUSED_PARAMETER(argc);
  94930. zStr = sqlite3_value_text(argv[0]);
  94931. if( zStr==0 ) return;
  94932. nStr = sqlite3_value_bytes(argv[0]);
  94933. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  94934. zPattern = sqlite3_value_text(argv[1]);
  94935. if( zPattern==0 ){
  94936. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  94937. || sqlite3_context_db_handle(context)->mallocFailed );
  94938. return;
  94939. }
  94940. if( zPattern[0]==0 ){
  94941. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  94942. sqlite3_result_value(context, argv[0]);
  94943. return;
  94944. }
  94945. nPattern = sqlite3_value_bytes(argv[1]);
  94946. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  94947. zRep = sqlite3_value_text(argv[2]);
  94948. if( zRep==0 ) return;
  94949. nRep = sqlite3_value_bytes(argv[2]);
  94950. assert( zRep==sqlite3_value_text(argv[2]) );
  94951. nOut = nStr + 1;
  94952. assert( nOut<SQLITE_MAX_LENGTH );
  94953. zOut = contextMalloc(context, (i64)nOut);
  94954. if( zOut==0 ){
  94955. return;
  94956. }
  94957. loopLimit = nStr - nPattern;
  94958. for(i=j=0; i<=loopLimit; i++){
  94959. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  94960. zOut[j++] = zStr[i];
  94961. }else{
  94962. u8 *zOld;
  94963. sqlite3 *db = sqlite3_context_db_handle(context);
  94964. nOut += nRep - nPattern;
  94965. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  94966. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  94967. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  94968. sqlite3_result_error_toobig(context);
  94969. sqlite3_free(zOut);
  94970. return;
  94971. }
  94972. zOld = zOut;
  94973. zOut = sqlite3_realloc64(zOut, (int)nOut);
  94974. if( zOut==0 ){
  94975. sqlite3_result_error_nomem(context);
  94976. sqlite3_free(zOld);
  94977. return;
  94978. }
  94979. memcpy(&zOut[j], zRep, nRep);
  94980. j += nRep;
  94981. i += nPattern-1;
  94982. }
  94983. }
  94984. assert( j+nStr-i+1==nOut );
  94985. memcpy(&zOut[j], &zStr[i], nStr-i);
  94986. j += nStr - i;
  94987. assert( j<=nOut );
  94988. zOut[j] = 0;
  94989. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  94990. }
  94991. /*
  94992. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  94993. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  94994. */
  94995. static void trimFunc(
  94996. sqlite3_context *context,
  94997. int argc,
  94998. sqlite3_value **argv
  94999. ){
  95000. const unsigned char *zIn; /* Input string */
  95001. const unsigned char *zCharSet; /* Set of characters to trim */
  95002. int nIn; /* Number of bytes in input */
  95003. int flags; /* 1: trimleft 2: trimright 3: trim */
  95004. int i; /* Loop counter */
  95005. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  95006. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  95007. int nChar; /* Number of characters in zCharSet */
  95008. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  95009. return;
  95010. }
  95011. zIn = sqlite3_value_text(argv[0]);
  95012. if( zIn==0 ) return;
  95013. nIn = sqlite3_value_bytes(argv[0]);
  95014. assert( zIn==sqlite3_value_text(argv[0]) );
  95015. if( argc==1 ){
  95016. static const unsigned char lenOne[] = { 1 };
  95017. static unsigned char * const azOne[] = { (u8*)" " };
  95018. nChar = 1;
  95019. aLen = (u8*)lenOne;
  95020. azChar = (unsigned char **)azOne;
  95021. zCharSet = 0;
  95022. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  95023. return;
  95024. }else{
  95025. const unsigned char *z;
  95026. for(z=zCharSet, nChar=0; *z; nChar++){
  95027. SQLITE_SKIP_UTF8(z);
  95028. }
  95029. if( nChar>0 ){
  95030. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  95031. if( azChar==0 ){
  95032. return;
  95033. }
  95034. aLen = (unsigned char*)&azChar[nChar];
  95035. for(z=zCharSet, nChar=0; *z; nChar++){
  95036. azChar[nChar] = (unsigned char *)z;
  95037. SQLITE_SKIP_UTF8(z);
  95038. aLen[nChar] = (u8)(z - azChar[nChar]);
  95039. }
  95040. }
  95041. }
  95042. if( nChar>0 ){
  95043. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  95044. if( flags & 1 ){
  95045. while( nIn>0 ){
  95046. int len = 0;
  95047. for(i=0; i<nChar; i++){
  95048. len = aLen[i];
  95049. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  95050. }
  95051. if( i>=nChar ) break;
  95052. zIn += len;
  95053. nIn -= len;
  95054. }
  95055. }
  95056. if( flags & 2 ){
  95057. while( nIn>0 ){
  95058. int len = 0;
  95059. for(i=0; i<nChar; i++){
  95060. len = aLen[i];
  95061. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  95062. }
  95063. if( i>=nChar ) break;
  95064. nIn -= len;
  95065. }
  95066. }
  95067. if( zCharSet ){
  95068. sqlite3_free(azChar);
  95069. }
  95070. }
  95071. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  95072. }
  95073. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  95074. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  95075. ** when SQLite is built.
  95076. */
  95077. #ifdef SQLITE_SOUNDEX
  95078. /*
  95079. ** Compute the soundex encoding of a word.
  95080. **
  95081. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  95082. ** soundex encoding of the string X.
  95083. */
  95084. static void soundexFunc(
  95085. sqlite3_context *context,
  95086. int argc,
  95087. sqlite3_value **argv
  95088. ){
  95089. char zResult[8];
  95090. const u8 *zIn;
  95091. int i, j;
  95092. static const unsigned char iCode[] = {
  95093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  95094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  95095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  95096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  95097. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  95098. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  95099. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  95100. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  95101. };
  95102. assert( argc==1 );
  95103. zIn = (u8*)sqlite3_value_text(argv[0]);
  95104. if( zIn==0 ) zIn = (u8*)"";
  95105. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  95106. if( zIn[i] ){
  95107. u8 prevcode = iCode[zIn[i]&0x7f];
  95108. zResult[0] = sqlite3Toupper(zIn[i]);
  95109. for(j=1; j<4 && zIn[i]; i++){
  95110. int code = iCode[zIn[i]&0x7f];
  95111. if( code>0 ){
  95112. if( code!=prevcode ){
  95113. prevcode = code;
  95114. zResult[j++] = code + '0';
  95115. }
  95116. }else{
  95117. prevcode = 0;
  95118. }
  95119. }
  95120. while( j<4 ){
  95121. zResult[j++] = '0';
  95122. }
  95123. zResult[j] = 0;
  95124. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  95125. }else{
  95126. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  95127. ** is NULL or contains no ASCII alphabetic characters. */
  95128. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  95129. }
  95130. }
  95131. #endif /* SQLITE_SOUNDEX */
  95132. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  95133. /*
  95134. ** A function that loads a shared-library extension then returns NULL.
  95135. */
  95136. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  95137. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  95138. const char *zProc;
  95139. sqlite3 *db = sqlite3_context_db_handle(context);
  95140. char *zErrMsg = 0;
  95141. if( argc==2 ){
  95142. zProc = (const char *)sqlite3_value_text(argv[1]);
  95143. }else{
  95144. zProc = 0;
  95145. }
  95146. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  95147. sqlite3_result_error(context, zErrMsg, -1);
  95148. sqlite3_free(zErrMsg);
  95149. }
  95150. }
  95151. #endif
  95152. /*
  95153. ** An instance of the following structure holds the context of a
  95154. ** sum() or avg() aggregate computation.
  95155. */
  95156. typedef struct SumCtx SumCtx;
  95157. struct SumCtx {
  95158. double rSum; /* Floating point sum */
  95159. i64 iSum; /* Integer sum */
  95160. i64 cnt; /* Number of elements summed */
  95161. u8 overflow; /* True if integer overflow seen */
  95162. u8 approx; /* True if non-integer value was input to the sum */
  95163. };
  95164. /*
  95165. ** Routines used to compute the sum, average, and total.
  95166. **
  95167. ** The SUM() function follows the (broken) SQL standard which means
  95168. ** that it returns NULL if it sums over no inputs. TOTAL returns
  95169. ** 0.0 in that case. In addition, TOTAL always returns a float where
  95170. ** SUM might return an integer if it never encounters a floating point
  95171. ** value. TOTAL never fails, but SUM might through an exception if
  95172. ** it overflows an integer.
  95173. */
  95174. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  95175. SumCtx *p;
  95176. int type;
  95177. assert( argc==1 );
  95178. UNUSED_PARAMETER(argc);
  95179. p = sqlite3_aggregate_context(context, sizeof(*p));
  95180. type = sqlite3_value_numeric_type(argv[0]);
  95181. if( p && type!=SQLITE_NULL ){
  95182. p->cnt++;
  95183. if( type==SQLITE_INTEGER ){
  95184. i64 v = sqlite3_value_int64(argv[0]);
  95185. p->rSum += v;
  95186. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  95187. p->overflow = 1;
  95188. }
  95189. }else{
  95190. p->rSum += sqlite3_value_double(argv[0]);
  95191. p->approx = 1;
  95192. }
  95193. }
  95194. }
  95195. static void sumFinalize(sqlite3_context *context){
  95196. SumCtx *p;
  95197. p = sqlite3_aggregate_context(context, 0);
  95198. if( p && p->cnt>0 ){
  95199. if( p->overflow ){
  95200. sqlite3_result_error(context,"integer overflow",-1);
  95201. }else if( p->approx ){
  95202. sqlite3_result_double(context, p->rSum);
  95203. }else{
  95204. sqlite3_result_int64(context, p->iSum);
  95205. }
  95206. }
  95207. }
  95208. static void avgFinalize(sqlite3_context *context){
  95209. SumCtx *p;
  95210. p = sqlite3_aggregate_context(context, 0);
  95211. if( p && p->cnt>0 ){
  95212. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  95213. }
  95214. }
  95215. static void totalFinalize(sqlite3_context *context){
  95216. SumCtx *p;
  95217. p = sqlite3_aggregate_context(context, 0);
  95218. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  95219. sqlite3_result_double(context, p ? p->rSum : (double)0);
  95220. }
  95221. /*
  95222. ** The following structure keeps track of state information for the
  95223. ** count() aggregate function.
  95224. */
  95225. typedef struct CountCtx CountCtx;
  95226. struct CountCtx {
  95227. i64 n;
  95228. };
  95229. /*
  95230. ** Routines to implement the count() aggregate function.
  95231. */
  95232. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  95233. CountCtx *p;
  95234. p = sqlite3_aggregate_context(context, sizeof(*p));
  95235. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  95236. p->n++;
  95237. }
  95238. #ifndef SQLITE_OMIT_DEPRECATED
  95239. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  95240. ** sure it still operates correctly, verify that its count agrees with our
  95241. ** internal count when using count(*) and when the total count can be
  95242. ** expressed as a 32-bit integer. */
  95243. assert( argc==1 || p==0 || p->n>0x7fffffff
  95244. || p->n==sqlite3_aggregate_count(context) );
  95245. #endif
  95246. }
  95247. static void countFinalize(sqlite3_context *context){
  95248. CountCtx *p;
  95249. p = sqlite3_aggregate_context(context, 0);
  95250. sqlite3_result_int64(context, p ? p->n : 0);
  95251. }
  95252. /*
  95253. ** Routines to implement min() and max() aggregate functions.
  95254. */
  95255. static void minmaxStep(
  95256. sqlite3_context *context,
  95257. int NotUsed,
  95258. sqlite3_value **argv
  95259. ){
  95260. Mem *pArg = (Mem *)argv[0];
  95261. Mem *pBest;
  95262. UNUSED_PARAMETER(NotUsed);
  95263. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  95264. if( !pBest ) return;
  95265. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  95266. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  95267. }else if( pBest->flags ){
  95268. int max;
  95269. int cmp;
  95270. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  95271. /* This step function is used for both the min() and max() aggregates,
  95272. ** the only difference between the two being that the sense of the
  95273. ** comparison is inverted. For the max() aggregate, the
  95274. ** sqlite3_user_data() function returns (void *)-1. For min() it
  95275. ** returns (void *)db, where db is the sqlite3* database pointer.
  95276. ** Therefore the next statement sets variable 'max' to 1 for the max()
  95277. ** aggregate, or 0 for min().
  95278. */
  95279. max = sqlite3_user_data(context)!=0;
  95280. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  95281. if( (max && cmp<0) || (!max && cmp>0) ){
  95282. sqlite3VdbeMemCopy(pBest, pArg);
  95283. }else{
  95284. sqlite3SkipAccumulatorLoad(context);
  95285. }
  95286. }else{
  95287. pBest->db = sqlite3_context_db_handle(context);
  95288. sqlite3VdbeMemCopy(pBest, pArg);
  95289. }
  95290. }
  95291. static void minMaxFinalize(sqlite3_context *context){
  95292. sqlite3_value *pRes;
  95293. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  95294. if( pRes ){
  95295. if( pRes->flags ){
  95296. sqlite3_result_value(context, pRes);
  95297. }
  95298. sqlite3VdbeMemRelease(pRes);
  95299. }
  95300. }
  95301. /*
  95302. ** group_concat(EXPR, ?SEPARATOR?)
  95303. */
  95304. static void groupConcatStep(
  95305. sqlite3_context *context,
  95306. int argc,
  95307. sqlite3_value **argv
  95308. ){
  95309. const char *zVal;
  95310. StrAccum *pAccum;
  95311. const char *zSep;
  95312. int nVal, nSep;
  95313. assert( argc==1 || argc==2 );
  95314. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  95315. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  95316. if( pAccum ){
  95317. sqlite3 *db = sqlite3_context_db_handle(context);
  95318. int firstTerm = pAccum->mxAlloc==0;
  95319. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  95320. if( !firstTerm ){
  95321. if( argc==2 ){
  95322. zSep = (char*)sqlite3_value_text(argv[1]);
  95323. nSep = sqlite3_value_bytes(argv[1]);
  95324. }else{
  95325. zSep = ",";
  95326. nSep = 1;
  95327. }
  95328. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  95329. }
  95330. zVal = (char*)sqlite3_value_text(argv[0]);
  95331. nVal = sqlite3_value_bytes(argv[0]);
  95332. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  95333. }
  95334. }
  95335. static void groupConcatFinalize(sqlite3_context *context){
  95336. StrAccum *pAccum;
  95337. pAccum = sqlite3_aggregate_context(context, 0);
  95338. if( pAccum ){
  95339. if( pAccum->accError==STRACCUM_TOOBIG ){
  95340. sqlite3_result_error_toobig(context);
  95341. }else if( pAccum->accError==STRACCUM_NOMEM ){
  95342. sqlite3_result_error_nomem(context);
  95343. }else{
  95344. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  95345. sqlite3_free);
  95346. }
  95347. }
  95348. }
  95349. /*
  95350. ** This routine does per-connection function registration. Most
  95351. ** of the built-in functions above are part of the global function set.
  95352. ** This routine only deals with those that are not global.
  95353. */
  95354. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  95355. int rc = sqlite3_overload_function(db, "MATCH", 2);
  95356. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  95357. if( rc==SQLITE_NOMEM ){
  95358. sqlite3OomFault(db);
  95359. }
  95360. }
  95361. /*
  95362. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  95363. */
  95364. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  95365. FuncDef *pDef;
  95366. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  95367. if( ALWAYS(pDef) ){
  95368. pDef->funcFlags |= flagVal;
  95369. }
  95370. }
  95371. /*
  95372. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  95373. ** parameter determines whether or not the LIKE operator is case
  95374. ** sensitive. GLOB is always case sensitive.
  95375. */
  95376. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  95377. struct compareInfo *pInfo;
  95378. if( caseSensitive ){
  95379. pInfo = (struct compareInfo*)&likeInfoAlt;
  95380. }else{
  95381. pInfo = (struct compareInfo*)&likeInfoNorm;
  95382. }
  95383. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  95384. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  95385. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  95386. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  95387. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  95388. setLikeOptFlag(db, "like",
  95389. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  95390. }
  95391. /*
  95392. ** pExpr points to an expression which implements a function. If
  95393. ** it is appropriate to apply the LIKE optimization to that function
  95394. ** then set aWc[0] through aWc[2] to the wildcard characters and
  95395. ** return TRUE. If the function is not a LIKE-style function then
  95396. ** return FALSE.
  95397. **
  95398. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  95399. ** the function (default for LIKE). If the function makes the distinction
  95400. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  95401. ** false.
  95402. */
  95403. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  95404. FuncDef *pDef;
  95405. if( pExpr->op!=TK_FUNCTION
  95406. || !pExpr->x.pList
  95407. || pExpr->x.pList->nExpr!=2
  95408. ){
  95409. return 0;
  95410. }
  95411. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  95412. pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
  95413. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  95414. return 0;
  95415. }
  95416. /* The memcpy() statement assumes that the wildcard characters are
  95417. ** the first three statements in the compareInfo structure. The
  95418. ** asserts() that follow verify that assumption
  95419. */
  95420. memcpy(aWc, pDef->pUserData, 3);
  95421. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  95422. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  95423. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  95424. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  95425. return 1;
  95426. }
  95427. /*
  95428. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  95429. ** to the global function hash table. This occurs at start-time (as
  95430. ** a consequence of calling sqlite3_initialize()).
  95431. **
  95432. ** After this routine runs
  95433. */
  95434. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  95435. /*
  95436. ** The following array holds FuncDef structures for all of the functions
  95437. ** defined in this file.
  95438. **
  95439. ** The array cannot be constant since changes are made to the
  95440. ** FuncDef.pHash elements at start-time. The elements of this array
  95441. ** are read-only after initialization is complete.
  95442. **
  95443. ** For peak efficiency, put the most frequently used function last.
  95444. */
  95445. static FuncDef aBuiltinFunc[] = {
  95446. #ifdef SQLITE_SOUNDEX
  95447. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  95448. #endif
  95449. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  95450. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  95451. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  95452. #endif
  95453. #if SQLITE_USER_AUTHENTICATION
  95454. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  95455. #endif
  95456. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  95457. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  95458. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  95459. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  95460. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  95461. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  95462. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  95463. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  95464. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  95465. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  95466. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  95467. FUNCTION(trim, 1, 3, 0, trimFunc ),
  95468. FUNCTION(trim, 2, 3, 0, trimFunc ),
  95469. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  95470. FUNCTION(min, 0, 0, 1, 0 ),
  95471. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  95472. SQLITE_FUNC_MINMAX ),
  95473. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  95474. FUNCTION(max, 0, 1, 1, 0 ),
  95475. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  95476. SQLITE_FUNC_MINMAX ),
  95477. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  95478. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  95479. FUNCTION(instr, 2, 0, 0, instrFunc ),
  95480. FUNCTION(printf, -1, 0, 0, printfFunc ),
  95481. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  95482. FUNCTION(char, -1, 0, 0, charFunc ),
  95483. FUNCTION(abs, 1, 0, 0, absFunc ),
  95484. #ifndef SQLITE_OMIT_FLOATING_POINT
  95485. FUNCTION(round, 1, 0, 0, roundFunc ),
  95486. FUNCTION(round, 2, 0, 0, roundFunc ),
  95487. #endif
  95488. FUNCTION(upper, 1, 0, 0, upperFunc ),
  95489. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  95490. FUNCTION(hex, 1, 0, 0, hexFunc ),
  95491. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  95492. VFUNCTION(random, 0, 0, 0, randomFunc ),
  95493. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  95494. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  95495. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  95496. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  95497. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  95498. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  95499. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  95500. VFUNCTION(changes, 0, 0, 0, changes ),
  95501. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  95502. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  95503. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  95504. FUNCTION(substr, 2, 0, 0, substrFunc ),
  95505. FUNCTION(substr, 3, 0, 0, substrFunc ),
  95506. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  95507. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  95508. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  95509. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  95510. SQLITE_FUNC_COUNT ),
  95511. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  95512. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  95513. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  95514. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  95515. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  95516. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  95517. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  95518. #else
  95519. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  95520. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  95521. #endif
  95522. FUNCTION(coalesce, 1, 0, 0, 0 ),
  95523. FUNCTION(coalesce, 0, 0, 0, 0 ),
  95524. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  95525. };
  95526. #ifndef SQLITE_OMIT_ALTERTABLE
  95527. sqlite3AlterFunctions();
  95528. #endif
  95529. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  95530. sqlite3AnalyzeFunctions();
  95531. #endif
  95532. sqlite3RegisterDateTimeFunctions();
  95533. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  95534. #if 0 /* Enable to print out how the built-in functions are hashed */
  95535. {
  95536. int i;
  95537. FuncDef *p;
  95538. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  95539. printf("FUNC-HASH %02d:", i);
  95540. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  95541. int n = sqlite3Strlen30(p->zName);
  95542. int h = p->zName[0] + n;
  95543. printf(" %s(%d)", p->zName, h);
  95544. }
  95545. printf("\n");
  95546. }
  95547. }
  95548. #endif
  95549. }
  95550. /************** End of func.c ************************************************/
  95551. /************** Begin file fkey.c ********************************************/
  95552. /*
  95553. **
  95554. ** The author disclaims copyright to this source code. In place of
  95555. ** a legal notice, here is a blessing:
  95556. **
  95557. ** May you do good and not evil.
  95558. ** May you find forgiveness for yourself and forgive others.
  95559. ** May you share freely, never taking more than you give.
  95560. **
  95561. *************************************************************************
  95562. ** This file contains code used by the compiler to add foreign key
  95563. ** support to compiled SQL statements.
  95564. */
  95565. /* #include "sqliteInt.h" */
  95566. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95567. #ifndef SQLITE_OMIT_TRIGGER
  95568. /*
  95569. ** Deferred and Immediate FKs
  95570. ** --------------------------
  95571. **
  95572. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  95573. ** If an immediate foreign key constraint is violated,
  95574. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  95575. ** statement transaction rolled back. If a
  95576. ** deferred foreign key constraint is violated, no action is taken
  95577. ** immediately. However if the application attempts to commit the
  95578. ** transaction before fixing the constraint violation, the attempt fails.
  95579. **
  95580. ** Deferred constraints are implemented using a simple counter associated
  95581. ** with the database handle. The counter is set to zero each time a
  95582. ** database transaction is opened. Each time a statement is executed
  95583. ** that causes a foreign key violation, the counter is incremented. Each
  95584. ** time a statement is executed that removes an existing violation from
  95585. ** the database, the counter is decremented. When the transaction is
  95586. ** committed, the commit fails if the current value of the counter is
  95587. ** greater than zero. This scheme has two big drawbacks:
  95588. **
  95589. ** * When a commit fails due to a deferred foreign key constraint,
  95590. ** there is no way to tell which foreign constraint is not satisfied,
  95591. ** or which row it is not satisfied for.
  95592. **
  95593. ** * If the database contains foreign key violations when the
  95594. ** transaction is opened, this may cause the mechanism to malfunction.
  95595. **
  95596. ** Despite these problems, this approach is adopted as it seems simpler
  95597. ** than the alternatives.
  95598. **
  95599. ** INSERT operations:
  95600. **
  95601. ** I.1) For each FK for which the table is the child table, search
  95602. ** the parent table for a match. If none is found increment the
  95603. ** constraint counter.
  95604. **
  95605. ** I.2) For each FK for which the table is the parent table,
  95606. ** search the child table for rows that correspond to the new
  95607. ** row in the parent table. Decrement the counter for each row
  95608. ** found (as the constraint is now satisfied).
  95609. **
  95610. ** DELETE operations:
  95611. **
  95612. ** D.1) For each FK for which the table is the child table,
  95613. ** search the parent table for a row that corresponds to the
  95614. ** deleted row in the child table. If such a row is not found,
  95615. ** decrement the counter.
  95616. **
  95617. ** D.2) For each FK for which the table is the parent table, search
  95618. ** the child table for rows that correspond to the deleted row
  95619. ** in the parent table. For each found increment the counter.
  95620. **
  95621. ** UPDATE operations:
  95622. **
  95623. ** An UPDATE command requires that all 4 steps above are taken, but only
  95624. ** for FK constraints for which the affected columns are actually
  95625. ** modified (values must be compared at runtime).
  95626. **
  95627. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  95628. ** This simplifies the implementation a bit.
  95629. **
  95630. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  95631. ** resolution is considered to delete rows before the new row is inserted.
  95632. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  95633. ** is thrown, even if the FK constraint would be satisfied after the new
  95634. ** row is inserted.
  95635. **
  95636. ** Immediate constraints are usually handled similarly. The only difference
  95637. ** is that the counter used is stored as part of each individual statement
  95638. ** object (struct Vdbe). If, after the statement has run, its immediate
  95639. ** constraint counter is greater than zero,
  95640. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  95641. ** and the statement transaction is rolled back. An exception is an INSERT
  95642. ** statement that inserts a single row only (no triggers). In this case,
  95643. ** instead of using a counter, an exception is thrown immediately if the
  95644. ** INSERT violates a foreign key constraint. This is necessary as such
  95645. ** an INSERT does not open a statement transaction.
  95646. **
  95647. ** TODO: How should dropping a table be handled? How should renaming a
  95648. ** table be handled?
  95649. **
  95650. **
  95651. ** Query API Notes
  95652. ** ---------------
  95653. **
  95654. ** Before coding an UPDATE or DELETE row operation, the code-generator
  95655. ** for those two operations needs to know whether or not the operation
  95656. ** requires any FK processing and, if so, which columns of the original
  95657. ** row are required by the FK processing VDBE code (i.e. if FKs were
  95658. ** implemented using triggers, which of the old.* columns would be
  95659. ** accessed). No information is required by the code-generator before
  95660. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  95661. ** generation code to query for this information are:
  95662. **
  95663. ** sqlite3FkRequired() - Test to see if FK processing is required.
  95664. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  95665. **
  95666. **
  95667. ** Externally accessible module functions
  95668. ** --------------------------------------
  95669. **
  95670. ** sqlite3FkCheck() - Check for foreign key violations.
  95671. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  95672. ** sqlite3FkDelete() - Delete an FKey structure.
  95673. */
  95674. /*
  95675. ** VDBE Calling Convention
  95676. ** -----------------------
  95677. **
  95678. ** Example:
  95679. **
  95680. ** For the following INSERT statement:
  95681. **
  95682. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  95683. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  95684. **
  95685. ** Register (x): 2 (type integer)
  95686. ** Register (x+1): 1 (type integer)
  95687. ** Register (x+2): NULL (type NULL)
  95688. ** Register (x+3): 3.1 (type real)
  95689. */
  95690. /*
  95691. ** A foreign key constraint requires that the key columns in the parent
  95692. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  95693. ** Given that pParent is the parent table for foreign key constraint pFKey,
  95694. ** search the schema for a unique index on the parent key columns.
  95695. **
  95696. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  95697. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  95698. ** is set to point to the unique index.
  95699. **
  95700. ** If the parent key consists of a single column (the foreign key constraint
  95701. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  95702. ** Otherwise, it is set to point to an allocated array of size N, where
  95703. ** N is the number of columns in the parent key. The first element of the
  95704. ** array is the index of the child table column that is mapped by the FK
  95705. ** constraint to the parent table column stored in the left-most column
  95706. ** of index *ppIdx. The second element of the array is the index of the
  95707. ** child table column that corresponds to the second left-most column of
  95708. ** *ppIdx, and so on.
  95709. **
  95710. ** If the required index cannot be found, either because:
  95711. **
  95712. ** 1) The named parent key columns do not exist, or
  95713. **
  95714. ** 2) The named parent key columns do exist, but are not subject to a
  95715. ** UNIQUE or PRIMARY KEY constraint, or
  95716. **
  95717. ** 3) No parent key columns were provided explicitly as part of the
  95718. ** foreign key definition, and the parent table does not have a
  95719. ** PRIMARY KEY, or
  95720. **
  95721. ** 4) No parent key columns were provided explicitly as part of the
  95722. ** foreign key definition, and the PRIMARY KEY of the parent table
  95723. ** consists of a different number of columns to the child key in
  95724. ** the child table.
  95725. **
  95726. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  95727. ** into pParse. If an OOM error occurs, non-zero is returned and the
  95728. ** pParse->db->mallocFailed flag is set.
  95729. */
  95730. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  95731. Parse *pParse, /* Parse context to store any error in */
  95732. Table *pParent, /* Parent table of FK constraint pFKey */
  95733. FKey *pFKey, /* Foreign key to find index for */
  95734. Index **ppIdx, /* OUT: Unique index on parent table */
  95735. int **paiCol /* OUT: Map of index columns in pFKey */
  95736. ){
  95737. Index *pIdx = 0; /* Value to return via *ppIdx */
  95738. int *aiCol = 0; /* Value to return via *paiCol */
  95739. int nCol = pFKey->nCol; /* Number of columns in parent key */
  95740. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  95741. /* The caller is responsible for zeroing output parameters. */
  95742. assert( ppIdx && *ppIdx==0 );
  95743. assert( !paiCol || *paiCol==0 );
  95744. assert( pParse );
  95745. /* If this is a non-composite (single column) foreign key, check if it
  95746. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  95747. ** and *paiCol set to zero and return early.
  95748. **
  95749. ** Otherwise, for a composite foreign key (more than one column), allocate
  95750. ** space for the aiCol array (returned via output parameter *paiCol).
  95751. ** Non-composite foreign keys do not require the aiCol array.
  95752. */
  95753. if( nCol==1 ){
  95754. /* The FK maps to the IPK if any of the following are true:
  95755. **
  95756. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  95757. ** mapped to the primary key of table pParent, or
  95758. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  95759. ** PRIMARY KEY.
  95760. */
  95761. if( pParent->iPKey>=0 ){
  95762. if( !zKey ) return 0;
  95763. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  95764. }
  95765. }else if( paiCol ){
  95766. assert( nCol>1 );
  95767. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  95768. if( !aiCol ) return 1;
  95769. *paiCol = aiCol;
  95770. }
  95771. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  95772. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  95773. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  95774. ** of columns. If each indexed column corresponds to a foreign key
  95775. ** column of pFKey, then this index is a winner. */
  95776. if( zKey==0 ){
  95777. /* If zKey is NULL, then this foreign key is implicitly mapped to
  95778. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  95779. ** identified by the test. */
  95780. if( IsPrimaryKeyIndex(pIdx) ){
  95781. if( aiCol ){
  95782. int i;
  95783. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  95784. }
  95785. break;
  95786. }
  95787. }else{
  95788. /* If zKey is non-NULL, then this foreign key was declared to
  95789. ** map to an explicit list of columns in table pParent. Check if this
  95790. ** index matches those columns. Also, check that the index uses
  95791. ** the default collation sequences for each column. */
  95792. int i, j;
  95793. for(i=0; i<nCol; i++){
  95794. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  95795. const char *zDfltColl; /* Def. collation for column */
  95796. char *zIdxCol; /* Name of indexed column */
  95797. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  95798. /* If the index uses a collation sequence that is different from
  95799. ** the default collation sequence for the column, this index is
  95800. ** unusable. Bail out early in this case. */
  95801. zDfltColl = pParent->aCol[iCol].zColl;
  95802. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  95803. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  95804. zIdxCol = pParent->aCol[iCol].zName;
  95805. for(j=0; j<nCol; j++){
  95806. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  95807. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  95808. break;
  95809. }
  95810. }
  95811. if( j==nCol ) break;
  95812. }
  95813. if( i==nCol ) break; /* pIdx is usable */
  95814. }
  95815. }
  95816. }
  95817. if( !pIdx ){
  95818. if( !pParse->disableTriggers ){
  95819. sqlite3ErrorMsg(pParse,
  95820. "foreign key mismatch - \"%w\" referencing \"%w\"",
  95821. pFKey->pFrom->zName, pFKey->zTo);
  95822. }
  95823. sqlite3DbFree(pParse->db, aiCol);
  95824. return 1;
  95825. }
  95826. *ppIdx = pIdx;
  95827. return 0;
  95828. }
  95829. /*
  95830. ** This function is called when a row is inserted into or deleted from the
  95831. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  95832. ** on the child table of pFKey, this function is invoked twice for each row
  95833. ** affected - once to "delete" the old row, and then again to "insert" the
  95834. ** new row.
  95835. **
  95836. ** Each time it is called, this function generates VDBE code to locate the
  95837. ** row in the parent table that corresponds to the row being inserted into
  95838. ** or deleted from the child table. If the parent row can be found, no
  95839. ** special action is taken. Otherwise, if the parent row can *not* be
  95840. ** found in the parent table:
  95841. **
  95842. ** Operation | FK type | Action taken
  95843. ** --------------------------------------------------------------------------
  95844. ** INSERT immediate Increment the "immediate constraint counter".
  95845. **
  95846. ** DELETE immediate Decrement the "immediate constraint counter".
  95847. **
  95848. ** INSERT deferred Increment the "deferred constraint counter".
  95849. **
  95850. ** DELETE deferred Decrement the "deferred constraint counter".
  95851. **
  95852. ** These operations are identified in the comment at the top of this file
  95853. ** (fkey.c) as "I.1" and "D.1".
  95854. */
  95855. static void fkLookupParent(
  95856. Parse *pParse, /* Parse context */
  95857. int iDb, /* Index of database housing pTab */
  95858. Table *pTab, /* Parent table of FK pFKey */
  95859. Index *pIdx, /* Unique index on parent key columns in pTab */
  95860. FKey *pFKey, /* Foreign key constraint */
  95861. int *aiCol, /* Map from parent key columns to child table columns */
  95862. int regData, /* Address of array containing child table row */
  95863. int nIncr, /* Increment constraint counter by this */
  95864. int isIgnore /* If true, pretend pTab contains all NULL values */
  95865. ){
  95866. int i; /* Iterator variable */
  95867. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  95868. int iCur = pParse->nTab - 1; /* Cursor number to use */
  95869. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  95870. /* If nIncr is less than zero, then check at runtime if there are any
  95871. ** outstanding constraints to resolve. If there are not, there is no need
  95872. ** to check if deleting this row resolves any outstanding violations.
  95873. **
  95874. ** Check if any of the key columns in the child table row are NULL. If
  95875. ** any are, then the constraint is considered satisfied. No need to
  95876. ** search for a matching row in the parent table. */
  95877. if( nIncr<0 ){
  95878. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  95879. VdbeCoverage(v);
  95880. }
  95881. for(i=0; i<pFKey->nCol; i++){
  95882. int iReg = aiCol[i] + regData + 1;
  95883. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  95884. }
  95885. if( isIgnore==0 ){
  95886. if( pIdx==0 ){
  95887. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  95888. ** column of the parent table (table pTab). */
  95889. int iMustBeInt; /* Address of MustBeInt instruction */
  95890. int regTemp = sqlite3GetTempReg(pParse);
  95891. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  95892. ** apply the affinity of the parent key). If this fails, then there
  95893. ** is no matching parent key. Before using MustBeInt, make a copy of
  95894. ** the value. Otherwise, the value inserted into the child key column
  95895. ** will have INTEGER affinity applied to it, which may not be correct. */
  95896. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  95897. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  95898. VdbeCoverage(v);
  95899. /* If the parent table is the same as the child table, and we are about
  95900. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  95901. ** then check if the row being inserted matches itself. If so, do not
  95902. ** increment the constraint-counter. */
  95903. if( pTab==pFKey->pFrom && nIncr==1 ){
  95904. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  95905. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  95906. }
  95907. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  95908. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  95909. sqlite3VdbeGoto(v, iOk);
  95910. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  95911. sqlite3VdbeJumpHere(v, iMustBeInt);
  95912. sqlite3ReleaseTempReg(pParse, regTemp);
  95913. }else{
  95914. int nCol = pFKey->nCol;
  95915. int regTemp = sqlite3GetTempRange(pParse, nCol);
  95916. int regRec = sqlite3GetTempReg(pParse);
  95917. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  95918. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95919. for(i=0; i<nCol; i++){
  95920. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  95921. }
  95922. /* If the parent table is the same as the child table, and we are about
  95923. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  95924. ** then check if the row being inserted matches itself. If so, do not
  95925. ** increment the constraint-counter.
  95926. **
  95927. ** If any of the parent-key values are NULL, then the row cannot match
  95928. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  95929. ** of the parent-key values are NULL (at this point it is known that
  95930. ** none of the child key values are).
  95931. */
  95932. if( pTab==pFKey->pFrom && nIncr==1 ){
  95933. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  95934. for(i=0; i<nCol; i++){
  95935. int iChild = aiCol[i]+1+regData;
  95936. int iParent = pIdx->aiColumn[i]+1+regData;
  95937. assert( pIdx->aiColumn[i]>=0 );
  95938. assert( aiCol[i]!=pTab->iPKey );
  95939. if( pIdx->aiColumn[i]==pTab->iPKey ){
  95940. /* The parent key is a composite key that includes the IPK column */
  95941. iParent = regData;
  95942. }
  95943. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  95944. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  95945. }
  95946. sqlite3VdbeGoto(v, iOk);
  95947. }
  95948. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  95949. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  95950. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  95951. sqlite3ReleaseTempReg(pParse, regRec);
  95952. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  95953. }
  95954. }
  95955. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  95956. && !pParse->pToplevel
  95957. && !pParse->isMultiWrite
  95958. ){
  95959. /* Special case: If this is an INSERT statement that will insert exactly
  95960. ** one row into the table, raise a constraint immediately instead of
  95961. ** incrementing a counter. This is necessary as the VM code is being
  95962. ** generated for will not open a statement transaction. */
  95963. assert( nIncr==1 );
  95964. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  95965. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  95966. }else{
  95967. if( nIncr>0 && pFKey->isDeferred==0 ){
  95968. sqlite3MayAbort(pParse);
  95969. }
  95970. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  95971. }
  95972. sqlite3VdbeResolveLabel(v, iOk);
  95973. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  95974. }
  95975. /*
  95976. ** Return an Expr object that refers to a memory register corresponding
  95977. ** to column iCol of table pTab.
  95978. **
  95979. ** regBase is the first of an array of register that contains the data
  95980. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  95981. ** column. regBase+2 holds the second column, and so forth.
  95982. */
  95983. static Expr *exprTableRegister(
  95984. Parse *pParse, /* Parsing and code generating context */
  95985. Table *pTab, /* The table whose content is at r[regBase]... */
  95986. int regBase, /* Contents of table pTab */
  95987. i16 iCol /* Which column of pTab is desired */
  95988. ){
  95989. Expr *pExpr;
  95990. Column *pCol;
  95991. const char *zColl;
  95992. sqlite3 *db = pParse->db;
  95993. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  95994. if( pExpr ){
  95995. if( iCol>=0 && iCol!=pTab->iPKey ){
  95996. pCol = &pTab->aCol[iCol];
  95997. pExpr->iTable = regBase + iCol + 1;
  95998. pExpr->affinity = pCol->affinity;
  95999. zColl = pCol->zColl;
  96000. if( zColl==0 ) zColl = db->pDfltColl->zName;
  96001. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  96002. }else{
  96003. pExpr->iTable = regBase;
  96004. pExpr->affinity = SQLITE_AFF_INTEGER;
  96005. }
  96006. }
  96007. return pExpr;
  96008. }
  96009. /*
  96010. ** Return an Expr object that refers to column iCol of table pTab which
  96011. ** has cursor iCur.
  96012. */
  96013. static Expr *exprTableColumn(
  96014. sqlite3 *db, /* The database connection */
  96015. Table *pTab, /* The table whose column is desired */
  96016. int iCursor, /* The open cursor on the table */
  96017. i16 iCol /* The column that is wanted */
  96018. ){
  96019. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  96020. if( pExpr ){
  96021. pExpr->pTab = pTab;
  96022. pExpr->iTable = iCursor;
  96023. pExpr->iColumn = iCol;
  96024. }
  96025. return pExpr;
  96026. }
  96027. /*
  96028. ** This function is called to generate code executed when a row is deleted
  96029. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  96030. ** deferred, when a row is inserted into the same table. When generating
  96031. ** code for an SQL UPDATE operation, this function may be called twice -
  96032. ** once to "delete" the old row and once to "insert" the new row.
  96033. **
  96034. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  96035. ** the number of FK violations in the db) or +1 when deleting one (as this
  96036. ** may increase the number of FK constraint problems).
  96037. **
  96038. ** The code generated by this function scans through the rows in the child
  96039. ** table that correspond to the parent table row being deleted or inserted.
  96040. ** For each child row found, one of the following actions is taken:
  96041. **
  96042. ** Operation | FK type | Action taken
  96043. ** --------------------------------------------------------------------------
  96044. ** DELETE immediate Increment the "immediate constraint counter".
  96045. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  96046. ** throw a "FOREIGN KEY constraint failed" exception.
  96047. **
  96048. ** INSERT immediate Decrement the "immediate constraint counter".
  96049. **
  96050. ** DELETE deferred Increment the "deferred constraint counter".
  96051. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  96052. ** throw a "FOREIGN KEY constraint failed" exception.
  96053. **
  96054. ** INSERT deferred Decrement the "deferred constraint counter".
  96055. **
  96056. ** These operations are identified in the comment at the top of this file
  96057. ** (fkey.c) as "I.2" and "D.2".
  96058. */
  96059. static void fkScanChildren(
  96060. Parse *pParse, /* Parse context */
  96061. SrcList *pSrc, /* The child table to be scanned */
  96062. Table *pTab, /* The parent table */
  96063. Index *pIdx, /* Index on parent covering the foreign key */
  96064. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  96065. int *aiCol, /* Map from pIdx cols to child table cols */
  96066. int regData, /* Parent row data starts here */
  96067. int nIncr /* Amount to increment deferred counter by */
  96068. ){
  96069. sqlite3 *db = pParse->db; /* Database handle */
  96070. int i; /* Iterator variable */
  96071. Expr *pWhere = 0; /* WHERE clause to scan with */
  96072. NameContext sNameContext; /* Context used to resolve WHERE clause */
  96073. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  96074. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  96075. Vdbe *v = sqlite3GetVdbe(pParse);
  96076. assert( pIdx==0 || pIdx->pTable==pTab );
  96077. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  96078. assert( pIdx!=0 || pFKey->nCol==1 );
  96079. assert( pIdx!=0 || HasRowid(pTab) );
  96080. if( nIncr<0 ){
  96081. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  96082. VdbeCoverage(v);
  96083. }
  96084. /* Create an Expr object representing an SQL expression like:
  96085. **
  96086. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  96087. **
  96088. ** The collation sequence used for the comparison should be that of
  96089. ** the parent key columns. The affinity of the parent key column should
  96090. ** be applied to each child key value before the comparison takes place.
  96091. */
  96092. for(i=0; i<pFKey->nCol; i++){
  96093. Expr *pLeft; /* Value from parent table row */
  96094. Expr *pRight; /* Column ref to child table */
  96095. Expr *pEq; /* Expression (pLeft = pRight) */
  96096. i16 iCol; /* Index of column in child table */
  96097. const char *zCol; /* Name of column in child table */
  96098. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  96099. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  96100. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  96101. assert( iCol>=0 );
  96102. zCol = pFKey->pFrom->aCol[iCol].zName;
  96103. pRight = sqlite3Expr(db, TK_ID, zCol);
  96104. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  96105. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  96106. }
  96107. /* If the child table is the same as the parent table, then add terms
  96108. ** to the WHERE clause that prevent this entry from being scanned.
  96109. ** The added WHERE clause terms are like this:
  96110. **
  96111. ** $current_rowid!=rowid
  96112. ** NOT( $current_a==a AND $current_b==b AND ... )
  96113. **
  96114. ** The first form is used for rowid tables. The second form is used
  96115. ** for WITHOUT ROWID tables. In the second form, the primary key is
  96116. ** (a,b,...)
  96117. */
  96118. if( pTab==pFKey->pFrom && nIncr>0 ){
  96119. Expr *pNe; /* Expression (pLeft != pRight) */
  96120. Expr *pLeft; /* Value from parent table row */
  96121. Expr *pRight; /* Column ref to child table */
  96122. if( HasRowid(pTab) ){
  96123. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  96124. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  96125. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  96126. }else{
  96127. Expr *pEq, *pAll = 0;
  96128. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  96129. assert( pIdx!=0 );
  96130. for(i=0; i<pPk->nKeyCol; i++){
  96131. i16 iCol = pIdx->aiColumn[i];
  96132. assert( iCol>=0 );
  96133. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  96134. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  96135. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  96136. pAll = sqlite3ExprAnd(db, pAll, pEq);
  96137. }
  96138. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  96139. }
  96140. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  96141. }
  96142. /* Resolve the references in the WHERE clause. */
  96143. memset(&sNameContext, 0, sizeof(NameContext));
  96144. sNameContext.pSrcList = pSrc;
  96145. sNameContext.pParse = pParse;
  96146. sqlite3ResolveExprNames(&sNameContext, pWhere);
  96147. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  96148. ** clause. For each row found, increment either the deferred or immediate
  96149. ** foreign key constraint counter. */
  96150. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  96151. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  96152. if( pWInfo ){
  96153. sqlite3WhereEnd(pWInfo);
  96154. }
  96155. /* Clean up the WHERE clause constructed above. */
  96156. sqlite3ExprDelete(db, pWhere);
  96157. if( iFkIfZero ){
  96158. sqlite3VdbeJumpHere(v, iFkIfZero);
  96159. }
  96160. }
  96161. /*
  96162. ** This function returns a linked list of FKey objects (connected by
  96163. ** FKey.pNextTo) holding all children of table pTab. For example,
  96164. ** given the following schema:
  96165. **
  96166. ** CREATE TABLE t1(a PRIMARY KEY);
  96167. ** CREATE TABLE t2(b REFERENCES t1(a);
  96168. **
  96169. ** Calling this function with table "t1" as an argument returns a pointer
  96170. ** to the FKey structure representing the foreign key constraint on table
  96171. ** "t2". Calling this function with "t2" as the argument would return a
  96172. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  96173. ** table).
  96174. */
  96175. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  96176. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  96177. }
  96178. /*
  96179. ** The second argument is a Trigger structure allocated by the
  96180. ** fkActionTrigger() routine. This function deletes the Trigger structure
  96181. ** and all of its sub-components.
  96182. **
  96183. ** The Trigger structure or any of its sub-components may be allocated from
  96184. ** the lookaside buffer belonging to database handle dbMem.
  96185. */
  96186. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  96187. if( p ){
  96188. TriggerStep *pStep = p->step_list;
  96189. sqlite3ExprDelete(dbMem, pStep->pWhere);
  96190. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  96191. sqlite3SelectDelete(dbMem, pStep->pSelect);
  96192. sqlite3ExprDelete(dbMem, p->pWhen);
  96193. sqlite3DbFree(dbMem, p);
  96194. }
  96195. }
  96196. /*
  96197. ** This function is called to generate code that runs when table pTab is
  96198. ** being dropped from the database. The SrcList passed as the second argument
  96199. ** to this function contains a single entry guaranteed to resolve to
  96200. ** table pTab.
  96201. **
  96202. ** Normally, no code is required. However, if either
  96203. **
  96204. ** (a) The table is the parent table of a FK constraint, or
  96205. ** (b) The table is the child table of a deferred FK constraint and it is
  96206. ** determined at runtime that there are outstanding deferred FK
  96207. ** constraint violations in the database,
  96208. **
  96209. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  96210. ** the table from the database. Triggers are disabled while running this
  96211. ** DELETE, but foreign key actions are not.
  96212. */
  96213. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  96214. sqlite3 *db = pParse->db;
  96215. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  96216. int iSkip = 0;
  96217. Vdbe *v = sqlite3GetVdbe(pParse);
  96218. assert( v ); /* VDBE has already been allocated */
  96219. if( sqlite3FkReferences(pTab)==0 ){
  96220. /* Search for a deferred foreign key constraint for which this table
  96221. ** is the child table. If one cannot be found, return without
  96222. ** generating any VDBE code. If one can be found, then jump over
  96223. ** the entire DELETE if there are no outstanding deferred constraints
  96224. ** when this statement is run. */
  96225. FKey *p;
  96226. for(p=pTab->pFKey; p; p=p->pNextFrom){
  96227. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  96228. }
  96229. if( !p ) return;
  96230. iSkip = sqlite3VdbeMakeLabel(v);
  96231. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  96232. }
  96233. pParse->disableTriggers = 1;
  96234. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  96235. pParse->disableTriggers = 0;
  96236. /* If the DELETE has generated immediate foreign key constraint
  96237. ** violations, halt the VDBE and return an error at this point, before
  96238. ** any modifications to the schema are made. This is because statement
  96239. ** transactions are not able to rollback schema changes.
  96240. **
  96241. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  96242. ** the statement transaction will not be rolled back even if FK
  96243. ** constraints are violated.
  96244. */
  96245. if( (db->flags & SQLITE_DeferFKs)==0 ){
  96246. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  96247. VdbeCoverage(v);
  96248. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  96249. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  96250. }
  96251. if( iSkip ){
  96252. sqlite3VdbeResolveLabel(v, iSkip);
  96253. }
  96254. }
  96255. }
  96256. /*
  96257. ** The second argument points to an FKey object representing a foreign key
  96258. ** for which pTab is the child table. An UPDATE statement against pTab
  96259. ** is currently being processed. For each column of the table that is
  96260. ** actually updated, the corresponding element in the aChange[] array
  96261. ** is zero or greater (if a column is unmodified the corresponding element
  96262. ** is set to -1). If the rowid column is modified by the UPDATE statement
  96263. ** the bChngRowid argument is non-zero.
  96264. **
  96265. ** This function returns true if any of the columns that are part of the
  96266. ** child key for FK constraint *p are modified.
  96267. */
  96268. static int fkChildIsModified(
  96269. Table *pTab, /* Table being updated */
  96270. FKey *p, /* Foreign key for which pTab is the child */
  96271. int *aChange, /* Array indicating modified columns */
  96272. int bChngRowid /* True if rowid is modified by this update */
  96273. ){
  96274. int i;
  96275. for(i=0; i<p->nCol; i++){
  96276. int iChildKey = p->aCol[i].iFrom;
  96277. if( aChange[iChildKey]>=0 ) return 1;
  96278. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  96279. }
  96280. return 0;
  96281. }
  96282. /*
  96283. ** The second argument points to an FKey object representing a foreign key
  96284. ** for which pTab is the parent table. An UPDATE statement against pTab
  96285. ** is currently being processed. For each column of the table that is
  96286. ** actually updated, the corresponding element in the aChange[] array
  96287. ** is zero or greater (if a column is unmodified the corresponding element
  96288. ** is set to -1). If the rowid column is modified by the UPDATE statement
  96289. ** the bChngRowid argument is non-zero.
  96290. **
  96291. ** This function returns true if any of the columns that are part of the
  96292. ** parent key for FK constraint *p are modified.
  96293. */
  96294. static int fkParentIsModified(
  96295. Table *pTab,
  96296. FKey *p,
  96297. int *aChange,
  96298. int bChngRowid
  96299. ){
  96300. int i;
  96301. for(i=0; i<p->nCol; i++){
  96302. char *zKey = p->aCol[i].zCol;
  96303. int iKey;
  96304. for(iKey=0; iKey<pTab->nCol; iKey++){
  96305. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  96306. Column *pCol = &pTab->aCol[iKey];
  96307. if( zKey ){
  96308. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  96309. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  96310. return 1;
  96311. }
  96312. }
  96313. }
  96314. }
  96315. return 0;
  96316. }
  96317. /*
  96318. ** Return true if the parser passed as the first argument is being
  96319. ** used to code a trigger that is really a "SET NULL" action belonging
  96320. ** to trigger pFKey.
  96321. */
  96322. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  96323. Parse *pTop = sqlite3ParseToplevel(pParse);
  96324. if( pTop->pTriggerPrg ){
  96325. Trigger *p = pTop->pTriggerPrg->pTrigger;
  96326. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  96327. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  96328. ){
  96329. return 1;
  96330. }
  96331. }
  96332. return 0;
  96333. }
  96334. /*
  96335. ** This function is called when inserting, deleting or updating a row of
  96336. ** table pTab to generate VDBE code to perform foreign key constraint
  96337. ** processing for the operation.
  96338. **
  96339. ** For a DELETE operation, parameter regOld is passed the index of the
  96340. ** first register in an array of (pTab->nCol+1) registers containing the
  96341. ** rowid of the row being deleted, followed by each of the column values
  96342. ** of the row being deleted, from left to right. Parameter regNew is passed
  96343. ** zero in this case.
  96344. **
  96345. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  96346. ** first register of an array of (pTab->nCol+1) registers containing the new
  96347. ** row data.
  96348. **
  96349. ** For an UPDATE operation, this function is called twice. Once before
  96350. ** the original record is deleted from the table using the calling convention
  96351. ** described for DELETE. Then again after the original record is deleted
  96352. ** but before the new record is inserted using the INSERT convention.
  96353. */
  96354. SQLITE_PRIVATE void sqlite3FkCheck(
  96355. Parse *pParse, /* Parse context */
  96356. Table *pTab, /* Row is being deleted from this table */
  96357. int regOld, /* Previous row data is stored here */
  96358. int regNew, /* New row data is stored here */
  96359. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  96360. int bChngRowid /* True if rowid is UPDATEd */
  96361. ){
  96362. sqlite3 *db = pParse->db; /* Database handle */
  96363. FKey *pFKey; /* Used to iterate through FKs */
  96364. int iDb; /* Index of database containing pTab */
  96365. const char *zDb; /* Name of database containing pTab */
  96366. int isIgnoreErrors = pParse->disableTriggers;
  96367. /* Exactly one of regOld and regNew should be non-zero. */
  96368. assert( (regOld==0)!=(regNew==0) );
  96369. /* If foreign-keys are disabled, this function is a no-op. */
  96370. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  96371. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96372. zDb = db->aDb[iDb].zName;
  96373. /* Loop through all the foreign key constraints for which pTab is the
  96374. ** child table (the table that the foreign key definition is part of). */
  96375. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  96376. Table *pTo; /* Parent table of foreign key pFKey */
  96377. Index *pIdx = 0; /* Index on key columns in pTo */
  96378. int *aiFree = 0;
  96379. int *aiCol;
  96380. int iCol;
  96381. int i;
  96382. int bIgnore = 0;
  96383. if( aChange
  96384. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  96385. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  96386. ){
  96387. continue;
  96388. }
  96389. /* Find the parent table of this foreign key. Also find a unique index
  96390. ** on the parent key columns in the parent table. If either of these
  96391. ** schema items cannot be located, set an error in pParse and return
  96392. ** early. */
  96393. if( pParse->disableTriggers ){
  96394. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  96395. }else{
  96396. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  96397. }
  96398. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  96399. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  96400. if( !isIgnoreErrors || db->mallocFailed ) return;
  96401. if( pTo==0 ){
  96402. /* If isIgnoreErrors is true, then a table is being dropped. In this
  96403. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  96404. ** before actually dropping it in order to check FK constraints.
  96405. ** If the parent table of an FK constraint on the current table is
  96406. ** missing, behave as if it is empty. i.e. decrement the relevant
  96407. ** FK counter for each row of the current table with non-NULL keys.
  96408. */
  96409. Vdbe *v = sqlite3GetVdbe(pParse);
  96410. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  96411. for(i=0; i<pFKey->nCol; i++){
  96412. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  96413. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  96414. }
  96415. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  96416. }
  96417. continue;
  96418. }
  96419. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  96420. if( aiFree ){
  96421. aiCol = aiFree;
  96422. }else{
  96423. iCol = pFKey->aCol[0].iFrom;
  96424. aiCol = &iCol;
  96425. }
  96426. for(i=0; i<pFKey->nCol; i++){
  96427. if( aiCol[i]==pTab->iPKey ){
  96428. aiCol[i] = -1;
  96429. }
  96430. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  96431. #ifndef SQLITE_OMIT_AUTHORIZATION
  96432. /* Request permission to read the parent key columns. If the
  96433. ** authorization callback returns SQLITE_IGNORE, behave as if any
  96434. ** values read from the parent table are NULL. */
  96435. if( db->xAuth ){
  96436. int rcauth;
  96437. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  96438. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  96439. bIgnore = (rcauth==SQLITE_IGNORE);
  96440. }
  96441. #endif
  96442. }
  96443. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  96444. ** a cursor to use to search the unique index on the parent key columns
  96445. ** in the parent table. */
  96446. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  96447. pParse->nTab++;
  96448. if( regOld!=0 ){
  96449. /* A row is being removed from the child table. Search for the parent.
  96450. ** If the parent does not exist, removing the child row resolves an
  96451. ** outstanding foreign key constraint violation. */
  96452. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  96453. }
  96454. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  96455. /* A row is being added to the child table. If a parent row cannot
  96456. ** be found, adding the child row has violated the FK constraint.
  96457. **
  96458. ** If this operation is being performed as part of a trigger program
  96459. ** that is actually a "SET NULL" action belonging to this very
  96460. ** foreign key, then omit this scan altogether. As all child key
  96461. ** values are guaranteed to be NULL, it is not possible for adding
  96462. ** this row to cause an FK violation. */
  96463. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  96464. }
  96465. sqlite3DbFree(db, aiFree);
  96466. }
  96467. /* Loop through all the foreign key constraints that refer to this table.
  96468. ** (the "child" constraints) */
  96469. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  96470. Index *pIdx = 0; /* Foreign key index for pFKey */
  96471. SrcList *pSrc;
  96472. int *aiCol = 0;
  96473. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  96474. continue;
  96475. }
  96476. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  96477. && !pParse->pToplevel && !pParse->isMultiWrite
  96478. ){
  96479. assert( regOld==0 && regNew!=0 );
  96480. /* Inserting a single row into a parent table cannot cause (or fix)
  96481. ** an immediate foreign key violation. So do nothing in this case. */
  96482. continue;
  96483. }
  96484. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  96485. if( !isIgnoreErrors || db->mallocFailed ) return;
  96486. continue;
  96487. }
  96488. assert( aiCol || pFKey->nCol==1 );
  96489. /* Create a SrcList structure containing the child table. We need the
  96490. ** child table as a SrcList for sqlite3WhereBegin() */
  96491. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  96492. if( pSrc ){
  96493. struct SrcList_item *pItem = pSrc->a;
  96494. pItem->pTab = pFKey->pFrom;
  96495. pItem->zName = pFKey->pFrom->zName;
  96496. pItem->pTab->nRef++;
  96497. pItem->iCursor = pParse->nTab++;
  96498. if( regNew!=0 ){
  96499. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  96500. }
  96501. if( regOld!=0 ){
  96502. int eAction = pFKey->aAction[aChange!=0];
  96503. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  96504. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  96505. ** action applies, then any foreign key violations caused by
  96506. ** removing the parent key will be rectified by the action trigger.
  96507. ** So do not set the "may-abort" flag in this case.
  96508. **
  96509. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  96510. ** may-abort flag will eventually be set on this statement anyway
  96511. ** (when this function is called as part of processing the UPDATE
  96512. ** within the action trigger).
  96513. **
  96514. ** Note 2: At first glance it may seem like SQLite could simply omit
  96515. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  96516. ** applies. The trouble starts if the CASCADE or SET NULL action
  96517. ** trigger causes other triggers or action rules attached to the
  96518. ** child table to fire. In these cases the fk constraint counters
  96519. ** might be set incorrectly if any OP_FkCounter related scans are
  96520. ** omitted. */
  96521. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  96522. sqlite3MayAbort(pParse);
  96523. }
  96524. }
  96525. pItem->zName = 0;
  96526. sqlite3SrcListDelete(db, pSrc);
  96527. }
  96528. sqlite3DbFree(db, aiCol);
  96529. }
  96530. }
  96531. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  96532. /*
  96533. ** This function is called before generating code to update or delete a
  96534. ** row contained in table pTab.
  96535. */
  96536. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  96537. Parse *pParse, /* Parse context */
  96538. Table *pTab /* Table being modified */
  96539. ){
  96540. u32 mask = 0;
  96541. if( pParse->db->flags&SQLITE_ForeignKeys ){
  96542. FKey *p;
  96543. int i;
  96544. for(p=pTab->pFKey; p; p=p->pNextFrom){
  96545. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  96546. }
  96547. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  96548. Index *pIdx = 0;
  96549. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  96550. if( pIdx ){
  96551. for(i=0; i<pIdx->nKeyCol; i++){
  96552. assert( pIdx->aiColumn[i]>=0 );
  96553. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  96554. }
  96555. }
  96556. }
  96557. }
  96558. return mask;
  96559. }
  96560. /*
  96561. ** This function is called before generating code to update or delete a
  96562. ** row contained in table pTab. If the operation is a DELETE, then
  96563. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  96564. ** to an array of size N, where N is the number of columns in table pTab.
  96565. ** If the i'th column is not modified by the UPDATE, then the corresponding
  96566. ** entry in the aChange[] array is set to -1. If the column is modified,
  96567. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  96568. ** UPDATE statement modifies the rowid fields of the table.
  96569. **
  96570. ** If any foreign key processing will be required, this function returns
  96571. ** true. If there is no foreign key related processing, this function
  96572. ** returns false.
  96573. */
  96574. SQLITE_PRIVATE int sqlite3FkRequired(
  96575. Parse *pParse, /* Parse context */
  96576. Table *pTab, /* Table being modified */
  96577. int *aChange, /* Non-NULL for UPDATE operations */
  96578. int chngRowid /* True for UPDATE that affects rowid */
  96579. ){
  96580. if( pParse->db->flags&SQLITE_ForeignKeys ){
  96581. if( !aChange ){
  96582. /* A DELETE operation. Foreign key processing is required if the
  96583. ** table in question is either the child or parent table for any
  96584. ** foreign key constraint. */
  96585. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  96586. }else{
  96587. /* This is an UPDATE. Foreign key processing is only required if the
  96588. ** operation modifies one or more child or parent key columns. */
  96589. FKey *p;
  96590. /* Check if any child key columns are being modified. */
  96591. for(p=pTab->pFKey; p; p=p->pNextFrom){
  96592. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  96593. }
  96594. /* Check if any parent key columns are being modified. */
  96595. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  96596. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  96597. }
  96598. }
  96599. }
  96600. return 0;
  96601. }
  96602. /*
  96603. ** This function is called when an UPDATE or DELETE operation is being
  96604. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  96605. ** If the current operation is an UPDATE, then the pChanges parameter is
  96606. ** passed a pointer to the list of columns being modified. If it is a
  96607. ** DELETE, pChanges is passed a NULL pointer.
  96608. **
  96609. ** It returns a pointer to a Trigger structure containing a trigger
  96610. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  96611. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  96612. ** returned (these actions require no special handling by the triggers
  96613. ** sub-system, code for them is created by fkScanChildren()).
  96614. **
  96615. ** For example, if pFKey is the foreign key and pTab is table "p" in
  96616. ** the following schema:
  96617. **
  96618. ** CREATE TABLE p(pk PRIMARY KEY);
  96619. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  96620. **
  96621. ** then the returned trigger structure is equivalent to:
  96622. **
  96623. ** CREATE TRIGGER ... DELETE ON p BEGIN
  96624. ** DELETE FROM c WHERE ck = old.pk;
  96625. ** END;
  96626. **
  96627. ** The returned pointer is cached as part of the foreign key object. It
  96628. ** is eventually freed along with the rest of the foreign key object by
  96629. ** sqlite3FkDelete().
  96630. */
  96631. static Trigger *fkActionTrigger(
  96632. Parse *pParse, /* Parse context */
  96633. Table *pTab, /* Table being updated or deleted from */
  96634. FKey *pFKey, /* Foreign key to get action for */
  96635. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  96636. ){
  96637. sqlite3 *db = pParse->db; /* Database handle */
  96638. int action; /* One of OE_None, OE_Cascade etc. */
  96639. Trigger *pTrigger; /* Trigger definition to return */
  96640. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  96641. action = pFKey->aAction[iAction];
  96642. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  96643. return 0;
  96644. }
  96645. pTrigger = pFKey->apTrigger[iAction];
  96646. if( action!=OE_None && !pTrigger ){
  96647. char const *zFrom; /* Name of child table */
  96648. int nFrom; /* Length in bytes of zFrom */
  96649. Index *pIdx = 0; /* Parent key index for this FK */
  96650. int *aiCol = 0; /* child table cols -> parent key cols */
  96651. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  96652. Expr *pWhere = 0; /* WHERE clause of trigger step */
  96653. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  96654. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  96655. int i; /* Iterator variable */
  96656. Expr *pWhen = 0; /* WHEN clause for the trigger */
  96657. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  96658. assert( aiCol || pFKey->nCol==1 );
  96659. for(i=0; i<pFKey->nCol; i++){
  96660. Token tOld = { "old", 3 }; /* Literal "old" token */
  96661. Token tNew = { "new", 3 }; /* Literal "new" token */
  96662. Token tFromCol; /* Name of column in child table */
  96663. Token tToCol; /* Name of column in parent table */
  96664. int iFromCol; /* Idx of column in child table */
  96665. Expr *pEq; /* tFromCol = OLD.tToCol */
  96666. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  96667. assert( iFromCol>=0 );
  96668. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  96669. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  96670. sqlite3TokenInit(&tToCol,
  96671. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  96672. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  96673. /* Create the expression "OLD.zToCol = zFromCol". It is important
  96674. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  96675. ** that the affinity and collation sequence associated with the
  96676. ** parent table are used for the comparison. */
  96677. pEq = sqlite3PExpr(pParse, TK_EQ,
  96678. sqlite3PExpr(pParse, TK_DOT,
  96679. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  96680. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  96681. , 0),
  96682. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  96683. , 0);
  96684. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  96685. /* For ON UPDATE, construct the next term of the WHEN clause.
  96686. ** The final WHEN clause will be like this:
  96687. **
  96688. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  96689. */
  96690. if( pChanges ){
  96691. pEq = sqlite3PExpr(pParse, TK_IS,
  96692. sqlite3PExpr(pParse, TK_DOT,
  96693. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  96694. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  96695. 0),
  96696. sqlite3PExpr(pParse, TK_DOT,
  96697. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  96698. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  96699. 0),
  96700. 0);
  96701. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  96702. }
  96703. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  96704. Expr *pNew;
  96705. if( action==OE_Cascade ){
  96706. pNew = sqlite3PExpr(pParse, TK_DOT,
  96707. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  96708. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  96709. , 0);
  96710. }else if( action==OE_SetDflt ){
  96711. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  96712. if( pDflt ){
  96713. pNew = sqlite3ExprDup(db, pDflt, 0);
  96714. }else{
  96715. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  96716. }
  96717. }else{
  96718. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  96719. }
  96720. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  96721. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  96722. }
  96723. }
  96724. sqlite3DbFree(db, aiCol);
  96725. zFrom = pFKey->pFrom->zName;
  96726. nFrom = sqlite3Strlen30(zFrom);
  96727. if( action==OE_Restrict ){
  96728. Token tFrom;
  96729. Expr *pRaise;
  96730. tFrom.z = zFrom;
  96731. tFrom.n = nFrom;
  96732. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  96733. if( pRaise ){
  96734. pRaise->affinity = OE_Abort;
  96735. }
  96736. pSelect = sqlite3SelectNew(pParse,
  96737. sqlite3ExprListAppend(pParse, 0, pRaise),
  96738. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  96739. pWhere,
  96740. 0, 0, 0, 0, 0, 0
  96741. );
  96742. pWhere = 0;
  96743. }
  96744. /* Disable lookaside memory allocation */
  96745. db->lookaside.bDisable++;
  96746. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  96747. sizeof(Trigger) + /* struct Trigger */
  96748. sizeof(TriggerStep) + /* Single step in trigger program */
  96749. nFrom + 1 /* Space for pStep->zTarget */
  96750. );
  96751. if( pTrigger ){
  96752. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  96753. pStep->zTarget = (char *)&pStep[1];
  96754. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  96755. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  96756. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  96757. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  96758. if( pWhen ){
  96759. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  96760. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  96761. }
  96762. }
  96763. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  96764. db->lookaside.bDisable--;
  96765. sqlite3ExprDelete(db, pWhere);
  96766. sqlite3ExprDelete(db, pWhen);
  96767. sqlite3ExprListDelete(db, pList);
  96768. sqlite3SelectDelete(db, pSelect);
  96769. if( db->mallocFailed==1 ){
  96770. fkTriggerDelete(db, pTrigger);
  96771. return 0;
  96772. }
  96773. assert( pStep!=0 );
  96774. switch( action ){
  96775. case OE_Restrict:
  96776. pStep->op = TK_SELECT;
  96777. break;
  96778. case OE_Cascade:
  96779. if( !pChanges ){
  96780. pStep->op = TK_DELETE;
  96781. break;
  96782. }
  96783. default:
  96784. pStep->op = TK_UPDATE;
  96785. }
  96786. pStep->pTrig = pTrigger;
  96787. pTrigger->pSchema = pTab->pSchema;
  96788. pTrigger->pTabSchema = pTab->pSchema;
  96789. pFKey->apTrigger[iAction] = pTrigger;
  96790. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  96791. }
  96792. return pTrigger;
  96793. }
  96794. /*
  96795. ** This function is called when deleting or updating a row to implement
  96796. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  96797. */
  96798. SQLITE_PRIVATE void sqlite3FkActions(
  96799. Parse *pParse, /* Parse context */
  96800. Table *pTab, /* Table being updated or deleted from */
  96801. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  96802. int regOld, /* Address of array containing old row */
  96803. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  96804. int bChngRowid /* True if rowid is UPDATEd */
  96805. ){
  96806. /* If foreign-key support is enabled, iterate through all FKs that
  96807. ** refer to table pTab. If there is an action associated with the FK
  96808. ** for this operation (either update or delete), invoke the associated
  96809. ** trigger sub-program. */
  96810. if( pParse->db->flags&SQLITE_ForeignKeys ){
  96811. FKey *pFKey; /* Iterator variable */
  96812. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  96813. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  96814. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  96815. if( pAct ){
  96816. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  96817. }
  96818. }
  96819. }
  96820. }
  96821. }
  96822. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  96823. /*
  96824. ** Free all memory associated with foreign key definitions attached to
  96825. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  96826. ** hash table.
  96827. */
  96828. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  96829. FKey *pFKey; /* Iterator variable */
  96830. FKey *pNext; /* Copy of pFKey->pNextFrom */
  96831. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  96832. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  96833. /* Remove the FK from the fkeyHash hash table. */
  96834. if( !db || db->pnBytesFreed==0 ){
  96835. if( pFKey->pPrevTo ){
  96836. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  96837. }else{
  96838. void *p = (void *)pFKey->pNextTo;
  96839. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  96840. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  96841. }
  96842. if( pFKey->pNextTo ){
  96843. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  96844. }
  96845. }
  96846. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  96847. ** classified as either immediate or deferred.
  96848. */
  96849. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  96850. /* Delete any triggers created to implement actions for this FK. */
  96851. #ifndef SQLITE_OMIT_TRIGGER
  96852. fkTriggerDelete(db, pFKey->apTrigger[0]);
  96853. fkTriggerDelete(db, pFKey->apTrigger[1]);
  96854. #endif
  96855. pNext = pFKey->pNextFrom;
  96856. sqlite3DbFree(db, pFKey);
  96857. }
  96858. }
  96859. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  96860. /************** End of fkey.c ************************************************/
  96861. /************** Begin file insert.c ******************************************/
  96862. /*
  96863. ** 2001 September 15
  96864. **
  96865. ** The author disclaims copyright to this source code. In place of
  96866. ** a legal notice, here is a blessing:
  96867. **
  96868. ** May you do good and not evil.
  96869. ** May you find forgiveness for yourself and forgive others.
  96870. ** May you share freely, never taking more than you give.
  96871. **
  96872. *************************************************************************
  96873. ** This file contains C code routines that are called by the parser
  96874. ** to handle INSERT statements in SQLite.
  96875. */
  96876. /* #include "sqliteInt.h" */
  96877. /*
  96878. ** Generate code that will
  96879. **
  96880. ** (1) acquire a lock for table pTab then
  96881. ** (2) open pTab as cursor iCur.
  96882. **
  96883. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  96884. ** for that table that is actually opened.
  96885. */
  96886. SQLITE_PRIVATE void sqlite3OpenTable(
  96887. Parse *pParse, /* Generate code into this VDBE */
  96888. int iCur, /* The cursor number of the table */
  96889. int iDb, /* The database index in sqlite3.aDb[] */
  96890. Table *pTab, /* The table to be opened */
  96891. int opcode /* OP_OpenRead or OP_OpenWrite */
  96892. ){
  96893. Vdbe *v;
  96894. assert( !IsVirtual(pTab) );
  96895. v = sqlite3GetVdbe(pParse);
  96896. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  96897. sqlite3TableLock(pParse, iDb, pTab->tnum,
  96898. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  96899. if( HasRowid(pTab) ){
  96900. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  96901. VdbeComment((v, "%s", pTab->zName));
  96902. }else{
  96903. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  96904. assert( pPk!=0 );
  96905. assert( pPk->tnum==pTab->tnum );
  96906. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  96907. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  96908. VdbeComment((v, "%s", pTab->zName));
  96909. }
  96910. }
  96911. /*
  96912. ** Return a pointer to the column affinity string associated with index
  96913. ** pIdx. A column affinity string has one character for each column in
  96914. ** the table, according to the affinity of the column:
  96915. **
  96916. ** Character Column affinity
  96917. ** ------------------------------
  96918. ** 'A' BLOB
  96919. ** 'B' TEXT
  96920. ** 'C' NUMERIC
  96921. ** 'D' INTEGER
  96922. ** 'F' REAL
  96923. **
  96924. ** An extra 'D' is appended to the end of the string to cover the
  96925. ** rowid that appears as the last column in every index.
  96926. **
  96927. ** Memory for the buffer containing the column index affinity string
  96928. ** is managed along with the rest of the Index structure. It will be
  96929. ** released when sqlite3DeleteIndex() is called.
  96930. */
  96931. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  96932. if( !pIdx->zColAff ){
  96933. /* The first time a column affinity string for a particular index is
  96934. ** required, it is allocated and populated here. It is then stored as
  96935. ** a member of the Index structure for subsequent use.
  96936. **
  96937. ** The column affinity string will eventually be deleted by
  96938. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  96939. ** up.
  96940. */
  96941. int n;
  96942. Table *pTab = pIdx->pTable;
  96943. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  96944. if( !pIdx->zColAff ){
  96945. sqlite3OomFault(db);
  96946. return 0;
  96947. }
  96948. for(n=0; n<pIdx->nColumn; n++){
  96949. i16 x = pIdx->aiColumn[n];
  96950. if( x>=0 ){
  96951. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  96952. }else if( x==XN_ROWID ){
  96953. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  96954. }else{
  96955. char aff;
  96956. assert( x==XN_EXPR );
  96957. assert( pIdx->aColExpr!=0 );
  96958. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  96959. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  96960. pIdx->zColAff[n] = aff;
  96961. }
  96962. }
  96963. pIdx->zColAff[n] = 0;
  96964. }
  96965. return pIdx->zColAff;
  96966. }
  96967. /*
  96968. ** Compute the affinity string for table pTab, if it has not already been
  96969. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  96970. **
  96971. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  96972. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  96973. ** for register iReg and following. Or if affinities exists and iReg==0,
  96974. ** then just set the P4 operand of the previous opcode (which should be
  96975. ** an OP_MakeRecord) to the affinity string.
  96976. **
  96977. ** A column affinity string has one character per column:
  96978. **
  96979. ** Character Column affinity
  96980. ** ------------------------------
  96981. ** 'A' BLOB
  96982. ** 'B' TEXT
  96983. ** 'C' NUMERIC
  96984. ** 'D' INTEGER
  96985. ** 'E' REAL
  96986. */
  96987. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  96988. int i;
  96989. char *zColAff = pTab->zColAff;
  96990. if( zColAff==0 ){
  96991. sqlite3 *db = sqlite3VdbeDb(v);
  96992. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  96993. if( !zColAff ){
  96994. sqlite3OomFault(db);
  96995. return;
  96996. }
  96997. for(i=0; i<pTab->nCol; i++){
  96998. zColAff[i] = pTab->aCol[i].affinity;
  96999. }
  97000. do{
  97001. zColAff[i--] = 0;
  97002. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  97003. pTab->zColAff = zColAff;
  97004. }
  97005. i = sqlite3Strlen30(zColAff);
  97006. if( i ){
  97007. if( iReg ){
  97008. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  97009. }else{
  97010. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  97011. }
  97012. }
  97013. }
  97014. /*
  97015. ** Return non-zero if the table pTab in database iDb or any of its indices
  97016. ** have been opened at any point in the VDBE program. This is used to see if
  97017. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  97018. ** run without using a temporary table for the results of the SELECT.
  97019. */
  97020. static int readsTable(Parse *p, int iDb, Table *pTab){
  97021. Vdbe *v = sqlite3GetVdbe(p);
  97022. int i;
  97023. int iEnd = sqlite3VdbeCurrentAddr(v);
  97024. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97025. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  97026. #endif
  97027. for(i=1; i<iEnd; i++){
  97028. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  97029. assert( pOp!=0 );
  97030. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  97031. Index *pIndex;
  97032. int tnum = pOp->p2;
  97033. if( tnum==pTab->tnum ){
  97034. return 1;
  97035. }
  97036. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  97037. if( tnum==pIndex->tnum ){
  97038. return 1;
  97039. }
  97040. }
  97041. }
  97042. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97043. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  97044. assert( pOp->p4.pVtab!=0 );
  97045. assert( pOp->p4type==P4_VTAB );
  97046. return 1;
  97047. }
  97048. #endif
  97049. }
  97050. return 0;
  97051. }
  97052. #ifndef SQLITE_OMIT_AUTOINCREMENT
  97053. /*
  97054. ** Locate or create an AutoincInfo structure associated with table pTab
  97055. ** which is in database iDb. Return the register number for the register
  97056. ** that holds the maximum rowid.
  97057. **
  97058. ** There is at most one AutoincInfo structure per table even if the
  97059. ** same table is autoincremented multiple times due to inserts within
  97060. ** triggers. A new AutoincInfo structure is created if this is the
  97061. ** first use of table pTab. On 2nd and subsequent uses, the original
  97062. ** AutoincInfo structure is used.
  97063. **
  97064. ** Three memory locations are allocated:
  97065. **
  97066. ** (1) Register to hold the name of the pTab table.
  97067. ** (2) Register to hold the maximum ROWID of pTab.
  97068. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  97069. **
  97070. ** The 2nd register is the one that is returned. That is all the
  97071. ** insert routine needs to know about.
  97072. */
  97073. static int autoIncBegin(
  97074. Parse *pParse, /* Parsing context */
  97075. int iDb, /* Index of the database holding pTab */
  97076. Table *pTab /* The table we are writing to */
  97077. ){
  97078. int memId = 0; /* Register holding maximum rowid */
  97079. if( pTab->tabFlags & TF_Autoincrement ){
  97080. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97081. AutoincInfo *pInfo;
  97082. pInfo = pToplevel->pAinc;
  97083. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  97084. if( pInfo==0 ){
  97085. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  97086. if( pInfo==0 ) return 0;
  97087. pInfo->pNext = pToplevel->pAinc;
  97088. pToplevel->pAinc = pInfo;
  97089. pInfo->pTab = pTab;
  97090. pInfo->iDb = iDb;
  97091. pToplevel->nMem++; /* Register to hold name of table */
  97092. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  97093. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  97094. }
  97095. memId = pInfo->regCtr;
  97096. }
  97097. return memId;
  97098. }
  97099. /*
  97100. ** This routine generates code that will initialize all of the
  97101. ** register used by the autoincrement tracker.
  97102. */
  97103. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  97104. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  97105. sqlite3 *db = pParse->db; /* The database connection */
  97106. Db *pDb; /* Database only autoinc table */
  97107. int memId; /* Register holding max rowid */
  97108. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  97109. /* This routine is never called during trigger-generation. It is
  97110. ** only called from the top-level */
  97111. assert( pParse->pTriggerTab==0 );
  97112. assert( sqlite3IsToplevel(pParse) );
  97113. assert( v ); /* We failed long ago if this is not so */
  97114. for(p = pParse->pAinc; p; p = p->pNext){
  97115. static const int iLn = VDBE_OFFSET_LINENO(2);
  97116. static const VdbeOpList autoInc[] = {
  97117. /* 0 */ {OP_Null, 0, 0, 0},
  97118. /* 1 */ {OP_Rewind, 0, 9, 0},
  97119. /* 2 */ {OP_Column, 0, 0, 0},
  97120. /* 3 */ {OP_Ne, 0, 7, 0},
  97121. /* 4 */ {OP_Rowid, 0, 0, 0},
  97122. /* 5 */ {OP_Column, 0, 1, 0},
  97123. /* 6 */ {OP_Goto, 0, 9, 0},
  97124. /* 7 */ {OP_Next, 0, 2, 0},
  97125. /* 8 */ {OP_Integer, 0, 0, 0},
  97126. /* 9 */ {OP_Close, 0, 0, 0}
  97127. };
  97128. VdbeOp *aOp;
  97129. pDb = &db->aDb[p->iDb];
  97130. memId = p->regCtr;
  97131. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  97132. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  97133. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  97134. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  97135. if( aOp==0 ) break;
  97136. aOp[0].p2 = memId;
  97137. aOp[0].p3 = memId+1;
  97138. aOp[2].p3 = memId;
  97139. aOp[3].p1 = memId-1;
  97140. aOp[3].p3 = memId;
  97141. aOp[3].p5 = SQLITE_JUMPIFNULL;
  97142. aOp[4].p2 = memId+1;
  97143. aOp[5].p3 = memId;
  97144. aOp[8].p2 = memId;
  97145. }
  97146. }
  97147. /*
  97148. ** Update the maximum rowid for an autoincrement calculation.
  97149. **
  97150. ** This routine should be called when the regRowid register holds a
  97151. ** new rowid that is about to be inserted. If that new rowid is
  97152. ** larger than the maximum rowid in the memId memory cell, then the
  97153. ** memory cell is updated.
  97154. */
  97155. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  97156. if( memId>0 ){
  97157. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  97158. }
  97159. }
  97160. /*
  97161. ** This routine generates the code needed to write autoincrement
  97162. ** maximum rowid values back into the sqlite_sequence register.
  97163. ** Every statement that might do an INSERT into an autoincrement
  97164. ** table (either directly or through triggers) needs to call this
  97165. ** routine just before the "exit" code.
  97166. */
  97167. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  97168. AutoincInfo *p;
  97169. Vdbe *v = pParse->pVdbe;
  97170. sqlite3 *db = pParse->db;
  97171. assert( v );
  97172. for(p = pParse->pAinc; p; p = p->pNext){
  97173. static const int iLn = VDBE_OFFSET_LINENO(2);
  97174. static const VdbeOpList autoIncEnd[] = {
  97175. /* 0 */ {OP_NotNull, 0, 2, 0},
  97176. /* 1 */ {OP_NewRowid, 0, 0, 0},
  97177. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  97178. /* 3 */ {OP_Insert, 0, 0, 0},
  97179. /* 4 */ {OP_Close, 0, 0, 0}
  97180. };
  97181. VdbeOp *aOp;
  97182. Db *pDb = &db->aDb[p->iDb];
  97183. int iRec;
  97184. int memId = p->regCtr;
  97185. iRec = sqlite3GetTempReg(pParse);
  97186. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  97187. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  97188. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  97189. if( aOp==0 ) break;
  97190. aOp[0].p1 = memId+1;
  97191. aOp[1].p2 = memId+1;
  97192. aOp[2].p1 = memId-1;
  97193. aOp[2].p3 = iRec;
  97194. aOp[3].p2 = iRec;
  97195. aOp[3].p3 = memId+1;
  97196. aOp[3].p5 = OPFLAG_APPEND;
  97197. sqlite3ReleaseTempReg(pParse, iRec);
  97198. }
  97199. }
  97200. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  97201. if( pParse->pAinc ) autoIncrementEnd(pParse);
  97202. }
  97203. #else
  97204. /*
  97205. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  97206. ** above are all no-ops
  97207. */
  97208. # define autoIncBegin(A,B,C) (0)
  97209. # define autoIncStep(A,B,C)
  97210. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  97211. /* Forward declaration */
  97212. static int xferOptimization(
  97213. Parse *pParse, /* Parser context */
  97214. Table *pDest, /* The table we are inserting into */
  97215. Select *pSelect, /* A SELECT statement to use as the data source */
  97216. int onError, /* How to handle constraint errors */
  97217. int iDbDest /* The database of pDest */
  97218. );
  97219. /*
  97220. ** This routine is called to handle SQL of the following forms:
  97221. **
  97222. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  97223. ** insert into TABLE (IDLIST) select
  97224. ** insert into TABLE (IDLIST) default values
  97225. **
  97226. ** The IDLIST following the table name is always optional. If omitted,
  97227. ** then a list of all (non-hidden) columns for the table is substituted.
  97228. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  97229. ** is omitted.
  97230. **
  97231. ** For the pSelect parameter holds the values to be inserted for the
  97232. ** first two forms shown above. A VALUES clause is really just short-hand
  97233. ** for a SELECT statement that omits the FROM clause and everything else
  97234. ** that follows. If the pSelect parameter is NULL, that means that the
  97235. ** DEFAULT VALUES form of the INSERT statement is intended.
  97236. **
  97237. ** The code generated follows one of four templates. For a simple
  97238. ** insert with data coming from a single-row VALUES clause, the code executes
  97239. ** once straight down through. Pseudo-code follows (we call this
  97240. ** the "1st template"):
  97241. **
  97242. ** open write cursor to <table> and its indices
  97243. ** put VALUES clause expressions into registers
  97244. ** write the resulting record into <table>
  97245. ** cleanup
  97246. **
  97247. ** The three remaining templates assume the statement is of the form
  97248. **
  97249. ** INSERT INTO <table> SELECT ...
  97250. **
  97251. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  97252. ** in other words if the SELECT pulls all columns from a single table
  97253. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  97254. ** if <table2> and <table1> are distinct tables but have identical
  97255. ** schemas, including all the same indices, then a special optimization
  97256. ** is invoked that copies raw records from <table2> over to <table1>.
  97257. ** See the xferOptimization() function for the implementation of this
  97258. ** template. This is the 2nd template.
  97259. **
  97260. ** open a write cursor to <table>
  97261. ** open read cursor on <table2>
  97262. ** transfer all records in <table2> over to <table>
  97263. ** close cursors
  97264. ** foreach index on <table>
  97265. ** open a write cursor on the <table> index
  97266. ** open a read cursor on the corresponding <table2> index
  97267. ** transfer all records from the read to the write cursors
  97268. ** close cursors
  97269. ** end foreach
  97270. **
  97271. ** The 3rd template is for when the second template does not apply
  97272. ** and the SELECT clause does not read from <table> at any time.
  97273. ** The generated code follows this template:
  97274. **
  97275. ** X <- A
  97276. ** goto B
  97277. ** A: setup for the SELECT
  97278. ** loop over the rows in the SELECT
  97279. ** load values into registers R..R+n
  97280. ** yield X
  97281. ** end loop
  97282. ** cleanup after the SELECT
  97283. ** end-coroutine X
  97284. ** B: open write cursor to <table> and its indices
  97285. ** C: yield X, at EOF goto D
  97286. ** insert the select result into <table> from R..R+n
  97287. ** goto C
  97288. ** D: cleanup
  97289. **
  97290. ** The 4th template is used if the insert statement takes its
  97291. ** values from a SELECT but the data is being inserted into a table
  97292. ** that is also read as part of the SELECT. In the third form,
  97293. ** we have to use an intermediate table to store the results of
  97294. ** the select. The template is like this:
  97295. **
  97296. ** X <- A
  97297. ** goto B
  97298. ** A: setup for the SELECT
  97299. ** loop over the tables in the SELECT
  97300. ** load value into register R..R+n
  97301. ** yield X
  97302. ** end loop
  97303. ** cleanup after the SELECT
  97304. ** end co-routine R
  97305. ** B: open temp table
  97306. ** L: yield X, at EOF goto M
  97307. ** insert row from R..R+n into temp table
  97308. ** goto L
  97309. ** M: open write cursor to <table> and its indices
  97310. ** rewind temp table
  97311. ** C: loop over rows of intermediate table
  97312. ** transfer values form intermediate table into <table>
  97313. ** end loop
  97314. ** D: cleanup
  97315. */
  97316. SQLITE_PRIVATE void sqlite3Insert(
  97317. Parse *pParse, /* Parser context */
  97318. SrcList *pTabList, /* Name of table into which we are inserting */
  97319. Select *pSelect, /* A SELECT statement to use as the data source */
  97320. IdList *pColumn, /* Column names corresponding to IDLIST. */
  97321. int onError /* How to handle constraint errors */
  97322. ){
  97323. sqlite3 *db; /* The main database structure */
  97324. Table *pTab; /* The table to insert into. aka TABLE */
  97325. char *zTab; /* Name of the table into which we are inserting */
  97326. const char *zDb; /* Name of the database holding this table */
  97327. int i, j, idx; /* Loop counters */
  97328. Vdbe *v; /* Generate code into this virtual machine */
  97329. Index *pIdx; /* For looping over indices of the table */
  97330. int nColumn; /* Number of columns in the data */
  97331. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  97332. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  97333. int iIdxCur = 0; /* First index cursor */
  97334. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  97335. int endOfLoop; /* Label for the end of the insertion loop */
  97336. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  97337. int addrInsTop = 0; /* Jump to label "D" */
  97338. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  97339. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  97340. int iDb; /* Index of database holding TABLE */
  97341. Db *pDb; /* The database containing table being inserted into */
  97342. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  97343. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  97344. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  97345. u8 bIdListInOrder; /* True if IDLIST is in table order */
  97346. ExprList *pList = 0; /* List of VALUES() to be inserted */
  97347. /* Register allocations */
  97348. int regFromSelect = 0;/* Base register for data coming from SELECT */
  97349. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  97350. int regRowCount = 0; /* Memory cell used for the row counter */
  97351. int regIns; /* Block of regs holding rowid+data being inserted */
  97352. int regRowid; /* registers holding insert rowid */
  97353. int regData; /* register holding first column to insert */
  97354. int *aRegIdx = 0; /* One register allocated to each index */
  97355. #ifndef SQLITE_OMIT_TRIGGER
  97356. int isView; /* True if attempting to insert into a view */
  97357. Trigger *pTrigger; /* List of triggers on pTab, if required */
  97358. int tmask; /* Mask of trigger times */
  97359. #endif
  97360. db = pParse->db;
  97361. memset(&dest, 0, sizeof(dest));
  97362. if( pParse->nErr || db->mallocFailed ){
  97363. goto insert_cleanup;
  97364. }
  97365. /* If the Select object is really just a simple VALUES() list with a
  97366. ** single row (the common case) then keep that one row of values
  97367. ** and discard the other (unused) parts of the pSelect object
  97368. */
  97369. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  97370. pList = pSelect->pEList;
  97371. pSelect->pEList = 0;
  97372. sqlite3SelectDelete(db, pSelect);
  97373. pSelect = 0;
  97374. }
  97375. /* Locate the table into which we will be inserting new information.
  97376. */
  97377. assert( pTabList->nSrc==1 );
  97378. zTab = pTabList->a[0].zName;
  97379. if( NEVER(zTab==0) ) goto insert_cleanup;
  97380. pTab = sqlite3SrcListLookup(pParse, pTabList);
  97381. if( pTab==0 ){
  97382. goto insert_cleanup;
  97383. }
  97384. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  97385. assert( iDb<db->nDb );
  97386. pDb = &db->aDb[iDb];
  97387. zDb = pDb->zName;
  97388. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  97389. goto insert_cleanup;
  97390. }
  97391. withoutRowid = !HasRowid(pTab);
  97392. /* Figure out if we have any triggers and if the table being
  97393. ** inserted into is a view
  97394. */
  97395. #ifndef SQLITE_OMIT_TRIGGER
  97396. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  97397. isView = pTab->pSelect!=0;
  97398. #else
  97399. # define pTrigger 0
  97400. # define tmask 0
  97401. # define isView 0
  97402. #endif
  97403. #ifdef SQLITE_OMIT_VIEW
  97404. # undef isView
  97405. # define isView 0
  97406. #endif
  97407. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  97408. /* If pTab is really a view, make sure it has been initialized.
  97409. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  97410. */
  97411. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  97412. goto insert_cleanup;
  97413. }
  97414. /* Cannot insert into a read-only table.
  97415. */
  97416. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  97417. goto insert_cleanup;
  97418. }
  97419. /* Allocate a VDBE
  97420. */
  97421. v = sqlite3GetVdbe(pParse);
  97422. if( v==0 ) goto insert_cleanup;
  97423. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  97424. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  97425. #ifndef SQLITE_OMIT_XFER_OPT
  97426. /* If the statement is of the form
  97427. **
  97428. ** INSERT INTO <table1> SELECT * FROM <table2>;
  97429. **
  97430. ** Then special optimizations can be applied that make the transfer
  97431. ** very fast and which reduce fragmentation of indices.
  97432. **
  97433. ** This is the 2nd template.
  97434. */
  97435. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  97436. assert( !pTrigger );
  97437. assert( pList==0 );
  97438. goto insert_end;
  97439. }
  97440. #endif /* SQLITE_OMIT_XFER_OPT */
  97441. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  97442. ** sqlite_sequence table and store it in memory cell regAutoinc.
  97443. */
  97444. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  97445. /* Allocate registers for holding the rowid of the new row,
  97446. ** the content of the new row, and the assembled row record.
  97447. */
  97448. regRowid = regIns = pParse->nMem+1;
  97449. pParse->nMem += pTab->nCol + 1;
  97450. if( IsVirtual(pTab) ){
  97451. regRowid++;
  97452. pParse->nMem++;
  97453. }
  97454. regData = regRowid+1;
  97455. /* If the INSERT statement included an IDLIST term, then make sure
  97456. ** all elements of the IDLIST really are columns of the table and
  97457. ** remember the column indices.
  97458. **
  97459. ** If the table has an INTEGER PRIMARY KEY column and that column
  97460. ** is named in the IDLIST, then record in the ipkColumn variable
  97461. ** the index into IDLIST of the primary key column. ipkColumn is
  97462. ** the index of the primary key as it appears in IDLIST, not as
  97463. ** is appears in the original table. (The index of the INTEGER
  97464. ** PRIMARY KEY in the original table is pTab->iPKey.)
  97465. */
  97466. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  97467. if( pColumn ){
  97468. for(i=0; i<pColumn->nId; i++){
  97469. pColumn->a[i].idx = -1;
  97470. }
  97471. for(i=0; i<pColumn->nId; i++){
  97472. for(j=0; j<pTab->nCol; j++){
  97473. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  97474. pColumn->a[i].idx = j;
  97475. if( i!=j ) bIdListInOrder = 0;
  97476. if( j==pTab->iPKey ){
  97477. ipkColumn = i; assert( !withoutRowid );
  97478. }
  97479. break;
  97480. }
  97481. }
  97482. if( j>=pTab->nCol ){
  97483. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  97484. ipkColumn = i;
  97485. bIdListInOrder = 0;
  97486. }else{
  97487. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  97488. pTabList, 0, pColumn->a[i].zName);
  97489. pParse->checkSchema = 1;
  97490. goto insert_cleanup;
  97491. }
  97492. }
  97493. }
  97494. }
  97495. /* Figure out how many columns of data are supplied. If the data
  97496. ** is coming from a SELECT statement, then generate a co-routine that
  97497. ** produces a single row of the SELECT on each invocation. The
  97498. ** co-routine is the common header to the 3rd and 4th templates.
  97499. */
  97500. if( pSelect ){
  97501. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  97502. ** Generate a co-routine to run the SELECT. */
  97503. int regYield; /* Register holding co-routine entry-point */
  97504. int addrTop; /* Top of the co-routine */
  97505. int rc; /* Result code */
  97506. regYield = ++pParse->nMem;
  97507. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  97508. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  97509. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  97510. dest.iSdst = bIdListInOrder ? regData : 0;
  97511. dest.nSdst = pTab->nCol;
  97512. rc = sqlite3Select(pParse, pSelect, &dest);
  97513. regFromSelect = dest.iSdst;
  97514. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  97515. sqlite3VdbeEndCoroutine(v, regYield);
  97516. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  97517. assert( pSelect->pEList );
  97518. nColumn = pSelect->pEList->nExpr;
  97519. /* Set useTempTable to TRUE if the result of the SELECT statement
  97520. ** should be written into a temporary table (template 4). Set to
  97521. ** FALSE if each output row of the SELECT can be written directly into
  97522. ** the destination table (template 3).
  97523. **
  97524. ** A temp table must be used if the table being updated is also one
  97525. ** of the tables being read by the SELECT statement. Also use a
  97526. ** temp table in the case of row triggers.
  97527. */
  97528. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  97529. useTempTable = 1;
  97530. }
  97531. if( useTempTable ){
  97532. /* Invoke the coroutine to extract information from the SELECT
  97533. ** and add it to a transient table srcTab. The code generated
  97534. ** here is from the 4th template:
  97535. **
  97536. ** B: open temp table
  97537. ** L: yield X, goto M at EOF
  97538. ** insert row from R..R+n into temp table
  97539. ** goto L
  97540. ** M: ...
  97541. */
  97542. int regRec; /* Register to hold packed record */
  97543. int regTempRowid; /* Register to hold temp table ROWID */
  97544. int addrL; /* Label "L" */
  97545. srcTab = pParse->nTab++;
  97546. regRec = sqlite3GetTempReg(pParse);
  97547. regTempRowid = sqlite3GetTempReg(pParse);
  97548. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  97549. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  97550. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  97551. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  97552. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  97553. sqlite3VdbeGoto(v, addrL);
  97554. sqlite3VdbeJumpHere(v, addrL);
  97555. sqlite3ReleaseTempReg(pParse, regRec);
  97556. sqlite3ReleaseTempReg(pParse, regTempRowid);
  97557. }
  97558. }else{
  97559. /* This is the case if the data for the INSERT is coming from a
  97560. ** single-row VALUES clause
  97561. */
  97562. NameContext sNC;
  97563. memset(&sNC, 0, sizeof(sNC));
  97564. sNC.pParse = pParse;
  97565. srcTab = -1;
  97566. assert( useTempTable==0 );
  97567. if( pList ){
  97568. nColumn = pList->nExpr;
  97569. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  97570. goto insert_cleanup;
  97571. }
  97572. }else{
  97573. nColumn = 0;
  97574. }
  97575. }
  97576. /* If there is no IDLIST term but the table has an integer primary
  97577. ** key, the set the ipkColumn variable to the integer primary key
  97578. ** column index in the original table definition.
  97579. */
  97580. if( pColumn==0 && nColumn>0 ){
  97581. ipkColumn = pTab->iPKey;
  97582. }
  97583. /* Make sure the number of columns in the source data matches the number
  97584. ** of columns to be inserted into the table.
  97585. */
  97586. for(i=0; i<pTab->nCol; i++){
  97587. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  97588. }
  97589. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  97590. sqlite3ErrorMsg(pParse,
  97591. "table %S has %d columns but %d values were supplied",
  97592. pTabList, 0, pTab->nCol-nHidden, nColumn);
  97593. goto insert_cleanup;
  97594. }
  97595. if( pColumn!=0 && nColumn!=pColumn->nId ){
  97596. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  97597. goto insert_cleanup;
  97598. }
  97599. /* Initialize the count of rows to be inserted
  97600. */
  97601. if( db->flags & SQLITE_CountRows ){
  97602. regRowCount = ++pParse->nMem;
  97603. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  97604. }
  97605. /* If this is not a view, open the table and and all indices */
  97606. if( !isView ){
  97607. int nIdx;
  97608. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  97609. &iDataCur, &iIdxCur);
  97610. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  97611. if( aRegIdx==0 ){
  97612. goto insert_cleanup;
  97613. }
  97614. for(i=0; i<nIdx; i++){
  97615. aRegIdx[i] = ++pParse->nMem;
  97616. }
  97617. }
  97618. /* This is the top of the main insertion loop */
  97619. if( useTempTable ){
  97620. /* This block codes the top of loop only. The complete loop is the
  97621. ** following pseudocode (template 4):
  97622. **
  97623. ** rewind temp table, if empty goto D
  97624. ** C: loop over rows of intermediate table
  97625. ** transfer values form intermediate table into <table>
  97626. ** end loop
  97627. ** D: ...
  97628. */
  97629. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  97630. addrCont = sqlite3VdbeCurrentAddr(v);
  97631. }else if( pSelect ){
  97632. /* This block codes the top of loop only. The complete loop is the
  97633. ** following pseudocode (template 3):
  97634. **
  97635. ** C: yield X, at EOF goto D
  97636. ** insert the select result into <table> from R..R+n
  97637. ** goto C
  97638. ** D: ...
  97639. */
  97640. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  97641. VdbeCoverage(v);
  97642. }
  97643. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  97644. */
  97645. endOfLoop = sqlite3VdbeMakeLabel(v);
  97646. if( tmask & TRIGGER_BEFORE ){
  97647. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  97648. /* build the NEW.* reference row. Note that if there is an INTEGER
  97649. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  97650. ** translated into a unique ID for the row. But on a BEFORE trigger,
  97651. ** we do not know what the unique ID will be (because the insert has
  97652. ** not happened yet) so we substitute a rowid of -1
  97653. */
  97654. if( ipkColumn<0 ){
  97655. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  97656. }else{
  97657. int addr1;
  97658. assert( !withoutRowid );
  97659. if( useTempTable ){
  97660. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  97661. }else{
  97662. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  97663. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  97664. }
  97665. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  97666. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  97667. sqlite3VdbeJumpHere(v, addr1);
  97668. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  97669. }
  97670. /* Cannot have triggers on a virtual table. If it were possible,
  97671. ** this block would have to account for hidden column.
  97672. */
  97673. assert( !IsVirtual(pTab) );
  97674. /* Create the new column data
  97675. */
  97676. for(i=j=0; i<pTab->nCol; i++){
  97677. if( pColumn ){
  97678. for(j=0; j<pColumn->nId; j++){
  97679. if( pColumn->a[j].idx==i ) break;
  97680. }
  97681. }
  97682. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  97683. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  97684. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  97685. }else if( useTempTable ){
  97686. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  97687. }else{
  97688. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  97689. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  97690. }
  97691. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  97692. }
  97693. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  97694. ** do not attempt any conversions before assembling the record.
  97695. ** If this is a real table, attempt conversions as required by the
  97696. ** table column affinities.
  97697. */
  97698. if( !isView ){
  97699. sqlite3TableAffinity(v, pTab, regCols+1);
  97700. }
  97701. /* Fire BEFORE or INSTEAD OF triggers */
  97702. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  97703. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  97704. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  97705. }
  97706. /* Compute the content of the next row to insert into a range of
  97707. ** registers beginning at regIns.
  97708. */
  97709. if( !isView ){
  97710. if( IsVirtual(pTab) ){
  97711. /* The row that the VUpdate opcode will delete: none */
  97712. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  97713. }
  97714. if( ipkColumn>=0 ){
  97715. if( useTempTable ){
  97716. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  97717. }else if( pSelect ){
  97718. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  97719. }else{
  97720. VdbeOp *pOp;
  97721. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  97722. pOp = sqlite3VdbeGetOp(v, -1);
  97723. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  97724. appendFlag = 1;
  97725. pOp->opcode = OP_NewRowid;
  97726. pOp->p1 = iDataCur;
  97727. pOp->p2 = regRowid;
  97728. pOp->p3 = regAutoinc;
  97729. }
  97730. }
  97731. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  97732. ** to generate a unique primary key value.
  97733. */
  97734. if( !appendFlag ){
  97735. int addr1;
  97736. if( !IsVirtual(pTab) ){
  97737. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  97738. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  97739. sqlite3VdbeJumpHere(v, addr1);
  97740. }else{
  97741. addr1 = sqlite3VdbeCurrentAddr(v);
  97742. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  97743. }
  97744. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  97745. }
  97746. }else if( IsVirtual(pTab) || withoutRowid ){
  97747. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  97748. }else{
  97749. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  97750. appendFlag = 1;
  97751. }
  97752. autoIncStep(pParse, regAutoinc, regRowid);
  97753. /* Compute data for all columns of the new entry, beginning
  97754. ** with the first column.
  97755. */
  97756. nHidden = 0;
  97757. for(i=0; i<pTab->nCol; i++){
  97758. int iRegStore = regRowid+1+i;
  97759. if( i==pTab->iPKey ){
  97760. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  97761. ** Whenever this column is read, the rowid will be substituted
  97762. ** in its place. Hence, fill this column with a NULL to avoid
  97763. ** taking up data space with information that will never be used.
  97764. ** As there may be shallow copies of this value, make it a soft-NULL */
  97765. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  97766. continue;
  97767. }
  97768. if( pColumn==0 ){
  97769. if( IsHiddenColumn(&pTab->aCol[i]) ){
  97770. j = -1;
  97771. nHidden++;
  97772. }else{
  97773. j = i - nHidden;
  97774. }
  97775. }else{
  97776. for(j=0; j<pColumn->nId; j++){
  97777. if( pColumn->a[j].idx==i ) break;
  97778. }
  97779. }
  97780. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  97781. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  97782. }else if( useTempTable ){
  97783. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  97784. }else if( pSelect ){
  97785. if( regFromSelect!=regData ){
  97786. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  97787. }
  97788. }else{
  97789. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  97790. }
  97791. }
  97792. /* Generate code to check constraints and generate index keys and
  97793. ** do the insertion.
  97794. */
  97795. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97796. if( IsVirtual(pTab) ){
  97797. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  97798. sqlite3VtabMakeWritable(pParse, pTab);
  97799. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  97800. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  97801. sqlite3MayAbort(pParse);
  97802. }else
  97803. #endif
  97804. {
  97805. int isReplace; /* Set to true if constraints may cause a replace */
  97806. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  97807. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
  97808. );
  97809. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  97810. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  97811. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  97812. }
  97813. }
  97814. /* Update the count of rows that are inserted
  97815. */
  97816. if( (db->flags & SQLITE_CountRows)!=0 ){
  97817. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  97818. }
  97819. if( pTrigger ){
  97820. /* Code AFTER triggers */
  97821. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  97822. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  97823. }
  97824. /* The bottom of the main insertion loop, if the data source
  97825. ** is a SELECT statement.
  97826. */
  97827. sqlite3VdbeResolveLabel(v, endOfLoop);
  97828. if( useTempTable ){
  97829. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  97830. sqlite3VdbeJumpHere(v, addrInsTop);
  97831. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  97832. }else if( pSelect ){
  97833. sqlite3VdbeGoto(v, addrCont);
  97834. sqlite3VdbeJumpHere(v, addrInsTop);
  97835. }
  97836. if( !IsVirtual(pTab) && !isView ){
  97837. /* Close all tables opened */
  97838. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  97839. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  97840. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  97841. }
  97842. }
  97843. insert_end:
  97844. /* Update the sqlite_sequence table by storing the content of the
  97845. ** maximum rowid counter values recorded while inserting into
  97846. ** autoincrement tables.
  97847. */
  97848. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  97849. sqlite3AutoincrementEnd(pParse);
  97850. }
  97851. /*
  97852. ** Return the number of rows inserted. If this routine is
  97853. ** generating code because of a call to sqlite3NestedParse(), do not
  97854. ** invoke the callback function.
  97855. */
  97856. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  97857. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  97858. sqlite3VdbeSetNumCols(v, 1);
  97859. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  97860. }
  97861. insert_cleanup:
  97862. sqlite3SrcListDelete(db, pTabList);
  97863. sqlite3ExprListDelete(db, pList);
  97864. sqlite3SelectDelete(db, pSelect);
  97865. sqlite3IdListDelete(db, pColumn);
  97866. sqlite3DbFree(db, aRegIdx);
  97867. }
  97868. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  97869. ** they may interfere with compilation of other functions in this file
  97870. ** (or in another file, if this file becomes part of the amalgamation). */
  97871. #ifdef isView
  97872. #undef isView
  97873. #endif
  97874. #ifdef pTrigger
  97875. #undef pTrigger
  97876. #endif
  97877. #ifdef tmask
  97878. #undef tmask
  97879. #endif
  97880. /*
  97881. ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  97882. */
  97883. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  97884. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  97885. /* This is the Walker callback from checkConstraintUnchanged(). Set
  97886. ** bit 0x01 of pWalker->eCode if
  97887. ** pWalker->eCode to 0 if this expression node references any of the
  97888. ** columns that are being modifed by an UPDATE statement.
  97889. */
  97890. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  97891. if( pExpr->op==TK_COLUMN ){
  97892. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  97893. if( pExpr->iColumn>=0 ){
  97894. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  97895. pWalker->eCode |= CKCNSTRNT_COLUMN;
  97896. }
  97897. }else{
  97898. pWalker->eCode |= CKCNSTRNT_ROWID;
  97899. }
  97900. }
  97901. return WRC_Continue;
  97902. }
  97903. /*
  97904. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  97905. ** only columns that are modified by the UPDATE are those for which
  97906. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  97907. **
  97908. ** Return true if CHECK constraint pExpr does not use any of the
  97909. ** changing columns (or the rowid if it is changing). In other words,
  97910. ** return true if this CHECK constraint can be skipped when validating
  97911. ** the new row in the UPDATE statement.
  97912. */
  97913. static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  97914. Walker w;
  97915. memset(&w, 0, sizeof(w));
  97916. w.eCode = 0;
  97917. w.xExprCallback = checkConstraintExprNode;
  97918. w.u.aiCol = aiChng;
  97919. sqlite3WalkExpr(&w, pExpr);
  97920. if( !chngRowid ){
  97921. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  97922. w.eCode &= ~CKCNSTRNT_ROWID;
  97923. }
  97924. testcase( w.eCode==0 );
  97925. testcase( w.eCode==CKCNSTRNT_COLUMN );
  97926. testcase( w.eCode==CKCNSTRNT_ROWID );
  97927. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  97928. return !w.eCode;
  97929. }
  97930. /*
  97931. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  97932. ** on table pTab.
  97933. **
  97934. ** The regNewData parameter is the first register in a range that contains
  97935. ** the data to be inserted or the data after the update. There will be
  97936. ** pTab->nCol+1 registers in this range. The first register (the one
  97937. ** that regNewData points to) will contain the new rowid, or NULL in the
  97938. ** case of a WITHOUT ROWID table. The second register in the range will
  97939. ** contain the content of the first table column. The third register will
  97940. ** contain the content of the second table column. And so forth.
  97941. **
  97942. ** The regOldData parameter is similar to regNewData except that it contains
  97943. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  97944. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  97945. ** checking regOldData for zero.
  97946. **
  97947. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  97948. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  97949. ** might be modified by the UPDATE. If pkChng is false, then the key of
  97950. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  97951. **
  97952. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  97953. ** was explicitly specified as part of the INSERT statement. If pkChng
  97954. ** is zero, it means that the either rowid is computed automatically or
  97955. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  97956. ** pkChng will only be true if the INSERT statement provides an integer
  97957. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  97958. **
  97959. ** The code generated by this routine will store new index entries into
  97960. ** registers identified by aRegIdx[]. No index entry is created for
  97961. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  97962. ** the same as the order of indices on the linked list of indices
  97963. ** at pTab->pIndex.
  97964. **
  97965. ** The caller must have already opened writeable cursors on the main
  97966. ** table and all applicable indices (that is to say, all indices for which
  97967. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  97968. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  97969. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  97970. ** for the first index in the pTab->pIndex list. Cursors for other indices
  97971. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  97972. **
  97973. ** This routine also generates code to check constraints. NOT NULL,
  97974. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  97975. ** then the appropriate action is performed. There are five possible
  97976. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  97977. **
  97978. ** Constraint type Action What Happens
  97979. ** --------------- ---------- ----------------------------------------
  97980. ** any ROLLBACK The current transaction is rolled back and
  97981. ** sqlite3_step() returns immediately with a
  97982. ** return code of SQLITE_CONSTRAINT.
  97983. **
  97984. ** any ABORT Back out changes from the current command
  97985. ** only (do not do a complete rollback) then
  97986. ** cause sqlite3_step() to return immediately
  97987. ** with SQLITE_CONSTRAINT.
  97988. **
  97989. ** any FAIL Sqlite3_step() returns immediately with a
  97990. ** return code of SQLITE_CONSTRAINT. The
  97991. ** transaction is not rolled back and any
  97992. ** changes to prior rows are retained.
  97993. **
  97994. ** any IGNORE The attempt in insert or update the current
  97995. ** row is skipped, without throwing an error.
  97996. ** Processing continues with the next row.
  97997. ** (There is an immediate jump to ignoreDest.)
  97998. **
  97999. ** NOT NULL REPLACE The NULL value is replace by the default
  98000. ** value for that column. If the default value
  98001. ** is NULL, the action is the same as ABORT.
  98002. **
  98003. ** UNIQUE REPLACE The other row that conflicts with the row
  98004. ** being inserted is removed.
  98005. **
  98006. ** CHECK REPLACE Illegal. The results in an exception.
  98007. **
  98008. ** Which action to take is determined by the overrideError parameter.
  98009. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  98010. ** is used. Or if pParse->onError==OE_Default then the onError value
  98011. ** for the constraint is used.
  98012. */
  98013. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  98014. Parse *pParse, /* The parser context */
  98015. Table *pTab, /* The table being inserted or updated */
  98016. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  98017. int iDataCur, /* Canonical data cursor (main table or PK index) */
  98018. int iIdxCur, /* First index cursor */
  98019. int regNewData, /* First register in a range holding values to insert */
  98020. int regOldData, /* Previous content. 0 for INSERTs */
  98021. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  98022. u8 overrideError, /* Override onError to this if not OE_Default */
  98023. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  98024. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  98025. int *aiChng /* column i is unchanged if aiChng[i]<0 */
  98026. ){
  98027. Vdbe *v; /* VDBE under constrution */
  98028. Index *pIdx; /* Pointer to one of the indices */
  98029. Index *pPk = 0; /* The PRIMARY KEY index */
  98030. sqlite3 *db; /* Database connection */
  98031. int i; /* loop counter */
  98032. int ix; /* Index loop counter */
  98033. int nCol; /* Number of columns */
  98034. int onError; /* Conflict resolution strategy */
  98035. int addr1; /* Address of jump instruction */
  98036. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  98037. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  98038. int ipkTop = 0; /* Top of the rowid change constraint check */
  98039. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  98040. u8 isUpdate; /* True if this is an UPDATE operation */
  98041. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  98042. int regRowid = -1; /* Register holding ROWID value */
  98043. isUpdate = regOldData!=0;
  98044. db = pParse->db;
  98045. v = sqlite3GetVdbe(pParse);
  98046. assert( v!=0 );
  98047. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  98048. nCol = pTab->nCol;
  98049. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  98050. ** normal rowid tables. nPkField is the number of key fields in the
  98051. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  98052. ** number of fields in the true primary key of the table. */
  98053. if( HasRowid(pTab) ){
  98054. pPk = 0;
  98055. nPkField = 1;
  98056. }else{
  98057. pPk = sqlite3PrimaryKeyIndex(pTab);
  98058. nPkField = pPk->nKeyCol;
  98059. }
  98060. /* Record that this module has started */
  98061. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  98062. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  98063. /* Test all NOT NULL constraints.
  98064. */
  98065. for(i=0; i<nCol; i++){
  98066. if( i==pTab->iPKey ){
  98067. continue; /* ROWID is never NULL */
  98068. }
  98069. if( aiChng && aiChng[i]<0 ){
  98070. /* Don't bother checking for NOT NULL on columns that do not change */
  98071. continue;
  98072. }
  98073. onError = pTab->aCol[i].notNull;
  98074. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  98075. if( overrideError!=OE_Default ){
  98076. onError = overrideError;
  98077. }else if( onError==OE_Default ){
  98078. onError = OE_Abort;
  98079. }
  98080. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  98081. onError = OE_Abort;
  98082. }
  98083. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  98084. || onError==OE_Ignore || onError==OE_Replace );
  98085. switch( onError ){
  98086. case OE_Abort:
  98087. sqlite3MayAbort(pParse);
  98088. /* Fall through */
  98089. case OE_Rollback:
  98090. case OE_Fail: {
  98091. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  98092. pTab->aCol[i].zName);
  98093. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  98094. regNewData+1+i, zMsg, P4_DYNAMIC);
  98095. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  98096. VdbeCoverage(v);
  98097. break;
  98098. }
  98099. case OE_Ignore: {
  98100. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  98101. VdbeCoverage(v);
  98102. break;
  98103. }
  98104. default: {
  98105. assert( onError==OE_Replace );
  98106. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  98107. VdbeCoverage(v);
  98108. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  98109. sqlite3VdbeJumpHere(v, addr1);
  98110. break;
  98111. }
  98112. }
  98113. }
  98114. /* Test all CHECK constraints
  98115. */
  98116. #ifndef SQLITE_OMIT_CHECK
  98117. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  98118. ExprList *pCheck = pTab->pCheck;
  98119. pParse->ckBase = regNewData+1;
  98120. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  98121. for(i=0; i<pCheck->nExpr; i++){
  98122. int allOk;
  98123. Expr *pExpr = pCheck->a[i].pExpr;
  98124. if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  98125. allOk = sqlite3VdbeMakeLabel(v);
  98126. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  98127. if( onError==OE_Ignore ){
  98128. sqlite3VdbeGoto(v, ignoreDest);
  98129. }else{
  98130. char *zName = pCheck->a[i].zName;
  98131. if( zName==0 ) zName = pTab->zName;
  98132. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  98133. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  98134. onError, zName, P4_TRANSIENT,
  98135. P5_ConstraintCheck);
  98136. }
  98137. sqlite3VdbeResolveLabel(v, allOk);
  98138. }
  98139. }
  98140. #endif /* !defined(SQLITE_OMIT_CHECK) */
  98141. /* If rowid is changing, make sure the new rowid does not previously
  98142. ** exist in the table.
  98143. */
  98144. if( pkChng && pPk==0 ){
  98145. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  98146. /* Figure out what action to take in case of a rowid collision */
  98147. onError = pTab->keyConf;
  98148. if( overrideError!=OE_Default ){
  98149. onError = overrideError;
  98150. }else if( onError==OE_Default ){
  98151. onError = OE_Abort;
  98152. }
  98153. if( isUpdate ){
  98154. /* pkChng!=0 does not mean that the rowid has change, only that
  98155. ** it might have changed. Skip the conflict logic below if the rowid
  98156. ** is unchanged. */
  98157. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  98158. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  98159. VdbeCoverage(v);
  98160. }
  98161. /* If the response to a rowid conflict is REPLACE but the response
  98162. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  98163. ** to defer the running of the rowid conflict checking until after
  98164. ** the UNIQUE constraints have run.
  98165. */
  98166. if( onError==OE_Replace && overrideError!=OE_Replace ){
  98167. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98168. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  98169. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  98170. break;
  98171. }
  98172. }
  98173. }
  98174. /* Check to see if the new rowid already exists in the table. Skip
  98175. ** the following conflict logic if it does not. */
  98176. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  98177. VdbeCoverage(v);
  98178. /* Generate code that deals with a rowid collision */
  98179. switch( onError ){
  98180. default: {
  98181. onError = OE_Abort;
  98182. /* Fall thru into the next case */
  98183. }
  98184. case OE_Rollback:
  98185. case OE_Abort:
  98186. case OE_Fail: {
  98187. sqlite3RowidConstraint(pParse, onError, pTab);
  98188. break;
  98189. }
  98190. case OE_Replace: {
  98191. /* If there are DELETE triggers on this table and the
  98192. ** recursive-triggers flag is set, call GenerateRowDelete() to
  98193. ** remove the conflicting row from the table. This will fire
  98194. ** the triggers and remove both the table and index b-tree entries.
  98195. **
  98196. ** Otherwise, if there are no triggers or the recursive-triggers
  98197. ** flag is not set, but the table has one or more indexes, call
  98198. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  98199. ** only. The table b-tree entry will be replaced by the new entry
  98200. ** when it is inserted.
  98201. **
  98202. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  98203. ** also invoke MultiWrite() to indicate that this VDBE may require
  98204. ** statement rollback (if the statement is aborted after the delete
  98205. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  98206. ** but being more selective here allows statements like:
  98207. **
  98208. ** REPLACE INTO t(rowid) VALUES($newrowid)
  98209. **
  98210. ** to run without a statement journal if there are no indexes on the
  98211. ** table.
  98212. */
  98213. Trigger *pTrigger = 0;
  98214. if( db->flags&SQLITE_RecTriggers ){
  98215. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  98216. }
  98217. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  98218. sqlite3MultiWrite(pParse);
  98219. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  98220. regNewData, 1, 0, OE_Replace,
  98221. ONEPASS_SINGLE, -1);
  98222. }else{
  98223. if( pTab->pIndex ){
  98224. sqlite3MultiWrite(pParse);
  98225. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  98226. }
  98227. }
  98228. seenReplace = 1;
  98229. break;
  98230. }
  98231. case OE_Ignore: {
  98232. /*assert( seenReplace==0 );*/
  98233. sqlite3VdbeGoto(v, ignoreDest);
  98234. break;
  98235. }
  98236. }
  98237. sqlite3VdbeResolveLabel(v, addrRowidOk);
  98238. if( ipkTop ){
  98239. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  98240. sqlite3VdbeJumpHere(v, ipkTop);
  98241. }
  98242. }
  98243. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  98244. ** index and making sure that duplicate entries do not already exist.
  98245. ** Compute the revised record entries for indices as we go.
  98246. **
  98247. ** This loop also handles the case of the PRIMARY KEY index for a
  98248. ** WITHOUT ROWID table.
  98249. */
  98250. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  98251. int regIdx; /* Range of registers hold conent for pIdx */
  98252. int regR; /* Range of registers holding conflicting PK */
  98253. int iThisCur; /* Cursor for this UNIQUE index */
  98254. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  98255. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  98256. if( bAffinityDone==0 ){
  98257. sqlite3TableAffinity(v, pTab, regNewData+1);
  98258. bAffinityDone = 1;
  98259. }
  98260. iThisCur = iIdxCur+ix;
  98261. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  98262. /* Skip partial indices for which the WHERE clause is not true */
  98263. if( pIdx->pPartIdxWhere ){
  98264. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  98265. pParse->ckBase = regNewData+1;
  98266. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  98267. SQLITE_JUMPIFNULL);
  98268. pParse->ckBase = 0;
  98269. }
  98270. /* Create a record for this index entry as it should appear after
  98271. ** the insert or update. Store that record in the aRegIdx[ix] register
  98272. */
  98273. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  98274. for(i=0; i<pIdx->nColumn; i++){
  98275. int iField = pIdx->aiColumn[i];
  98276. int x;
  98277. if( iField==XN_EXPR ){
  98278. pParse->ckBase = regNewData+1;
  98279. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  98280. pParse->ckBase = 0;
  98281. VdbeComment((v, "%s column %d", pIdx->zName, i));
  98282. }else{
  98283. if( iField==XN_ROWID || iField==pTab->iPKey ){
  98284. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  98285. x = regNewData;
  98286. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  98287. }else{
  98288. x = iField + regNewData + 1;
  98289. }
  98290. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  98291. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  98292. }
  98293. }
  98294. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  98295. VdbeComment((v, "for %s", pIdx->zName));
  98296. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  98297. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  98298. ** of a WITHOUT ROWID table and there has been no change the
  98299. ** primary key, then no collision is possible. The collision detection
  98300. ** logic below can all be skipped. */
  98301. if( isUpdate && pPk==pIdx && pkChng==0 ){
  98302. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  98303. continue;
  98304. }
  98305. /* Find out what action to take in case there is a uniqueness conflict */
  98306. onError = pIdx->onError;
  98307. if( onError==OE_None ){
  98308. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  98309. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  98310. continue; /* pIdx is not a UNIQUE index */
  98311. }
  98312. if( overrideError!=OE_Default ){
  98313. onError = overrideError;
  98314. }else if( onError==OE_Default ){
  98315. onError = OE_Abort;
  98316. }
  98317. /* Check to see if the new index entry will be unique */
  98318. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  98319. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  98320. /* Generate code to handle collisions */
  98321. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  98322. if( isUpdate || onError==OE_Replace ){
  98323. if( HasRowid(pTab) ){
  98324. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  98325. /* Conflict only if the rowid of the existing index entry
  98326. ** is different from old-rowid */
  98327. if( isUpdate ){
  98328. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  98329. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  98330. VdbeCoverage(v);
  98331. }
  98332. }else{
  98333. int x;
  98334. /* Extract the PRIMARY KEY from the end of the index entry and
  98335. ** store it in registers regR..regR+nPk-1 */
  98336. if( pIdx!=pPk ){
  98337. for(i=0; i<pPk->nKeyCol; i++){
  98338. assert( pPk->aiColumn[i]>=0 );
  98339. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  98340. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  98341. VdbeComment((v, "%s.%s", pTab->zName,
  98342. pTab->aCol[pPk->aiColumn[i]].zName));
  98343. }
  98344. }
  98345. if( isUpdate ){
  98346. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  98347. ** table, only conflict if the new PRIMARY KEY values are actually
  98348. ** different from the old.
  98349. **
  98350. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  98351. ** of the matched index row are different from the original PRIMARY
  98352. ** KEY values of this row before the update. */
  98353. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  98354. int op = OP_Ne;
  98355. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  98356. for(i=0; i<pPk->nKeyCol; i++){
  98357. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  98358. x = pPk->aiColumn[i];
  98359. assert( x>=0 );
  98360. if( i==(pPk->nKeyCol-1) ){
  98361. addrJump = addrUniqueOk;
  98362. op = OP_Eq;
  98363. }
  98364. sqlite3VdbeAddOp4(v, op,
  98365. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  98366. );
  98367. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  98368. VdbeCoverageIf(v, op==OP_Eq);
  98369. VdbeCoverageIf(v, op==OP_Ne);
  98370. }
  98371. }
  98372. }
  98373. }
  98374. /* Generate code that executes if the new index entry is not unique */
  98375. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  98376. || onError==OE_Ignore || onError==OE_Replace );
  98377. switch( onError ){
  98378. case OE_Rollback:
  98379. case OE_Abort:
  98380. case OE_Fail: {
  98381. sqlite3UniqueConstraint(pParse, onError, pIdx);
  98382. break;
  98383. }
  98384. case OE_Ignore: {
  98385. sqlite3VdbeGoto(v, ignoreDest);
  98386. break;
  98387. }
  98388. default: {
  98389. Trigger *pTrigger = 0;
  98390. assert( onError==OE_Replace );
  98391. sqlite3MultiWrite(pParse);
  98392. if( db->flags&SQLITE_RecTriggers ){
  98393. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  98394. }
  98395. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  98396. regR, nPkField, 0, OE_Replace,
  98397. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
  98398. seenReplace = 1;
  98399. break;
  98400. }
  98401. }
  98402. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  98403. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  98404. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  98405. }
  98406. if( ipkTop ){
  98407. sqlite3VdbeGoto(v, ipkTop+1);
  98408. sqlite3VdbeJumpHere(v, ipkBottom);
  98409. }
  98410. *pbMayReplace = seenReplace;
  98411. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  98412. }
  98413. /*
  98414. ** This routine generates code to finish the INSERT or UPDATE operation
  98415. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  98416. ** A consecutive range of registers starting at regNewData contains the
  98417. ** rowid and the content to be inserted.
  98418. **
  98419. ** The arguments to this routine should be the same as the first six
  98420. ** arguments to sqlite3GenerateConstraintChecks.
  98421. */
  98422. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  98423. Parse *pParse, /* The parser context */
  98424. Table *pTab, /* the table into which we are inserting */
  98425. int iDataCur, /* Cursor of the canonical data source */
  98426. int iIdxCur, /* First index cursor */
  98427. int regNewData, /* Range of content */
  98428. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  98429. int isUpdate, /* True for UPDATE, False for INSERT */
  98430. int appendBias, /* True if this is likely to be an append */
  98431. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  98432. ){
  98433. Vdbe *v; /* Prepared statements under construction */
  98434. Index *pIdx; /* An index being inserted or updated */
  98435. u8 pik_flags; /* flag values passed to the btree insert */
  98436. int regData; /* Content registers (after the rowid) */
  98437. int regRec; /* Register holding assembled record for the table */
  98438. int i; /* Loop counter */
  98439. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  98440. v = sqlite3GetVdbe(pParse);
  98441. assert( v!=0 );
  98442. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  98443. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  98444. if( aRegIdx[i]==0 ) continue;
  98445. bAffinityDone = 1;
  98446. if( pIdx->pPartIdxWhere ){
  98447. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  98448. VdbeCoverage(v);
  98449. }
  98450. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  98451. pik_flags = 0;
  98452. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  98453. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  98454. assert( pParse->nested==0 );
  98455. pik_flags |= OPFLAG_NCHANGE;
  98456. }
  98457. sqlite3VdbeChangeP5(v, pik_flags);
  98458. }
  98459. if( !HasRowid(pTab) ) return;
  98460. regData = regNewData + 1;
  98461. regRec = sqlite3GetTempReg(pParse);
  98462. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  98463. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  98464. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  98465. if( pParse->nested ){
  98466. pik_flags = 0;
  98467. }else{
  98468. pik_flags = OPFLAG_NCHANGE;
  98469. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  98470. }
  98471. if( appendBias ){
  98472. pik_flags |= OPFLAG_APPEND;
  98473. }
  98474. if( useSeekResult ){
  98475. pik_flags |= OPFLAG_USESEEKRESULT;
  98476. }
  98477. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  98478. if( !pParse->nested ){
  98479. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  98480. }
  98481. sqlite3VdbeChangeP5(v, pik_flags);
  98482. }
  98483. /*
  98484. ** Allocate cursors for the pTab table and all its indices and generate
  98485. ** code to open and initialized those cursors.
  98486. **
  98487. ** The cursor for the object that contains the complete data (normally
  98488. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  98489. ** ROWID table) is returned in *piDataCur. The first index cursor is
  98490. ** returned in *piIdxCur. The number of indices is returned.
  98491. **
  98492. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  98493. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  98494. ** If iBase is negative, then allocate the next available cursor.
  98495. **
  98496. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  98497. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  98498. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  98499. ** pTab->pIndex list.
  98500. **
  98501. ** If pTab is a virtual table, then this routine is a no-op and the
  98502. ** *piDataCur and *piIdxCur values are left uninitialized.
  98503. */
  98504. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  98505. Parse *pParse, /* Parsing context */
  98506. Table *pTab, /* Table to be opened */
  98507. int op, /* OP_OpenRead or OP_OpenWrite */
  98508. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  98509. int iBase, /* Use this for the table cursor, if there is one */
  98510. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  98511. int *piDataCur, /* Write the database source cursor number here */
  98512. int *piIdxCur /* Write the first index cursor number here */
  98513. ){
  98514. int i;
  98515. int iDb;
  98516. int iDataCur;
  98517. Index *pIdx;
  98518. Vdbe *v;
  98519. assert( op==OP_OpenRead || op==OP_OpenWrite );
  98520. assert( op==OP_OpenWrite || p5==0 );
  98521. if( IsVirtual(pTab) ){
  98522. /* This routine is a no-op for virtual tables. Leave the output
  98523. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  98524. ** can detect if they are used by mistake in the caller. */
  98525. return 0;
  98526. }
  98527. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  98528. v = sqlite3GetVdbe(pParse);
  98529. assert( v!=0 );
  98530. if( iBase<0 ) iBase = pParse->nTab;
  98531. iDataCur = iBase++;
  98532. if( piDataCur ) *piDataCur = iDataCur;
  98533. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  98534. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  98535. }else{
  98536. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  98537. }
  98538. if( piIdxCur ) *piIdxCur = iBase;
  98539. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  98540. int iIdxCur = iBase++;
  98541. assert( pIdx->pSchema==pTab->pSchema );
  98542. if( aToOpen==0 || aToOpen[i+1] ){
  98543. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  98544. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  98545. VdbeComment((v, "%s", pIdx->zName));
  98546. }
  98547. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  98548. if( piDataCur ) *piDataCur = iIdxCur;
  98549. }else{
  98550. sqlite3VdbeChangeP5(v, p5);
  98551. }
  98552. }
  98553. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  98554. return i;
  98555. }
  98556. #ifdef SQLITE_TEST
  98557. /*
  98558. ** The following global variable is incremented whenever the
  98559. ** transfer optimization is used. This is used for testing
  98560. ** purposes only - to make sure the transfer optimization really
  98561. ** is happening when it is supposed to.
  98562. */
  98563. SQLITE_API int sqlite3_xferopt_count;
  98564. #endif /* SQLITE_TEST */
  98565. #ifndef SQLITE_OMIT_XFER_OPT
  98566. /*
  98567. ** Check to see if index pSrc is compatible as a source of data
  98568. ** for index pDest in an insert transfer optimization. The rules
  98569. ** for a compatible index:
  98570. **
  98571. ** * The index is over the same set of columns
  98572. ** * The same DESC and ASC markings occurs on all columns
  98573. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  98574. ** * The same collating sequence on each column
  98575. ** * The index has the exact same WHERE clause
  98576. */
  98577. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  98578. int i;
  98579. assert( pDest && pSrc );
  98580. assert( pDest->pTable!=pSrc->pTable );
  98581. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  98582. return 0; /* Different number of columns */
  98583. }
  98584. if( pDest->onError!=pSrc->onError ){
  98585. return 0; /* Different conflict resolution strategies */
  98586. }
  98587. for(i=0; i<pSrc->nKeyCol; i++){
  98588. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  98589. return 0; /* Different columns indexed */
  98590. }
  98591. if( pSrc->aiColumn[i]==XN_EXPR ){
  98592. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  98593. if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
  98594. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  98595. return 0; /* Different expressions in the index */
  98596. }
  98597. }
  98598. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  98599. return 0; /* Different sort orders */
  98600. }
  98601. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  98602. return 0; /* Different collating sequences */
  98603. }
  98604. }
  98605. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  98606. return 0; /* Different WHERE clauses */
  98607. }
  98608. /* If no test above fails then the indices must be compatible */
  98609. return 1;
  98610. }
  98611. /*
  98612. ** Attempt the transfer optimization on INSERTs of the form
  98613. **
  98614. ** INSERT INTO tab1 SELECT * FROM tab2;
  98615. **
  98616. ** The xfer optimization transfers raw records from tab2 over to tab1.
  98617. ** Columns are not decoded and reassembled, which greatly improves
  98618. ** performance. Raw index records are transferred in the same way.
  98619. **
  98620. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  98621. ** There are lots of rules for determining compatibility - see comments
  98622. ** embedded in the code for details.
  98623. **
  98624. ** This routine returns TRUE if the optimization is guaranteed to be used.
  98625. ** Sometimes the xfer optimization will only work if the destination table
  98626. ** is empty - a factor that can only be determined at run-time. In that
  98627. ** case, this routine generates code for the xfer optimization but also
  98628. ** does a test to see if the destination table is empty and jumps over the
  98629. ** xfer optimization code if the test fails. In that case, this routine
  98630. ** returns FALSE so that the caller will know to go ahead and generate
  98631. ** an unoptimized transfer. This routine also returns FALSE if there
  98632. ** is no chance that the xfer optimization can be applied.
  98633. **
  98634. ** This optimization is particularly useful at making VACUUM run faster.
  98635. */
  98636. static int xferOptimization(
  98637. Parse *pParse, /* Parser context */
  98638. Table *pDest, /* The table we are inserting into */
  98639. Select *pSelect, /* A SELECT statement to use as the data source */
  98640. int onError, /* How to handle constraint errors */
  98641. int iDbDest /* The database of pDest */
  98642. ){
  98643. sqlite3 *db = pParse->db;
  98644. ExprList *pEList; /* The result set of the SELECT */
  98645. Table *pSrc; /* The table in the FROM clause of SELECT */
  98646. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  98647. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  98648. int i; /* Loop counter */
  98649. int iDbSrc; /* The database of pSrc */
  98650. int iSrc, iDest; /* Cursors from source and destination */
  98651. int addr1, addr2; /* Loop addresses */
  98652. int emptyDestTest = 0; /* Address of test for empty pDest */
  98653. int emptySrcTest = 0; /* Address of test for empty pSrc */
  98654. Vdbe *v; /* The VDBE we are building */
  98655. int regAutoinc; /* Memory register used by AUTOINC */
  98656. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  98657. int regData, regRowid; /* Registers holding data and rowid */
  98658. if( pSelect==0 ){
  98659. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  98660. }
  98661. if( pParse->pWith || pSelect->pWith ){
  98662. /* Do not attempt to process this query if there are an WITH clauses
  98663. ** attached to it. Proceeding may generate a false "no such table: xxx"
  98664. ** error if pSelect reads from a CTE named "xxx". */
  98665. return 0;
  98666. }
  98667. if( sqlite3TriggerList(pParse, pDest) ){
  98668. return 0; /* tab1 must not have triggers */
  98669. }
  98670. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98671. if( pDest->tabFlags & TF_Virtual ){
  98672. return 0; /* tab1 must not be a virtual table */
  98673. }
  98674. #endif
  98675. if( onError==OE_Default ){
  98676. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  98677. if( onError==OE_Default ) onError = OE_Abort;
  98678. }
  98679. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  98680. if( pSelect->pSrc->nSrc!=1 ){
  98681. return 0; /* FROM clause must have exactly one term */
  98682. }
  98683. if( pSelect->pSrc->a[0].pSelect ){
  98684. return 0; /* FROM clause cannot contain a subquery */
  98685. }
  98686. if( pSelect->pWhere ){
  98687. return 0; /* SELECT may not have a WHERE clause */
  98688. }
  98689. if( pSelect->pOrderBy ){
  98690. return 0; /* SELECT may not have an ORDER BY clause */
  98691. }
  98692. /* Do not need to test for a HAVING clause. If HAVING is present but
  98693. ** there is no ORDER BY, we will get an error. */
  98694. if( pSelect->pGroupBy ){
  98695. return 0; /* SELECT may not have a GROUP BY clause */
  98696. }
  98697. if( pSelect->pLimit ){
  98698. return 0; /* SELECT may not have a LIMIT clause */
  98699. }
  98700. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  98701. if( pSelect->pPrior ){
  98702. return 0; /* SELECT may not be a compound query */
  98703. }
  98704. if( pSelect->selFlags & SF_Distinct ){
  98705. return 0; /* SELECT may not be DISTINCT */
  98706. }
  98707. pEList = pSelect->pEList;
  98708. assert( pEList!=0 );
  98709. if( pEList->nExpr!=1 ){
  98710. return 0; /* The result set must have exactly one column */
  98711. }
  98712. assert( pEList->a[0].pExpr );
  98713. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  98714. return 0; /* The result set must be the special operator "*" */
  98715. }
  98716. /* At this point we have established that the statement is of the
  98717. ** correct syntactic form to participate in this optimization. Now
  98718. ** we have to check the semantics.
  98719. */
  98720. pItem = pSelect->pSrc->a;
  98721. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  98722. if( pSrc==0 ){
  98723. return 0; /* FROM clause does not contain a real table */
  98724. }
  98725. if( pSrc==pDest ){
  98726. return 0; /* tab1 and tab2 may not be the same table */
  98727. }
  98728. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  98729. return 0; /* source and destination must both be WITHOUT ROWID or not */
  98730. }
  98731. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98732. if( pSrc->tabFlags & TF_Virtual ){
  98733. return 0; /* tab2 must not be a virtual table */
  98734. }
  98735. #endif
  98736. if( pSrc->pSelect ){
  98737. return 0; /* tab2 may not be a view */
  98738. }
  98739. if( pDest->nCol!=pSrc->nCol ){
  98740. return 0; /* Number of columns must be the same in tab1 and tab2 */
  98741. }
  98742. if( pDest->iPKey!=pSrc->iPKey ){
  98743. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  98744. }
  98745. for(i=0; i<pDest->nCol; i++){
  98746. Column *pDestCol = &pDest->aCol[i];
  98747. Column *pSrcCol = &pSrc->aCol[i];
  98748. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  98749. if( (db->flags & SQLITE_Vacuum)==0
  98750. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  98751. ){
  98752. return 0; /* Neither table may have __hidden__ columns */
  98753. }
  98754. #endif
  98755. if( pDestCol->affinity!=pSrcCol->affinity ){
  98756. return 0; /* Affinity must be the same on all columns */
  98757. }
  98758. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  98759. return 0; /* Collating sequence must be the same on all columns */
  98760. }
  98761. if( pDestCol->notNull && !pSrcCol->notNull ){
  98762. return 0; /* tab2 must be NOT NULL if tab1 is */
  98763. }
  98764. /* Default values for second and subsequent columns need to match. */
  98765. if( i>0 ){
  98766. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  98767. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  98768. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  98769. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  98770. pSrcCol->pDflt->u.zToken)!=0)
  98771. ){
  98772. return 0; /* Default values must be the same for all columns */
  98773. }
  98774. }
  98775. }
  98776. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  98777. if( IsUniqueIndex(pDestIdx) ){
  98778. destHasUniqueIdx = 1;
  98779. }
  98780. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  98781. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  98782. }
  98783. if( pSrcIdx==0 ){
  98784. return 0; /* pDestIdx has no corresponding index in pSrc */
  98785. }
  98786. }
  98787. #ifndef SQLITE_OMIT_CHECK
  98788. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  98789. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  98790. }
  98791. #endif
  98792. #ifndef SQLITE_OMIT_FOREIGN_KEY
  98793. /* Disallow the transfer optimization if the destination table constains
  98794. ** any foreign key constraints. This is more restrictive than necessary.
  98795. ** But the main beneficiary of the transfer optimization is the VACUUM
  98796. ** command, and the VACUUM command disables foreign key constraints. So
  98797. ** the extra complication to make this rule less restrictive is probably
  98798. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  98799. */
  98800. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  98801. return 0;
  98802. }
  98803. #endif
  98804. if( (db->flags & SQLITE_CountRows)!=0 ){
  98805. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  98806. }
  98807. /* If we get this far, it means that the xfer optimization is at
  98808. ** least a possibility, though it might only work if the destination
  98809. ** table (tab1) is initially empty.
  98810. */
  98811. #ifdef SQLITE_TEST
  98812. sqlite3_xferopt_count++;
  98813. #endif
  98814. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  98815. v = sqlite3GetVdbe(pParse);
  98816. sqlite3CodeVerifySchema(pParse, iDbSrc);
  98817. iSrc = pParse->nTab++;
  98818. iDest = pParse->nTab++;
  98819. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  98820. regData = sqlite3GetTempReg(pParse);
  98821. regRowid = sqlite3GetTempReg(pParse);
  98822. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  98823. assert( HasRowid(pDest) || destHasUniqueIdx );
  98824. if( (db->flags & SQLITE_Vacuum)==0 && (
  98825. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  98826. || destHasUniqueIdx /* (2) */
  98827. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  98828. )){
  98829. /* In some circumstances, we are able to run the xfer optimization
  98830. ** only if the destination table is initially empty. Unless the
  98831. ** SQLITE_Vacuum flag is set, this block generates code to make
  98832. ** that determination. If SQLITE_Vacuum is set, then the destination
  98833. ** table is always empty.
  98834. **
  98835. ** Conditions under which the destination must be empty:
  98836. **
  98837. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  98838. ** (If the destination is not initially empty, the rowid fields
  98839. ** of index entries might need to change.)
  98840. **
  98841. ** (2) The destination has a unique index. (The xfer optimization
  98842. ** is unable to test uniqueness.)
  98843. **
  98844. ** (3) onError is something other than OE_Abort and OE_Rollback.
  98845. */
  98846. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  98847. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  98848. sqlite3VdbeJumpHere(v, addr1);
  98849. }
  98850. if( HasRowid(pSrc) ){
  98851. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  98852. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  98853. if( pDest->iPKey>=0 ){
  98854. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  98855. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  98856. VdbeCoverage(v);
  98857. sqlite3RowidConstraint(pParse, onError, pDest);
  98858. sqlite3VdbeJumpHere(v, addr2);
  98859. autoIncStep(pParse, regAutoinc, regRowid);
  98860. }else if( pDest->pIndex==0 ){
  98861. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  98862. }else{
  98863. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  98864. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  98865. }
  98866. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  98867. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  98868. pDest->zName, 0);
  98869. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  98870. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  98871. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  98872. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  98873. }else{
  98874. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  98875. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  98876. }
  98877. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  98878. u8 idxInsFlags = 0;
  98879. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  98880. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  98881. }
  98882. assert( pSrcIdx );
  98883. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  98884. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  98885. VdbeComment((v, "%s", pSrcIdx->zName));
  98886. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  98887. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  98888. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  98889. VdbeComment((v, "%s", pDestIdx->zName));
  98890. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  98891. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  98892. if( db->flags & SQLITE_Vacuum ){
  98893. /* This INSERT command is part of a VACUUM operation, which guarantees
  98894. ** that the destination table is empty. If all indexed columns use
  98895. ** collation sequence BINARY, then it can also be assumed that the
  98896. ** index will be populated by inserting keys in strictly sorted
  98897. ** order. In this case, instead of seeking within the b-tree as part
  98898. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  98899. ** OP_IdxInsert to seek to the point within the b-tree where each key
  98900. ** should be inserted. This is faster.
  98901. **
  98902. ** If any of the indexed columns use a collation sequence other than
  98903. ** BINARY, this optimization is disabled. This is because the user
  98904. ** might change the definition of a collation sequence and then run
  98905. ** a VACUUM command. In that case keys may not be written in strictly
  98906. ** sorted order. */
  98907. for(i=0; i<pSrcIdx->nColumn; i++){
  98908. const char *zColl = pSrcIdx->azColl[i];
  98909. assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
  98910. || sqlite3StrBINARY==zColl );
  98911. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  98912. }
  98913. if( i==pSrcIdx->nColumn ){
  98914. idxInsFlags = OPFLAG_USESEEKRESULT;
  98915. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  98916. }
  98917. }
  98918. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  98919. idxInsFlags |= OPFLAG_NCHANGE;
  98920. }
  98921. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  98922. sqlite3VdbeChangeP5(v, idxInsFlags);
  98923. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  98924. sqlite3VdbeJumpHere(v, addr1);
  98925. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  98926. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  98927. }
  98928. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  98929. sqlite3ReleaseTempReg(pParse, regRowid);
  98930. sqlite3ReleaseTempReg(pParse, regData);
  98931. if( emptyDestTest ){
  98932. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  98933. sqlite3VdbeJumpHere(v, emptyDestTest);
  98934. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  98935. return 0;
  98936. }else{
  98937. return 1;
  98938. }
  98939. }
  98940. #endif /* SQLITE_OMIT_XFER_OPT */
  98941. /************** End of insert.c **********************************************/
  98942. /************** Begin file legacy.c ******************************************/
  98943. /*
  98944. ** 2001 September 15
  98945. **
  98946. ** The author disclaims copyright to this source code. In place of
  98947. ** a legal notice, here is a blessing:
  98948. **
  98949. ** May you do good and not evil.
  98950. ** May you find forgiveness for yourself and forgive others.
  98951. ** May you share freely, never taking more than you give.
  98952. **
  98953. *************************************************************************
  98954. ** Main file for the SQLite library. The routines in this file
  98955. ** implement the programmer interface to the library. Routines in
  98956. ** other files are for internal use by SQLite and should not be
  98957. ** accessed by users of the library.
  98958. */
  98959. /* #include "sqliteInt.h" */
  98960. /*
  98961. ** Execute SQL code. Return one of the SQLITE_ success/failure
  98962. ** codes. Also write an error message into memory obtained from
  98963. ** malloc() and make *pzErrMsg point to that message.
  98964. **
  98965. ** If the SQL is a query, then for each row in the query result
  98966. ** the xCallback() function is called. pArg becomes the first
  98967. ** argument to xCallback(). If xCallback=NULL then no callback
  98968. ** is invoked, even for queries.
  98969. */
  98970. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  98971. sqlite3 *db, /* The database on which the SQL executes */
  98972. const char *zSql, /* The SQL to be executed */
  98973. sqlite3_callback xCallback, /* Invoke this callback routine */
  98974. void *pArg, /* First argument to xCallback() */
  98975. char **pzErrMsg /* Write error messages here */
  98976. ){
  98977. int rc = SQLITE_OK; /* Return code */
  98978. const char *zLeftover; /* Tail of unprocessed SQL */
  98979. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  98980. char **azCols = 0; /* Names of result columns */
  98981. int callbackIsInit; /* True if callback data is initialized */
  98982. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  98983. if( zSql==0 ) zSql = "";
  98984. sqlite3_mutex_enter(db->mutex);
  98985. sqlite3Error(db, SQLITE_OK);
  98986. while( rc==SQLITE_OK && zSql[0] ){
  98987. int nCol;
  98988. char **azVals = 0;
  98989. pStmt = 0;
  98990. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  98991. assert( rc==SQLITE_OK || pStmt==0 );
  98992. if( rc!=SQLITE_OK ){
  98993. continue;
  98994. }
  98995. if( !pStmt ){
  98996. /* this happens for a comment or white-space */
  98997. zSql = zLeftover;
  98998. continue;
  98999. }
  99000. callbackIsInit = 0;
  99001. nCol = sqlite3_column_count(pStmt);
  99002. while( 1 ){
  99003. int i;
  99004. rc = sqlite3_step(pStmt);
  99005. /* Invoke the callback function if required */
  99006. if( xCallback && (SQLITE_ROW==rc ||
  99007. (SQLITE_DONE==rc && !callbackIsInit
  99008. && db->flags&SQLITE_NullCallback)) ){
  99009. if( !callbackIsInit ){
  99010. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  99011. if( azCols==0 ){
  99012. goto exec_out;
  99013. }
  99014. for(i=0; i<nCol; i++){
  99015. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  99016. /* sqlite3VdbeSetColName() installs column names as UTF8
  99017. ** strings so there is no way for sqlite3_column_name() to fail. */
  99018. assert( azCols[i]!=0 );
  99019. }
  99020. callbackIsInit = 1;
  99021. }
  99022. if( rc==SQLITE_ROW ){
  99023. azVals = &azCols[nCol];
  99024. for(i=0; i<nCol; i++){
  99025. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  99026. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  99027. sqlite3OomFault(db);
  99028. goto exec_out;
  99029. }
  99030. }
  99031. }
  99032. if( xCallback(pArg, nCol, azVals, azCols) ){
  99033. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  99034. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  99035. ** return SQLITE_ABORT. */
  99036. rc = SQLITE_ABORT;
  99037. sqlite3VdbeFinalize((Vdbe *)pStmt);
  99038. pStmt = 0;
  99039. sqlite3Error(db, SQLITE_ABORT);
  99040. goto exec_out;
  99041. }
  99042. }
  99043. if( rc!=SQLITE_ROW ){
  99044. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  99045. pStmt = 0;
  99046. zSql = zLeftover;
  99047. while( sqlite3Isspace(zSql[0]) ) zSql++;
  99048. break;
  99049. }
  99050. }
  99051. sqlite3DbFree(db, azCols);
  99052. azCols = 0;
  99053. }
  99054. exec_out:
  99055. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  99056. sqlite3DbFree(db, azCols);
  99057. rc = sqlite3ApiExit(db, rc);
  99058. if( rc!=SQLITE_OK && pzErrMsg ){
  99059. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  99060. *pzErrMsg = sqlite3Malloc(nErrMsg);
  99061. if( *pzErrMsg ){
  99062. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  99063. }else{
  99064. rc = SQLITE_NOMEM_BKPT;
  99065. sqlite3Error(db, SQLITE_NOMEM);
  99066. }
  99067. }else if( pzErrMsg ){
  99068. *pzErrMsg = 0;
  99069. }
  99070. assert( (rc&db->errMask)==rc );
  99071. sqlite3_mutex_leave(db->mutex);
  99072. return rc;
  99073. }
  99074. /************** End of legacy.c **********************************************/
  99075. /************** Begin file loadext.c *****************************************/
  99076. /*
  99077. ** 2006 June 7
  99078. **
  99079. ** The author disclaims copyright to this source code. In place of
  99080. ** a legal notice, here is a blessing:
  99081. **
  99082. ** May you do good and not evil.
  99083. ** May you find forgiveness for yourself and forgive others.
  99084. ** May you share freely, never taking more than you give.
  99085. **
  99086. *************************************************************************
  99087. ** This file contains code used to dynamically load extensions into
  99088. ** the SQLite library.
  99089. */
  99090. #ifndef SQLITE_CORE
  99091. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  99092. #endif
  99093. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  99094. /************** Begin file sqlite3ext.h **************************************/
  99095. /*
  99096. ** 2006 June 7
  99097. **
  99098. ** The author disclaims copyright to this source code. In place of
  99099. ** a legal notice, here is a blessing:
  99100. **
  99101. ** May you do good and not evil.
  99102. ** May you find forgiveness for yourself and forgive others.
  99103. ** May you share freely, never taking more than you give.
  99104. **
  99105. *************************************************************************
  99106. ** This header file defines the SQLite interface for use by
  99107. ** shared libraries that want to be imported as extensions into
  99108. ** an SQLite instance. Shared libraries that intend to be loaded
  99109. ** as extensions by SQLite should #include this file instead of
  99110. ** sqlite3.h.
  99111. */
  99112. #ifndef _SQLITE3EXT_H_
  99113. #define _SQLITE3EXT_H_
  99114. /* #include "sqlite3.h" */
  99115. typedef struct sqlite3_api_routines sqlite3_api_routines;
  99116. /*
  99117. ** The following structure holds pointers to all of the SQLite API
  99118. ** routines.
  99119. **
  99120. ** WARNING: In order to maintain backwards compatibility, add new
  99121. ** interfaces to the end of this structure only. If you insert new
  99122. ** interfaces in the middle of this structure, then older different
  99123. ** versions of SQLite will not be able to load each other's shared
  99124. ** libraries!
  99125. */
  99126. struct sqlite3_api_routines {
  99127. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  99128. int (*aggregate_count)(sqlite3_context*);
  99129. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  99130. int (*bind_double)(sqlite3_stmt*,int,double);
  99131. int (*bind_int)(sqlite3_stmt*,int,int);
  99132. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  99133. int (*bind_null)(sqlite3_stmt*,int);
  99134. int (*bind_parameter_count)(sqlite3_stmt*);
  99135. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  99136. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  99137. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  99138. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  99139. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  99140. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  99141. int (*busy_timeout)(sqlite3*,int ms);
  99142. int (*changes)(sqlite3*);
  99143. int (*close)(sqlite3*);
  99144. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  99145. int eTextRep,const char*));
  99146. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  99147. int eTextRep,const void*));
  99148. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  99149. int (*column_bytes)(sqlite3_stmt*,int iCol);
  99150. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  99151. int (*column_count)(sqlite3_stmt*pStmt);
  99152. const char * (*column_database_name)(sqlite3_stmt*,int);
  99153. const void * (*column_database_name16)(sqlite3_stmt*,int);
  99154. const char * (*column_decltype)(sqlite3_stmt*,int i);
  99155. const void * (*column_decltype16)(sqlite3_stmt*,int);
  99156. double (*column_double)(sqlite3_stmt*,int iCol);
  99157. int (*column_int)(sqlite3_stmt*,int iCol);
  99158. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  99159. const char * (*column_name)(sqlite3_stmt*,int);
  99160. const void * (*column_name16)(sqlite3_stmt*,int);
  99161. const char * (*column_origin_name)(sqlite3_stmt*,int);
  99162. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  99163. const char * (*column_table_name)(sqlite3_stmt*,int);
  99164. const void * (*column_table_name16)(sqlite3_stmt*,int);
  99165. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  99166. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  99167. int (*column_type)(sqlite3_stmt*,int iCol);
  99168. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  99169. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  99170. int (*complete)(const char*sql);
  99171. int (*complete16)(const void*sql);
  99172. int (*create_collation)(sqlite3*,const char*,int,void*,
  99173. int(*)(void*,int,const void*,int,const void*));
  99174. int (*create_collation16)(sqlite3*,const void*,int,void*,
  99175. int(*)(void*,int,const void*,int,const void*));
  99176. int (*create_function)(sqlite3*,const char*,int,int,void*,
  99177. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  99178. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  99179. void (*xFinal)(sqlite3_context*));
  99180. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  99181. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  99182. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  99183. void (*xFinal)(sqlite3_context*));
  99184. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  99185. int (*data_count)(sqlite3_stmt*pStmt);
  99186. sqlite3 * (*db_handle)(sqlite3_stmt*);
  99187. int (*declare_vtab)(sqlite3*,const char*);
  99188. int (*enable_shared_cache)(int);
  99189. int (*errcode)(sqlite3*db);
  99190. const char * (*errmsg)(sqlite3*);
  99191. const void * (*errmsg16)(sqlite3*);
  99192. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  99193. int (*expired)(sqlite3_stmt*);
  99194. int (*finalize)(sqlite3_stmt*pStmt);
  99195. void (*free)(void*);
  99196. void (*free_table)(char**result);
  99197. int (*get_autocommit)(sqlite3*);
  99198. void * (*get_auxdata)(sqlite3_context*,int);
  99199. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  99200. int (*global_recover)(void);
  99201. void (*interruptx)(sqlite3*);
  99202. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  99203. const char * (*libversion)(void);
  99204. int (*libversion_number)(void);
  99205. void *(*malloc)(int);
  99206. char * (*mprintf)(const char*,...);
  99207. int (*open)(const char*,sqlite3**);
  99208. int (*open16)(const void*,sqlite3**);
  99209. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  99210. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  99211. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  99212. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  99213. void *(*realloc)(void*,int);
  99214. int (*reset)(sqlite3_stmt*pStmt);
  99215. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  99216. void (*result_double)(sqlite3_context*,double);
  99217. void (*result_error)(sqlite3_context*,const char*,int);
  99218. void (*result_error16)(sqlite3_context*,const void*,int);
  99219. void (*result_int)(sqlite3_context*,int);
  99220. void (*result_int64)(sqlite3_context*,sqlite_int64);
  99221. void (*result_null)(sqlite3_context*);
  99222. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  99223. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  99224. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  99225. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  99226. void (*result_value)(sqlite3_context*,sqlite3_value*);
  99227. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  99228. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  99229. const char*,const char*),void*);
  99230. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  99231. char * (*snprintf)(int,char*,const char*,...);
  99232. int (*step)(sqlite3_stmt*);
  99233. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  99234. char const**,char const**,int*,int*,int*);
  99235. void (*thread_cleanup)(void);
  99236. int (*total_changes)(sqlite3*);
  99237. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  99238. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  99239. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  99240. sqlite_int64),void*);
  99241. void * (*user_data)(sqlite3_context*);
  99242. const void * (*value_blob)(sqlite3_value*);
  99243. int (*value_bytes)(sqlite3_value*);
  99244. int (*value_bytes16)(sqlite3_value*);
  99245. double (*value_double)(sqlite3_value*);
  99246. int (*value_int)(sqlite3_value*);
  99247. sqlite_int64 (*value_int64)(sqlite3_value*);
  99248. int (*value_numeric_type)(sqlite3_value*);
  99249. const unsigned char * (*value_text)(sqlite3_value*);
  99250. const void * (*value_text16)(sqlite3_value*);
  99251. const void * (*value_text16be)(sqlite3_value*);
  99252. const void * (*value_text16le)(sqlite3_value*);
  99253. int (*value_type)(sqlite3_value*);
  99254. char *(*vmprintf)(const char*,va_list);
  99255. /* Added ??? */
  99256. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  99257. /* Added by 3.3.13 */
  99258. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  99259. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  99260. int (*clear_bindings)(sqlite3_stmt*);
  99261. /* Added by 3.4.1 */
  99262. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  99263. void (*xDestroy)(void *));
  99264. /* Added by 3.5.0 */
  99265. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  99266. int (*blob_bytes)(sqlite3_blob*);
  99267. int (*blob_close)(sqlite3_blob*);
  99268. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  99269. int,sqlite3_blob**);
  99270. int (*blob_read)(sqlite3_blob*,void*,int,int);
  99271. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  99272. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  99273. int(*)(void*,int,const void*,int,const void*),
  99274. void(*)(void*));
  99275. int (*file_control)(sqlite3*,const char*,int,void*);
  99276. sqlite3_int64 (*memory_highwater)(int);
  99277. sqlite3_int64 (*memory_used)(void);
  99278. sqlite3_mutex *(*mutex_alloc)(int);
  99279. void (*mutex_enter)(sqlite3_mutex*);
  99280. void (*mutex_free)(sqlite3_mutex*);
  99281. void (*mutex_leave)(sqlite3_mutex*);
  99282. int (*mutex_try)(sqlite3_mutex*);
  99283. int (*open_v2)(const char*,sqlite3**,int,const char*);
  99284. int (*release_memory)(int);
  99285. void (*result_error_nomem)(sqlite3_context*);
  99286. void (*result_error_toobig)(sqlite3_context*);
  99287. int (*sleep)(int);
  99288. void (*soft_heap_limit)(int);
  99289. sqlite3_vfs *(*vfs_find)(const char*);
  99290. int (*vfs_register)(sqlite3_vfs*,int);
  99291. int (*vfs_unregister)(sqlite3_vfs*);
  99292. int (*xthreadsafe)(void);
  99293. void (*result_zeroblob)(sqlite3_context*,int);
  99294. void (*result_error_code)(sqlite3_context*,int);
  99295. int (*test_control)(int, ...);
  99296. void (*randomness)(int,void*);
  99297. sqlite3 *(*context_db_handle)(sqlite3_context*);
  99298. int (*extended_result_codes)(sqlite3*,int);
  99299. int (*limit)(sqlite3*,int,int);
  99300. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  99301. const char *(*sql)(sqlite3_stmt*);
  99302. int (*status)(int,int*,int*,int);
  99303. int (*backup_finish)(sqlite3_backup*);
  99304. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  99305. int (*backup_pagecount)(sqlite3_backup*);
  99306. int (*backup_remaining)(sqlite3_backup*);
  99307. int (*backup_step)(sqlite3_backup*,int);
  99308. const char *(*compileoption_get)(int);
  99309. int (*compileoption_used)(const char*);
  99310. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  99311. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  99312. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  99313. void (*xFinal)(sqlite3_context*),
  99314. void(*xDestroy)(void*));
  99315. int (*db_config)(sqlite3*,int,...);
  99316. sqlite3_mutex *(*db_mutex)(sqlite3*);
  99317. int (*db_status)(sqlite3*,int,int*,int*,int);
  99318. int (*extended_errcode)(sqlite3*);
  99319. void (*log)(int,const char*,...);
  99320. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  99321. const char *(*sourceid)(void);
  99322. int (*stmt_status)(sqlite3_stmt*,int,int);
  99323. int (*strnicmp)(const char*,const char*,int);
  99324. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  99325. int (*wal_autocheckpoint)(sqlite3*,int);
  99326. int (*wal_checkpoint)(sqlite3*,const char*);
  99327. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  99328. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  99329. int (*vtab_config)(sqlite3*,int op,...);
  99330. int (*vtab_on_conflict)(sqlite3*);
  99331. /* Version 3.7.16 and later */
  99332. int (*close_v2)(sqlite3*);
  99333. const char *(*db_filename)(sqlite3*,const char*);
  99334. int (*db_readonly)(sqlite3*,const char*);
  99335. int (*db_release_memory)(sqlite3*);
  99336. const char *(*errstr)(int);
  99337. int (*stmt_busy)(sqlite3_stmt*);
  99338. int (*stmt_readonly)(sqlite3_stmt*);
  99339. int (*stricmp)(const char*,const char*);
  99340. int (*uri_boolean)(const char*,const char*,int);
  99341. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  99342. const char *(*uri_parameter)(const char*,const char*);
  99343. char *(*vsnprintf)(int,char*,const char*,va_list);
  99344. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  99345. /* Version 3.8.7 and later */
  99346. int (*auto_extension)(void(*)(void));
  99347. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  99348. void(*)(void*));
  99349. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  99350. void(*)(void*),unsigned char);
  99351. int (*cancel_auto_extension)(void(*)(void));
  99352. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  99353. void *(*malloc64)(sqlite3_uint64);
  99354. sqlite3_uint64 (*msize)(void*);
  99355. void *(*realloc64)(void*,sqlite3_uint64);
  99356. void (*reset_auto_extension)(void);
  99357. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  99358. void(*)(void*));
  99359. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  99360. void(*)(void*), unsigned char);
  99361. int (*strglob)(const char*,const char*);
  99362. /* Version 3.8.11 and later */
  99363. sqlite3_value *(*value_dup)(const sqlite3_value*);
  99364. void (*value_free)(sqlite3_value*);
  99365. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  99366. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  99367. /* Version 3.9.0 and later */
  99368. unsigned int (*value_subtype)(sqlite3_value*);
  99369. void (*result_subtype)(sqlite3_context*,unsigned int);
  99370. /* Version 3.10.0 and later */
  99371. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  99372. int (*strlike)(const char*,const char*,unsigned int);
  99373. int (*db_cacheflush)(sqlite3*);
  99374. /* Version 3.12.0 and later */
  99375. int (*system_errno)(sqlite3*);
  99376. };
  99377. /*
  99378. ** The following macros redefine the API routines so that they are
  99379. ** redirected through the global sqlite3_api structure.
  99380. **
  99381. ** This header file is also used by the loadext.c source file
  99382. ** (part of the main SQLite library - not an extension) so that
  99383. ** it can get access to the sqlite3_api_routines structure
  99384. ** definition. But the main library does not want to redefine
  99385. ** the API. So the redefinition macros are only valid if the
  99386. ** SQLITE_CORE macros is undefined.
  99387. */
  99388. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  99389. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  99390. #ifndef SQLITE_OMIT_DEPRECATED
  99391. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  99392. #endif
  99393. #define sqlite3_bind_blob sqlite3_api->bind_blob
  99394. #define sqlite3_bind_double sqlite3_api->bind_double
  99395. #define sqlite3_bind_int sqlite3_api->bind_int
  99396. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  99397. #define sqlite3_bind_null sqlite3_api->bind_null
  99398. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  99399. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  99400. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  99401. #define sqlite3_bind_text sqlite3_api->bind_text
  99402. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  99403. #define sqlite3_bind_value sqlite3_api->bind_value
  99404. #define sqlite3_busy_handler sqlite3_api->busy_handler
  99405. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  99406. #define sqlite3_changes sqlite3_api->changes
  99407. #define sqlite3_close sqlite3_api->close
  99408. #define sqlite3_collation_needed sqlite3_api->collation_needed
  99409. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  99410. #define sqlite3_column_blob sqlite3_api->column_blob
  99411. #define sqlite3_column_bytes sqlite3_api->column_bytes
  99412. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  99413. #define sqlite3_column_count sqlite3_api->column_count
  99414. #define sqlite3_column_database_name sqlite3_api->column_database_name
  99415. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  99416. #define sqlite3_column_decltype sqlite3_api->column_decltype
  99417. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  99418. #define sqlite3_column_double sqlite3_api->column_double
  99419. #define sqlite3_column_int sqlite3_api->column_int
  99420. #define sqlite3_column_int64 sqlite3_api->column_int64
  99421. #define sqlite3_column_name sqlite3_api->column_name
  99422. #define sqlite3_column_name16 sqlite3_api->column_name16
  99423. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  99424. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  99425. #define sqlite3_column_table_name sqlite3_api->column_table_name
  99426. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  99427. #define sqlite3_column_text sqlite3_api->column_text
  99428. #define sqlite3_column_text16 sqlite3_api->column_text16
  99429. #define sqlite3_column_type sqlite3_api->column_type
  99430. #define sqlite3_column_value sqlite3_api->column_value
  99431. #define sqlite3_commit_hook sqlite3_api->commit_hook
  99432. #define sqlite3_complete sqlite3_api->complete
  99433. #define sqlite3_complete16 sqlite3_api->complete16
  99434. #define sqlite3_create_collation sqlite3_api->create_collation
  99435. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  99436. #define sqlite3_create_function sqlite3_api->create_function
  99437. #define sqlite3_create_function16 sqlite3_api->create_function16
  99438. #define sqlite3_create_module sqlite3_api->create_module
  99439. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  99440. #define sqlite3_data_count sqlite3_api->data_count
  99441. #define sqlite3_db_handle sqlite3_api->db_handle
  99442. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  99443. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  99444. #define sqlite3_errcode sqlite3_api->errcode
  99445. #define sqlite3_errmsg sqlite3_api->errmsg
  99446. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  99447. #define sqlite3_exec sqlite3_api->exec
  99448. #ifndef SQLITE_OMIT_DEPRECATED
  99449. #define sqlite3_expired sqlite3_api->expired
  99450. #endif
  99451. #define sqlite3_finalize sqlite3_api->finalize
  99452. #define sqlite3_free sqlite3_api->free
  99453. #define sqlite3_free_table sqlite3_api->free_table
  99454. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  99455. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  99456. #define sqlite3_get_table sqlite3_api->get_table
  99457. #ifndef SQLITE_OMIT_DEPRECATED
  99458. #define sqlite3_global_recover sqlite3_api->global_recover
  99459. #endif
  99460. #define sqlite3_interrupt sqlite3_api->interruptx
  99461. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  99462. #define sqlite3_libversion sqlite3_api->libversion
  99463. #define sqlite3_libversion_number sqlite3_api->libversion_number
  99464. #define sqlite3_malloc sqlite3_api->malloc
  99465. #define sqlite3_mprintf sqlite3_api->mprintf
  99466. #define sqlite3_open sqlite3_api->open
  99467. #define sqlite3_open16 sqlite3_api->open16
  99468. #define sqlite3_prepare sqlite3_api->prepare
  99469. #define sqlite3_prepare16 sqlite3_api->prepare16
  99470. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  99471. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  99472. #define sqlite3_profile sqlite3_api->profile
  99473. #define sqlite3_progress_handler sqlite3_api->progress_handler
  99474. #define sqlite3_realloc sqlite3_api->realloc
  99475. #define sqlite3_reset sqlite3_api->reset
  99476. #define sqlite3_result_blob sqlite3_api->result_blob
  99477. #define sqlite3_result_double sqlite3_api->result_double
  99478. #define sqlite3_result_error sqlite3_api->result_error
  99479. #define sqlite3_result_error16 sqlite3_api->result_error16
  99480. #define sqlite3_result_int sqlite3_api->result_int
  99481. #define sqlite3_result_int64 sqlite3_api->result_int64
  99482. #define sqlite3_result_null sqlite3_api->result_null
  99483. #define sqlite3_result_text sqlite3_api->result_text
  99484. #define sqlite3_result_text16 sqlite3_api->result_text16
  99485. #define sqlite3_result_text16be sqlite3_api->result_text16be
  99486. #define sqlite3_result_text16le sqlite3_api->result_text16le
  99487. #define sqlite3_result_value sqlite3_api->result_value
  99488. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  99489. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  99490. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  99491. #define sqlite3_snprintf sqlite3_api->snprintf
  99492. #define sqlite3_step sqlite3_api->step
  99493. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  99494. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  99495. #define sqlite3_total_changes sqlite3_api->total_changes
  99496. #define sqlite3_trace sqlite3_api->trace
  99497. #ifndef SQLITE_OMIT_DEPRECATED
  99498. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  99499. #endif
  99500. #define sqlite3_update_hook sqlite3_api->update_hook
  99501. #define sqlite3_user_data sqlite3_api->user_data
  99502. #define sqlite3_value_blob sqlite3_api->value_blob
  99503. #define sqlite3_value_bytes sqlite3_api->value_bytes
  99504. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  99505. #define sqlite3_value_double sqlite3_api->value_double
  99506. #define sqlite3_value_int sqlite3_api->value_int
  99507. #define sqlite3_value_int64 sqlite3_api->value_int64
  99508. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  99509. #define sqlite3_value_text sqlite3_api->value_text
  99510. #define sqlite3_value_text16 sqlite3_api->value_text16
  99511. #define sqlite3_value_text16be sqlite3_api->value_text16be
  99512. #define sqlite3_value_text16le sqlite3_api->value_text16le
  99513. #define sqlite3_value_type sqlite3_api->value_type
  99514. #define sqlite3_vmprintf sqlite3_api->vmprintf
  99515. #define sqlite3_vsnprintf sqlite3_api->vsnprintf
  99516. #define sqlite3_overload_function sqlite3_api->overload_function
  99517. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  99518. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  99519. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  99520. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  99521. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  99522. #define sqlite3_blob_close sqlite3_api->blob_close
  99523. #define sqlite3_blob_open sqlite3_api->blob_open
  99524. #define sqlite3_blob_read sqlite3_api->blob_read
  99525. #define sqlite3_blob_write sqlite3_api->blob_write
  99526. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  99527. #define sqlite3_file_control sqlite3_api->file_control
  99528. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  99529. #define sqlite3_memory_used sqlite3_api->memory_used
  99530. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  99531. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  99532. #define sqlite3_mutex_free sqlite3_api->mutex_free
  99533. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  99534. #define sqlite3_mutex_try sqlite3_api->mutex_try
  99535. #define sqlite3_open_v2 sqlite3_api->open_v2
  99536. #define sqlite3_release_memory sqlite3_api->release_memory
  99537. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  99538. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  99539. #define sqlite3_sleep sqlite3_api->sleep
  99540. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  99541. #define sqlite3_vfs_find sqlite3_api->vfs_find
  99542. #define sqlite3_vfs_register sqlite3_api->vfs_register
  99543. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  99544. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  99545. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  99546. #define sqlite3_result_error_code sqlite3_api->result_error_code
  99547. #define sqlite3_test_control sqlite3_api->test_control
  99548. #define sqlite3_randomness sqlite3_api->randomness
  99549. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  99550. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  99551. #define sqlite3_limit sqlite3_api->limit
  99552. #define sqlite3_next_stmt sqlite3_api->next_stmt
  99553. #define sqlite3_sql sqlite3_api->sql
  99554. #define sqlite3_status sqlite3_api->status
  99555. #define sqlite3_backup_finish sqlite3_api->backup_finish
  99556. #define sqlite3_backup_init sqlite3_api->backup_init
  99557. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  99558. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  99559. #define sqlite3_backup_step sqlite3_api->backup_step
  99560. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  99561. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  99562. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  99563. #define sqlite3_db_config sqlite3_api->db_config
  99564. #define sqlite3_db_mutex sqlite3_api->db_mutex
  99565. #define sqlite3_db_status sqlite3_api->db_status
  99566. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  99567. #define sqlite3_log sqlite3_api->log
  99568. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  99569. #define sqlite3_sourceid sqlite3_api->sourceid
  99570. #define sqlite3_stmt_status sqlite3_api->stmt_status
  99571. #define sqlite3_strnicmp sqlite3_api->strnicmp
  99572. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  99573. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  99574. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  99575. #define sqlite3_wal_hook sqlite3_api->wal_hook
  99576. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  99577. #define sqlite3_vtab_config sqlite3_api->vtab_config
  99578. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  99579. /* Version 3.7.16 and later */
  99580. #define sqlite3_close_v2 sqlite3_api->close_v2
  99581. #define sqlite3_db_filename sqlite3_api->db_filename
  99582. #define sqlite3_db_readonly sqlite3_api->db_readonly
  99583. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  99584. #define sqlite3_errstr sqlite3_api->errstr
  99585. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  99586. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  99587. #define sqlite3_stricmp sqlite3_api->stricmp
  99588. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  99589. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  99590. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  99591. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  99592. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  99593. /* Version 3.8.7 and later */
  99594. #define sqlite3_auto_extension sqlite3_api->auto_extension
  99595. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  99596. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  99597. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  99598. #define sqlite3_load_extension sqlite3_api->load_extension
  99599. #define sqlite3_malloc64 sqlite3_api->malloc64
  99600. #define sqlite3_msize sqlite3_api->msize
  99601. #define sqlite3_realloc64 sqlite3_api->realloc64
  99602. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  99603. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  99604. #define sqlite3_result_text64 sqlite3_api->result_text64
  99605. #define sqlite3_strglob sqlite3_api->strglob
  99606. /* Version 3.8.11 and later */
  99607. #define sqlite3_value_dup sqlite3_api->value_dup
  99608. #define sqlite3_value_free sqlite3_api->value_free
  99609. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  99610. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  99611. /* Version 3.9.0 and later */
  99612. #define sqlite3_value_subtype sqlite3_api->value_subtype
  99613. #define sqlite3_result_subtype sqlite3_api->result_subtype
  99614. /* Version 3.10.0 and later */
  99615. #define sqlite3_status64 sqlite3_api->status64
  99616. #define sqlite3_strlike sqlite3_api->strlike
  99617. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  99618. /* Version 3.12.0 and later */
  99619. #define sqlite3_system_errno sqlite3_api->system_errno
  99620. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  99621. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  99622. /* This case when the file really is being compiled as a loadable
  99623. ** extension */
  99624. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  99625. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  99626. # define SQLITE_EXTENSION_INIT3 \
  99627. extern const sqlite3_api_routines *sqlite3_api;
  99628. #else
  99629. /* This case when the file is being statically linked into the
  99630. ** application */
  99631. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  99632. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  99633. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  99634. #endif
  99635. #endif /* _SQLITE3EXT_H_ */
  99636. /************** End of sqlite3ext.h ******************************************/
  99637. /************** Continuing where we left off in loadext.c ********************/
  99638. /* #include "sqliteInt.h" */
  99639. /* #include <string.h> */
  99640. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  99641. /*
  99642. ** Some API routines are omitted when various features are
  99643. ** excluded from a build of SQLite. Substitute a NULL pointer
  99644. ** for any missing APIs.
  99645. */
  99646. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  99647. # define sqlite3_column_database_name 0
  99648. # define sqlite3_column_database_name16 0
  99649. # define sqlite3_column_table_name 0
  99650. # define sqlite3_column_table_name16 0
  99651. # define sqlite3_column_origin_name 0
  99652. # define sqlite3_column_origin_name16 0
  99653. #endif
  99654. #ifdef SQLITE_OMIT_AUTHORIZATION
  99655. # define sqlite3_set_authorizer 0
  99656. #endif
  99657. #ifdef SQLITE_OMIT_UTF16
  99658. # define sqlite3_bind_text16 0
  99659. # define sqlite3_collation_needed16 0
  99660. # define sqlite3_column_decltype16 0
  99661. # define sqlite3_column_name16 0
  99662. # define sqlite3_column_text16 0
  99663. # define sqlite3_complete16 0
  99664. # define sqlite3_create_collation16 0
  99665. # define sqlite3_create_function16 0
  99666. # define sqlite3_errmsg16 0
  99667. # define sqlite3_open16 0
  99668. # define sqlite3_prepare16 0
  99669. # define sqlite3_prepare16_v2 0
  99670. # define sqlite3_result_error16 0
  99671. # define sqlite3_result_text16 0
  99672. # define sqlite3_result_text16be 0
  99673. # define sqlite3_result_text16le 0
  99674. # define sqlite3_value_text16 0
  99675. # define sqlite3_value_text16be 0
  99676. # define sqlite3_value_text16le 0
  99677. # define sqlite3_column_database_name16 0
  99678. # define sqlite3_column_table_name16 0
  99679. # define sqlite3_column_origin_name16 0
  99680. #endif
  99681. #ifdef SQLITE_OMIT_COMPLETE
  99682. # define sqlite3_complete 0
  99683. # define sqlite3_complete16 0
  99684. #endif
  99685. #ifdef SQLITE_OMIT_DECLTYPE
  99686. # define sqlite3_column_decltype16 0
  99687. # define sqlite3_column_decltype 0
  99688. #endif
  99689. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  99690. # define sqlite3_progress_handler 0
  99691. #endif
  99692. #ifdef SQLITE_OMIT_VIRTUALTABLE
  99693. # define sqlite3_create_module 0
  99694. # define sqlite3_create_module_v2 0
  99695. # define sqlite3_declare_vtab 0
  99696. # define sqlite3_vtab_config 0
  99697. # define sqlite3_vtab_on_conflict 0
  99698. #endif
  99699. #ifdef SQLITE_OMIT_SHARED_CACHE
  99700. # define sqlite3_enable_shared_cache 0
  99701. #endif
  99702. #ifdef SQLITE_OMIT_TRACE
  99703. # define sqlite3_profile 0
  99704. # define sqlite3_trace 0
  99705. #endif
  99706. #ifdef SQLITE_OMIT_GET_TABLE
  99707. # define sqlite3_free_table 0
  99708. # define sqlite3_get_table 0
  99709. #endif
  99710. #ifdef SQLITE_OMIT_INCRBLOB
  99711. #define sqlite3_bind_zeroblob 0
  99712. #define sqlite3_blob_bytes 0
  99713. #define sqlite3_blob_close 0
  99714. #define sqlite3_blob_open 0
  99715. #define sqlite3_blob_read 0
  99716. #define sqlite3_blob_write 0
  99717. #define sqlite3_blob_reopen 0
  99718. #endif
  99719. /*
  99720. ** The following structure contains pointers to all SQLite API routines.
  99721. ** A pointer to this structure is passed into extensions when they are
  99722. ** loaded so that the extension can make calls back into the SQLite
  99723. ** library.
  99724. **
  99725. ** When adding new APIs, add them to the bottom of this structure
  99726. ** in order to preserve backwards compatibility.
  99727. **
  99728. ** Extensions that use newer APIs should first call the
  99729. ** sqlite3_libversion_number() to make sure that the API they
  99730. ** intend to use is supported by the library. Extensions should
  99731. ** also check to make sure that the pointer to the function is
  99732. ** not NULL before calling it.
  99733. */
  99734. static const sqlite3_api_routines sqlite3Apis = {
  99735. sqlite3_aggregate_context,
  99736. #ifndef SQLITE_OMIT_DEPRECATED
  99737. sqlite3_aggregate_count,
  99738. #else
  99739. 0,
  99740. #endif
  99741. sqlite3_bind_blob,
  99742. sqlite3_bind_double,
  99743. sqlite3_bind_int,
  99744. sqlite3_bind_int64,
  99745. sqlite3_bind_null,
  99746. sqlite3_bind_parameter_count,
  99747. sqlite3_bind_parameter_index,
  99748. sqlite3_bind_parameter_name,
  99749. sqlite3_bind_text,
  99750. sqlite3_bind_text16,
  99751. sqlite3_bind_value,
  99752. sqlite3_busy_handler,
  99753. sqlite3_busy_timeout,
  99754. sqlite3_changes,
  99755. sqlite3_close,
  99756. sqlite3_collation_needed,
  99757. sqlite3_collation_needed16,
  99758. sqlite3_column_blob,
  99759. sqlite3_column_bytes,
  99760. sqlite3_column_bytes16,
  99761. sqlite3_column_count,
  99762. sqlite3_column_database_name,
  99763. sqlite3_column_database_name16,
  99764. sqlite3_column_decltype,
  99765. sqlite3_column_decltype16,
  99766. sqlite3_column_double,
  99767. sqlite3_column_int,
  99768. sqlite3_column_int64,
  99769. sqlite3_column_name,
  99770. sqlite3_column_name16,
  99771. sqlite3_column_origin_name,
  99772. sqlite3_column_origin_name16,
  99773. sqlite3_column_table_name,
  99774. sqlite3_column_table_name16,
  99775. sqlite3_column_text,
  99776. sqlite3_column_text16,
  99777. sqlite3_column_type,
  99778. sqlite3_column_value,
  99779. sqlite3_commit_hook,
  99780. sqlite3_complete,
  99781. sqlite3_complete16,
  99782. sqlite3_create_collation,
  99783. sqlite3_create_collation16,
  99784. sqlite3_create_function,
  99785. sqlite3_create_function16,
  99786. sqlite3_create_module,
  99787. sqlite3_data_count,
  99788. sqlite3_db_handle,
  99789. sqlite3_declare_vtab,
  99790. sqlite3_enable_shared_cache,
  99791. sqlite3_errcode,
  99792. sqlite3_errmsg,
  99793. sqlite3_errmsg16,
  99794. sqlite3_exec,
  99795. #ifndef SQLITE_OMIT_DEPRECATED
  99796. sqlite3_expired,
  99797. #else
  99798. 0,
  99799. #endif
  99800. sqlite3_finalize,
  99801. sqlite3_free,
  99802. sqlite3_free_table,
  99803. sqlite3_get_autocommit,
  99804. sqlite3_get_auxdata,
  99805. sqlite3_get_table,
  99806. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  99807. sqlite3_interrupt,
  99808. sqlite3_last_insert_rowid,
  99809. sqlite3_libversion,
  99810. sqlite3_libversion_number,
  99811. sqlite3_malloc,
  99812. sqlite3_mprintf,
  99813. sqlite3_open,
  99814. sqlite3_open16,
  99815. sqlite3_prepare,
  99816. sqlite3_prepare16,
  99817. sqlite3_profile,
  99818. sqlite3_progress_handler,
  99819. sqlite3_realloc,
  99820. sqlite3_reset,
  99821. sqlite3_result_blob,
  99822. sqlite3_result_double,
  99823. sqlite3_result_error,
  99824. sqlite3_result_error16,
  99825. sqlite3_result_int,
  99826. sqlite3_result_int64,
  99827. sqlite3_result_null,
  99828. sqlite3_result_text,
  99829. sqlite3_result_text16,
  99830. sqlite3_result_text16be,
  99831. sqlite3_result_text16le,
  99832. sqlite3_result_value,
  99833. sqlite3_rollback_hook,
  99834. sqlite3_set_authorizer,
  99835. sqlite3_set_auxdata,
  99836. sqlite3_snprintf,
  99837. sqlite3_step,
  99838. sqlite3_table_column_metadata,
  99839. #ifndef SQLITE_OMIT_DEPRECATED
  99840. sqlite3_thread_cleanup,
  99841. #else
  99842. 0,
  99843. #endif
  99844. sqlite3_total_changes,
  99845. sqlite3_trace,
  99846. #ifndef SQLITE_OMIT_DEPRECATED
  99847. sqlite3_transfer_bindings,
  99848. #else
  99849. 0,
  99850. #endif
  99851. sqlite3_update_hook,
  99852. sqlite3_user_data,
  99853. sqlite3_value_blob,
  99854. sqlite3_value_bytes,
  99855. sqlite3_value_bytes16,
  99856. sqlite3_value_double,
  99857. sqlite3_value_int,
  99858. sqlite3_value_int64,
  99859. sqlite3_value_numeric_type,
  99860. sqlite3_value_text,
  99861. sqlite3_value_text16,
  99862. sqlite3_value_text16be,
  99863. sqlite3_value_text16le,
  99864. sqlite3_value_type,
  99865. sqlite3_vmprintf,
  99866. /*
  99867. ** The original API set ends here. All extensions can call any
  99868. ** of the APIs above provided that the pointer is not NULL. But
  99869. ** before calling APIs that follow, extension should check the
  99870. ** sqlite3_libversion_number() to make sure they are dealing with
  99871. ** a library that is new enough to support that API.
  99872. *************************************************************************
  99873. */
  99874. sqlite3_overload_function,
  99875. /*
  99876. ** Added after 3.3.13
  99877. */
  99878. sqlite3_prepare_v2,
  99879. sqlite3_prepare16_v2,
  99880. sqlite3_clear_bindings,
  99881. /*
  99882. ** Added for 3.4.1
  99883. */
  99884. sqlite3_create_module_v2,
  99885. /*
  99886. ** Added for 3.5.0
  99887. */
  99888. sqlite3_bind_zeroblob,
  99889. sqlite3_blob_bytes,
  99890. sqlite3_blob_close,
  99891. sqlite3_blob_open,
  99892. sqlite3_blob_read,
  99893. sqlite3_blob_write,
  99894. sqlite3_create_collation_v2,
  99895. sqlite3_file_control,
  99896. sqlite3_memory_highwater,
  99897. sqlite3_memory_used,
  99898. #ifdef SQLITE_MUTEX_OMIT
  99899. 0,
  99900. 0,
  99901. 0,
  99902. 0,
  99903. 0,
  99904. #else
  99905. sqlite3_mutex_alloc,
  99906. sqlite3_mutex_enter,
  99907. sqlite3_mutex_free,
  99908. sqlite3_mutex_leave,
  99909. sqlite3_mutex_try,
  99910. #endif
  99911. sqlite3_open_v2,
  99912. sqlite3_release_memory,
  99913. sqlite3_result_error_nomem,
  99914. sqlite3_result_error_toobig,
  99915. sqlite3_sleep,
  99916. sqlite3_soft_heap_limit,
  99917. sqlite3_vfs_find,
  99918. sqlite3_vfs_register,
  99919. sqlite3_vfs_unregister,
  99920. /*
  99921. ** Added for 3.5.8
  99922. */
  99923. sqlite3_threadsafe,
  99924. sqlite3_result_zeroblob,
  99925. sqlite3_result_error_code,
  99926. sqlite3_test_control,
  99927. sqlite3_randomness,
  99928. sqlite3_context_db_handle,
  99929. /*
  99930. ** Added for 3.6.0
  99931. */
  99932. sqlite3_extended_result_codes,
  99933. sqlite3_limit,
  99934. sqlite3_next_stmt,
  99935. sqlite3_sql,
  99936. sqlite3_status,
  99937. /*
  99938. ** Added for 3.7.4
  99939. */
  99940. sqlite3_backup_finish,
  99941. sqlite3_backup_init,
  99942. sqlite3_backup_pagecount,
  99943. sqlite3_backup_remaining,
  99944. sqlite3_backup_step,
  99945. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99946. sqlite3_compileoption_get,
  99947. sqlite3_compileoption_used,
  99948. #else
  99949. 0,
  99950. 0,
  99951. #endif
  99952. sqlite3_create_function_v2,
  99953. sqlite3_db_config,
  99954. sqlite3_db_mutex,
  99955. sqlite3_db_status,
  99956. sqlite3_extended_errcode,
  99957. sqlite3_log,
  99958. sqlite3_soft_heap_limit64,
  99959. sqlite3_sourceid,
  99960. sqlite3_stmt_status,
  99961. sqlite3_strnicmp,
  99962. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  99963. sqlite3_unlock_notify,
  99964. #else
  99965. 0,
  99966. #endif
  99967. #ifndef SQLITE_OMIT_WAL
  99968. sqlite3_wal_autocheckpoint,
  99969. sqlite3_wal_checkpoint,
  99970. sqlite3_wal_hook,
  99971. #else
  99972. 0,
  99973. 0,
  99974. 0,
  99975. #endif
  99976. sqlite3_blob_reopen,
  99977. sqlite3_vtab_config,
  99978. sqlite3_vtab_on_conflict,
  99979. sqlite3_close_v2,
  99980. sqlite3_db_filename,
  99981. sqlite3_db_readonly,
  99982. sqlite3_db_release_memory,
  99983. sqlite3_errstr,
  99984. sqlite3_stmt_busy,
  99985. sqlite3_stmt_readonly,
  99986. sqlite3_stricmp,
  99987. sqlite3_uri_boolean,
  99988. sqlite3_uri_int64,
  99989. sqlite3_uri_parameter,
  99990. sqlite3_vsnprintf,
  99991. sqlite3_wal_checkpoint_v2,
  99992. /* Version 3.8.7 and later */
  99993. sqlite3_auto_extension,
  99994. sqlite3_bind_blob64,
  99995. sqlite3_bind_text64,
  99996. sqlite3_cancel_auto_extension,
  99997. sqlite3_load_extension,
  99998. sqlite3_malloc64,
  99999. sqlite3_msize,
  100000. sqlite3_realloc64,
  100001. sqlite3_reset_auto_extension,
  100002. sqlite3_result_blob64,
  100003. sqlite3_result_text64,
  100004. sqlite3_strglob,
  100005. /* Version 3.8.11 and later */
  100006. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  100007. sqlite3_value_free,
  100008. sqlite3_result_zeroblob64,
  100009. sqlite3_bind_zeroblob64,
  100010. /* Version 3.9.0 and later */
  100011. sqlite3_value_subtype,
  100012. sqlite3_result_subtype,
  100013. /* Version 3.10.0 and later */
  100014. sqlite3_status64,
  100015. sqlite3_strlike,
  100016. sqlite3_db_cacheflush,
  100017. /* Version 3.12.0 and later */
  100018. sqlite3_system_errno
  100019. };
  100020. /*
  100021. ** Attempt to load an SQLite extension library contained in the file
  100022. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  100023. ** default entry point name (sqlite3_extension_init) is used. Use
  100024. ** of the default name is recommended.
  100025. **
  100026. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  100027. **
  100028. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  100029. ** error message text. The calling function should free this memory
  100030. ** by calling sqlite3DbFree(db, ).
  100031. */
  100032. static int sqlite3LoadExtension(
  100033. sqlite3 *db, /* Load the extension into this database connection */
  100034. const char *zFile, /* Name of the shared library containing extension */
  100035. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  100036. char **pzErrMsg /* Put error message here if not 0 */
  100037. ){
  100038. sqlite3_vfs *pVfs = db->pVfs;
  100039. void *handle;
  100040. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  100041. char *zErrmsg = 0;
  100042. const char *zEntry;
  100043. char *zAltEntry = 0;
  100044. void **aHandle;
  100045. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  100046. int ii;
  100047. /* Shared library endings to try if zFile cannot be loaded as written */
  100048. static const char *azEndings[] = {
  100049. #if SQLITE_OS_WIN
  100050. "dll"
  100051. #elif defined(__APPLE__)
  100052. "dylib"
  100053. #else
  100054. "so"
  100055. #endif
  100056. };
  100057. if( pzErrMsg ) *pzErrMsg = 0;
  100058. /* Ticket #1863. To avoid a creating security problems for older
  100059. ** applications that relink against newer versions of SQLite, the
  100060. ** ability to run load_extension is turned off by default. One
  100061. ** must call sqlite3_enable_load_extension() to turn on extension
  100062. ** loading. Otherwise you get the following error.
  100063. */
  100064. if( (db->flags & SQLITE_LoadExtension)==0 ){
  100065. if( pzErrMsg ){
  100066. *pzErrMsg = sqlite3_mprintf("not authorized");
  100067. }
  100068. return SQLITE_ERROR;
  100069. }
  100070. zEntry = zProc ? zProc : "sqlite3_extension_init";
  100071. handle = sqlite3OsDlOpen(pVfs, zFile);
  100072. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  100073. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  100074. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  100075. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  100076. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  100077. sqlite3_free(zAltFile);
  100078. }
  100079. #endif
  100080. if( handle==0 ){
  100081. if( pzErrMsg ){
  100082. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  100083. if( zErrmsg ){
  100084. sqlite3_snprintf(nMsg, zErrmsg,
  100085. "unable to open shared library [%s]", zFile);
  100086. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  100087. }
  100088. }
  100089. return SQLITE_ERROR;
  100090. }
  100091. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  100092. sqlite3OsDlSym(pVfs, handle, zEntry);
  100093. /* If no entry point was specified and the default legacy
  100094. ** entry point name "sqlite3_extension_init" was not found, then
  100095. ** construct an entry point name "sqlite3_X_init" where the X is
  100096. ** replaced by the lowercase value of every ASCII alphabetic
  100097. ** character in the filename after the last "/" upto the first ".",
  100098. ** and eliding the first three characters if they are "lib".
  100099. ** Examples:
  100100. **
  100101. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  100102. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  100103. */
  100104. if( xInit==0 && zProc==0 ){
  100105. int iFile, iEntry, c;
  100106. int ncFile = sqlite3Strlen30(zFile);
  100107. zAltEntry = sqlite3_malloc64(ncFile+30);
  100108. if( zAltEntry==0 ){
  100109. sqlite3OsDlClose(pVfs, handle);
  100110. return SQLITE_NOMEM_BKPT;
  100111. }
  100112. memcpy(zAltEntry, "sqlite3_", 8);
  100113. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  100114. iFile++;
  100115. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  100116. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  100117. if( sqlite3Isalpha(c) ){
  100118. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  100119. }
  100120. }
  100121. memcpy(zAltEntry+iEntry, "_init", 6);
  100122. zEntry = zAltEntry;
  100123. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  100124. sqlite3OsDlSym(pVfs, handle, zEntry);
  100125. }
  100126. if( xInit==0 ){
  100127. if( pzErrMsg ){
  100128. nMsg += sqlite3Strlen30(zEntry);
  100129. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  100130. if( zErrmsg ){
  100131. sqlite3_snprintf(nMsg, zErrmsg,
  100132. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  100133. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  100134. }
  100135. }
  100136. sqlite3OsDlClose(pVfs, handle);
  100137. sqlite3_free(zAltEntry);
  100138. return SQLITE_ERROR;
  100139. }
  100140. sqlite3_free(zAltEntry);
  100141. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  100142. if( pzErrMsg ){
  100143. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  100144. }
  100145. sqlite3_free(zErrmsg);
  100146. sqlite3OsDlClose(pVfs, handle);
  100147. return SQLITE_ERROR;
  100148. }
  100149. /* Append the new shared library handle to the db->aExtension array. */
  100150. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  100151. if( aHandle==0 ){
  100152. return SQLITE_NOMEM_BKPT;
  100153. }
  100154. if( db->nExtension>0 ){
  100155. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  100156. }
  100157. sqlite3DbFree(db, db->aExtension);
  100158. db->aExtension = aHandle;
  100159. db->aExtension[db->nExtension++] = handle;
  100160. return SQLITE_OK;
  100161. }
  100162. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  100163. sqlite3 *db, /* Load the extension into this database connection */
  100164. const char *zFile, /* Name of the shared library containing extension */
  100165. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  100166. char **pzErrMsg /* Put error message here if not 0 */
  100167. ){
  100168. int rc;
  100169. sqlite3_mutex_enter(db->mutex);
  100170. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  100171. rc = sqlite3ApiExit(db, rc);
  100172. sqlite3_mutex_leave(db->mutex);
  100173. return rc;
  100174. }
  100175. /*
  100176. ** Call this routine when the database connection is closing in order
  100177. ** to clean up loaded extensions
  100178. */
  100179. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  100180. int i;
  100181. assert( sqlite3_mutex_held(db->mutex) );
  100182. for(i=0; i<db->nExtension; i++){
  100183. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  100184. }
  100185. sqlite3DbFree(db, db->aExtension);
  100186. }
  100187. /*
  100188. ** Enable or disable extension loading. Extension loading is disabled by
  100189. ** default so as not to open security holes in older applications.
  100190. */
  100191. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  100192. sqlite3_mutex_enter(db->mutex);
  100193. if( onoff ){
  100194. db->flags |= SQLITE_LoadExtension;
  100195. }else{
  100196. db->flags &= ~SQLITE_LoadExtension;
  100197. }
  100198. sqlite3_mutex_leave(db->mutex);
  100199. return SQLITE_OK;
  100200. }
  100201. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  100202. /*
  100203. ** The auto-extension code added regardless of whether or not extension
  100204. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  100205. ** code if regular extension loading is not available. This is that
  100206. ** dummy pointer.
  100207. */
  100208. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  100209. static const sqlite3_api_routines sqlite3Apis = { 0 };
  100210. #endif
  100211. /*
  100212. ** The following object holds the list of automatically loaded
  100213. ** extensions.
  100214. **
  100215. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  100216. ** mutex must be held while accessing this list.
  100217. */
  100218. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  100219. static SQLITE_WSD struct sqlite3AutoExtList {
  100220. u32 nExt; /* Number of entries in aExt[] */
  100221. void (**aExt)(void); /* Pointers to the extension init functions */
  100222. } sqlite3Autoext = { 0, 0 };
  100223. /* The "wsdAutoext" macro will resolve to the autoextension
  100224. ** state vector. If writable static data is unsupported on the target,
  100225. ** we have to locate the state vector at run-time. In the more common
  100226. ** case where writable static data is supported, wsdStat can refer directly
  100227. ** to the "sqlite3Autoext" state vector declared above.
  100228. */
  100229. #ifdef SQLITE_OMIT_WSD
  100230. # define wsdAutoextInit \
  100231. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  100232. # define wsdAutoext x[0]
  100233. #else
  100234. # define wsdAutoextInit
  100235. # define wsdAutoext sqlite3Autoext
  100236. #endif
  100237. /*
  100238. ** Register a statically linked extension that is automatically
  100239. ** loaded by every new database connection.
  100240. */
  100241. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
  100242. int rc = SQLITE_OK;
  100243. #ifndef SQLITE_OMIT_AUTOINIT
  100244. rc = sqlite3_initialize();
  100245. if( rc ){
  100246. return rc;
  100247. }else
  100248. #endif
  100249. {
  100250. u32 i;
  100251. #if SQLITE_THREADSAFE
  100252. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  100253. #endif
  100254. wsdAutoextInit;
  100255. sqlite3_mutex_enter(mutex);
  100256. for(i=0; i<wsdAutoext.nExt; i++){
  100257. if( wsdAutoext.aExt[i]==xInit ) break;
  100258. }
  100259. if( i==wsdAutoext.nExt ){
  100260. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  100261. void (**aNew)(void);
  100262. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  100263. if( aNew==0 ){
  100264. rc = SQLITE_NOMEM_BKPT;
  100265. }else{
  100266. wsdAutoext.aExt = aNew;
  100267. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  100268. wsdAutoext.nExt++;
  100269. }
  100270. }
  100271. sqlite3_mutex_leave(mutex);
  100272. assert( (rc&0xff)==rc );
  100273. return rc;
  100274. }
  100275. }
  100276. /*
  100277. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  100278. ** set of routines that is invoked for each new database connection, if it
  100279. ** is currently on the list. If xInit is not on the list, then this
  100280. ** routine is a no-op.
  100281. **
  100282. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  100283. ** was not on the list.
  100284. */
  100285. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
  100286. #if SQLITE_THREADSAFE
  100287. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  100288. #endif
  100289. int i;
  100290. int n = 0;
  100291. wsdAutoextInit;
  100292. sqlite3_mutex_enter(mutex);
  100293. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  100294. if( wsdAutoext.aExt[i]==xInit ){
  100295. wsdAutoext.nExt--;
  100296. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  100297. n++;
  100298. break;
  100299. }
  100300. }
  100301. sqlite3_mutex_leave(mutex);
  100302. return n;
  100303. }
  100304. /*
  100305. ** Reset the automatic extension loading mechanism.
  100306. */
  100307. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
  100308. #ifndef SQLITE_OMIT_AUTOINIT
  100309. if( sqlite3_initialize()==SQLITE_OK )
  100310. #endif
  100311. {
  100312. #if SQLITE_THREADSAFE
  100313. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  100314. #endif
  100315. wsdAutoextInit;
  100316. sqlite3_mutex_enter(mutex);
  100317. sqlite3_free(wsdAutoext.aExt);
  100318. wsdAutoext.aExt = 0;
  100319. wsdAutoext.nExt = 0;
  100320. sqlite3_mutex_leave(mutex);
  100321. }
  100322. }
  100323. /*
  100324. ** Load all automatic extensions.
  100325. **
  100326. ** If anything goes wrong, set an error in the database connection.
  100327. */
  100328. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  100329. u32 i;
  100330. int go = 1;
  100331. int rc;
  100332. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  100333. wsdAutoextInit;
  100334. if( wsdAutoext.nExt==0 ){
  100335. /* Common case: early out without every having to acquire a mutex */
  100336. return;
  100337. }
  100338. for(i=0; go; i++){
  100339. char *zErrmsg;
  100340. #if SQLITE_THREADSAFE
  100341. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  100342. #endif
  100343. sqlite3_mutex_enter(mutex);
  100344. if( i>=wsdAutoext.nExt ){
  100345. xInit = 0;
  100346. go = 0;
  100347. }else{
  100348. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  100349. wsdAutoext.aExt[i];
  100350. }
  100351. sqlite3_mutex_leave(mutex);
  100352. zErrmsg = 0;
  100353. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  100354. sqlite3ErrorWithMsg(db, rc,
  100355. "automatic extension loading failed: %s", zErrmsg);
  100356. go = 0;
  100357. }
  100358. sqlite3_free(zErrmsg);
  100359. }
  100360. }
  100361. /************** End of loadext.c *********************************************/
  100362. /************** Begin file pragma.c ******************************************/
  100363. /*
  100364. ** 2003 April 6
  100365. **
  100366. ** The author disclaims copyright to this source code. In place of
  100367. ** a legal notice, here is a blessing:
  100368. **
  100369. ** May you do good and not evil.
  100370. ** May you find forgiveness for yourself and forgive others.
  100371. ** May you share freely, never taking more than you give.
  100372. **
  100373. *************************************************************************
  100374. ** This file contains code used to implement the PRAGMA command.
  100375. */
  100376. /* #include "sqliteInt.h" */
  100377. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  100378. # if defined(__APPLE__)
  100379. # define SQLITE_ENABLE_LOCKING_STYLE 1
  100380. # else
  100381. # define SQLITE_ENABLE_LOCKING_STYLE 0
  100382. # endif
  100383. #endif
  100384. /***************************************************************************
  100385. ** The "pragma.h" include file is an automatically generated file that
  100386. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  100387. ** object. This ensures that the aPragmaName[] table is arranged in
  100388. ** lexicographical order to facility a binary search of the pragma name.
  100389. ** Do not edit pragma.h directly. Edit and rerun the script in at
  100390. ** ../tool/mkpragmatab.tcl. */
  100391. /************** Include pragma.h in the middle of pragma.c *******************/
  100392. /************** Begin file pragma.h ******************************************/
  100393. /* DO NOT EDIT!
  100394. ** This file is automatically generated by the script at
  100395. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  100396. ** that script and rerun it.
  100397. */
  100398. #define PragTyp_HEADER_VALUE 0
  100399. #define PragTyp_AUTO_VACUUM 1
  100400. #define PragTyp_FLAG 2
  100401. #define PragTyp_BUSY_TIMEOUT 3
  100402. #define PragTyp_CACHE_SIZE 4
  100403. #define PragTyp_CACHE_SPILL 5
  100404. #define PragTyp_CASE_SENSITIVE_LIKE 6
  100405. #define PragTyp_COLLATION_LIST 7
  100406. #define PragTyp_COMPILE_OPTIONS 8
  100407. #define PragTyp_DATA_STORE_DIRECTORY 9
  100408. #define PragTyp_DATABASE_LIST 10
  100409. #define PragTyp_DEFAULT_CACHE_SIZE 11
  100410. #define PragTyp_ENCODING 12
  100411. #define PragTyp_FOREIGN_KEY_CHECK 13
  100412. #define PragTyp_FOREIGN_KEY_LIST 14
  100413. #define PragTyp_INCREMENTAL_VACUUM 15
  100414. #define PragTyp_INDEX_INFO 16
  100415. #define PragTyp_INDEX_LIST 17
  100416. #define PragTyp_INTEGRITY_CHECK 18
  100417. #define PragTyp_JOURNAL_MODE 19
  100418. #define PragTyp_JOURNAL_SIZE_LIMIT 20
  100419. #define PragTyp_LOCK_PROXY_FILE 21
  100420. #define PragTyp_LOCKING_MODE 22
  100421. #define PragTyp_PAGE_COUNT 23
  100422. #define PragTyp_MMAP_SIZE 24
  100423. #define PragTyp_PAGE_SIZE 25
  100424. #define PragTyp_SECURE_DELETE 26
  100425. #define PragTyp_SHRINK_MEMORY 27
  100426. #define PragTyp_SOFT_HEAP_LIMIT 28
  100427. #define PragTyp_STATS 29
  100428. #define PragTyp_SYNCHRONOUS 30
  100429. #define PragTyp_TABLE_INFO 31
  100430. #define PragTyp_TEMP_STORE 32
  100431. #define PragTyp_TEMP_STORE_DIRECTORY 33
  100432. #define PragTyp_THREADS 34
  100433. #define PragTyp_WAL_AUTOCHECKPOINT 35
  100434. #define PragTyp_WAL_CHECKPOINT 36
  100435. #define PragTyp_ACTIVATE_EXTENSIONS 37
  100436. #define PragTyp_HEXKEY 38
  100437. #define PragTyp_KEY 39
  100438. #define PragTyp_REKEY 40
  100439. #define PragTyp_LOCK_STATUS 41
  100440. #define PragTyp_PARSER_TRACE 42
  100441. #define PragFlag_NeedSchema 0x01
  100442. #define PragFlag_ReadOnly 0x02
  100443. static const struct sPragmaNames {
  100444. const char *const zName; /* Name of pragma */
  100445. u8 ePragTyp; /* PragTyp_XXX value */
  100446. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  100447. u32 iArg; /* Extra argument */
  100448. } aPragmaNames[] = {
  100449. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  100450. { /* zName: */ "activate_extensions",
  100451. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  100452. /* ePragFlag: */ 0,
  100453. /* iArg: */ 0 },
  100454. #endif
  100455. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  100456. { /* zName: */ "application_id",
  100457. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  100458. /* ePragFlag: */ 0,
  100459. /* iArg: */ BTREE_APPLICATION_ID },
  100460. #endif
  100461. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  100462. { /* zName: */ "auto_vacuum",
  100463. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  100464. /* ePragFlag: */ PragFlag_NeedSchema,
  100465. /* iArg: */ 0 },
  100466. #endif
  100467. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100468. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  100469. { /* zName: */ "automatic_index",
  100470. /* ePragTyp: */ PragTyp_FLAG,
  100471. /* ePragFlag: */ 0,
  100472. /* iArg: */ SQLITE_AutoIndex },
  100473. #endif
  100474. #endif
  100475. { /* zName: */ "busy_timeout",
  100476. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  100477. /* ePragFlag: */ 0,
  100478. /* iArg: */ 0 },
  100479. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100480. { /* zName: */ "cache_size",
  100481. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  100482. /* ePragFlag: */ PragFlag_NeedSchema,
  100483. /* iArg: */ 0 },
  100484. #endif
  100485. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100486. { /* zName: */ "cache_spill",
  100487. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  100488. /* ePragFlag: */ 0,
  100489. /* iArg: */ 0 },
  100490. #endif
  100491. { /* zName: */ "case_sensitive_like",
  100492. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  100493. /* ePragFlag: */ 0,
  100494. /* iArg: */ 0 },
  100495. { /* zName: */ "cell_size_check",
  100496. /* ePragTyp: */ PragTyp_FLAG,
  100497. /* ePragFlag: */ 0,
  100498. /* iArg: */ SQLITE_CellSizeCk },
  100499. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100500. { /* zName: */ "checkpoint_fullfsync",
  100501. /* ePragTyp: */ PragTyp_FLAG,
  100502. /* ePragFlag: */ 0,
  100503. /* iArg: */ SQLITE_CkptFullFSync },
  100504. #endif
  100505. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  100506. { /* zName: */ "collation_list",
  100507. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  100508. /* ePragFlag: */ 0,
  100509. /* iArg: */ 0 },
  100510. #endif
  100511. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  100512. { /* zName: */ "compile_options",
  100513. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  100514. /* ePragFlag: */ 0,
  100515. /* iArg: */ 0 },
  100516. #endif
  100517. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100518. { /* zName: */ "count_changes",
  100519. /* ePragTyp: */ PragTyp_FLAG,
  100520. /* ePragFlag: */ 0,
  100521. /* iArg: */ SQLITE_CountRows },
  100522. #endif
  100523. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  100524. { /* zName: */ "data_store_directory",
  100525. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  100526. /* ePragFlag: */ 0,
  100527. /* iArg: */ 0 },
  100528. #endif
  100529. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  100530. { /* zName: */ "data_version",
  100531. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  100532. /* ePragFlag: */ PragFlag_ReadOnly,
  100533. /* iArg: */ BTREE_DATA_VERSION },
  100534. #endif
  100535. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  100536. { /* zName: */ "database_list",
  100537. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  100538. /* ePragFlag: */ PragFlag_NeedSchema,
  100539. /* iArg: */ 0 },
  100540. #endif
  100541. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  100542. { /* zName: */ "default_cache_size",
  100543. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  100544. /* ePragFlag: */ PragFlag_NeedSchema,
  100545. /* iArg: */ 0 },
  100546. #endif
  100547. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100548. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  100549. { /* zName: */ "defer_foreign_keys",
  100550. /* ePragTyp: */ PragTyp_FLAG,
  100551. /* ePragFlag: */ 0,
  100552. /* iArg: */ SQLITE_DeferFKs },
  100553. #endif
  100554. #endif
  100555. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100556. { /* zName: */ "empty_result_callbacks",
  100557. /* ePragTyp: */ PragTyp_FLAG,
  100558. /* ePragFlag: */ 0,
  100559. /* iArg: */ SQLITE_NullCallback },
  100560. #endif
  100561. #if !defined(SQLITE_OMIT_UTF16)
  100562. { /* zName: */ "encoding",
  100563. /* ePragTyp: */ PragTyp_ENCODING,
  100564. /* ePragFlag: */ 0,
  100565. /* iArg: */ 0 },
  100566. #endif
  100567. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  100568. { /* zName: */ "foreign_key_check",
  100569. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  100570. /* ePragFlag: */ PragFlag_NeedSchema,
  100571. /* iArg: */ 0 },
  100572. #endif
  100573. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  100574. { /* zName: */ "foreign_key_list",
  100575. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  100576. /* ePragFlag: */ PragFlag_NeedSchema,
  100577. /* iArg: */ 0 },
  100578. #endif
  100579. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100580. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  100581. { /* zName: */ "foreign_keys",
  100582. /* ePragTyp: */ PragTyp_FLAG,
  100583. /* ePragFlag: */ 0,
  100584. /* iArg: */ SQLITE_ForeignKeys },
  100585. #endif
  100586. #endif
  100587. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  100588. { /* zName: */ "freelist_count",
  100589. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  100590. /* ePragFlag: */ PragFlag_ReadOnly,
  100591. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  100592. #endif
  100593. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100594. { /* zName: */ "full_column_names",
  100595. /* ePragTyp: */ PragTyp_FLAG,
  100596. /* ePragFlag: */ 0,
  100597. /* iArg: */ SQLITE_FullColNames },
  100598. { /* zName: */ "fullfsync",
  100599. /* ePragTyp: */ PragTyp_FLAG,
  100600. /* ePragFlag: */ 0,
  100601. /* iArg: */ SQLITE_FullFSync },
  100602. #endif
  100603. #if defined(SQLITE_HAS_CODEC)
  100604. { /* zName: */ "hexkey",
  100605. /* ePragTyp: */ PragTyp_HEXKEY,
  100606. /* ePragFlag: */ 0,
  100607. /* iArg: */ 0 },
  100608. { /* zName: */ "hexrekey",
  100609. /* ePragTyp: */ PragTyp_HEXKEY,
  100610. /* ePragFlag: */ 0,
  100611. /* iArg: */ 0 },
  100612. #endif
  100613. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100614. #if !defined(SQLITE_OMIT_CHECK)
  100615. { /* zName: */ "ignore_check_constraints",
  100616. /* ePragTyp: */ PragTyp_FLAG,
  100617. /* ePragFlag: */ 0,
  100618. /* iArg: */ SQLITE_IgnoreChecks },
  100619. #endif
  100620. #endif
  100621. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  100622. { /* zName: */ "incremental_vacuum",
  100623. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  100624. /* ePragFlag: */ PragFlag_NeedSchema,
  100625. /* iArg: */ 0 },
  100626. #endif
  100627. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  100628. { /* zName: */ "index_info",
  100629. /* ePragTyp: */ PragTyp_INDEX_INFO,
  100630. /* ePragFlag: */ PragFlag_NeedSchema,
  100631. /* iArg: */ 0 },
  100632. { /* zName: */ "index_list",
  100633. /* ePragTyp: */ PragTyp_INDEX_LIST,
  100634. /* ePragFlag: */ PragFlag_NeedSchema,
  100635. /* iArg: */ 0 },
  100636. { /* zName: */ "index_xinfo",
  100637. /* ePragTyp: */ PragTyp_INDEX_INFO,
  100638. /* ePragFlag: */ PragFlag_NeedSchema,
  100639. /* iArg: */ 1 },
  100640. #endif
  100641. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  100642. { /* zName: */ "integrity_check",
  100643. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  100644. /* ePragFlag: */ PragFlag_NeedSchema,
  100645. /* iArg: */ 0 },
  100646. #endif
  100647. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100648. { /* zName: */ "journal_mode",
  100649. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  100650. /* ePragFlag: */ PragFlag_NeedSchema,
  100651. /* iArg: */ 0 },
  100652. { /* zName: */ "journal_size_limit",
  100653. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  100654. /* ePragFlag: */ 0,
  100655. /* iArg: */ 0 },
  100656. #endif
  100657. #if defined(SQLITE_HAS_CODEC)
  100658. { /* zName: */ "key",
  100659. /* ePragTyp: */ PragTyp_KEY,
  100660. /* ePragFlag: */ 0,
  100661. /* iArg: */ 0 },
  100662. #endif
  100663. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100664. { /* zName: */ "legacy_file_format",
  100665. /* ePragTyp: */ PragTyp_FLAG,
  100666. /* ePragFlag: */ 0,
  100667. /* iArg: */ SQLITE_LegacyFileFmt },
  100668. #endif
  100669. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  100670. { /* zName: */ "lock_proxy_file",
  100671. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  100672. /* ePragFlag: */ 0,
  100673. /* iArg: */ 0 },
  100674. #endif
  100675. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  100676. { /* zName: */ "lock_status",
  100677. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  100678. /* ePragFlag: */ 0,
  100679. /* iArg: */ 0 },
  100680. #endif
  100681. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100682. { /* zName: */ "locking_mode",
  100683. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  100684. /* ePragFlag: */ 0,
  100685. /* iArg: */ 0 },
  100686. { /* zName: */ "max_page_count",
  100687. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  100688. /* ePragFlag: */ PragFlag_NeedSchema,
  100689. /* iArg: */ 0 },
  100690. { /* zName: */ "mmap_size",
  100691. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  100692. /* ePragFlag: */ 0,
  100693. /* iArg: */ 0 },
  100694. { /* zName: */ "page_count",
  100695. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  100696. /* ePragFlag: */ PragFlag_NeedSchema,
  100697. /* iArg: */ 0 },
  100698. { /* zName: */ "page_size",
  100699. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  100700. /* ePragFlag: */ 0,
  100701. /* iArg: */ 0 },
  100702. #endif
  100703. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  100704. { /* zName: */ "parser_trace",
  100705. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  100706. /* ePragFlag: */ 0,
  100707. /* iArg: */ 0 },
  100708. #endif
  100709. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100710. { /* zName: */ "query_only",
  100711. /* ePragTyp: */ PragTyp_FLAG,
  100712. /* ePragFlag: */ 0,
  100713. /* iArg: */ SQLITE_QueryOnly },
  100714. #endif
  100715. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  100716. { /* zName: */ "quick_check",
  100717. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  100718. /* ePragFlag: */ PragFlag_NeedSchema,
  100719. /* iArg: */ 0 },
  100720. #endif
  100721. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100722. { /* zName: */ "read_uncommitted",
  100723. /* ePragTyp: */ PragTyp_FLAG,
  100724. /* ePragFlag: */ 0,
  100725. /* iArg: */ SQLITE_ReadUncommitted },
  100726. { /* zName: */ "recursive_triggers",
  100727. /* ePragTyp: */ PragTyp_FLAG,
  100728. /* ePragFlag: */ 0,
  100729. /* iArg: */ SQLITE_RecTriggers },
  100730. #endif
  100731. #if defined(SQLITE_HAS_CODEC)
  100732. { /* zName: */ "rekey",
  100733. /* ePragTyp: */ PragTyp_REKEY,
  100734. /* ePragFlag: */ 0,
  100735. /* iArg: */ 0 },
  100736. #endif
  100737. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100738. { /* zName: */ "reverse_unordered_selects",
  100739. /* ePragTyp: */ PragTyp_FLAG,
  100740. /* ePragFlag: */ 0,
  100741. /* iArg: */ SQLITE_ReverseOrder },
  100742. #endif
  100743. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  100744. { /* zName: */ "schema_version",
  100745. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  100746. /* ePragFlag: */ 0,
  100747. /* iArg: */ BTREE_SCHEMA_VERSION },
  100748. #endif
  100749. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100750. { /* zName: */ "secure_delete",
  100751. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  100752. /* ePragFlag: */ 0,
  100753. /* iArg: */ 0 },
  100754. #endif
  100755. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100756. { /* zName: */ "short_column_names",
  100757. /* ePragTyp: */ PragTyp_FLAG,
  100758. /* ePragFlag: */ 0,
  100759. /* iArg: */ SQLITE_ShortColNames },
  100760. #endif
  100761. { /* zName: */ "shrink_memory",
  100762. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  100763. /* ePragFlag: */ 0,
  100764. /* iArg: */ 0 },
  100765. { /* zName: */ "soft_heap_limit",
  100766. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  100767. /* ePragFlag: */ 0,
  100768. /* iArg: */ 0 },
  100769. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100770. #if defined(SQLITE_DEBUG)
  100771. { /* zName: */ "sql_trace",
  100772. /* ePragTyp: */ PragTyp_FLAG,
  100773. /* ePragFlag: */ 0,
  100774. /* iArg: */ SQLITE_SqlTrace },
  100775. #endif
  100776. #endif
  100777. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  100778. { /* zName: */ "stats",
  100779. /* ePragTyp: */ PragTyp_STATS,
  100780. /* ePragFlag: */ PragFlag_NeedSchema,
  100781. /* iArg: */ 0 },
  100782. #endif
  100783. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100784. { /* zName: */ "synchronous",
  100785. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  100786. /* ePragFlag: */ PragFlag_NeedSchema,
  100787. /* iArg: */ 0 },
  100788. #endif
  100789. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  100790. { /* zName: */ "table_info",
  100791. /* ePragTyp: */ PragTyp_TABLE_INFO,
  100792. /* ePragFlag: */ PragFlag_NeedSchema,
  100793. /* iArg: */ 0 },
  100794. #endif
  100795. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100796. { /* zName: */ "temp_store",
  100797. /* ePragTyp: */ PragTyp_TEMP_STORE,
  100798. /* ePragFlag: */ 0,
  100799. /* iArg: */ 0 },
  100800. { /* zName: */ "temp_store_directory",
  100801. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  100802. /* ePragFlag: */ 0,
  100803. /* iArg: */ 0 },
  100804. #endif
  100805. { /* zName: */ "threads",
  100806. /* ePragTyp: */ PragTyp_THREADS,
  100807. /* ePragFlag: */ 0,
  100808. /* iArg: */ 0 },
  100809. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  100810. { /* zName: */ "user_version",
  100811. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  100812. /* ePragFlag: */ 0,
  100813. /* iArg: */ BTREE_USER_VERSION },
  100814. #endif
  100815. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100816. #if defined(SQLITE_DEBUG)
  100817. { /* zName: */ "vdbe_addoptrace",
  100818. /* ePragTyp: */ PragTyp_FLAG,
  100819. /* ePragFlag: */ 0,
  100820. /* iArg: */ SQLITE_VdbeAddopTrace },
  100821. { /* zName: */ "vdbe_debug",
  100822. /* ePragTyp: */ PragTyp_FLAG,
  100823. /* ePragFlag: */ 0,
  100824. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  100825. { /* zName: */ "vdbe_eqp",
  100826. /* ePragTyp: */ PragTyp_FLAG,
  100827. /* ePragFlag: */ 0,
  100828. /* iArg: */ SQLITE_VdbeEQP },
  100829. { /* zName: */ "vdbe_listing",
  100830. /* ePragTyp: */ PragTyp_FLAG,
  100831. /* ePragFlag: */ 0,
  100832. /* iArg: */ SQLITE_VdbeListing },
  100833. { /* zName: */ "vdbe_trace",
  100834. /* ePragTyp: */ PragTyp_FLAG,
  100835. /* ePragFlag: */ 0,
  100836. /* iArg: */ SQLITE_VdbeTrace },
  100837. #endif
  100838. #endif
  100839. #if !defined(SQLITE_OMIT_WAL)
  100840. { /* zName: */ "wal_autocheckpoint",
  100841. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  100842. /* ePragFlag: */ 0,
  100843. /* iArg: */ 0 },
  100844. { /* zName: */ "wal_checkpoint",
  100845. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  100846. /* ePragFlag: */ PragFlag_NeedSchema,
  100847. /* iArg: */ 0 },
  100848. #endif
  100849. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100850. { /* zName: */ "writable_schema",
  100851. /* ePragTyp: */ PragTyp_FLAG,
  100852. /* ePragFlag: */ 0,
  100853. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  100854. #endif
  100855. };
  100856. /* Number of pragmas: 60 on by default, 73 total. */
  100857. /************** End of pragma.h **********************************************/
  100858. /************** Continuing where we left off in pragma.c *********************/
  100859. /*
  100860. ** Interpret the given string as a safety level. Return 0 for OFF,
  100861. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  100862. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  100863. ** if the omitFull parameter it 1.
  100864. **
  100865. ** Note that the values returned are one less that the values that
  100866. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  100867. ** to support legacy SQL code. The safety level used to be boolean
  100868. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  100869. */
  100870. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  100871. /* 123456789 123456789 123 */
  100872. static const char zText[] = "onoffalseyestruextrafull";
  100873. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  100874. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  100875. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  100876. /* on no off false yes true extra full */
  100877. int i, n;
  100878. if( sqlite3Isdigit(*z) ){
  100879. return (u8)sqlite3Atoi(z);
  100880. }
  100881. n = sqlite3Strlen30(z);
  100882. for(i=0; i<ArraySize(iLength); i++){
  100883. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  100884. && (!omitFull || iValue[i]<=1)
  100885. ){
  100886. return iValue[i];
  100887. }
  100888. }
  100889. return dflt;
  100890. }
  100891. /*
  100892. ** Interpret the given string as a boolean value.
  100893. */
  100894. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  100895. return getSafetyLevel(z,1,dflt)!=0;
  100896. }
  100897. /* The sqlite3GetBoolean() function is used by other modules but the
  100898. ** remainder of this file is specific to PRAGMA processing. So omit
  100899. ** the rest of the file if PRAGMAs are omitted from the build.
  100900. */
  100901. #if !defined(SQLITE_OMIT_PRAGMA)
  100902. /*
  100903. ** Interpret the given string as a locking mode value.
  100904. */
  100905. static int getLockingMode(const char *z){
  100906. if( z ){
  100907. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  100908. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  100909. }
  100910. return PAGER_LOCKINGMODE_QUERY;
  100911. }
  100912. #ifndef SQLITE_OMIT_AUTOVACUUM
  100913. /*
  100914. ** Interpret the given string as an auto-vacuum mode value.
  100915. **
  100916. ** The following strings, "none", "full" and "incremental" are
  100917. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  100918. */
  100919. static int getAutoVacuum(const char *z){
  100920. int i;
  100921. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  100922. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  100923. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  100924. i = sqlite3Atoi(z);
  100925. return (u8)((i>=0&&i<=2)?i:0);
  100926. }
  100927. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  100928. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100929. /*
  100930. ** Interpret the given string as a temp db location. Return 1 for file
  100931. ** backed temporary databases, 2 for the Red-Black tree in memory database
  100932. ** and 0 to use the compile-time default.
  100933. */
  100934. static int getTempStore(const char *z){
  100935. if( z[0]>='0' && z[0]<='2' ){
  100936. return z[0] - '0';
  100937. }else if( sqlite3StrICmp(z, "file")==0 ){
  100938. return 1;
  100939. }else if( sqlite3StrICmp(z, "memory")==0 ){
  100940. return 2;
  100941. }else{
  100942. return 0;
  100943. }
  100944. }
  100945. #endif /* SQLITE_PAGER_PRAGMAS */
  100946. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100947. /*
  100948. ** Invalidate temp storage, either when the temp storage is changed
  100949. ** from default, or when 'file' and the temp_store_directory has changed
  100950. */
  100951. static int invalidateTempStorage(Parse *pParse){
  100952. sqlite3 *db = pParse->db;
  100953. if( db->aDb[1].pBt!=0 ){
  100954. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  100955. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  100956. "from within a transaction");
  100957. return SQLITE_ERROR;
  100958. }
  100959. sqlite3BtreeClose(db->aDb[1].pBt);
  100960. db->aDb[1].pBt = 0;
  100961. sqlite3ResetAllSchemasOfConnection(db);
  100962. }
  100963. return SQLITE_OK;
  100964. }
  100965. #endif /* SQLITE_PAGER_PRAGMAS */
  100966. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100967. /*
  100968. ** If the TEMP database is open, close it and mark the database schema
  100969. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  100970. ** or DEFAULT_TEMP_STORE pragmas.
  100971. */
  100972. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  100973. int ts = getTempStore(zStorageType);
  100974. sqlite3 *db = pParse->db;
  100975. if( db->temp_store==ts ) return SQLITE_OK;
  100976. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  100977. return SQLITE_ERROR;
  100978. }
  100979. db->temp_store = (u8)ts;
  100980. return SQLITE_OK;
  100981. }
  100982. #endif /* SQLITE_PAGER_PRAGMAS */
  100983. /*
  100984. ** Set the names of the first N columns to the values in azCol[]
  100985. */
  100986. static void setAllColumnNames(
  100987. Vdbe *v, /* The query under construction */
  100988. int N, /* Number of columns */
  100989. const char **azCol /* Names of columns */
  100990. ){
  100991. int i;
  100992. sqlite3VdbeSetNumCols(v, N);
  100993. for(i=0; i<N; i++){
  100994. sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
  100995. }
  100996. }
  100997. static void setOneColumnName(Vdbe *v, const char *z){
  100998. setAllColumnNames(v, 1, &z);
  100999. }
  101000. /*
  101001. ** Generate code to return a single integer value.
  101002. */
  101003. static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
  101004. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  101005. setOneColumnName(v, zLabel);
  101006. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  101007. }
  101008. /*
  101009. ** Generate code to return a single text value.
  101010. */
  101011. static void returnSingleText(
  101012. Vdbe *v, /* Prepared statement under construction */
  101013. const char *zLabel, /* Name of the result column */
  101014. const char *zValue /* Value to be returned */
  101015. ){
  101016. if( zValue ){
  101017. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  101018. setOneColumnName(v, zLabel);
  101019. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  101020. }
  101021. }
  101022. /*
  101023. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  101024. ** set these values for all pagers.
  101025. */
  101026. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  101027. static void setAllPagerFlags(sqlite3 *db){
  101028. if( db->autoCommit ){
  101029. Db *pDb = db->aDb;
  101030. int n = db->nDb;
  101031. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  101032. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  101033. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  101034. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  101035. == PAGER_FLAGS_MASK );
  101036. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  101037. while( (n--) > 0 ){
  101038. if( pDb->pBt ){
  101039. sqlite3BtreeSetPagerFlags(pDb->pBt,
  101040. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  101041. }
  101042. pDb++;
  101043. }
  101044. }
  101045. }
  101046. #else
  101047. # define setAllPagerFlags(X) /* no-op */
  101048. #endif
  101049. /*
  101050. ** Return a human-readable name for a constraint resolution action.
  101051. */
  101052. #ifndef SQLITE_OMIT_FOREIGN_KEY
  101053. static const char *actionName(u8 action){
  101054. const char *zName;
  101055. switch( action ){
  101056. case OE_SetNull: zName = "SET NULL"; break;
  101057. case OE_SetDflt: zName = "SET DEFAULT"; break;
  101058. case OE_Cascade: zName = "CASCADE"; break;
  101059. case OE_Restrict: zName = "RESTRICT"; break;
  101060. default: zName = "NO ACTION";
  101061. assert( action==OE_None ); break;
  101062. }
  101063. return zName;
  101064. }
  101065. #endif
  101066. /*
  101067. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  101068. ** defined in pager.h. This function returns the associated lowercase
  101069. ** journal-mode name.
  101070. */
  101071. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  101072. static char * const azModeName[] = {
  101073. "delete", "persist", "off", "truncate", "memory"
  101074. #ifndef SQLITE_OMIT_WAL
  101075. , "wal"
  101076. #endif
  101077. };
  101078. assert( PAGER_JOURNALMODE_DELETE==0 );
  101079. assert( PAGER_JOURNALMODE_PERSIST==1 );
  101080. assert( PAGER_JOURNALMODE_OFF==2 );
  101081. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  101082. assert( PAGER_JOURNALMODE_MEMORY==4 );
  101083. assert( PAGER_JOURNALMODE_WAL==5 );
  101084. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  101085. if( eMode==ArraySize(azModeName) ) return 0;
  101086. return azModeName[eMode];
  101087. }
  101088. /*
  101089. ** Process a pragma statement.
  101090. **
  101091. ** Pragmas are of this form:
  101092. **
  101093. ** PRAGMA [schema.]id [= value]
  101094. **
  101095. ** The identifier might also be a string. The value is a string, and
  101096. ** identifier, or a number. If minusFlag is true, then the value is
  101097. ** a number that was preceded by a minus sign.
  101098. **
  101099. ** If the left side is "database.id" then pId1 is the database name
  101100. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  101101. ** id and pId2 is any empty string.
  101102. */
  101103. SQLITE_PRIVATE void sqlite3Pragma(
  101104. Parse *pParse,
  101105. Token *pId1, /* First part of [schema.]id field */
  101106. Token *pId2, /* Second part of [schema.]id field, or NULL */
  101107. Token *pValue, /* Token for <value>, or NULL */
  101108. int minusFlag /* True if a '-' sign preceded <value> */
  101109. ){
  101110. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  101111. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  101112. const char *zDb = 0; /* The database name */
  101113. Token *pId; /* Pointer to <id> token */
  101114. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  101115. int iDb; /* Database index for <database> */
  101116. int lwr, upr, mid = 0; /* Binary search bounds */
  101117. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  101118. sqlite3 *db = pParse->db; /* The database connection */
  101119. Db *pDb; /* The specific database being pragmaed */
  101120. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  101121. const struct sPragmaNames *pPragma;
  101122. if( v==0 ) return;
  101123. sqlite3VdbeRunOnlyOnce(v);
  101124. pParse->nMem = 2;
  101125. /* Interpret the [schema.] part of the pragma statement. iDb is the
  101126. ** index of the database this pragma is being applied to in db.aDb[]. */
  101127. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  101128. if( iDb<0 ) return;
  101129. pDb = &db->aDb[iDb];
  101130. /* If the temp database has been explicitly named as part of the
  101131. ** pragma, make sure it is open.
  101132. */
  101133. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  101134. return;
  101135. }
  101136. zLeft = sqlite3NameFromToken(db, pId);
  101137. if( !zLeft ) return;
  101138. if( minusFlag ){
  101139. zRight = sqlite3MPrintf(db, "-%T", pValue);
  101140. }else{
  101141. zRight = sqlite3NameFromToken(db, pValue);
  101142. }
  101143. assert( pId2 );
  101144. zDb = pId2->n>0 ? pDb->zName : 0;
  101145. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  101146. goto pragma_out;
  101147. }
  101148. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  101149. ** connection. If it returns SQLITE_OK, then assume that the VFS
  101150. ** handled the pragma and generate a no-op prepared statement.
  101151. **
  101152. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  101153. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  101154. ** object corresponding to the database file to which the pragma
  101155. ** statement refers.
  101156. **
  101157. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  101158. ** file control is an array of pointers to strings (char**) in which the
  101159. ** second element of the array is the name of the pragma and the third
  101160. ** element is the argument to the pragma or NULL if the pragma has no
  101161. ** argument.
  101162. */
  101163. aFcntl[0] = 0;
  101164. aFcntl[1] = zLeft;
  101165. aFcntl[2] = zRight;
  101166. aFcntl[3] = 0;
  101167. db->busyHandler.nBusy = 0;
  101168. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  101169. if( rc==SQLITE_OK ){
  101170. returnSingleText(v, "result", aFcntl[0]);
  101171. sqlite3_free(aFcntl[0]);
  101172. goto pragma_out;
  101173. }
  101174. if( rc!=SQLITE_NOTFOUND ){
  101175. if( aFcntl[0] ){
  101176. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  101177. sqlite3_free(aFcntl[0]);
  101178. }
  101179. pParse->nErr++;
  101180. pParse->rc = rc;
  101181. goto pragma_out;
  101182. }
  101183. /* Locate the pragma in the lookup table */
  101184. lwr = 0;
  101185. upr = ArraySize(aPragmaNames)-1;
  101186. while( lwr<=upr ){
  101187. mid = (lwr+upr)/2;
  101188. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  101189. if( rc==0 ) break;
  101190. if( rc<0 ){
  101191. upr = mid - 1;
  101192. }else{
  101193. lwr = mid + 1;
  101194. }
  101195. }
  101196. if( lwr>upr ) goto pragma_out;
  101197. pPragma = &aPragmaNames[mid];
  101198. /* Make sure the database schema is loaded if the pragma requires that */
  101199. if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
  101200. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  101201. }
  101202. /* Jump to the appropriate pragma handler */
  101203. switch( pPragma->ePragTyp ){
  101204. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  101205. /*
  101206. ** PRAGMA [schema.]default_cache_size
  101207. ** PRAGMA [schema.]default_cache_size=N
  101208. **
  101209. ** The first form reports the current persistent setting for the
  101210. ** page cache size. The value returned is the maximum number of
  101211. ** pages in the page cache. The second form sets both the current
  101212. ** page cache size value and the persistent page cache size value
  101213. ** stored in the database file.
  101214. **
  101215. ** Older versions of SQLite would set the default cache size to a
  101216. ** negative number to indicate synchronous=OFF. These days, synchronous
  101217. ** is always on by default regardless of the sign of the default cache
  101218. ** size. But continue to take the absolute value of the default cache
  101219. ** size of historical compatibility.
  101220. */
  101221. case PragTyp_DEFAULT_CACHE_SIZE: {
  101222. static const int iLn = VDBE_OFFSET_LINENO(2);
  101223. static const VdbeOpList getCacheSize[] = {
  101224. { OP_Transaction, 0, 0, 0}, /* 0 */
  101225. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  101226. { OP_IfPos, 1, 8, 0},
  101227. { OP_Integer, 0, 2, 0},
  101228. { OP_Subtract, 1, 2, 1},
  101229. { OP_IfPos, 1, 8, 0},
  101230. { OP_Integer, 0, 1, 0}, /* 6 */
  101231. { OP_Noop, 0, 0, 0},
  101232. { OP_ResultRow, 1, 1, 0},
  101233. };
  101234. VdbeOp *aOp;
  101235. sqlite3VdbeUsesBtree(v, iDb);
  101236. if( !zRight ){
  101237. setOneColumnName(v, "cache_size");
  101238. pParse->nMem += 2;
  101239. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  101240. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  101241. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  101242. aOp[0].p1 = iDb;
  101243. aOp[1].p1 = iDb;
  101244. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  101245. }else{
  101246. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  101247. sqlite3BeginWriteOperation(pParse, 0, iDb);
  101248. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  101249. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101250. pDb->pSchema->cache_size = size;
  101251. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  101252. }
  101253. break;
  101254. }
  101255. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  101256. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  101257. /*
  101258. ** PRAGMA [schema.]page_size
  101259. ** PRAGMA [schema.]page_size=N
  101260. **
  101261. ** The first form reports the current setting for the
  101262. ** database page size in bytes. The second form sets the
  101263. ** database page size value. The value can only be set if
  101264. ** the database has not yet been created.
  101265. */
  101266. case PragTyp_PAGE_SIZE: {
  101267. Btree *pBt = pDb->pBt;
  101268. assert( pBt!=0 );
  101269. if( !zRight ){
  101270. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  101271. returnSingleInt(v, "page_size", size);
  101272. }else{
  101273. /* Malloc may fail when setting the page-size, as there is an internal
  101274. ** buffer that the pager module resizes using sqlite3_realloc().
  101275. */
  101276. db->nextPagesize = sqlite3Atoi(zRight);
  101277. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  101278. sqlite3OomFault(db);
  101279. }
  101280. }
  101281. break;
  101282. }
  101283. /*
  101284. ** PRAGMA [schema.]secure_delete
  101285. ** PRAGMA [schema.]secure_delete=ON/OFF
  101286. **
  101287. ** The first form reports the current setting for the
  101288. ** secure_delete flag. The second form changes the secure_delete
  101289. ** flag setting and reports thenew value.
  101290. */
  101291. case PragTyp_SECURE_DELETE: {
  101292. Btree *pBt = pDb->pBt;
  101293. int b = -1;
  101294. assert( pBt!=0 );
  101295. if( zRight ){
  101296. b = sqlite3GetBoolean(zRight, 0);
  101297. }
  101298. if( pId2->n==0 && b>=0 ){
  101299. int ii;
  101300. for(ii=0; ii<db->nDb; ii++){
  101301. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  101302. }
  101303. }
  101304. b = sqlite3BtreeSecureDelete(pBt, b);
  101305. returnSingleInt(v, "secure_delete", b);
  101306. break;
  101307. }
  101308. /*
  101309. ** PRAGMA [schema.]max_page_count
  101310. ** PRAGMA [schema.]max_page_count=N
  101311. **
  101312. ** The first form reports the current setting for the
  101313. ** maximum number of pages in the database file. The
  101314. ** second form attempts to change this setting. Both
  101315. ** forms return the current setting.
  101316. **
  101317. ** The absolute value of N is used. This is undocumented and might
  101318. ** change. The only purpose is to provide an easy way to test
  101319. ** the sqlite3AbsInt32() function.
  101320. **
  101321. ** PRAGMA [schema.]page_count
  101322. **
  101323. ** Return the number of pages in the specified database.
  101324. */
  101325. case PragTyp_PAGE_COUNT: {
  101326. int iReg;
  101327. sqlite3CodeVerifySchema(pParse, iDb);
  101328. iReg = ++pParse->nMem;
  101329. if( sqlite3Tolower(zLeft[0])=='p' ){
  101330. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  101331. }else{
  101332. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  101333. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  101334. }
  101335. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  101336. sqlite3VdbeSetNumCols(v, 1);
  101337. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  101338. break;
  101339. }
  101340. /*
  101341. ** PRAGMA [schema.]locking_mode
  101342. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  101343. */
  101344. case PragTyp_LOCKING_MODE: {
  101345. const char *zRet = "normal";
  101346. int eMode = getLockingMode(zRight);
  101347. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  101348. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  101349. ** the current default locking mode (which may be different to
  101350. ** the locking-mode of the main database).
  101351. */
  101352. eMode = db->dfltLockMode;
  101353. }else{
  101354. Pager *pPager;
  101355. if( pId2->n==0 ){
  101356. /* This indicates that no database name was specified as part
  101357. ** of the PRAGMA command. In this case the locking-mode must be
  101358. ** set on all attached databases, as well as the main db file.
  101359. **
  101360. ** Also, the sqlite3.dfltLockMode variable is set so that
  101361. ** any subsequently attached databases also use the specified
  101362. ** locking mode.
  101363. */
  101364. int ii;
  101365. assert(pDb==&db->aDb[0]);
  101366. for(ii=2; ii<db->nDb; ii++){
  101367. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  101368. sqlite3PagerLockingMode(pPager, eMode);
  101369. }
  101370. db->dfltLockMode = (u8)eMode;
  101371. }
  101372. pPager = sqlite3BtreePager(pDb->pBt);
  101373. eMode = sqlite3PagerLockingMode(pPager, eMode);
  101374. }
  101375. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  101376. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  101377. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  101378. zRet = "exclusive";
  101379. }
  101380. returnSingleText(v, "locking_mode", zRet);
  101381. break;
  101382. }
  101383. /*
  101384. ** PRAGMA [schema.]journal_mode
  101385. ** PRAGMA [schema.]journal_mode =
  101386. ** (delete|persist|off|truncate|memory|wal|off)
  101387. */
  101388. case PragTyp_JOURNAL_MODE: {
  101389. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  101390. int ii; /* Loop counter */
  101391. setOneColumnName(v, "journal_mode");
  101392. if( zRight==0 ){
  101393. /* If there is no "=MODE" part of the pragma, do a query for the
  101394. ** current mode */
  101395. eMode = PAGER_JOURNALMODE_QUERY;
  101396. }else{
  101397. const char *zMode;
  101398. int n = sqlite3Strlen30(zRight);
  101399. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  101400. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  101401. }
  101402. if( !zMode ){
  101403. /* If the "=MODE" part does not match any known journal mode,
  101404. ** then do a query */
  101405. eMode = PAGER_JOURNALMODE_QUERY;
  101406. }
  101407. }
  101408. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  101409. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  101410. iDb = 0;
  101411. pId2->n = 1;
  101412. }
  101413. for(ii=db->nDb-1; ii>=0; ii--){
  101414. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  101415. sqlite3VdbeUsesBtree(v, ii);
  101416. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  101417. }
  101418. }
  101419. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  101420. break;
  101421. }
  101422. /*
  101423. ** PRAGMA [schema.]journal_size_limit
  101424. ** PRAGMA [schema.]journal_size_limit=N
  101425. **
  101426. ** Get or set the size limit on rollback journal files.
  101427. */
  101428. case PragTyp_JOURNAL_SIZE_LIMIT: {
  101429. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  101430. i64 iLimit = -2;
  101431. if( zRight ){
  101432. sqlite3DecOrHexToI64(zRight, &iLimit);
  101433. if( iLimit<-1 ) iLimit = -1;
  101434. }
  101435. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  101436. returnSingleInt(v, "journal_size_limit", iLimit);
  101437. break;
  101438. }
  101439. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  101440. /*
  101441. ** PRAGMA [schema.]auto_vacuum
  101442. ** PRAGMA [schema.]auto_vacuum=N
  101443. **
  101444. ** Get or set the value of the database 'auto-vacuum' parameter.
  101445. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  101446. */
  101447. #ifndef SQLITE_OMIT_AUTOVACUUM
  101448. case PragTyp_AUTO_VACUUM: {
  101449. Btree *pBt = pDb->pBt;
  101450. assert( pBt!=0 );
  101451. if( !zRight ){
  101452. returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  101453. }else{
  101454. int eAuto = getAutoVacuum(zRight);
  101455. assert( eAuto>=0 && eAuto<=2 );
  101456. db->nextAutovac = (u8)eAuto;
  101457. /* Call SetAutoVacuum() to set initialize the internal auto and
  101458. ** incr-vacuum flags. This is required in case this connection
  101459. ** creates the database file. It is important that it is created
  101460. ** as an auto-vacuum capable db.
  101461. */
  101462. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  101463. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  101464. /* When setting the auto_vacuum mode to either "full" or
  101465. ** "incremental", write the value of meta[6] in the database
  101466. ** file. Before writing to meta[6], check that meta[3] indicates
  101467. ** that this really is an auto-vacuum capable database.
  101468. */
  101469. static const int iLn = VDBE_OFFSET_LINENO(2);
  101470. static const VdbeOpList setMeta6[] = {
  101471. { OP_Transaction, 0, 1, 0}, /* 0 */
  101472. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  101473. { OP_If, 1, 0, 0}, /* 2 */
  101474. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  101475. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  101476. };
  101477. VdbeOp *aOp;
  101478. int iAddr = sqlite3VdbeCurrentAddr(v);
  101479. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  101480. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  101481. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  101482. aOp[0].p1 = iDb;
  101483. aOp[1].p1 = iDb;
  101484. aOp[2].p2 = iAddr+4;
  101485. aOp[4].p1 = iDb;
  101486. aOp[4].p3 = eAuto - 1;
  101487. sqlite3VdbeUsesBtree(v, iDb);
  101488. }
  101489. }
  101490. break;
  101491. }
  101492. #endif
  101493. /*
  101494. ** PRAGMA [schema.]incremental_vacuum(N)
  101495. **
  101496. ** Do N steps of incremental vacuuming on a database.
  101497. */
  101498. #ifndef SQLITE_OMIT_AUTOVACUUM
  101499. case PragTyp_INCREMENTAL_VACUUM: {
  101500. int iLimit, addr;
  101501. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  101502. iLimit = 0x7fffffff;
  101503. }
  101504. sqlite3BeginWriteOperation(pParse, 0, iDb);
  101505. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  101506. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  101507. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  101508. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  101509. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  101510. sqlite3VdbeJumpHere(v, addr);
  101511. break;
  101512. }
  101513. #endif
  101514. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  101515. /*
  101516. ** PRAGMA [schema.]cache_size
  101517. ** PRAGMA [schema.]cache_size=N
  101518. **
  101519. ** The first form reports the current local setting for the
  101520. ** page cache size. The second form sets the local
  101521. ** page cache size value. If N is positive then that is the
  101522. ** number of pages in the cache. If N is negative, then the
  101523. ** number of pages is adjusted so that the cache uses -N kibibytes
  101524. ** of memory.
  101525. */
  101526. case PragTyp_CACHE_SIZE: {
  101527. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101528. if( !zRight ){
  101529. returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
  101530. }else{
  101531. int size = sqlite3Atoi(zRight);
  101532. pDb->pSchema->cache_size = size;
  101533. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  101534. }
  101535. break;
  101536. }
  101537. /*
  101538. ** PRAGMA [schema.]cache_spill
  101539. ** PRAGMA cache_spill=BOOLEAN
  101540. ** PRAGMA [schema.]cache_spill=N
  101541. **
  101542. ** The first form reports the current local setting for the
  101543. ** page cache spill size. The second form turns cache spill on
  101544. ** or off. When turnning cache spill on, the size is set to the
  101545. ** current cache_size. The third form sets a spill size that
  101546. ** may be different form the cache size.
  101547. ** If N is positive then that is the
  101548. ** number of pages in the cache. If N is negative, then the
  101549. ** number of pages is adjusted so that the cache uses -N kibibytes
  101550. ** of memory.
  101551. **
  101552. ** If the number of cache_spill pages is less then the number of
  101553. ** cache_size pages, no spilling occurs until the page count exceeds
  101554. ** the number of cache_size pages.
  101555. **
  101556. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  101557. ** not just the schema specified.
  101558. */
  101559. case PragTyp_CACHE_SPILL: {
  101560. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101561. if( !zRight ){
  101562. returnSingleInt(v, "cache_spill",
  101563. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  101564. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  101565. }else{
  101566. int size = 1;
  101567. if( sqlite3GetInt32(zRight, &size) ){
  101568. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  101569. }
  101570. if( sqlite3GetBoolean(zRight, size!=0) ){
  101571. db->flags |= SQLITE_CacheSpill;
  101572. }else{
  101573. db->flags &= ~SQLITE_CacheSpill;
  101574. }
  101575. setAllPagerFlags(db);
  101576. }
  101577. break;
  101578. }
  101579. /*
  101580. ** PRAGMA [schema.]mmap_size(N)
  101581. **
  101582. ** Used to set mapping size limit. The mapping size limit is
  101583. ** used to limit the aggregate size of all memory mapped regions of the
  101584. ** database file. If this parameter is set to zero, then memory mapping
  101585. ** is not used at all. If N is negative, then the default memory map
  101586. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  101587. ** The parameter N is measured in bytes.
  101588. **
  101589. ** This value is advisory. The underlying VFS is free to memory map
  101590. ** as little or as much as it wants. Except, if N is set to 0 then the
  101591. ** upper layers will never invoke the xFetch interfaces to the VFS.
  101592. */
  101593. case PragTyp_MMAP_SIZE: {
  101594. sqlite3_int64 sz;
  101595. #if SQLITE_MAX_MMAP_SIZE>0
  101596. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101597. if( zRight ){
  101598. int ii;
  101599. sqlite3DecOrHexToI64(zRight, &sz);
  101600. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  101601. if( pId2->n==0 ) db->szMmap = sz;
  101602. for(ii=db->nDb-1; ii>=0; ii--){
  101603. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  101604. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  101605. }
  101606. }
  101607. }
  101608. sz = -1;
  101609. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  101610. #else
  101611. sz = 0;
  101612. rc = SQLITE_OK;
  101613. #endif
  101614. if( rc==SQLITE_OK ){
  101615. returnSingleInt(v, "mmap_size", sz);
  101616. }else if( rc!=SQLITE_NOTFOUND ){
  101617. pParse->nErr++;
  101618. pParse->rc = rc;
  101619. }
  101620. break;
  101621. }
  101622. /*
  101623. ** PRAGMA temp_store
  101624. ** PRAGMA temp_store = "default"|"memory"|"file"
  101625. **
  101626. ** Return or set the local value of the temp_store flag. Changing
  101627. ** the local value does not make changes to the disk file and the default
  101628. ** value will be restored the next time the database is opened.
  101629. **
  101630. ** Note that it is possible for the library compile-time options to
  101631. ** override this setting
  101632. */
  101633. case PragTyp_TEMP_STORE: {
  101634. if( !zRight ){
  101635. returnSingleInt(v, "temp_store", db->temp_store);
  101636. }else{
  101637. changeTempStorage(pParse, zRight);
  101638. }
  101639. break;
  101640. }
  101641. /*
  101642. ** PRAGMA temp_store_directory
  101643. ** PRAGMA temp_store_directory = ""|"directory_name"
  101644. **
  101645. ** Return or set the local value of the temp_store_directory flag. Changing
  101646. ** the value sets a specific directory to be used for temporary files.
  101647. ** Setting to a null string reverts to the default temporary directory search.
  101648. ** If temporary directory is changed, then invalidateTempStorage.
  101649. **
  101650. */
  101651. case PragTyp_TEMP_STORE_DIRECTORY: {
  101652. if( !zRight ){
  101653. returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
  101654. }else{
  101655. #ifndef SQLITE_OMIT_WSD
  101656. if( zRight[0] ){
  101657. int res;
  101658. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  101659. if( rc!=SQLITE_OK || res==0 ){
  101660. sqlite3ErrorMsg(pParse, "not a writable directory");
  101661. goto pragma_out;
  101662. }
  101663. }
  101664. if( SQLITE_TEMP_STORE==0
  101665. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  101666. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  101667. ){
  101668. invalidateTempStorage(pParse);
  101669. }
  101670. sqlite3_free(sqlite3_temp_directory);
  101671. if( zRight[0] ){
  101672. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  101673. }else{
  101674. sqlite3_temp_directory = 0;
  101675. }
  101676. #endif /* SQLITE_OMIT_WSD */
  101677. }
  101678. break;
  101679. }
  101680. #if SQLITE_OS_WIN
  101681. /*
  101682. ** PRAGMA data_store_directory
  101683. ** PRAGMA data_store_directory = ""|"directory_name"
  101684. **
  101685. ** Return or set the local value of the data_store_directory flag. Changing
  101686. ** the value sets a specific directory to be used for database files that
  101687. ** were specified with a relative pathname. Setting to a null string reverts
  101688. ** to the default database directory, which for database files specified with
  101689. ** a relative path will probably be based on the current directory for the
  101690. ** process. Database file specified with an absolute path are not impacted
  101691. ** by this setting, regardless of its value.
  101692. **
  101693. */
  101694. case PragTyp_DATA_STORE_DIRECTORY: {
  101695. if( !zRight ){
  101696. returnSingleText(v, "data_store_directory", sqlite3_data_directory);
  101697. }else{
  101698. #ifndef SQLITE_OMIT_WSD
  101699. if( zRight[0] ){
  101700. int res;
  101701. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  101702. if( rc!=SQLITE_OK || res==0 ){
  101703. sqlite3ErrorMsg(pParse, "not a writable directory");
  101704. goto pragma_out;
  101705. }
  101706. }
  101707. sqlite3_free(sqlite3_data_directory);
  101708. if( zRight[0] ){
  101709. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  101710. }else{
  101711. sqlite3_data_directory = 0;
  101712. }
  101713. #endif /* SQLITE_OMIT_WSD */
  101714. }
  101715. break;
  101716. }
  101717. #endif
  101718. #if SQLITE_ENABLE_LOCKING_STYLE
  101719. /*
  101720. ** PRAGMA [schema.]lock_proxy_file
  101721. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  101722. **
  101723. ** Return or set the value of the lock_proxy_file flag. Changing
  101724. ** the value sets a specific file to be used for database access locks.
  101725. **
  101726. */
  101727. case PragTyp_LOCK_PROXY_FILE: {
  101728. if( !zRight ){
  101729. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  101730. char *proxy_file_path = NULL;
  101731. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  101732. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  101733. &proxy_file_path);
  101734. returnSingleText(v, "lock_proxy_file", proxy_file_path);
  101735. }else{
  101736. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  101737. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  101738. int res;
  101739. if( zRight[0] ){
  101740. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  101741. zRight);
  101742. } else {
  101743. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  101744. NULL);
  101745. }
  101746. if( res!=SQLITE_OK ){
  101747. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  101748. goto pragma_out;
  101749. }
  101750. }
  101751. break;
  101752. }
  101753. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  101754. /*
  101755. ** PRAGMA [schema.]synchronous
  101756. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  101757. **
  101758. ** Return or set the local value of the synchronous flag. Changing
  101759. ** the local value does not make changes to the disk file and the
  101760. ** default value will be restored the next time the database is
  101761. ** opened.
  101762. */
  101763. case PragTyp_SYNCHRONOUS: {
  101764. if( !zRight ){
  101765. returnSingleInt(v, "synchronous", pDb->safety_level-1);
  101766. }else{
  101767. if( !db->autoCommit ){
  101768. sqlite3ErrorMsg(pParse,
  101769. "Safety level may not be changed inside a transaction");
  101770. }else{
  101771. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  101772. if( iLevel==0 ) iLevel = 1;
  101773. pDb->safety_level = iLevel;
  101774. pDb->bSyncSet = 1;
  101775. setAllPagerFlags(db);
  101776. }
  101777. }
  101778. break;
  101779. }
  101780. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  101781. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  101782. case PragTyp_FLAG: {
  101783. if( zRight==0 ){
  101784. returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
  101785. }else{
  101786. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  101787. if( db->autoCommit==0 ){
  101788. /* Foreign key support may not be enabled or disabled while not
  101789. ** in auto-commit mode. */
  101790. mask &= ~(SQLITE_ForeignKeys);
  101791. }
  101792. #if SQLITE_USER_AUTHENTICATION
  101793. if( db->auth.authLevel==UAUTH_User ){
  101794. /* Do not allow non-admin users to modify the schema arbitrarily */
  101795. mask &= ~(SQLITE_WriteSchema);
  101796. }
  101797. #endif
  101798. if( sqlite3GetBoolean(zRight, 0) ){
  101799. db->flags |= mask;
  101800. }else{
  101801. db->flags &= ~mask;
  101802. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  101803. }
  101804. /* Many of the flag-pragmas modify the code generated by the SQL
  101805. ** compiler (eg. count_changes). So add an opcode to expire all
  101806. ** compiled SQL statements after modifying a pragma value.
  101807. */
  101808. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  101809. setAllPagerFlags(db);
  101810. }
  101811. break;
  101812. }
  101813. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  101814. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  101815. /*
  101816. ** PRAGMA table_info(<table>)
  101817. **
  101818. ** Return a single row for each column of the named table. The columns of
  101819. ** the returned data set are:
  101820. **
  101821. ** cid: Column id (numbered from left to right, starting at 0)
  101822. ** name: Column name
  101823. ** type: Column declaration type.
  101824. ** notnull: True if 'NOT NULL' is part of column declaration
  101825. ** dflt_value: The default value for the column, if any.
  101826. */
  101827. case PragTyp_TABLE_INFO: if( zRight ){
  101828. Table *pTab;
  101829. pTab = sqlite3FindTable(db, zRight, zDb);
  101830. if( pTab ){
  101831. static const char *azCol[] = {
  101832. "cid", "name", "type", "notnull", "dflt_value", "pk"
  101833. };
  101834. int i, k;
  101835. int nHidden = 0;
  101836. Column *pCol;
  101837. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  101838. pParse->nMem = 6;
  101839. sqlite3CodeVerifySchema(pParse, iDb);
  101840. setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
  101841. sqlite3ViewGetColumnNames(pParse, pTab);
  101842. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  101843. if( IsHiddenColumn(pCol) ){
  101844. nHidden++;
  101845. continue;
  101846. }
  101847. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  101848. k = 0;
  101849. }else if( pPk==0 ){
  101850. k = 1;
  101851. }else{
  101852. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  101853. }
  101854. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  101855. sqlite3VdbeMultiLoad(v, 1, "issisi",
  101856. i-nHidden,
  101857. pCol->zName,
  101858. sqlite3ColumnType(pCol,""),
  101859. pCol->notNull ? 1 : 0,
  101860. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  101861. k);
  101862. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  101863. }
  101864. }
  101865. }
  101866. break;
  101867. case PragTyp_STATS: {
  101868. static const char *azCol[] = { "table", "index", "width", "height" };
  101869. Index *pIdx;
  101870. HashElem *i;
  101871. v = sqlite3GetVdbe(pParse);
  101872. pParse->nMem = 4;
  101873. sqlite3CodeVerifySchema(pParse, iDb);
  101874. setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
  101875. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  101876. Table *pTab = sqliteHashData(i);
  101877. sqlite3VdbeMultiLoad(v, 1, "ssii",
  101878. pTab->zName,
  101879. 0,
  101880. pTab->szTabRow,
  101881. pTab->nRowLogEst);
  101882. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  101883. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101884. sqlite3VdbeMultiLoad(v, 2, "sii",
  101885. pIdx->zName,
  101886. pIdx->szIdxRow,
  101887. pIdx->aiRowLogEst[0]);
  101888. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  101889. }
  101890. }
  101891. }
  101892. break;
  101893. case PragTyp_INDEX_INFO: if( zRight ){
  101894. Index *pIdx;
  101895. Table *pTab;
  101896. pIdx = sqlite3FindIndex(db, zRight, zDb);
  101897. if( pIdx ){
  101898. static const char *azCol[] = {
  101899. "seqno", "cid", "name", "desc", "coll", "key"
  101900. };
  101901. int i;
  101902. int mx;
  101903. if( pPragma->iArg ){
  101904. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  101905. mx = pIdx->nColumn;
  101906. pParse->nMem = 6;
  101907. }else{
  101908. /* PRAGMA index_info (legacy version) */
  101909. mx = pIdx->nKeyCol;
  101910. pParse->nMem = 3;
  101911. }
  101912. pTab = pIdx->pTable;
  101913. sqlite3CodeVerifySchema(pParse, iDb);
  101914. assert( pParse->nMem<=ArraySize(azCol) );
  101915. setAllColumnNames(v, pParse->nMem, azCol);
  101916. for(i=0; i<mx; i++){
  101917. i16 cnum = pIdx->aiColumn[i];
  101918. sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
  101919. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  101920. if( pPragma->iArg ){
  101921. sqlite3VdbeMultiLoad(v, 4, "isi",
  101922. pIdx->aSortOrder[i],
  101923. pIdx->azColl[i],
  101924. i<pIdx->nKeyCol);
  101925. }
  101926. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  101927. }
  101928. }
  101929. }
  101930. break;
  101931. case PragTyp_INDEX_LIST: if( zRight ){
  101932. Index *pIdx;
  101933. Table *pTab;
  101934. int i;
  101935. pTab = sqlite3FindTable(db, zRight, zDb);
  101936. if( pTab ){
  101937. static const char *azCol[] = {
  101938. "seq", "name", "unique", "origin", "partial"
  101939. };
  101940. v = sqlite3GetVdbe(pParse);
  101941. pParse->nMem = 5;
  101942. sqlite3CodeVerifySchema(pParse, iDb);
  101943. setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) );
  101944. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  101945. const char *azOrigin[] = { "c", "u", "pk" };
  101946. sqlite3VdbeMultiLoad(v, 1, "isisi",
  101947. i,
  101948. pIdx->zName,
  101949. IsUniqueIndex(pIdx),
  101950. azOrigin[pIdx->idxType],
  101951. pIdx->pPartIdxWhere!=0);
  101952. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  101953. }
  101954. }
  101955. }
  101956. break;
  101957. case PragTyp_DATABASE_LIST: {
  101958. static const char *azCol[] = { "seq", "name", "file" };
  101959. int i;
  101960. pParse->nMem = 3;
  101961. setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  101962. for(i=0; i<db->nDb; i++){
  101963. if( db->aDb[i].pBt==0 ) continue;
  101964. assert( db->aDb[i].zName!=0 );
  101965. sqlite3VdbeMultiLoad(v, 1, "iss",
  101966. i,
  101967. db->aDb[i].zName,
  101968. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  101969. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  101970. }
  101971. }
  101972. break;
  101973. case PragTyp_COLLATION_LIST: {
  101974. static const char *azCol[] = { "seq", "name" };
  101975. int i = 0;
  101976. HashElem *p;
  101977. pParse->nMem = 2;
  101978. setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  101979. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  101980. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  101981. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  101982. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  101983. }
  101984. }
  101985. break;
  101986. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  101987. #ifndef SQLITE_OMIT_FOREIGN_KEY
  101988. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  101989. FKey *pFK;
  101990. Table *pTab;
  101991. pTab = sqlite3FindTable(db, zRight, zDb);
  101992. if( pTab ){
  101993. v = sqlite3GetVdbe(pParse);
  101994. pFK = pTab->pFKey;
  101995. if( pFK ){
  101996. static const char *azCol[] = {
  101997. "id", "seq", "table", "from", "to", "on_update", "on_delete",
  101998. "match"
  101999. };
  102000. int i = 0;
  102001. pParse->nMem = 8;
  102002. sqlite3CodeVerifySchema(pParse, iDb);
  102003. setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
  102004. while(pFK){
  102005. int j;
  102006. for(j=0; j<pFK->nCol; j++){
  102007. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  102008. i,
  102009. j,
  102010. pFK->zTo,
  102011. pTab->aCol[pFK->aCol[j].iFrom].zName,
  102012. pFK->aCol[j].zCol,
  102013. actionName(pFK->aAction[1]), /* ON UPDATE */
  102014. actionName(pFK->aAction[0]), /* ON DELETE */
  102015. "NONE");
  102016. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  102017. }
  102018. ++i;
  102019. pFK = pFK->pNextFrom;
  102020. }
  102021. }
  102022. }
  102023. }
  102024. break;
  102025. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  102026. #ifndef SQLITE_OMIT_FOREIGN_KEY
  102027. #ifndef SQLITE_OMIT_TRIGGER
  102028. case PragTyp_FOREIGN_KEY_CHECK: {
  102029. FKey *pFK; /* A foreign key constraint */
  102030. Table *pTab; /* Child table contain "REFERENCES" keyword */
  102031. Table *pParent; /* Parent table that child points to */
  102032. Index *pIdx; /* Index in the parent table */
  102033. int i; /* Loop counter: Foreign key number for pTab */
  102034. int j; /* Loop counter: Field of the foreign key */
  102035. HashElem *k; /* Loop counter: Next table in schema */
  102036. int x; /* result variable */
  102037. int regResult; /* 3 registers to hold a result row */
  102038. int regKey; /* Register to hold key for checking the FK */
  102039. int regRow; /* Registers to hold a row from pTab */
  102040. int addrTop; /* Top of a loop checking foreign keys */
  102041. int addrOk; /* Jump here if the key is OK */
  102042. int *aiCols; /* child to parent column mapping */
  102043. static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
  102044. regResult = pParse->nMem+1;
  102045. pParse->nMem += 4;
  102046. regKey = ++pParse->nMem;
  102047. regRow = ++pParse->nMem;
  102048. v = sqlite3GetVdbe(pParse);
  102049. setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
  102050. sqlite3CodeVerifySchema(pParse, iDb);
  102051. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  102052. while( k ){
  102053. if( zRight ){
  102054. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  102055. k = 0;
  102056. }else{
  102057. pTab = (Table*)sqliteHashData(k);
  102058. k = sqliteHashNext(k);
  102059. }
  102060. if( pTab==0 || pTab->pFKey==0 ) continue;
  102061. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  102062. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  102063. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  102064. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  102065. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  102066. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  102067. if( pParent==0 ) continue;
  102068. pIdx = 0;
  102069. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  102070. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  102071. if( x==0 ){
  102072. if( pIdx==0 ){
  102073. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  102074. }else{
  102075. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  102076. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  102077. }
  102078. }else{
  102079. k = 0;
  102080. break;
  102081. }
  102082. }
  102083. assert( pParse->nErr>0 || pFK==0 );
  102084. if( pFK ) break;
  102085. if( pParse->nTab<i ) pParse->nTab = i;
  102086. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  102087. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  102088. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  102089. pIdx = 0;
  102090. aiCols = 0;
  102091. if( pParent ){
  102092. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  102093. assert( x==0 );
  102094. }
  102095. addrOk = sqlite3VdbeMakeLabel(v);
  102096. if( pParent && pIdx==0 ){
  102097. int iKey = pFK->aCol[0].iFrom;
  102098. assert( iKey>=0 && iKey<pTab->nCol );
  102099. if( iKey!=pTab->iPKey ){
  102100. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  102101. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  102102. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  102103. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  102104. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  102105. }else{
  102106. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  102107. }
  102108. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  102109. sqlite3VdbeGoto(v, addrOk);
  102110. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  102111. }else{
  102112. for(j=0; j<pFK->nCol; j++){
  102113. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  102114. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  102115. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  102116. }
  102117. if( pParent ){
  102118. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  102119. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  102120. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  102121. VdbeCoverage(v);
  102122. }
  102123. }
  102124. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  102125. sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
  102126. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  102127. sqlite3VdbeResolveLabel(v, addrOk);
  102128. sqlite3DbFree(db, aiCols);
  102129. }
  102130. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  102131. sqlite3VdbeJumpHere(v, addrTop);
  102132. }
  102133. }
  102134. break;
  102135. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  102136. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  102137. #ifndef NDEBUG
  102138. case PragTyp_PARSER_TRACE: {
  102139. if( zRight ){
  102140. if( sqlite3GetBoolean(zRight, 0) ){
  102141. sqlite3ParserTrace(stdout, "parser: ");
  102142. }else{
  102143. sqlite3ParserTrace(0, 0);
  102144. }
  102145. }
  102146. }
  102147. break;
  102148. #endif
  102149. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  102150. ** used will be case sensitive or not depending on the RHS.
  102151. */
  102152. case PragTyp_CASE_SENSITIVE_LIKE: {
  102153. if( zRight ){
  102154. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  102155. }
  102156. }
  102157. break;
  102158. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  102159. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  102160. #endif
  102161. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  102162. /* Pragma "quick_check" is reduced version of
  102163. ** integrity_check designed to detect most database corruption
  102164. ** without most of the overhead of a full integrity-check.
  102165. */
  102166. case PragTyp_INTEGRITY_CHECK: {
  102167. int i, j, addr, mxErr;
  102168. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  102169. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  102170. ** then iDb is set to the index of the database identified by <db>.
  102171. ** In this case, the integrity of database iDb only is verified by
  102172. ** the VDBE created below.
  102173. **
  102174. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  102175. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  102176. ** to -1 here, to indicate that the VDBE should verify the integrity
  102177. ** of all attached databases. */
  102178. assert( iDb>=0 );
  102179. assert( iDb==0 || pId2->z );
  102180. if( pId2->z==0 ) iDb = -1;
  102181. /* Initialize the VDBE program */
  102182. pParse->nMem = 6;
  102183. setOneColumnName(v, "integrity_check");
  102184. /* Set the maximum error count */
  102185. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  102186. if( zRight ){
  102187. sqlite3GetInt32(zRight, &mxErr);
  102188. if( mxErr<=0 ){
  102189. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  102190. }
  102191. }
  102192. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  102193. /* Do an integrity check on each database file */
  102194. for(i=0; i<db->nDb; i++){
  102195. HashElem *x;
  102196. Hash *pTbls;
  102197. int *aRoot;
  102198. int cnt = 0;
  102199. int mxIdx = 0;
  102200. int nIdx;
  102201. if( OMIT_TEMPDB && i==1 ) continue;
  102202. if( iDb>=0 && i!=iDb ) continue;
  102203. sqlite3CodeVerifySchema(pParse, i);
  102204. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  102205. VdbeCoverage(v);
  102206. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  102207. sqlite3VdbeJumpHere(v, addr);
  102208. /* Do an integrity check of the B-Tree
  102209. **
  102210. ** Begin by finding the root pages numbers
  102211. ** for all tables and indices in the database.
  102212. */
  102213. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  102214. pTbls = &db->aDb[i].pSchema->tblHash;
  102215. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  102216. Table *pTab = sqliteHashData(x);
  102217. Index *pIdx;
  102218. if( HasRowid(pTab) ) cnt++;
  102219. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  102220. if( nIdx>mxIdx ) mxIdx = nIdx;
  102221. }
  102222. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  102223. if( aRoot==0 ) break;
  102224. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  102225. Table *pTab = sqliteHashData(x);
  102226. Index *pIdx;
  102227. if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
  102228. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102229. aRoot[cnt++] = pIdx->tnum;
  102230. }
  102231. }
  102232. aRoot[cnt] = 0;
  102233. /* Make sure sufficient number of registers have been allocated */
  102234. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  102235. /* Do the b-tree integrity checks */
  102236. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  102237. sqlite3VdbeChangeP5(v, (u8)i);
  102238. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  102239. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  102240. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  102241. P4_DYNAMIC);
  102242. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  102243. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  102244. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  102245. sqlite3VdbeJumpHere(v, addr);
  102246. /* Make sure all the indices are constructed correctly.
  102247. */
  102248. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  102249. Table *pTab = sqliteHashData(x);
  102250. Index *pIdx, *pPk;
  102251. Index *pPrior = 0;
  102252. int loopTop;
  102253. int iDataCur, iIdxCur;
  102254. int r1 = -1;
  102255. if( pTab->pIndex==0 ) continue;
  102256. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  102257. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  102258. VdbeCoverage(v);
  102259. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  102260. sqlite3VdbeJumpHere(v, addr);
  102261. sqlite3ExprCacheClear(pParse);
  102262. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  102263. 1, 0, &iDataCur, &iIdxCur);
  102264. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  102265. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  102266. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  102267. }
  102268. assert( pParse->nMem>=8+j );
  102269. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  102270. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  102271. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  102272. /* Verify that all NOT NULL columns really are NOT NULL */
  102273. for(j=0; j<pTab->nCol; j++){
  102274. char *zErr;
  102275. int jmp2, jmp3;
  102276. if( j==pTab->iPKey ) continue;
  102277. if( pTab->aCol[j].notNull==0 ) continue;
  102278. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  102279. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  102280. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  102281. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  102282. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  102283. pTab->aCol[j].zName);
  102284. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  102285. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  102286. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  102287. sqlite3VdbeAddOp0(v, OP_Halt);
  102288. sqlite3VdbeJumpHere(v, jmp2);
  102289. sqlite3VdbeJumpHere(v, jmp3);
  102290. }
  102291. /* Validate index entries for the current row */
  102292. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  102293. int jmp2, jmp3, jmp4, jmp5;
  102294. int ckUniq = sqlite3VdbeMakeLabel(v);
  102295. if( pPk==pIdx ) continue;
  102296. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  102297. pPrior, r1);
  102298. pPrior = pIdx;
  102299. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  102300. /* Verify that an index entry exists for the current table row */
  102301. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  102302. pIdx->nColumn); VdbeCoverage(v);
  102303. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  102304. sqlite3VdbeLoadString(v, 3, "row ");
  102305. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  102306. sqlite3VdbeLoadString(v, 4, " missing from index ");
  102307. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  102308. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  102309. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  102310. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  102311. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  102312. sqlite3VdbeAddOp0(v, OP_Halt);
  102313. sqlite3VdbeJumpHere(v, jmp2);
  102314. /* For UNIQUE indexes, verify that only one entry exists with the
  102315. ** current key. The entry is unique if (1) any column is NULL
  102316. ** or (2) the next entry has a different key */
  102317. if( IsUniqueIndex(pIdx) ){
  102318. int uniqOk = sqlite3VdbeMakeLabel(v);
  102319. int jmp6;
  102320. int kk;
  102321. for(kk=0; kk<pIdx->nKeyCol; kk++){
  102322. int iCol = pIdx->aiColumn[kk];
  102323. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  102324. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  102325. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  102326. VdbeCoverage(v);
  102327. }
  102328. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  102329. sqlite3VdbeGoto(v, uniqOk);
  102330. sqlite3VdbeJumpHere(v, jmp6);
  102331. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  102332. pIdx->nKeyCol); VdbeCoverage(v);
  102333. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  102334. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  102335. sqlite3VdbeGoto(v, jmp5);
  102336. sqlite3VdbeResolveLabel(v, uniqOk);
  102337. }
  102338. sqlite3VdbeJumpHere(v, jmp4);
  102339. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  102340. }
  102341. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  102342. sqlite3VdbeJumpHere(v, loopTop-1);
  102343. #ifndef SQLITE_OMIT_BTREECOUNT
  102344. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  102345. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  102346. if( pPk==pIdx ) continue;
  102347. addr = sqlite3VdbeCurrentAddr(v);
  102348. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  102349. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  102350. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  102351. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  102352. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  102353. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  102354. sqlite3VdbeLoadString(v, 3, pIdx->zName);
  102355. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  102356. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  102357. }
  102358. #endif /* SQLITE_OMIT_BTREECOUNT */
  102359. }
  102360. }
  102361. {
  102362. static const int iLn = VDBE_OFFSET_LINENO(2);
  102363. static const VdbeOpList endCode[] = {
  102364. { OP_AddImm, 1, 0, 0}, /* 0 */
  102365. { OP_If, 1, 4, 0}, /* 1 */
  102366. { OP_String8, 0, 3, 0}, /* 2 */
  102367. { OP_ResultRow, 3, 1, 0}, /* 3 */
  102368. };
  102369. VdbeOp *aOp;
  102370. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  102371. if( aOp ){
  102372. aOp[0].p2 = -mxErr;
  102373. aOp[2].p4type = P4_STATIC;
  102374. aOp[2].p4.z = "ok";
  102375. }
  102376. }
  102377. }
  102378. break;
  102379. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  102380. #ifndef SQLITE_OMIT_UTF16
  102381. /*
  102382. ** PRAGMA encoding
  102383. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  102384. **
  102385. ** In its first form, this pragma returns the encoding of the main
  102386. ** database. If the database is not initialized, it is initialized now.
  102387. **
  102388. ** The second form of this pragma is a no-op if the main database file
  102389. ** has not already been initialized. In this case it sets the default
  102390. ** encoding that will be used for the main database file if a new file
  102391. ** is created. If an existing main database file is opened, then the
  102392. ** default text encoding for the existing database is used.
  102393. **
  102394. ** In all cases new databases created using the ATTACH command are
  102395. ** created to use the same default text encoding as the main database. If
  102396. ** the main database has not been initialized and/or created when ATTACH
  102397. ** is executed, this is done before the ATTACH operation.
  102398. **
  102399. ** In the second form this pragma sets the text encoding to be used in
  102400. ** new database files created using this database handle. It is only
  102401. ** useful if invoked immediately after the main database i
  102402. */
  102403. case PragTyp_ENCODING: {
  102404. static const struct EncName {
  102405. char *zName;
  102406. u8 enc;
  102407. } encnames[] = {
  102408. { "UTF8", SQLITE_UTF8 },
  102409. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  102410. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  102411. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  102412. { "UTF16le", SQLITE_UTF16LE },
  102413. { "UTF16be", SQLITE_UTF16BE },
  102414. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  102415. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  102416. { 0, 0 }
  102417. };
  102418. const struct EncName *pEnc;
  102419. if( !zRight ){ /* "PRAGMA encoding" */
  102420. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  102421. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  102422. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  102423. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  102424. returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
  102425. }else{ /* "PRAGMA encoding = XXX" */
  102426. /* Only change the value of sqlite.enc if the database handle is not
  102427. ** initialized. If the main database exists, the new sqlite.enc value
  102428. ** will be overwritten when the schema is next loaded. If it does not
  102429. ** already exists, it will be created to use the new encoding value.
  102430. */
  102431. if(
  102432. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  102433. DbHasProperty(db, 0, DB_Empty)
  102434. ){
  102435. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  102436. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  102437. SCHEMA_ENC(db) = ENC(db) =
  102438. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  102439. break;
  102440. }
  102441. }
  102442. if( !pEnc->zName ){
  102443. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  102444. }
  102445. }
  102446. }
  102447. }
  102448. break;
  102449. #endif /* SQLITE_OMIT_UTF16 */
  102450. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  102451. /*
  102452. ** PRAGMA [schema.]schema_version
  102453. ** PRAGMA [schema.]schema_version = <integer>
  102454. **
  102455. ** PRAGMA [schema.]user_version
  102456. ** PRAGMA [schema.]user_version = <integer>
  102457. **
  102458. ** PRAGMA [schema.]freelist_count
  102459. **
  102460. ** PRAGMA [schema.]data_version
  102461. **
  102462. ** PRAGMA [schema.]application_id
  102463. ** PRAGMA [schema.]application_id = <integer>
  102464. **
  102465. ** The pragma's schema_version and user_version are used to set or get
  102466. ** the value of the schema-version and user-version, respectively. Both
  102467. ** the schema-version and the user-version are 32-bit signed integers
  102468. ** stored in the database header.
  102469. **
  102470. ** The schema-cookie is usually only manipulated internally by SQLite. It
  102471. ** is incremented by SQLite whenever the database schema is modified (by
  102472. ** creating or dropping a table or index). The schema version is used by
  102473. ** SQLite each time a query is executed to ensure that the internal cache
  102474. ** of the schema used when compiling the SQL query matches the schema of
  102475. ** the database against which the compiled query is actually executed.
  102476. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  102477. ** the schema-version is potentially dangerous and may lead to program
  102478. ** crashes or database corruption. Use with caution!
  102479. **
  102480. ** The user-version is not used internally by SQLite. It may be used by
  102481. ** applications for any purpose.
  102482. */
  102483. case PragTyp_HEADER_VALUE: {
  102484. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  102485. sqlite3VdbeUsesBtree(v, iDb);
  102486. if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
  102487. /* Write the specified cookie value */
  102488. static const VdbeOpList setCookie[] = {
  102489. { OP_Transaction, 0, 1, 0}, /* 0 */
  102490. { OP_SetCookie, 0, 0, 0}, /* 1 */
  102491. };
  102492. VdbeOp *aOp;
  102493. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  102494. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  102495. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  102496. aOp[0].p1 = iDb;
  102497. aOp[1].p1 = iDb;
  102498. aOp[1].p2 = iCookie;
  102499. aOp[1].p3 = sqlite3Atoi(zRight);
  102500. }else{
  102501. /* Read the specified cookie value */
  102502. static const VdbeOpList readCookie[] = {
  102503. { OP_Transaction, 0, 0, 0}, /* 0 */
  102504. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  102505. { OP_ResultRow, 1, 1, 0}
  102506. };
  102507. VdbeOp *aOp;
  102508. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  102509. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  102510. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  102511. aOp[0].p1 = iDb;
  102512. aOp[1].p1 = iDb;
  102513. aOp[1].p3 = iCookie;
  102514. sqlite3VdbeSetNumCols(v, 1);
  102515. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  102516. sqlite3VdbeReusable(v);
  102517. }
  102518. }
  102519. break;
  102520. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  102521. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  102522. /*
  102523. ** PRAGMA compile_options
  102524. **
  102525. ** Return the names of all compile-time options used in this build,
  102526. ** one option per row.
  102527. */
  102528. case PragTyp_COMPILE_OPTIONS: {
  102529. int i = 0;
  102530. const char *zOpt;
  102531. pParse->nMem = 1;
  102532. setOneColumnName(v, "compile_option");
  102533. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  102534. sqlite3VdbeLoadString(v, 1, zOpt);
  102535. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  102536. }
  102537. sqlite3VdbeReusable(v);
  102538. }
  102539. break;
  102540. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  102541. #ifndef SQLITE_OMIT_WAL
  102542. /*
  102543. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  102544. **
  102545. ** Checkpoint the database.
  102546. */
  102547. case PragTyp_WAL_CHECKPOINT: {
  102548. static const char *azCol[] = { "busy", "log", "checkpointed" };
  102549. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  102550. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  102551. if( zRight ){
  102552. if( sqlite3StrICmp(zRight, "full")==0 ){
  102553. eMode = SQLITE_CHECKPOINT_FULL;
  102554. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  102555. eMode = SQLITE_CHECKPOINT_RESTART;
  102556. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  102557. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  102558. }
  102559. }
  102560. setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  102561. pParse->nMem = 3;
  102562. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  102563. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  102564. }
  102565. break;
  102566. /*
  102567. ** PRAGMA wal_autocheckpoint
  102568. ** PRAGMA wal_autocheckpoint = N
  102569. **
  102570. ** Configure a database connection to automatically checkpoint a database
  102571. ** after accumulating N frames in the log. Or query for the current value
  102572. ** of N.
  102573. */
  102574. case PragTyp_WAL_AUTOCHECKPOINT: {
  102575. if( zRight ){
  102576. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  102577. }
  102578. returnSingleInt(v, "wal_autocheckpoint",
  102579. db->xWalCallback==sqlite3WalDefaultHook ?
  102580. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  102581. }
  102582. break;
  102583. #endif
  102584. /*
  102585. ** PRAGMA shrink_memory
  102586. **
  102587. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  102588. ** connection on which it is invoked to free up as much memory as it
  102589. ** can, by calling sqlite3_db_release_memory().
  102590. */
  102591. case PragTyp_SHRINK_MEMORY: {
  102592. sqlite3_db_release_memory(db);
  102593. break;
  102594. }
  102595. /*
  102596. ** PRAGMA busy_timeout
  102597. ** PRAGMA busy_timeout = N
  102598. **
  102599. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  102600. ** if one is set. If no busy handler or a different busy handler is set
  102601. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  102602. ** disables the timeout.
  102603. */
  102604. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  102605. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  102606. if( zRight ){
  102607. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  102608. }
  102609. returnSingleInt(v, "timeout", db->busyTimeout);
  102610. break;
  102611. }
  102612. /*
  102613. ** PRAGMA soft_heap_limit
  102614. ** PRAGMA soft_heap_limit = N
  102615. **
  102616. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  102617. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  102618. ** specified and is a non-negative integer.
  102619. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  102620. ** returns the same integer that would be returned by the
  102621. ** sqlite3_soft_heap_limit64(-1) C-language function.
  102622. */
  102623. case PragTyp_SOFT_HEAP_LIMIT: {
  102624. sqlite3_int64 N;
  102625. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  102626. sqlite3_soft_heap_limit64(N);
  102627. }
  102628. returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  102629. break;
  102630. }
  102631. /*
  102632. ** PRAGMA threads
  102633. ** PRAGMA threads = N
  102634. **
  102635. ** Configure the maximum number of worker threads. Return the new
  102636. ** maximum, which might be less than requested.
  102637. */
  102638. case PragTyp_THREADS: {
  102639. sqlite3_int64 N;
  102640. if( zRight
  102641. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  102642. && N>=0
  102643. ){
  102644. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  102645. }
  102646. returnSingleInt(v, "threads",
  102647. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  102648. break;
  102649. }
  102650. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  102651. /*
  102652. ** Report the current state of file logs for all databases
  102653. */
  102654. case PragTyp_LOCK_STATUS: {
  102655. static const char *const azLockName[] = {
  102656. "unlocked", "shared", "reserved", "pending", "exclusive"
  102657. };
  102658. static const char *azCol[] = { "database", "status" };
  102659. int i;
  102660. setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  102661. pParse->nMem = 2;
  102662. for(i=0; i<db->nDb; i++){
  102663. Btree *pBt;
  102664. const char *zState = "unknown";
  102665. int j;
  102666. if( db->aDb[i].zName==0 ) continue;
  102667. pBt = db->aDb[i].pBt;
  102668. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  102669. zState = "closed";
  102670. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  102671. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  102672. zState = azLockName[j];
  102673. }
  102674. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
  102675. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  102676. }
  102677. break;
  102678. }
  102679. #endif
  102680. #ifdef SQLITE_HAS_CODEC
  102681. case PragTyp_KEY: {
  102682. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  102683. break;
  102684. }
  102685. case PragTyp_REKEY: {
  102686. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  102687. break;
  102688. }
  102689. case PragTyp_HEXKEY: {
  102690. if( zRight ){
  102691. u8 iByte;
  102692. int i;
  102693. char zKey[40];
  102694. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  102695. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  102696. if( (i&1)!=0 ) zKey[i/2] = iByte;
  102697. }
  102698. if( (zLeft[3] & 0xf)==0xb ){
  102699. sqlite3_key_v2(db, zDb, zKey, i/2);
  102700. }else{
  102701. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  102702. }
  102703. }
  102704. break;
  102705. }
  102706. #endif
  102707. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  102708. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  102709. #ifdef SQLITE_HAS_CODEC
  102710. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  102711. sqlite3_activate_see(&zRight[4]);
  102712. }
  102713. #endif
  102714. #ifdef SQLITE_ENABLE_CEROD
  102715. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  102716. sqlite3_activate_cerod(&zRight[6]);
  102717. }
  102718. #endif
  102719. }
  102720. break;
  102721. #endif
  102722. } /* End of the PRAGMA switch */
  102723. pragma_out:
  102724. sqlite3DbFree(db, zLeft);
  102725. sqlite3DbFree(db, zRight);
  102726. }
  102727. #endif /* SQLITE_OMIT_PRAGMA */
  102728. /************** End of pragma.c **********************************************/
  102729. /************** Begin file prepare.c *****************************************/
  102730. /*
  102731. ** 2005 May 25
  102732. **
  102733. ** The author disclaims copyright to this source code. In place of
  102734. ** a legal notice, here is a blessing:
  102735. **
  102736. ** May you do good and not evil.
  102737. ** May you find forgiveness for yourself and forgive others.
  102738. ** May you share freely, never taking more than you give.
  102739. **
  102740. *************************************************************************
  102741. ** This file contains the implementation of the sqlite3_prepare()
  102742. ** interface, and routines that contribute to loading the database schema
  102743. ** from disk.
  102744. */
  102745. /* #include "sqliteInt.h" */
  102746. /*
  102747. ** Fill the InitData structure with an error message that indicates
  102748. ** that the database is corrupt.
  102749. */
  102750. static void corruptSchema(
  102751. InitData *pData, /* Initialization context */
  102752. const char *zObj, /* Object being parsed at the point of error */
  102753. const char *zExtra /* Error information */
  102754. ){
  102755. sqlite3 *db = pData->db;
  102756. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  102757. char *z;
  102758. if( zObj==0 ) zObj = "?";
  102759. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  102760. if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  102761. sqlite3DbFree(db, *pData->pzErrMsg);
  102762. *pData->pzErrMsg = z;
  102763. }
  102764. pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
  102765. }
  102766. /*
  102767. ** This is the callback routine for the code that initializes the
  102768. ** database. See sqlite3Init() below for additional information.
  102769. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  102770. **
  102771. ** Each callback contains the following information:
  102772. **
  102773. ** argv[0] = name of thing being created
  102774. ** argv[1] = root page number for table or index. 0 for trigger or view.
  102775. ** argv[2] = SQL text for the CREATE statement.
  102776. **
  102777. */
  102778. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  102779. InitData *pData = (InitData*)pInit;
  102780. sqlite3 *db = pData->db;
  102781. int iDb = pData->iDb;
  102782. assert( argc==3 );
  102783. UNUSED_PARAMETER2(NotUsed, argc);
  102784. assert( sqlite3_mutex_held(db->mutex) );
  102785. DbClearProperty(db, iDb, DB_Empty);
  102786. if( db->mallocFailed ){
  102787. corruptSchema(pData, argv[0], 0);
  102788. return 1;
  102789. }
  102790. assert( iDb>=0 && iDb<db->nDb );
  102791. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  102792. if( argv[1]==0 ){
  102793. corruptSchema(pData, argv[0], 0);
  102794. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  102795. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  102796. ** But because db->init.busy is set to 1, no VDBE code is generated
  102797. ** or executed. All the parser does is build the internal data
  102798. ** structures that describe the table, index, or view.
  102799. */
  102800. int rc;
  102801. sqlite3_stmt *pStmt;
  102802. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  102803. assert( db->init.busy );
  102804. db->init.iDb = iDb;
  102805. db->init.newTnum = sqlite3Atoi(argv[1]);
  102806. db->init.orphanTrigger = 0;
  102807. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  102808. rc = db->errCode;
  102809. assert( (rc&0xFF)==(rcp&0xFF) );
  102810. db->init.iDb = 0;
  102811. if( SQLITE_OK!=rc ){
  102812. if( db->init.orphanTrigger ){
  102813. assert( iDb==1 );
  102814. }else{
  102815. pData->rc = rc;
  102816. if( rc==SQLITE_NOMEM ){
  102817. sqlite3OomFault(db);
  102818. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  102819. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  102820. }
  102821. }
  102822. }
  102823. sqlite3_finalize(pStmt);
  102824. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  102825. corruptSchema(pData, argv[0], 0);
  102826. }else{
  102827. /* If the SQL column is blank it means this is an index that
  102828. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  102829. ** constraint for a CREATE TABLE. The index should have already
  102830. ** been created when we processed the CREATE TABLE. All we have
  102831. ** to do here is record the root page number for that index.
  102832. */
  102833. Index *pIndex;
  102834. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  102835. if( pIndex==0 ){
  102836. /* This can occur if there exists an index on a TEMP table which
  102837. ** has the same name as another index on a permanent index. Since
  102838. ** the permanent table is hidden by the TEMP table, we can also
  102839. ** safely ignore the index on the permanent table.
  102840. */
  102841. /* Do Nothing */;
  102842. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  102843. corruptSchema(pData, argv[0], "invalid rootpage");
  102844. }
  102845. }
  102846. return 0;
  102847. }
  102848. /*
  102849. ** Attempt to read the database schema and initialize internal
  102850. ** data structures for a single database file. The index of the
  102851. ** database file is given by iDb. iDb==0 is used for the main
  102852. ** database. iDb==1 should never be used. iDb>=2 is used for
  102853. ** auxiliary databases. Return one of the SQLITE_ error codes to
  102854. ** indicate success or failure.
  102855. */
  102856. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  102857. int rc;
  102858. int i;
  102859. #ifndef SQLITE_OMIT_DEPRECATED
  102860. int size;
  102861. #endif
  102862. Db *pDb;
  102863. char const *azArg[4];
  102864. int meta[5];
  102865. InitData initData;
  102866. const char *zMasterName;
  102867. int openedTransaction = 0;
  102868. assert( iDb>=0 && iDb<db->nDb );
  102869. assert( db->aDb[iDb].pSchema );
  102870. assert( sqlite3_mutex_held(db->mutex) );
  102871. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  102872. /* Construct the in-memory representation schema tables (sqlite_master or
  102873. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  102874. ** table name will be inserted automatically by the parser so we can just
  102875. ** use the abbreviation "x" here. The parser will also automatically tag
  102876. ** the schema table as read-only. */
  102877. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  102878. azArg[1] = "1";
  102879. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  102880. "rootpage integer,sql text)";
  102881. azArg[3] = 0;
  102882. initData.db = db;
  102883. initData.iDb = iDb;
  102884. initData.rc = SQLITE_OK;
  102885. initData.pzErrMsg = pzErrMsg;
  102886. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  102887. if( initData.rc ){
  102888. rc = initData.rc;
  102889. goto error_out;
  102890. }
  102891. /* Create a cursor to hold the database open
  102892. */
  102893. pDb = &db->aDb[iDb];
  102894. if( pDb->pBt==0 ){
  102895. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  102896. DbSetProperty(db, 1, DB_SchemaLoaded);
  102897. }
  102898. return SQLITE_OK;
  102899. }
  102900. /* If there is not already a read-only (or read-write) transaction opened
  102901. ** on the b-tree database, open one now. If a transaction is opened, it
  102902. ** will be closed before this function returns. */
  102903. sqlite3BtreeEnter(pDb->pBt);
  102904. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  102905. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  102906. if( rc!=SQLITE_OK ){
  102907. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  102908. goto initone_error_out;
  102909. }
  102910. openedTransaction = 1;
  102911. }
  102912. /* Get the database meta information.
  102913. **
  102914. ** Meta values are as follows:
  102915. ** meta[0] Schema cookie. Changes with each schema change.
  102916. ** meta[1] File format of schema layer.
  102917. ** meta[2] Size of the page cache.
  102918. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  102919. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  102920. ** meta[5] User version
  102921. ** meta[6] Incremental vacuum mode
  102922. ** meta[7] unused
  102923. ** meta[8] unused
  102924. ** meta[9] unused
  102925. **
  102926. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  102927. ** the possible values of meta[4].
  102928. */
  102929. for(i=0; i<ArraySize(meta); i++){
  102930. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  102931. }
  102932. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  102933. /* If opening a non-empty database, check the text encoding. For the
  102934. ** main database, set sqlite3.enc to the encoding of the main database.
  102935. ** For an attached db, it is an error if the encoding is not the same
  102936. ** as sqlite3.enc.
  102937. */
  102938. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  102939. if( iDb==0 ){
  102940. #ifndef SQLITE_OMIT_UTF16
  102941. u8 encoding;
  102942. /* If opening the main database, set ENC(db). */
  102943. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  102944. if( encoding==0 ) encoding = SQLITE_UTF8;
  102945. ENC(db) = encoding;
  102946. #else
  102947. ENC(db) = SQLITE_UTF8;
  102948. #endif
  102949. }else{
  102950. /* If opening an attached database, the encoding much match ENC(db) */
  102951. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  102952. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  102953. " text encoding as main database");
  102954. rc = SQLITE_ERROR;
  102955. goto initone_error_out;
  102956. }
  102957. }
  102958. }else{
  102959. DbSetProperty(db, iDb, DB_Empty);
  102960. }
  102961. pDb->pSchema->enc = ENC(db);
  102962. if( pDb->pSchema->cache_size==0 ){
  102963. #ifndef SQLITE_OMIT_DEPRECATED
  102964. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  102965. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  102966. pDb->pSchema->cache_size = size;
  102967. #else
  102968. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  102969. #endif
  102970. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  102971. }
  102972. /*
  102973. ** file_format==1 Version 3.0.0.
  102974. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  102975. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  102976. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  102977. */
  102978. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  102979. if( pDb->pSchema->file_format==0 ){
  102980. pDb->pSchema->file_format = 1;
  102981. }
  102982. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  102983. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  102984. rc = SQLITE_ERROR;
  102985. goto initone_error_out;
  102986. }
  102987. /* Ticket #2804: When we open a database in the newer file format,
  102988. ** clear the legacy_file_format pragma flag so that a VACUUM will
  102989. ** not downgrade the database and thus invalidate any descending
  102990. ** indices that the user might have created.
  102991. */
  102992. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  102993. db->flags &= ~SQLITE_LegacyFileFmt;
  102994. }
  102995. /* Read the schema information out of the schema tables
  102996. */
  102997. assert( db->init.busy );
  102998. {
  102999. char *zSql;
  103000. zSql = sqlite3MPrintf(db,
  103001. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  103002. db->aDb[iDb].zName, zMasterName);
  103003. #ifndef SQLITE_OMIT_AUTHORIZATION
  103004. {
  103005. sqlite3_xauth xAuth;
  103006. xAuth = db->xAuth;
  103007. db->xAuth = 0;
  103008. #endif
  103009. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  103010. #ifndef SQLITE_OMIT_AUTHORIZATION
  103011. db->xAuth = xAuth;
  103012. }
  103013. #endif
  103014. if( rc==SQLITE_OK ) rc = initData.rc;
  103015. sqlite3DbFree(db, zSql);
  103016. #ifndef SQLITE_OMIT_ANALYZE
  103017. if( rc==SQLITE_OK ){
  103018. sqlite3AnalysisLoad(db, iDb);
  103019. }
  103020. #endif
  103021. }
  103022. if( db->mallocFailed ){
  103023. rc = SQLITE_NOMEM_BKPT;
  103024. sqlite3ResetAllSchemasOfConnection(db);
  103025. }
  103026. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  103027. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  103028. ** the schema loaded, even if errors occurred. In this situation the
  103029. ** current sqlite3_prepare() operation will fail, but the following one
  103030. ** will attempt to compile the supplied statement against whatever subset
  103031. ** of the schema was loaded before the error occurred. The primary
  103032. ** purpose of this is to allow access to the sqlite_master table
  103033. ** even when its contents have been corrupted.
  103034. */
  103035. DbSetProperty(db, iDb, DB_SchemaLoaded);
  103036. rc = SQLITE_OK;
  103037. }
  103038. /* Jump here for an error that occurs after successfully allocating
  103039. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  103040. ** before that point, jump to error_out.
  103041. */
  103042. initone_error_out:
  103043. if( openedTransaction ){
  103044. sqlite3BtreeCommit(pDb->pBt);
  103045. }
  103046. sqlite3BtreeLeave(pDb->pBt);
  103047. error_out:
  103048. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  103049. sqlite3OomFault(db);
  103050. }
  103051. return rc;
  103052. }
  103053. /*
  103054. ** Initialize all database files - the main database file, the file
  103055. ** used to store temporary tables, and any additional database files
  103056. ** created using ATTACH statements. Return a success code. If an
  103057. ** error occurs, write an error message into *pzErrMsg.
  103058. **
  103059. ** After a database is initialized, the DB_SchemaLoaded bit is set
  103060. ** bit is set in the flags field of the Db structure. If the database
  103061. ** file was of zero-length, then the DB_Empty flag is also set.
  103062. */
  103063. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  103064. int i, rc;
  103065. int commit_internal = !(db->flags&SQLITE_InternChanges);
  103066. assert( sqlite3_mutex_held(db->mutex) );
  103067. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  103068. assert( db->init.busy==0 );
  103069. rc = SQLITE_OK;
  103070. db->init.busy = 1;
  103071. ENC(db) = SCHEMA_ENC(db);
  103072. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  103073. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  103074. rc = sqlite3InitOne(db, i, pzErrMsg);
  103075. if( rc ){
  103076. sqlite3ResetOneSchema(db, i);
  103077. }
  103078. }
  103079. /* Once all the other databases have been initialized, load the schema
  103080. ** for the TEMP database. This is loaded last, as the TEMP database
  103081. ** schema may contain references to objects in other databases.
  103082. */
  103083. #ifndef SQLITE_OMIT_TEMPDB
  103084. assert( db->nDb>1 );
  103085. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  103086. rc = sqlite3InitOne(db, 1, pzErrMsg);
  103087. if( rc ){
  103088. sqlite3ResetOneSchema(db, 1);
  103089. }
  103090. }
  103091. #endif
  103092. db->init.busy = 0;
  103093. if( rc==SQLITE_OK && commit_internal ){
  103094. sqlite3CommitInternalChanges(db);
  103095. }
  103096. return rc;
  103097. }
  103098. /*
  103099. ** This routine is a no-op if the database schema is already initialized.
  103100. ** Otherwise, the schema is loaded. An error code is returned.
  103101. */
  103102. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  103103. int rc = SQLITE_OK;
  103104. sqlite3 *db = pParse->db;
  103105. assert( sqlite3_mutex_held(db->mutex) );
  103106. if( !db->init.busy ){
  103107. rc = sqlite3Init(db, &pParse->zErrMsg);
  103108. }
  103109. if( rc!=SQLITE_OK ){
  103110. pParse->rc = rc;
  103111. pParse->nErr++;
  103112. }
  103113. return rc;
  103114. }
  103115. /*
  103116. ** Check schema cookies in all databases. If any cookie is out
  103117. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  103118. ** make no changes to pParse->rc.
  103119. */
  103120. static void schemaIsValid(Parse *pParse){
  103121. sqlite3 *db = pParse->db;
  103122. int iDb;
  103123. int rc;
  103124. int cookie;
  103125. assert( pParse->checkSchema );
  103126. assert( sqlite3_mutex_held(db->mutex) );
  103127. for(iDb=0; iDb<db->nDb; iDb++){
  103128. int openedTransaction = 0; /* True if a transaction is opened */
  103129. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  103130. if( pBt==0 ) continue;
  103131. /* If there is not already a read-only (or read-write) transaction opened
  103132. ** on the b-tree database, open one now. If a transaction is opened, it
  103133. ** will be closed immediately after reading the meta-value. */
  103134. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  103135. rc = sqlite3BtreeBeginTrans(pBt, 0);
  103136. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  103137. sqlite3OomFault(db);
  103138. }
  103139. if( rc!=SQLITE_OK ) return;
  103140. openedTransaction = 1;
  103141. }
  103142. /* Read the schema cookie from the database. If it does not match the
  103143. ** value stored as part of the in-memory schema representation,
  103144. ** set Parse.rc to SQLITE_SCHEMA. */
  103145. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  103146. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103147. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  103148. sqlite3ResetOneSchema(db, iDb);
  103149. pParse->rc = SQLITE_SCHEMA;
  103150. }
  103151. /* Close the transaction, if one was opened. */
  103152. if( openedTransaction ){
  103153. sqlite3BtreeCommit(pBt);
  103154. }
  103155. }
  103156. }
  103157. /*
  103158. ** Convert a schema pointer into the iDb index that indicates
  103159. ** which database file in db->aDb[] the schema refers to.
  103160. **
  103161. ** If the same database is attached more than once, the first
  103162. ** attached database is returned.
  103163. */
  103164. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  103165. int i = -1000000;
  103166. /* If pSchema is NULL, then return -1000000. This happens when code in
  103167. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  103168. ** created by a sub-select). In this case the return value of this
  103169. ** function should never be used.
  103170. **
  103171. ** We return -1000000 instead of the more usual -1 simply because using
  103172. ** -1000000 as the incorrect index into db->aDb[] is much
  103173. ** more likely to cause a segfault than -1 (of course there are assert()
  103174. ** statements too, but it never hurts to play the odds).
  103175. */
  103176. assert( sqlite3_mutex_held(db->mutex) );
  103177. if( pSchema ){
  103178. for(i=0; ALWAYS(i<db->nDb); i++){
  103179. if( db->aDb[i].pSchema==pSchema ){
  103180. break;
  103181. }
  103182. }
  103183. assert( i>=0 && i<db->nDb );
  103184. }
  103185. return i;
  103186. }
  103187. /*
  103188. ** Free all memory allocations in the pParse object
  103189. */
  103190. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  103191. if( pParse ){
  103192. sqlite3 *db = pParse->db;
  103193. sqlite3DbFree(db, pParse->aLabel);
  103194. sqlite3ExprListDelete(db, pParse->pConstExpr);
  103195. if( db ){
  103196. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  103197. db->lookaside.bDisable -= pParse->disableLookaside;
  103198. }
  103199. pParse->disableLookaside = 0;
  103200. }
  103201. }
  103202. /*
  103203. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  103204. */
  103205. static int sqlite3Prepare(
  103206. sqlite3 *db, /* Database handle. */
  103207. const char *zSql, /* UTF-8 encoded SQL statement. */
  103208. int nBytes, /* Length of zSql in bytes. */
  103209. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  103210. Vdbe *pReprepare, /* VM being reprepared */
  103211. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103212. const char **pzTail /* OUT: End of parsed string */
  103213. ){
  103214. Parse *pParse; /* Parsing context */
  103215. char *zErrMsg = 0; /* Error message */
  103216. int rc = SQLITE_OK; /* Result code */
  103217. int i; /* Loop counter */
  103218. /* Allocate the parsing context */
  103219. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  103220. if( pParse==0 ){
  103221. rc = SQLITE_NOMEM_BKPT;
  103222. goto end_prepare;
  103223. }
  103224. pParse->pReprepare = pReprepare;
  103225. assert( ppStmt && *ppStmt==0 );
  103226. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  103227. assert( sqlite3_mutex_held(db->mutex) );
  103228. /* Check to verify that it is possible to get a read lock on all
  103229. ** database schemas. The inability to get a read lock indicates that
  103230. ** some other database connection is holding a write-lock, which in
  103231. ** turn means that the other connection has made uncommitted changes
  103232. ** to the schema.
  103233. **
  103234. ** Were we to proceed and prepare the statement against the uncommitted
  103235. ** schema changes and if those schema changes are subsequently rolled
  103236. ** back and different changes are made in their place, then when this
  103237. ** prepared statement goes to run the schema cookie would fail to detect
  103238. ** the schema change. Disaster would follow.
  103239. **
  103240. ** This thread is currently holding mutexes on all Btrees (because
  103241. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  103242. ** is not possible for another thread to start a new schema change
  103243. ** while this routine is running. Hence, we do not need to hold
  103244. ** locks on the schema, we just need to make sure nobody else is
  103245. ** holding them.
  103246. **
  103247. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  103248. ** but it does *not* override schema lock detection, so this all still
  103249. ** works even if READ_UNCOMMITTED is set.
  103250. */
  103251. for(i=0; i<db->nDb; i++) {
  103252. Btree *pBt = db->aDb[i].pBt;
  103253. if( pBt ){
  103254. assert( sqlite3BtreeHoldsMutex(pBt) );
  103255. rc = sqlite3BtreeSchemaLocked(pBt);
  103256. if( rc ){
  103257. const char *zDb = db->aDb[i].zName;
  103258. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  103259. testcase( db->flags & SQLITE_ReadUncommitted );
  103260. goto end_prepare;
  103261. }
  103262. }
  103263. }
  103264. sqlite3VtabUnlockList(db);
  103265. pParse->db = db;
  103266. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  103267. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  103268. char *zSqlCopy;
  103269. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  103270. testcase( nBytes==mxLen );
  103271. testcase( nBytes==mxLen+1 );
  103272. if( nBytes>mxLen ){
  103273. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  103274. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  103275. goto end_prepare;
  103276. }
  103277. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  103278. if( zSqlCopy ){
  103279. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  103280. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  103281. sqlite3DbFree(db, zSqlCopy);
  103282. }else{
  103283. pParse->zTail = &zSql[nBytes];
  103284. }
  103285. }else{
  103286. sqlite3RunParser(pParse, zSql, &zErrMsg);
  103287. }
  103288. assert( 0==pParse->nQueryLoop );
  103289. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  103290. if( pParse->checkSchema ){
  103291. schemaIsValid(pParse);
  103292. }
  103293. if( db->mallocFailed ){
  103294. pParse->rc = SQLITE_NOMEM_BKPT;
  103295. }
  103296. if( pzTail ){
  103297. *pzTail = pParse->zTail;
  103298. }
  103299. rc = pParse->rc;
  103300. #ifndef SQLITE_OMIT_EXPLAIN
  103301. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  103302. static const char * const azColName[] = {
  103303. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  103304. "selectid", "order", "from", "detail"
  103305. };
  103306. int iFirst, mx;
  103307. if( pParse->explain==2 ){
  103308. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  103309. iFirst = 8;
  103310. mx = 12;
  103311. }else{
  103312. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  103313. iFirst = 0;
  103314. mx = 8;
  103315. }
  103316. for(i=iFirst; i<mx; i++){
  103317. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  103318. azColName[i], SQLITE_STATIC);
  103319. }
  103320. }
  103321. #endif
  103322. if( db->init.busy==0 ){
  103323. Vdbe *pVdbe = pParse->pVdbe;
  103324. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  103325. }
  103326. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  103327. sqlite3VdbeFinalize(pParse->pVdbe);
  103328. assert(!(*ppStmt));
  103329. }else{
  103330. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  103331. }
  103332. if( zErrMsg ){
  103333. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  103334. sqlite3DbFree(db, zErrMsg);
  103335. }else{
  103336. sqlite3Error(db, rc);
  103337. }
  103338. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  103339. while( pParse->pTriggerPrg ){
  103340. TriggerPrg *pT = pParse->pTriggerPrg;
  103341. pParse->pTriggerPrg = pT->pNext;
  103342. sqlite3DbFree(db, pT);
  103343. }
  103344. end_prepare:
  103345. sqlite3ParserReset(pParse);
  103346. sqlite3StackFree(db, pParse);
  103347. rc = sqlite3ApiExit(db, rc);
  103348. assert( (rc&db->errMask)==rc );
  103349. return rc;
  103350. }
  103351. static int sqlite3LockAndPrepare(
  103352. sqlite3 *db, /* Database handle. */
  103353. const char *zSql, /* UTF-8 encoded SQL statement. */
  103354. int nBytes, /* Length of zSql in bytes. */
  103355. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  103356. Vdbe *pOld, /* VM being reprepared */
  103357. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103358. const char **pzTail /* OUT: End of parsed string */
  103359. ){
  103360. int rc;
  103361. #ifdef SQLITE_ENABLE_API_ARMOR
  103362. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  103363. #endif
  103364. *ppStmt = 0;
  103365. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  103366. return SQLITE_MISUSE_BKPT;
  103367. }
  103368. sqlite3_mutex_enter(db->mutex);
  103369. sqlite3BtreeEnterAll(db);
  103370. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  103371. if( rc==SQLITE_SCHEMA ){
  103372. sqlite3_finalize(*ppStmt);
  103373. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  103374. }
  103375. sqlite3BtreeLeaveAll(db);
  103376. sqlite3_mutex_leave(db->mutex);
  103377. assert( rc==SQLITE_OK || *ppStmt==0 );
  103378. return rc;
  103379. }
  103380. /*
  103381. ** Rerun the compilation of a statement after a schema change.
  103382. **
  103383. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  103384. ** if the statement cannot be recompiled because another connection has
  103385. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  103386. ** occurs, return SQLITE_SCHEMA.
  103387. */
  103388. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  103389. int rc;
  103390. sqlite3_stmt *pNew;
  103391. const char *zSql;
  103392. sqlite3 *db;
  103393. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  103394. zSql = sqlite3_sql((sqlite3_stmt *)p);
  103395. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  103396. db = sqlite3VdbeDb(p);
  103397. assert( sqlite3_mutex_held(db->mutex) );
  103398. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  103399. if( rc ){
  103400. if( rc==SQLITE_NOMEM ){
  103401. sqlite3OomFault(db);
  103402. }
  103403. assert( pNew==0 );
  103404. return rc;
  103405. }else{
  103406. assert( pNew!=0 );
  103407. }
  103408. sqlite3VdbeSwap((Vdbe*)pNew, p);
  103409. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  103410. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  103411. sqlite3VdbeFinalize((Vdbe*)pNew);
  103412. return SQLITE_OK;
  103413. }
  103414. /*
  103415. ** Two versions of the official API. Legacy and new use. In the legacy
  103416. ** version, the original SQL text is not saved in the prepared statement
  103417. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  103418. ** sqlite3_step(). In the new version, the original SQL text is retained
  103419. ** and the statement is automatically recompiled if an schema change
  103420. ** occurs.
  103421. */
  103422. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  103423. sqlite3 *db, /* Database handle. */
  103424. const char *zSql, /* UTF-8 encoded SQL statement. */
  103425. int nBytes, /* Length of zSql in bytes. */
  103426. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103427. const char **pzTail /* OUT: End of parsed string */
  103428. ){
  103429. int rc;
  103430. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  103431. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  103432. return rc;
  103433. }
  103434. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  103435. sqlite3 *db, /* Database handle. */
  103436. const char *zSql, /* UTF-8 encoded SQL statement. */
  103437. int nBytes, /* Length of zSql in bytes. */
  103438. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103439. const char **pzTail /* OUT: End of parsed string */
  103440. ){
  103441. int rc;
  103442. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  103443. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  103444. return rc;
  103445. }
  103446. #ifndef SQLITE_OMIT_UTF16
  103447. /*
  103448. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  103449. */
  103450. static int sqlite3Prepare16(
  103451. sqlite3 *db, /* Database handle. */
  103452. const void *zSql, /* UTF-16 encoded SQL statement. */
  103453. int nBytes, /* Length of zSql in bytes. */
  103454. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  103455. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103456. const void **pzTail /* OUT: End of parsed string */
  103457. ){
  103458. /* This function currently works by first transforming the UTF-16
  103459. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  103460. ** tricky bit is figuring out the pointer to return in *pzTail.
  103461. */
  103462. char *zSql8;
  103463. const char *zTail8 = 0;
  103464. int rc = SQLITE_OK;
  103465. #ifdef SQLITE_ENABLE_API_ARMOR
  103466. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  103467. #endif
  103468. *ppStmt = 0;
  103469. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  103470. return SQLITE_MISUSE_BKPT;
  103471. }
  103472. if( nBytes>=0 ){
  103473. int sz;
  103474. const char *z = (const char*)zSql;
  103475. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  103476. nBytes = sz;
  103477. }
  103478. sqlite3_mutex_enter(db->mutex);
  103479. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  103480. if( zSql8 ){
  103481. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  103482. }
  103483. if( zTail8 && pzTail ){
  103484. /* If sqlite3_prepare returns a tail pointer, we calculate the
  103485. ** equivalent pointer into the UTF-16 string by counting the unicode
  103486. ** characters between zSql8 and zTail8, and then returning a pointer
  103487. ** the same number of characters into the UTF-16 string.
  103488. */
  103489. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  103490. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  103491. }
  103492. sqlite3DbFree(db, zSql8);
  103493. rc = sqlite3ApiExit(db, rc);
  103494. sqlite3_mutex_leave(db->mutex);
  103495. return rc;
  103496. }
  103497. /*
  103498. ** Two versions of the official API. Legacy and new use. In the legacy
  103499. ** version, the original SQL text is not saved in the prepared statement
  103500. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  103501. ** sqlite3_step(). In the new version, the original SQL text is retained
  103502. ** and the statement is automatically recompiled if an schema change
  103503. ** occurs.
  103504. */
  103505. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  103506. sqlite3 *db, /* Database handle. */
  103507. const void *zSql, /* UTF-16 encoded SQL statement. */
  103508. int nBytes, /* Length of zSql in bytes. */
  103509. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103510. const void **pzTail /* OUT: End of parsed string */
  103511. ){
  103512. int rc;
  103513. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  103514. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  103515. return rc;
  103516. }
  103517. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  103518. sqlite3 *db, /* Database handle. */
  103519. const void *zSql, /* UTF-16 encoded SQL statement. */
  103520. int nBytes, /* Length of zSql in bytes. */
  103521. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  103522. const void **pzTail /* OUT: End of parsed string */
  103523. ){
  103524. int rc;
  103525. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  103526. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  103527. return rc;
  103528. }
  103529. #endif /* SQLITE_OMIT_UTF16 */
  103530. /************** End of prepare.c *********************************************/
  103531. /************** Begin file select.c ******************************************/
  103532. /*
  103533. ** 2001 September 15
  103534. **
  103535. ** The author disclaims copyright to this source code. In place of
  103536. ** a legal notice, here is a blessing:
  103537. **
  103538. ** May you do good and not evil.
  103539. ** May you find forgiveness for yourself and forgive others.
  103540. ** May you share freely, never taking more than you give.
  103541. **
  103542. *************************************************************************
  103543. ** This file contains C code routines that are called by the parser
  103544. ** to handle SELECT statements in SQLite.
  103545. */
  103546. /* #include "sqliteInt.h" */
  103547. /*
  103548. ** Trace output macros
  103549. */
  103550. #if SELECTTRACE_ENABLED
  103551. /***/ int sqlite3SelectTrace = 0;
  103552. # define SELECTTRACE(K,P,S,X) \
  103553. if(sqlite3SelectTrace&(K)) \
  103554. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  103555. (S)->zSelName,(S)),\
  103556. sqlite3DebugPrintf X
  103557. #else
  103558. # define SELECTTRACE(K,P,S,X)
  103559. #endif
  103560. /*
  103561. ** An instance of the following object is used to record information about
  103562. ** how to process the DISTINCT keyword, to simplify passing that information
  103563. ** into the selectInnerLoop() routine.
  103564. */
  103565. typedef struct DistinctCtx DistinctCtx;
  103566. struct DistinctCtx {
  103567. u8 isTnct; /* True if the DISTINCT keyword is present */
  103568. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  103569. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  103570. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  103571. };
  103572. /*
  103573. ** An instance of the following object is used to record information about
  103574. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  103575. */
  103576. typedef struct SortCtx SortCtx;
  103577. struct SortCtx {
  103578. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  103579. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  103580. int iECursor; /* Cursor number for the sorter */
  103581. int regReturn; /* Register holding block-output return address */
  103582. int labelBkOut; /* Start label for the block-output subroutine */
  103583. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  103584. int labelDone; /* Jump here when done, ex: LIMIT reached */
  103585. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  103586. };
  103587. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  103588. /*
  103589. ** Delete all the content of a Select structure. Deallocate the structure
  103590. ** itself only if bFree is true.
  103591. */
  103592. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  103593. while( p ){
  103594. Select *pPrior = p->pPrior;
  103595. sqlite3ExprListDelete(db, p->pEList);
  103596. sqlite3SrcListDelete(db, p->pSrc);
  103597. sqlite3ExprDelete(db, p->pWhere);
  103598. sqlite3ExprListDelete(db, p->pGroupBy);
  103599. sqlite3ExprDelete(db, p->pHaving);
  103600. sqlite3ExprListDelete(db, p->pOrderBy);
  103601. sqlite3ExprDelete(db, p->pLimit);
  103602. sqlite3ExprDelete(db, p->pOffset);
  103603. sqlite3WithDelete(db, p->pWith);
  103604. if( bFree ) sqlite3DbFree(db, p);
  103605. p = pPrior;
  103606. bFree = 1;
  103607. }
  103608. }
  103609. /*
  103610. ** Initialize a SelectDest structure.
  103611. */
  103612. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  103613. pDest->eDest = (u8)eDest;
  103614. pDest->iSDParm = iParm;
  103615. pDest->affSdst = 0;
  103616. pDest->iSdst = 0;
  103617. pDest->nSdst = 0;
  103618. }
  103619. /*
  103620. ** Allocate a new Select structure and return a pointer to that
  103621. ** structure.
  103622. */
  103623. SQLITE_PRIVATE Select *sqlite3SelectNew(
  103624. Parse *pParse, /* Parsing context */
  103625. ExprList *pEList, /* which columns to include in the result */
  103626. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  103627. Expr *pWhere, /* the WHERE clause */
  103628. ExprList *pGroupBy, /* the GROUP BY clause */
  103629. Expr *pHaving, /* the HAVING clause */
  103630. ExprList *pOrderBy, /* the ORDER BY clause */
  103631. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  103632. Expr *pLimit, /* LIMIT value. NULL means not used */
  103633. Expr *pOffset /* OFFSET value. NULL means no offset */
  103634. ){
  103635. Select *pNew;
  103636. Select standin;
  103637. sqlite3 *db = pParse->db;
  103638. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  103639. if( pNew==0 ){
  103640. assert( db->mallocFailed );
  103641. pNew = &standin;
  103642. }
  103643. if( pEList==0 ){
  103644. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
  103645. }
  103646. pNew->pEList = pEList;
  103647. pNew->op = TK_SELECT;
  103648. pNew->selFlags = selFlags;
  103649. pNew->iLimit = 0;
  103650. pNew->iOffset = 0;
  103651. #if SELECTTRACE_ENABLED
  103652. pNew->zSelName[0] = 0;
  103653. #endif
  103654. pNew->addrOpenEphm[0] = -1;
  103655. pNew->addrOpenEphm[1] = -1;
  103656. pNew->nSelectRow = 0;
  103657. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  103658. pNew->pSrc = pSrc;
  103659. pNew->pWhere = pWhere;
  103660. pNew->pGroupBy = pGroupBy;
  103661. pNew->pHaving = pHaving;
  103662. pNew->pOrderBy = pOrderBy;
  103663. pNew->pPrior = 0;
  103664. pNew->pNext = 0;
  103665. pNew->pLimit = pLimit;
  103666. pNew->pOffset = pOffset;
  103667. pNew->pWith = 0;
  103668. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
  103669. if( db->mallocFailed ) {
  103670. clearSelect(db, pNew, pNew!=&standin);
  103671. pNew = 0;
  103672. }else{
  103673. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  103674. }
  103675. assert( pNew!=&standin );
  103676. return pNew;
  103677. }
  103678. #if SELECTTRACE_ENABLED
  103679. /*
  103680. ** Set the name of a Select object
  103681. */
  103682. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  103683. if( p && zName ){
  103684. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  103685. }
  103686. }
  103687. #endif
  103688. /*
  103689. ** Delete the given Select structure and all of its substructures.
  103690. */
  103691. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  103692. clearSelect(db, p, 1);
  103693. }
  103694. /*
  103695. ** Return a pointer to the right-most SELECT statement in a compound.
  103696. */
  103697. static Select *findRightmost(Select *p){
  103698. while( p->pNext ) p = p->pNext;
  103699. return p;
  103700. }
  103701. /*
  103702. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  103703. ** type of join. Return an integer constant that expresses that type
  103704. ** in terms of the following bit values:
  103705. **
  103706. ** JT_INNER
  103707. ** JT_CROSS
  103708. ** JT_OUTER
  103709. ** JT_NATURAL
  103710. ** JT_LEFT
  103711. ** JT_RIGHT
  103712. **
  103713. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  103714. **
  103715. ** If an illegal or unsupported join type is seen, then still return
  103716. ** a join type, but put an error in the pParse structure.
  103717. */
  103718. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  103719. int jointype = 0;
  103720. Token *apAll[3];
  103721. Token *p;
  103722. /* 0123456789 123456789 123456789 123 */
  103723. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  103724. static const struct {
  103725. u8 i; /* Beginning of keyword text in zKeyText[] */
  103726. u8 nChar; /* Length of the keyword in characters */
  103727. u8 code; /* Join type mask */
  103728. } aKeyword[] = {
  103729. /* natural */ { 0, 7, JT_NATURAL },
  103730. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  103731. /* outer */ { 10, 5, JT_OUTER },
  103732. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  103733. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  103734. /* inner */ { 23, 5, JT_INNER },
  103735. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  103736. };
  103737. int i, j;
  103738. apAll[0] = pA;
  103739. apAll[1] = pB;
  103740. apAll[2] = pC;
  103741. for(i=0; i<3 && apAll[i]; i++){
  103742. p = apAll[i];
  103743. for(j=0; j<ArraySize(aKeyword); j++){
  103744. if( p->n==aKeyword[j].nChar
  103745. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  103746. jointype |= aKeyword[j].code;
  103747. break;
  103748. }
  103749. }
  103750. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  103751. if( j>=ArraySize(aKeyword) ){
  103752. jointype |= JT_ERROR;
  103753. break;
  103754. }
  103755. }
  103756. if(
  103757. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  103758. (jointype & JT_ERROR)!=0
  103759. ){
  103760. const char *zSp = " ";
  103761. assert( pB!=0 );
  103762. if( pC==0 ){ zSp++; }
  103763. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  103764. "%T %T%s%T", pA, pB, zSp, pC);
  103765. jointype = JT_INNER;
  103766. }else if( (jointype & JT_OUTER)!=0
  103767. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  103768. sqlite3ErrorMsg(pParse,
  103769. "RIGHT and FULL OUTER JOINs are not currently supported");
  103770. jointype = JT_INNER;
  103771. }
  103772. return jointype;
  103773. }
  103774. /*
  103775. ** Return the index of a column in a table. Return -1 if the column
  103776. ** is not contained in the table.
  103777. */
  103778. static int columnIndex(Table *pTab, const char *zCol){
  103779. int i;
  103780. for(i=0; i<pTab->nCol; i++){
  103781. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  103782. }
  103783. return -1;
  103784. }
  103785. /*
  103786. ** Search the first N tables in pSrc, from left to right, looking for a
  103787. ** table that has a column named zCol.
  103788. **
  103789. ** When found, set *piTab and *piCol to the table index and column index
  103790. ** of the matching column and return TRUE.
  103791. **
  103792. ** If not found, return FALSE.
  103793. */
  103794. static int tableAndColumnIndex(
  103795. SrcList *pSrc, /* Array of tables to search */
  103796. int N, /* Number of tables in pSrc->a[] to search */
  103797. const char *zCol, /* Name of the column we are looking for */
  103798. int *piTab, /* Write index of pSrc->a[] here */
  103799. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  103800. ){
  103801. int i; /* For looping over tables in pSrc */
  103802. int iCol; /* Index of column matching zCol */
  103803. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  103804. for(i=0; i<N; i++){
  103805. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  103806. if( iCol>=0 ){
  103807. if( piTab ){
  103808. *piTab = i;
  103809. *piCol = iCol;
  103810. }
  103811. return 1;
  103812. }
  103813. }
  103814. return 0;
  103815. }
  103816. /*
  103817. ** This function is used to add terms implied by JOIN syntax to the
  103818. ** WHERE clause expression of a SELECT statement. The new term, which
  103819. ** is ANDed with the existing WHERE clause, is of the form:
  103820. **
  103821. ** (tab1.col1 = tab2.col2)
  103822. **
  103823. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  103824. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  103825. ** column iColRight of tab2.
  103826. */
  103827. static void addWhereTerm(
  103828. Parse *pParse, /* Parsing context */
  103829. SrcList *pSrc, /* List of tables in FROM clause */
  103830. int iLeft, /* Index of first table to join in pSrc */
  103831. int iColLeft, /* Index of column in first table */
  103832. int iRight, /* Index of second table in pSrc */
  103833. int iColRight, /* Index of column in second table */
  103834. int isOuterJoin, /* True if this is an OUTER join */
  103835. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  103836. ){
  103837. sqlite3 *db = pParse->db;
  103838. Expr *pE1;
  103839. Expr *pE2;
  103840. Expr *pEq;
  103841. assert( iLeft<iRight );
  103842. assert( pSrc->nSrc>iRight );
  103843. assert( pSrc->a[iLeft].pTab );
  103844. assert( pSrc->a[iRight].pTab );
  103845. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  103846. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  103847. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  103848. if( pEq && isOuterJoin ){
  103849. ExprSetProperty(pEq, EP_FromJoin);
  103850. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  103851. ExprSetVVAProperty(pEq, EP_NoReduce);
  103852. pEq->iRightJoinTable = (i16)pE2->iTable;
  103853. }
  103854. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  103855. }
  103856. /*
  103857. ** Set the EP_FromJoin property on all terms of the given expression.
  103858. ** And set the Expr.iRightJoinTable to iTable for every term in the
  103859. ** expression.
  103860. **
  103861. ** The EP_FromJoin property is used on terms of an expression to tell
  103862. ** the LEFT OUTER JOIN processing logic that this term is part of the
  103863. ** join restriction specified in the ON or USING clause and not a part
  103864. ** of the more general WHERE clause. These terms are moved over to the
  103865. ** WHERE clause during join processing but we need to remember that they
  103866. ** originated in the ON or USING clause.
  103867. **
  103868. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  103869. ** expression depends on table iRightJoinTable even if that table is not
  103870. ** explicitly mentioned in the expression. That information is needed
  103871. ** for cases like this:
  103872. **
  103873. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  103874. **
  103875. ** The where clause needs to defer the handling of the t1.x=5
  103876. ** term until after the t2 loop of the join. In that way, a
  103877. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  103878. ** defer the handling of t1.x=5, it will be processed immediately
  103879. ** after the t1 loop and rows with t1.x!=5 will never appear in
  103880. ** the output, which is incorrect.
  103881. */
  103882. static void setJoinExpr(Expr *p, int iTable){
  103883. while( p ){
  103884. ExprSetProperty(p, EP_FromJoin);
  103885. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  103886. ExprSetVVAProperty(p, EP_NoReduce);
  103887. p->iRightJoinTable = (i16)iTable;
  103888. if( p->op==TK_FUNCTION && p->x.pList ){
  103889. int i;
  103890. for(i=0; i<p->x.pList->nExpr; i++){
  103891. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  103892. }
  103893. }
  103894. setJoinExpr(p->pLeft, iTable);
  103895. p = p->pRight;
  103896. }
  103897. }
  103898. /*
  103899. ** This routine processes the join information for a SELECT statement.
  103900. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  103901. ** NATURAL joins also create extra WHERE clause terms.
  103902. **
  103903. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  103904. ** The left most table is the first entry in Select.pSrc. The right-most
  103905. ** table is the last entry. The join operator is held in the entry to
  103906. ** the left. Thus entry 0 contains the join operator for the join between
  103907. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  103908. ** also attached to the left entry.
  103909. **
  103910. ** This routine returns the number of errors encountered.
  103911. */
  103912. static int sqliteProcessJoin(Parse *pParse, Select *p){
  103913. SrcList *pSrc; /* All tables in the FROM clause */
  103914. int i, j; /* Loop counters */
  103915. struct SrcList_item *pLeft; /* Left table being joined */
  103916. struct SrcList_item *pRight; /* Right table being joined */
  103917. pSrc = p->pSrc;
  103918. pLeft = &pSrc->a[0];
  103919. pRight = &pLeft[1];
  103920. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  103921. Table *pLeftTab = pLeft->pTab;
  103922. Table *pRightTab = pRight->pTab;
  103923. int isOuter;
  103924. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  103925. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  103926. /* When the NATURAL keyword is present, add WHERE clause terms for
  103927. ** every column that the two tables have in common.
  103928. */
  103929. if( pRight->fg.jointype & JT_NATURAL ){
  103930. if( pRight->pOn || pRight->pUsing ){
  103931. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  103932. "an ON or USING clause", 0);
  103933. return 1;
  103934. }
  103935. for(j=0; j<pRightTab->nCol; j++){
  103936. char *zName; /* Name of column in the right table */
  103937. int iLeft; /* Matching left table */
  103938. int iLeftCol; /* Matching column in the left table */
  103939. zName = pRightTab->aCol[j].zName;
  103940. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  103941. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  103942. isOuter, &p->pWhere);
  103943. }
  103944. }
  103945. }
  103946. /* Disallow both ON and USING clauses in the same join
  103947. */
  103948. if( pRight->pOn && pRight->pUsing ){
  103949. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  103950. "clauses in the same join");
  103951. return 1;
  103952. }
  103953. /* Add the ON clause to the end of the WHERE clause, connected by
  103954. ** an AND operator.
  103955. */
  103956. if( pRight->pOn ){
  103957. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  103958. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  103959. pRight->pOn = 0;
  103960. }
  103961. /* Create extra terms on the WHERE clause for each column named
  103962. ** in the USING clause. Example: If the two tables to be joined are
  103963. ** A and B and the USING clause names X, Y, and Z, then add this
  103964. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  103965. ** Report an error if any column mentioned in the USING clause is
  103966. ** not contained in both tables to be joined.
  103967. */
  103968. if( pRight->pUsing ){
  103969. IdList *pList = pRight->pUsing;
  103970. for(j=0; j<pList->nId; j++){
  103971. char *zName; /* Name of the term in the USING clause */
  103972. int iLeft; /* Table on the left with matching column name */
  103973. int iLeftCol; /* Column number of matching column on the left */
  103974. int iRightCol; /* Column number of matching column on the right */
  103975. zName = pList->a[j].zName;
  103976. iRightCol = columnIndex(pRightTab, zName);
  103977. if( iRightCol<0
  103978. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  103979. ){
  103980. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  103981. "not present in both tables", zName);
  103982. return 1;
  103983. }
  103984. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  103985. isOuter, &p->pWhere);
  103986. }
  103987. }
  103988. }
  103989. return 0;
  103990. }
  103991. /* Forward reference */
  103992. static KeyInfo *keyInfoFromExprList(
  103993. Parse *pParse, /* Parsing context */
  103994. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  103995. int iStart, /* Begin with this column of pList */
  103996. int nExtra /* Add this many extra columns to the end */
  103997. );
  103998. /*
  103999. ** Generate code that will push the record in registers regData
  104000. ** through regData+nData-1 onto the sorter.
  104001. */
  104002. static void pushOntoSorter(
  104003. Parse *pParse, /* Parser context */
  104004. SortCtx *pSort, /* Information about the ORDER BY clause */
  104005. Select *pSelect, /* The whole SELECT statement */
  104006. int regData, /* First register holding data to be sorted */
  104007. int regOrigData, /* First register holding data before packing */
  104008. int nData, /* Number of elements in the data array */
  104009. int nPrefixReg /* No. of reg prior to regData available for use */
  104010. ){
  104011. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  104012. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  104013. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  104014. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  104015. int regBase; /* Regs for sorter record */
  104016. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  104017. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  104018. int op; /* Opcode to add sorter record to sorter */
  104019. int iLimit; /* LIMIT counter */
  104020. assert( bSeq==0 || bSeq==1 );
  104021. assert( nData==1 || regData==regOrigData );
  104022. if( nPrefixReg ){
  104023. assert( nPrefixReg==nExpr+bSeq );
  104024. regBase = regData - nExpr - bSeq;
  104025. }else{
  104026. regBase = pParse->nMem + 1;
  104027. pParse->nMem += nBase;
  104028. }
  104029. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  104030. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  104031. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  104032. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  104033. SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
  104034. if( bSeq ){
  104035. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  104036. }
  104037. if( nPrefixReg==0 ){
  104038. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  104039. }
  104040. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  104041. if( nOBSat>0 ){
  104042. int regPrevKey; /* The first nOBSat columns of the previous row */
  104043. int addrFirst; /* Address of the OP_IfNot opcode */
  104044. int addrJmp; /* Address of the OP_Jump opcode */
  104045. VdbeOp *pOp; /* Opcode that opens the sorter */
  104046. int nKey; /* Number of sorting key columns, including OP_Sequence */
  104047. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  104048. regPrevKey = pParse->nMem+1;
  104049. pParse->nMem += pSort->nOBSat;
  104050. nKey = nExpr - pSort->nOBSat + bSeq;
  104051. if( bSeq ){
  104052. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  104053. }else{
  104054. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  104055. }
  104056. VdbeCoverage(v);
  104057. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  104058. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  104059. if( pParse->db->mallocFailed ) return;
  104060. pOp->p2 = nKey + nData;
  104061. pKI = pOp->p4.pKeyInfo;
  104062. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  104063. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  104064. testcase( pKI->nXField>2 );
  104065. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  104066. pKI->nXField-1);
  104067. addrJmp = sqlite3VdbeCurrentAddr(v);
  104068. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  104069. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  104070. pSort->regReturn = ++pParse->nMem;
  104071. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  104072. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  104073. if( iLimit ){
  104074. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  104075. VdbeCoverage(v);
  104076. }
  104077. sqlite3VdbeJumpHere(v, addrFirst);
  104078. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  104079. sqlite3VdbeJumpHere(v, addrJmp);
  104080. }
  104081. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  104082. op = OP_SorterInsert;
  104083. }else{
  104084. op = OP_IdxInsert;
  104085. }
  104086. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  104087. if( iLimit ){
  104088. int addr;
  104089. addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
  104090. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  104091. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  104092. sqlite3VdbeJumpHere(v, addr);
  104093. }
  104094. }
  104095. /*
  104096. ** Add code to implement the OFFSET
  104097. */
  104098. static void codeOffset(
  104099. Vdbe *v, /* Generate code into this VM */
  104100. int iOffset, /* Register holding the offset counter */
  104101. int iContinue /* Jump here to skip the current record */
  104102. ){
  104103. if( iOffset>0 ){
  104104. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  104105. VdbeComment((v, "OFFSET"));
  104106. }
  104107. }
  104108. /*
  104109. ** Add code that will check to make sure the N registers starting at iMem
  104110. ** form a distinct entry. iTab is a sorting index that holds previously
  104111. ** seen combinations of the N values. A new entry is made in iTab
  104112. ** if the current N values are new.
  104113. **
  104114. ** A jump to addrRepeat is made and the N+1 values are popped from the
  104115. ** stack if the top N elements are not distinct.
  104116. */
  104117. static void codeDistinct(
  104118. Parse *pParse, /* Parsing and code generating context */
  104119. int iTab, /* A sorting index used to test for distinctness */
  104120. int addrRepeat, /* Jump to here if not distinct */
  104121. int N, /* Number of elements */
  104122. int iMem /* First element */
  104123. ){
  104124. Vdbe *v;
  104125. int r1;
  104126. v = pParse->pVdbe;
  104127. r1 = sqlite3GetTempReg(pParse);
  104128. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  104129. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  104130. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  104131. sqlite3ReleaseTempReg(pParse, r1);
  104132. }
  104133. #ifndef SQLITE_OMIT_SUBQUERY
  104134. /*
  104135. ** Generate an error message when a SELECT is used within a subexpression
  104136. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  104137. ** column. We do this in a subroutine because the error used to occur
  104138. ** in multiple places. (The error only occurs in one place now, but we
  104139. ** retain the subroutine to minimize code disruption.)
  104140. */
  104141. static int checkForMultiColumnSelectError(
  104142. Parse *pParse, /* Parse context. */
  104143. SelectDest *pDest, /* Destination of SELECT results */
  104144. int nExpr /* Number of result columns returned by SELECT */
  104145. ){
  104146. int eDest = pDest->eDest;
  104147. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  104148. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  104149. "a SELECT that is part of an expression");
  104150. return 1;
  104151. }else{
  104152. return 0;
  104153. }
  104154. }
  104155. #endif
  104156. /*
  104157. ** This routine generates the code for the inside of the inner loop
  104158. ** of a SELECT.
  104159. **
  104160. ** If srcTab is negative, then the pEList expressions
  104161. ** are evaluated in order to get the data for this row. If srcTab is
  104162. ** zero or more, then data is pulled from srcTab and pEList is used only
  104163. ** to get number columns and the datatype for each column.
  104164. */
  104165. static void selectInnerLoop(
  104166. Parse *pParse, /* The parser context */
  104167. Select *p, /* The complete select statement being coded */
  104168. ExprList *pEList, /* List of values being extracted */
  104169. int srcTab, /* Pull data from this table */
  104170. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  104171. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  104172. SelectDest *pDest, /* How to dispose of the results */
  104173. int iContinue, /* Jump here to continue with next row */
  104174. int iBreak /* Jump here to break out of the inner loop */
  104175. ){
  104176. Vdbe *v = pParse->pVdbe;
  104177. int i;
  104178. int hasDistinct; /* True if the DISTINCT keyword is present */
  104179. int regResult; /* Start of memory holding result set */
  104180. int eDest = pDest->eDest; /* How to dispose of results */
  104181. int iParm = pDest->iSDParm; /* First argument to disposal method */
  104182. int nResultCol; /* Number of result columns */
  104183. int nPrefixReg = 0; /* Number of extra registers before regResult */
  104184. assert( v );
  104185. assert( pEList!=0 );
  104186. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  104187. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  104188. if( pSort==0 && !hasDistinct ){
  104189. assert( iContinue!=0 );
  104190. codeOffset(v, p->iOffset, iContinue);
  104191. }
  104192. /* Pull the requested columns.
  104193. */
  104194. nResultCol = pEList->nExpr;
  104195. if( pDest->iSdst==0 ){
  104196. if( pSort ){
  104197. nPrefixReg = pSort->pOrderBy->nExpr;
  104198. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  104199. pParse->nMem += nPrefixReg;
  104200. }
  104201. pDest->iSdst = pParse->nMem+1;
  104202. pParse->nMem += nResultCol;
  104203. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  104204. /* This is an error condition that can result, for example, when a SELECT
  104205. ** on the right-hand side of an INSERT contains more result columns than
  104206. ** there are columns in the table on the left. The error will be caught
  104207. ** and reported later. But we need to make sure enough memory is allocated
  104208. ** to avoid other spurious errors in the meantime. */
  104209. pParse->nMem += nResultCol;
  104210. }
  104211. pDest->nSdst = nResultCol;
  104212. regResult = pDest->iSdst;
  104213. if( srcTab>=0 ){
  104214. for(i=0; i<nResultCol; i++){
  104215. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  104216. VdbeComment((v, "%s", pEList->a[i].zName));
  104217. }
  104218. }else if( eDest!=SRT_Exists ){
  104219. /* If the destination is an EXISTS(...) expression, the actual
  104220. ** values returned by the SELECT are not required.
  104221. */
  104222. u8 ecelFlags;
  104223. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  104224. ecelFlags = SQLITE_ECEL_DUP;
  104225. }else{
  104226. ecelFlags = 0;
  104227. }
  104228. sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
  104229. }
  104230. /* If the DISTINCT keyword was present on the SELECT statement
  104231. ** and this row has been seen before, then do not make this row
  104232. ** part of the result.
  104233. */
  104234. if( hasDistinct ){
  104235. switch( pDistinct->eTnctType ){
  104236. case WHERE_DISTINCT_ORDERED: {
  104237. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  104238. int iJump; /* Jump destination */
  104239. int regPrev; /* Previous row content */
  104240. /* Allocate space for the previous row */
  104241. regPrev = pParse->nMem+1;
  104242. pParse->nMem += nResultCol;
  104243. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  104244. ** sets the MEM_Cleared bit on the first register of the
  104245. ** previous value. This will cause the OP_Ne below to always
  104246. ** fail on the first iteration of the loop even if the first
  104247. ** row is all NULLs.
  104248. */
  104249. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  104250. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  104251. pOp->opcode = OP_Null;
  104252. pOp->p1 = 1;
  104253. pOp->p2 = regPrev;
  104254. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  104255. for(i=0; i<nResultCol; i++){
  104256. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  104257. if( i<nResultCol-1 ){
  104258. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  104259. VdbeCoverage(v);
  104260. }else{
  104261. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  104262. VdbeCoverage(v);
  104263. }
  104264. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  104265. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  104266. }
  104267. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  104268. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  104269. break;
  104270. }
  104271. case WHERE_DISTINCT_UNIQUE: {
  104272. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  104273. break;
  104274. }
  104275. default: {
  104276. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  104277. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  104278. regResult);
  104279. break;
  104280. }
  104281. }
  104282. if( pSort==0 ){
  104283. codeOffset(v, p->iOffset, iContinue);
  104284. }
  104285. }
  104286. switch( eDest ){
  104287. /* In this mode, write each query result to the key of the temporary
  104288. ** table iParm.
  104289. */
  104290. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  104291. case SRT_Union: {
  104292. int r1;
  104293. r1 = sqlite3GetTempReg(pParse);
  104294. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  104295. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  104296. sqlite3ReleaseTempReg(pParse, r1);
  104297. break;
  104298. }
  104299. /* Construct a record from the query result, but instead of
  104300. ** saving that record, use it as a key to delete elements from
  104301. ** the temporary table iParm.
  104302. */
  104303. case SRT_Except: {
  104304. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  104305. break;
  104306. }
  104307. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  104308. /* Store the result as data using a unique key.
  104309. */
  104310. case SRT_Fifo:
  104311. case SRT_DistFifo:
  104312. case SRT_Table:
  104313. case SRT_EphemTab: {
  104314. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  104315. testcase( eDest==SRT_Table );
  104316. testcase( eDest==SRT_EphemTab );
  104317. testcase( eDest==SRT_Fifo );
  104318. testcase( eDest==SRT_DistFifo );
  104319. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  104320. #ifndef SQLITE_OMIT_CTE
  104321. if( eDest==SRT_DistFifo ){
  104322. /* If the destination is DistFifo, then cursor (iParm+1) is open
  104323. ** on an ephemeral index. If the current row is already present
  104324. ** in the index, do not write it to the output. If not, add the
  104325. ** current row to the index and proceed with writing it to the
  104326. ** output table as well. */
  104327. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  104328. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  104329. VdbeCoverage(v);
  104330. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  104331. assert( pSort==0 );
  104332. }
  104333. #endif
  104334. if( pSort ){
  104335. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  104336. }else{
  104337. int r2 = sqlite3GetTempReg(pParse);
  104338. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  104339. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  104340. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  104341. sqlite3ReleaseTempReg(pParse, r2);
  104342. }
  104343. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  104344. break;
  104345. }
  104346. #ifndef SQLITE_OMIT_SUBQUERY
  104347. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  104348. ** then there should be a single item on the stack. Write this
  104349. ** item into the set table with bogus data.
  104350. */
  104351. case SRT_Set: {
  104352. assert( nResultCol==1 );
  104353. pDest->affSdst =
  104354. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  104355. if( pSort ){
  104356. /* At first glance you would think we could optimize out the
  104357. ** ORDER BY in this case since the order of entries in the set
  104358. ** does not matter. But there might be a LIMIT clause, in which
  104359. ** case the order does matter */
  104360. pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
  104361. }else{
  104362. int r1 = sqlite3GetTempReg(pParse);
  104363. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  104364. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  104365. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  104366. sqlite3ReleaseTempReg(pParse, r1);
  104367. }
  104368. break;
  104369. }
  104370. /* If any row exist in the result set, record that fact and abort.
  104371. */
  104372. case SRT_Exists: {
  104373. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  104374. /* The LIMIT clause will terminate the loop for us */
  104375. break;
  104376. }
  104377. /* If this is a scalar select that is part of an expression, then
  104378. ** store the results in the appropriate memory cell and break out
  104379. ** of the scan loop.
  104380. */
  104381. case SRT_Mem: {
  104382. assert( nResultCol==1 );
  104383. if( pSort ){
  104384. pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
  104385. }else{
  104386. assert( regResult==iParm );
  104387. /* The LIMIT clause will jump out of the loop for us */
  104388. }
  104389. break;
  104390. }
  104391. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  104392. case SRT_Coroutine: /* Send data to a co-routine */
  104393. case SRT_Output: { /* Return the results */
  104394. testcase( eDest==SRT_Coroutine );
  104395. testcase( eDest==SRT_Output );
  104396. if( pSort ){
  104397. pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
  104398. nPrefixReg);
  104399. }else if( eDest==SRT_Coroutine ){
  104400. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  104401. }else{
  104402. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  104403. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  104404. }
  104405. break;
  104406. }
  104407. #ifndef SQLITE_OMIT_CTE
  104408. /* Write the results into a priority queue that is order according to
  104409. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  104410. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  104411. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  104412. ** final OP_Sequence column. The last column is the record as a blob.
  104413. */
  104414. case SRT_DistQueue:
  104415. case SRT_Queue: {
  104416. int nKey;
  104417. int r1, r2, r3;
  104418. int addrTest = 0;
  104419. ExprList *pSO;
  104420. pSO = pDest->pOrderBy;
  104421. assert( pSO );
  104422. nKey = pSO->nExpr;
  104423. r1 = sqlite3GetTempReg(pParse);
  104424. r2 = sqlite3GetTempRange(pParse, nKey+2);
  104425. r3 = r2+nKey+1;
  104426. if( eDest==SRT_DistQueue ){
  104427. /* If the destination is DistQueue, then cursor (iParm+1) is open
  104428. ** on a second ephemeral index that holds all values every previously
  104429. ** added to the queue. */
  104430. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  104431. regResult, nResultCol);
  104432. VdbeCoverage(v);
  104433. }
  104434. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  104435. if( eDest==SRT_DistQueue ){
  104436. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  104437. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  104438. }
  104439. for(i=0; i<nKey; i++){
  104440. sqlite3VdbeAddOp2(v, OP_SCopy,
  104441. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  104442. r2+i);
  104443. }
  104444. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  104445. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  104446. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  104447. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  104448. sqlite3ReleaseTempReg(pParse, r1);
  104449. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  104450. break;
  104451. }
  104452. #endif /* SQLITE_OMIT_CTE */
  104453. #if !defined(SQLITE_OMIT_TRIGGER)
  104454. /* Discard the results. This is used for SELECT statements inside
  104455. ** the body of a TRIGGER. The purpose of such selects is to call
  104456. ** user-defined functions that have side effects. We do not care
  104457. ** about the actual results of the select.
  104458. */
  104459. default: {
  104460. assert( eDest==SRT_Discard );
  104461. break;
  104462. }
  104463. #endif
  104464. }
  104465. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  104466. ** there is a sorter, in which case the sorter has already limited
  104467. ** the output for us.
  104468. */
  104469. if( pSort==0 && p->iLimit ){
  104470. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  104471. }
  104472. }
  104473. /*
  104474. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  104475. ** X extra columns.
  104476. */
  104477. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  104478. int nExtra = (N+X)*(sizeof(CollSeq*)+1);
  104479. KeyInfo *p = sqlite3Malloc(sizeof(KeyInfo) + nExtra);
  104480. if( p ){
  104481. p->aSortOrder = (u8*)&p->aColl[N+X];
  104482. p->nField = (u16)N;
  104483. p->nXField = (u16)X;
  104484. p->enc = ENC(db);
  104485. p->db = db;
  104486. p->nRef = 1;
  104487. memset(&p[1], 0, nExtra);
  104488. }else{
  104489. sqlite3OomFault(db);
  104490. }
  104491. return p;
  104492. }
  104493. /*
  104494. ** Deallocate a KeyInfo object
  104495. */
  104496. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  104497. if( p ){
  104498. assert( p->nRef>0 );
  104499. p->nRef--;
  104500. if( p->nRef==0 ) sqlite3DbFree(0, p);
  104501. }
  104502. }
  104503. /*
  104504. ** Make a new pointer to a KeyInfo object
  104505. */
  104506. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  104507. if( p ){
  104508. assert( p->nRef>0 );
  104509. p->nRef++;
  104510. }
  104511. return p;
  104512. }
  104513. #ifdef SQLITE_DEBUG
  104514. /*
  104515. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  104516. ** can only be changed if this is just a single reference to the object.
  104517. **
  104518. ** This routine is used only inside of assert() statements.
  104519. */
  104520. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  104521. #endif /* SQLITE_DEBUG */
  104522. /*
  104523. ** Given an expression list, generate a KeyInfo structure that records
  104524. ** the collating sequence for each expression in that expression list.
  104525. **
  104526. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  104527. ** KeyInfo structure is appropriate for initializing a virtual index to
  104528. ** implement that clause. If the ExprList is the result set of a SELECT
  104529. ** then the KeyInfo structure is appropriate for initializing a virtual
  104530. ** index to implement a DISTINCT test.
  104531. **
  104532. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  104533. ** function is responsible for seeing that this structure is eventually
  104534. ** freed.
  104535. */
  104536. static KeyInfo *keyInfoFromExprList(
  104537. Parse *pParse, /* Parsing context */
  104538. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  104539. int iStart, /* Begin with this column of pList */
  104540. int nExtra /* Add this many extra columns to the end */
  104541. ){
  104542. int nExpr;
  104543. KeyInfo *pInfo;
  104544. struct ExprList_item *pItem;
  104545. sqlite3 *db = pParse->db;
  104546. int i;
  104547. nExpr = pList->nExpr;
  104548. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  104549. if( pInfo ){
  104550. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  104551. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  104552. CollSeq *pColl;
  104553. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  104554. if( !pColl ) pColl = db->pDfltColl;
  104555. pInfo->aColl[i-iStart] = pColl;
  104556. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  104557. }
  104558. }
  104559. return pInfo;
  104560. }
  104561. /*
  104562. ** Name of the connection operator, used for error messages.
  104563. */
  104564. static const char *selectOpName(int id){
  104565. char *z;
  104566. switch( id ){
  104567. case TK_ALL: z = "UNION ALL"; break;
  104568. case TK_INTERSECT: z = "INTERSECT"; break;
  104569. case TK_EXCEPT: z = "EXCEPT"; break;
  104570. default: z = "UNION"; break;
  104571. }
  104572. return z;
  104573. }
  104574. #ifndef SQLITE_OMIT_EXPLAIN
  104575. /*
  104576. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  104577. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  104578. ** where the caption is of the form:
  104579. **
  104580. ** "USE TEMP B-TREE FOR xxx"
  104581. **
  104582. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  104583. ** is determined by the zUsage argument.
  104584. */
  104585. static void explainTempTable(Parse *pParse, const char *zUsage){
  104586. if( pParse->explain==2 ){
  104587. Vdbe *v = pParse->pVdbe;
  104588. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  104589. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  104590. }
  104591. }
  104592. /*
  104593. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  104594. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  104595. ** in sqlite3Select() to assign values to structure member variables that
  104596. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  104597. ** code with #ifndef directives.
  104598. */
  104599. # define explainSetInteger(a, b) a = b
  104600. #else
  104601. /* No-op versions of the explainXXX() functions and macros. */
  104602. # define explainTempTable(y,z)
  104603. # define explainSetInteger(y,z)
  104604. #endif
  104605. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  104606. /*
  104607. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  104608. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  104609. ** where the caption is of one of the two forms:
  104610. **
  104611. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  104612. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  104613. **
  104614. ** where iSub1 and iSub2 are the integers passed as the corresponding
  104615. ** function parameters, and op is the text representation of the parameter
  104616. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  104617. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  104618. ** false, or the second form if it is true.
  104619. */
  104620. static void explainComposite(
  104621. Parse *pParse, /* Parse context */
  104622. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  104623. int iSub1, /* Subquery id 1 */
  104624. int iSub2, /* Subquery id 2 */
  104625. int bUseTmp /* True if a temp table was used */
  104626. ){
  104627. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  104628. if( pParse->explain==2 ){
  104629. Vdbe *v = pParse->pVdbe;
  104630. char *zMsg = sqlite3MPrintf(
  104631. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  104632. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  104633. );
  104634. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  104635. }
  104636. }
  104637. #else
  104638. /* No-op versions of the explainXXX() functions and macros. */
  104639. # define explainComposite(v,w,x,y,z)
  104640. #endif
  104641. /*
  104642. ** If the inner loop was generated using a non-null pOrderBy argument,
  104643. ** then the results were placed in a sorter. After the loop is terminated
  104644. ** we need to run the sorter and output the results. The following
  104645. ** routine generates the code needed to do that.
  104646. */
  104647. static void generateSortTail(
  104648. Parse *pParse, /* Parsing context */
  104649. Select *p, /* The SELECT statement */
  104650. SortCtx *pSort, /* Information on the ORDER BY clause */
  104651. int nColumn, /* Number of columns of data */
  104652. SelectDest *pDest /* Write the sorted results here */
  104653. ){
  104654. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  104655. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  104656. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  104657. int addr;
  104658. int addrOnce = 0;
  104659. int iTab;
  104660. ExprList *pOrderBy = pSort->pOrderBy;
  104661. int eDest = pDest->eDest;
  104662. int iParm = pDest->iSDParm;
  104663. int regRow;
  104664. int regRowid;
  104665. int nKey;
  104666. int iSortTab; /* Sorter cursor to read from */
  104667. int nSortData; /* Trailing values to read from sorter */
  104668. int i;
  104669. int bSeq; /* True if sorter record includes seq. no. */
  104670. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  104671. struct ExprList_item *aOutEx = p->pEList->a;
  104672. #endif
  104673. assert( addrBreak<0 );
  104674. if( pSort->labelBkOut ){
  104675. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  104676. sqlite3VdbeGoto(v, addrBreak);
  104677. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  104678. }
  104679. iTab = pSort->iECursor;
  104680. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  104681. regRowid = 0;
  104682. regRow = pDest->iSdst;
  104683. nSortData = nColumn;
  104684. }else{
  104685. regRowid = sqlite3GetTempReg(pParse);
  104686. regRow = sqlite3GetTempReg(pParse);
  104687. nSortData = 1;
  104688. }
  104689. nKey = pOrderBy->nExpr - pSort->nOBSat;
  104690. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  104691. int regSortOut = ++pParse->nMem;
  104692. iSortTab = pParse->nTab++;
  104693. if( pSort->labelBkOut ){
  104694. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  104695. }
  104696. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  104697. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  104698. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  104699. VdbeCoverage(v);
  104700. codeOffset(v, p->iOffset, addrContinue);
  104701. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  104702. bSeq = 0;
  104703. }else{
  104704. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  104705. codeOffset(v, p->iOffset, addrContinue);
  104706. iSortTab = iTab;
  104707. bSeq = 1;
  104708. }
  104709. for(i=0; i<nSortData; i++){
  104710. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  104711. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  104712. }
  104713. switch( eDest ){
  104714. case SRT_EphemTab: {
  104715. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  104716. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  104717. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  104718. break;
  104719. }
  104720. #ifndef SQLITE_OMIT_SUBQUERY
  104721. case SRT_Set: {
  104722. assert( nColumn==1 );
  104723. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  104724. &pDest->affSdst, 1);
  104725. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  104726. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  104727. break;
  104728. }
  104729. case SRT_Mem: {
  104730. assert( nColumn==1 );
  104731. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  104732. /* The LIMIT clause will terminate the loop for us */
  104733. break;
  104734. }
  104735. #endif
  104736. default: {
  104737. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  104738. testcase( eDest==SRT_Output );
  104739. testcase( eDest==SRT_Coroutine );
  104740. if( eDest==SRT_Output ){
  104741. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  104742. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  104743. }else{
  104744. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  104745. }
  104746. break;
  104747. }
  104748. }
  104749. if( regRowid ){
  104750. sqlite3ReleaseTempReg(pParse, regRow);
  104751. sqlite3ReleaseTempReg(pParse, regRowid);
  104752. }
  104753. /* The bottom of the loop
  104754. */
  104755. sqlite3VdbeResolveLabel(v, addrContinue);
  104756. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  104757. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  104758. }else{
  104759. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  104760. }
  104761. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  104762. sqlite3VdbeResolveLabel(v, addrBreak);
  104763. }
  104764. /*
  104765. ** Return a pointer to a string containing the 'declaration type' of the
  104766. ** expression pExpr. The string may be treated as static by the caller.
  104767. **
  104768. ** Also try to estimate the size of the returned value and return that
  104769. ** result in *pEstWidth.
  104770. **
  104771. ** The declaration type is the exact datatype definition extracted from the
  104772. ** original CREATE TABLE statement if the expression is a column. The
  104773. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  104774. ** is considered a column can be complex in the presence of subqueries. The
  104775. ** result-set expression in all of the following SELECT statements is
  104776. ** considered a column by this function.
  104777. **
  104778. ** SELECT col FROM tbl;
  104779. ** SELECT (SELECT col FROM tbl;
  104780. ** SELECT (SELECT col FROM tbl);
  104781. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  104782. **
  104783. ** The declaration type for any expression other than a column is NULL.
  104784. **
  104785. ** This routine has either 3 or 6 parameters depending on whether or not
  104786. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  104787. */
  104788. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104789. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  104790. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  104791. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  104792. #endif
  104793. static const char *columnTypeImpl(
  104794. NameContext *pNC,
  104795. Expr *pExpr,
  104796. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104797. const char **pzOrigDb,
  104798. const char **pzOrigTab,
  104799. const char **pzOrigCol,
  104800. #endif
  104801. u8 *pEstWidth
  104802. ){
  104803. char const *zType = 0;
  104804. int j;
  104805. u8 estWidth = 1;
  104806. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104807. char const *zOrigDb = 0;
  104808. char const *zOrigTab = 0;
  104809. char const *zOrigCol = 0;
  104810. #endif
  104811. assert( pExpr!=0 );
  104812. assert( pNC->pSrcList!=0 );
  104813. switch( pExpr->op ){
  104814. case TK_AGG_COLUMN:
  104815. case TK_COLUMN: {
  104816. /* The expression is a column. Locate the table the column is being
  104817. ** extracted from in NameContext.pSrcList. This table may be real
  104818. ** database table or a subquery.
  104819. */
  104820. Table *pTab = 0; /* Table structure column is extracted from */
  104821. Select *pS = 0; /* Select the column is extracted from */
  104822. int iCol = pExpr->iColumn; /* Index of column in pTab */
  104823. testcase( pExpr->op==TK_AGG_COLUMN );
  104824. testcase( pExpr->op==TK_COLUMN );
  104825. while( pNC && !pTab ){
  104826. SrcList *pTabList = pNC->pSrcList;
  104827. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  104828. if( j<pTabList->nSrc ){
  104829. pTab = pTabList->a[j].pTab;
  104830. pS = pTabList->a[j].pSelect;
  104831. }else{
  104832. pNC = pNC->pNext;
  104833. }
  104834. }
  104835. if( pTab==0 ){
  104836. /* At one time, code such as "SELECT new.x" within a trigger would
  104837. ** cause this condition to run. Since then, we have restructured how
  104838. ** trigger code is generated and so this condition is no longer
  104839. ** possible. However, it can still be true for statements like
  104840. ** the following:
  104841. **
  104842. ** CREATE TABLE t1(col INTEGER);
  104843. ** SELECT (SELECT t1.col) FROM FROM t1;
  104844. **
  104845. ** when columnType() is called on the expression "t1.col" in the
  104846. ** sub-select. In this case, set the column type to NULL, even
  104847. ** though it should really be "INTEGER".
  104848. **
  104849. ** This is not a problem, as the column type of "t1.col" is never
  104850. ** used. When columnType() is called on the expression
  104851. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  104852. ** branch below. */
  104853. break;
  104854. }
  104855. assert( pTab && pExpr->pTab==pTab );
  104856. if( pS ){
  104857. /* The "table" is actually a sub-select or a view in the FROM clause
  104858. ** of the SELECT statement. Return the declaration type and origin
  104859. ** data for the result-set column of the sub-select.
  104860. */
  104861. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  104862. /* If iCol is less than zero, then the expression requests the
  104863. ** rowid of the sub-select or view. This expression is legal (see
  104864. ** test case misc2.2.2) - it always evaluates to NULL.
  104865. **
  104866. ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
  104867. ** caught already by name resolution.
  104868. */
  104869. NameContext sNC;
  104870. Expr *p = pS->pEList->a[iCol].pExpr;
  104871. sNC.pSrcList = pS->pSrc;
  104872. sNC.pNext = pNC;
  104873. sNC.pParse = pNC->pParse;
  104874. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  104875. }
  104876. }else if( pTab->pSchema ){
  104877. /* A real table */
  104878. assert( !pS );
  104879. if( iCol<0 ) iCol = pTab->iPKey;
  104880. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  104881. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104882. if( iCol<0 ){
  104883. zType = "INTEGER";
  104884. zOrigCol = "rowid";
  104885. }else{
  104886. zOrigCol = pTab->aCol[iCol].zName;
  104887. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  104888. estWidth = pTab->aCol[iCol].szEst;
  104889. }
  104890. zOrigTab = pTab->zName;
  104891. if( pNC->pParse ){
  104892. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  104893. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  104894. }
  104895. #else
  104896. if( iCol<0 ){
  104897. zType = "INTEGER";
  104898. }else{
  104899. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  104900. estWidth = pTab->aCol[iCol].szEst;
  104901. }
  104902. #endif
  104903. }
  104904. break;
  104905. }
  104906. #ifndef SQLITE_OMIT_SUBQUERY
  104907. case TK_SELECT: {
  104908. /* The expression is a sub-select. Return the declaration type and
  104909. ** origin info for the single column in the result set of the SELECT
  104910. ** statement.
  104911. */
  104912. NameContext sNC;
  104913. Select *pS = pExpr->x.pSelect;
  104914. Expr *p = pS->pEList->a[0].pExpr;
  104915. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  104916. sNC.pSrcList = pS->pSrc;
  104917. sNC.pNext = pNC;
  104918. sNC.pParse = pNC->pParse;
  104919. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  104920. break;
  104921. }
  104922. #endif
  104923. }
  104924. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104925. if( pzOrigDb ){
  104926. assert( pzOrigTab && pzOrigCol );
  104927. *pzOrigDb = zOrigDb;
  104928. *pzOrigTab = zOrigTab;
  104929. *pzOrigCol = zOrigCol;
  104930. }
  104931. #endif
  104932. if( pEstWidth ) *pEstWidth = estWidth;
  104933. return zType;
  104934. }
  104935. /*
  104936. ** Generate code that will tell the VDBE the declaration types of columns
  104937. ** in the result set.
  104938. */
  104939. static void generateColumnTypes(
  104940. Parse *pParse, /* Parser context */
  104941. SrcList *pTabList, /* List of tables */
  104942. ExprList *pEList /* Expressions defining the result set */
  104943. ){
  104944. #ifndef SQLITE_OMIT_DECLTYPE
  104945. Vdbe *v = pParse->pVdbe;
  104946. int i;
  104947. NameContext sNC;
  104948. sNC.pSrcList = pTabList;
  104949. sNC.pParse = pParse;
  104950. for(i=0; i<pEList->nExpr; i++){
  104951. Expr *p = pEList->a[i].pExpr;
  104952. const char *zType;
  104953. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104954. const char *zOrigDb = 0;
  104955. const char *zOrigTab = 0;
  104956. const char *zOrigCol = 0;
  104957. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  104958. /* The vdbe must make its own copy of the column-type and other
  104959. ** column specific strings, in case the schema is reset before this
  104960. ** virtual machine is deleted.
  104961. */
  104962. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  104963. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  104964. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  104965. #else
  104966. zType = columnType(&sNC, p, 0, 0, 0, 0);
  104967. #endif
  104968. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  104969. }
  104970. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  104971. }
  104972. /*
  104973. ** Generate code that will tell the VDBE the names of columns
  104974. ** in the result set. This information is used to provide the
  104975. ** azCol[] values in the callback.
  104976. */
  104977. static void generateColumnNames(
  104978. Parse *pParse, /* Parser context */
  104979. SrcList *pTabList, /* List of tables */
  104980. ExprList *pEList /* Expressions defining the result set */
  104981. ){
  104982. Vdbe *v = pParse->pVdbe;
  104983. int i, j;
  104984. sqlite3 *db = pParse->db;
  104985. int fullNames, shortNames;
  104986. #ifndef SQLITE_OMIT_EXPLAIN
  104987. /* If this is an EXPLAIN, skip this step */
  104988. if( pParse->explain ){
  104989. return;
  104990. }
  104991. #endif
  104992. if( pParse->colNamesSet || db->mallocFailed ) return;
  104993. assert( v!=0 );
  104994. assert( pTabList!=0 );
  104995. pParse->colNamesSet = 1;
  104996. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  104997. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  104998. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  104999. for(i=0; i<pEList->nExpr; i++){
  105000. Expr *p;
  105001. p = pEList->a[i].pExpr;
  105002. if( NEVER(p==0) ) continue;
  105003. if( pEList->a[i].zName ){
  105004. char *zName = pEList->a[i].zName;
  105005. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  105006. }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
  105007. Table *pTab;
  105008. char *zCol;
  105009. int iCol = p->iColumn;
  105010. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  105011. if( pTabList->a[j].iCursor==p->iTable ) break;
  105012. }
  105013. assert( j<pTabList->nSrc );
  105014. pTab = pTabList->a[j].pTab;
  105015. if( iCol<0 ) iCol = pTab->iPKey;
  105016. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  105017. if( iCol<0 ){
  105018. zCol = "rowid";
  105019. }else{
  105020. zCol = pTab->aCol[iCol].zName;
  105021. }
  105022. if( !shortNames && !fullNames ){
  105023. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  105024. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  105025. }else if( fullNames ){
  105026. char *zName = 0;
  105027. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  105028. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  105029. }else{
  105030. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  105031. }
  105032. }else{
  105033. const char *z = pEList->a[i].zSpan;
  105034. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  105035. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  105036. }
  105037. }
  105038. generateColumnTypes(pParse, pTabList, pEList);
  105039. }
  105040. /*
  105041. ** Given an expression list (which is really the list of expressions
  105042. ** that form the result set of a SELECT statement) compute appropriate
  105043. ** column names for a table that would hold the expression list.
  105044. **
  105045. ** All column names will be unique.
  105046. **
  105047. ** Only the column names are computed. Column.zType, Column.zColl,
  105048. ** and other fields of Column are zeroed.
  105049. **
  105050. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  105051. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  105052. */
  105053. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  105054. Parse *pParse, /* Parsing context */
  105055. ExprList *pEList, /* Expr list from which to derive column names */
  105056. i16 *pnCol, /* Write the number of columns here */
  105057. Column **paCol /* Write the new column list here */
  105058. ){
  105059. sqlite3 *db = pParse->db; /* Database connection */
  105060. int i, j; /* Loop counters */
  105061. u32 cnt; /* Index added to make the name unique */
  105062. Column *aCol, *pCol; /* For looping over result columns */
  105063. int nCol; /* Number of columns in the result set */
  105064. Expr *p; /* Expression for a single result column */
  105065. char *zName; /* Column name */
  105066. int nName; /* Size of name in zName[] */
  105067. Hash ht; /* Hash table of column names */
  105068. sqlite3HashInit(&ht);
  105069. if( pEList ){
  105070. nCol = pEList->nExpr;
  105071. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  105072. testcase( aCol==0 );
  105073. }else{
  105074. nCol = 0;
  105075. aCol = 0;
  105076. }
  105077. assert( nCol==(i16)nCol );
  105078. *pnCol = nCol;
  105079. *paCol = aCol;
  105080. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  105081. /* Get an appropriate name for the column
  105082. */
  105083. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  105084. if( (zName = pEList->a[i].zName)!=0 ){
  105085. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  105086. }else{
  105087. Expr *pColExpr = p; /* The expression that is the result column name */
  105088. Table *pTab; /* Table associated with this expression */
  105089. while( pColExpr->op==TK_DOT ){
  105090. pColExpr = pColExpr->pRight;
  105091. assert( pColExpr!=0 );
  105092. }
  105093. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  105094. /* For columns use the column name name */
  105095. int iCol = pColExpr->iColumn;
  105096. pTab = pColExpr->pTab;
  105097. if( iCol<0 ) iCol = pTab->iPKey;
  105098. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  105099. }else if( pColExpr->op==TK_ID ){
  105100. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  105101. zName = pColExpr->u.zToken;
  105102. }else{
  105103. /* Use the original text of the column expression as its name */
  105104. zName = pEList->a[i].zSpan;
  105105. }
  105106. }
  105107. zName = sqlite3MPrintf(db, "%s", zName);
  105108. /* Make sure the column name is unique. If the name is not unique,
  105109. ** append an integer to the name so that it becomes unique.
  105110. */
  105111. cnt = 0;
  105112. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  105113. nName = sqlite3Strlen30(zName);
  105114. if( nName>0 ){
  105115. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  105116. if( zName[j]==':' ) nName = j;
  105117. }
  105118. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  105119. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  105120. }
  105121. pCol->zName = zName;
  105122. sqlite3ColumnPropertiesFromName(0, pCol);
  105123. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  105124. sqlite3OomFault(db);
  105125. }
  105126. }
  105127. sqlite3HashClear(&ht);
  105128. if( db->mallocFailed ){
  105129. for(j=0; j<i; j++){
  105130. sqlite3DbFree(db, aCol[j].zName);
  105131. }
  105132. sqlite3DbFree(db, aCol);
  105133. *paCol = 0;
  105134. *pnCol = 0;
  105135. return SQLITE_NOMEM_BKPT;
  105136. }
  105137. return SQLITE_OK;
  105138. }
  105139. /*
  105140. ** Add type and collation information to a column list based on
  105141. ** a SELECT statement.
  105142. **
  105143. ** The column list presumably came from selectColumnNamesFromExprList().
  105144. ** The column list has only names, not types or collations. This
  105145. ** routine goes through and adds the types and collations.
  105146. **
  105147. ** This routine requires that all identifiers in the SELECT
  105148. ** statement be resolved.
  105149. */
  105150. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  105151. Parse *pParse, /* Parsing contexts */
  105152. Table *pTab, /* Add column type information to this table */
  105153. Select *pSelect /* SELECT used to determine types and collations */
  105154. ){
  105155. sqlite3 *db = pParse->db;
  105156. NameContext sNC;
  105157. Column *pCol;
  105158. CollSeq *pColl;
  105159. int i;
  105160. Expr *p;
  105161. struct ExprList_item *a;
  105162. u64 szAll = 0;
  105163. assert( pSelect!=0 );
  105164. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  105165. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  105166. if( db->mallocFailed ) return;
  105167. memset(&sNC, 0, sizeof(sNC));
  105168. sNC.pSrcList = pSelect->pSrc;
  105169. a = pSelect->pEList->a;
  105170. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  105171. const char *zType;
  105172. int n, m;
  105173. p = a[i].pExpr;
  105174. zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
  105175. szAll += pCol->szEst;
  105176. pCol->affinity = sqlite3ExprAffinity(p);
  105177. if( zType && (m = sqlite3Strlen30(zType))>0 ){
  105178. n = sqlite3Strlen30(pCol->zName);
  105179. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  105180. if( pCol->zName ){
  105181. memcpy(&pCol->zName[n+1], zType, m+1);
  105182. pCol->colFlags |= COLFLAG_HASTYPE;
  105183. }
  105184. }
  105185. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  105186. pColl = sqlite3ExprCollSeq(pParse, p);
  105187. if( pColl && pCol->zColl==0 ){
  105188. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  105189. }
  105190. }
  105191. pTab->szTabRow = sqlite3LogEst(szAll*4);
  105192. }
  105193. /*
  105194. ** Given a SELECT statement, generate a Table structure that describes
  105195. ** the result set of that SELECT.
  105196. */
  105197. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  105198. Table *pTab;
  105199. sqlite3 *db = pParse->db;
  105200. int savedFlags;
  105201. savedFlags = db->flags;
  105202. db->flags &= ~SQLITE_FullColNames;
  105203. db->flags |= SQLITE_ShortColNames;
  105204. sqlite3SelectPrep(pParse, pSelect, 0);
  105205. if( pParse->nErr ) return 0;
  105206. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  105207. db->flags = savedFlags;
  105208. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  105209. if( pTab==0 ){
  105210. return 0;
  105211. }
  105212. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  105213. ** is disabled */
  105214. assert( db->lookaside.bDisable );
  105215. pTab->nRef = 1;
  105216. pTab->zName = 0;
  105217. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  105218. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  105219. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  105220. pTab->iPKey = -1;
  105221. if( db->mallocFailed ){
  105222. sqlite3DeleteTable(db, pTab);
  105223. return 0;
  105224. }
  105225. return pTab;
  105226. }
  105227. /*
  105228. ** Get a VDBE for the given parser context. Create a new one if necessary.
  105229. ** If an error occurs, return NULL and leave a message in pParse.
  105230. */
  105231. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  105232. Vdbe *v = pParse->pVdbe;
  105233. if( v==0 ){
  105234. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  105235. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  105236. if( pParse->pToplevel==0
  105237. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  105238. ){
  105239. pParse->okConstFactor = 1;
  105240. }
  105241. }
  105242. return v;
  105243. }
  105244. /*
  105245. ** Compute the iLimit and iOffset fields of the SELECT based on the
  105246. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  105247. ** that appear in the original SQL statement after the LIMIT and OFFSET
  105248. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  105249. ** are the integer memory register numbers for counters used to compute
  105250. ** the limit and offset. If there is no limit and/or offset, then
  105251. ** iLimit and iOffset are negative.
  105252. **
  105253. ** This routine changes the values of iLimit and iOffset only if
  105254. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  105255. ** iOffset should have been preset to appropriate default values (zero)
  105256. ** prior to calling this routine.
  105257. **
  105258. ** The iOffset register (if it exists) is initialized to the value
  105259. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  105260. ** iOffset+1 is initialized to LIMIT+OFFSET.
  105261. **
  105262. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  105263. ** redefined. The UNION ALL operator uses this property to force
  105264. ** the reuse of the same limit and offset registers across multiple
  105265. ** SELECT statements.
  105266. */
  105267. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  105268. Vdbe *v = 0;
  105269. int iLimit = 0;
  105270. int iOffset;
  105271. int n;
  105272. if( p->iLimit ) return;
  105273. /*
  105274. ** "LIMIT -1" always shows all rows. There is some
  105275. ** controversy about what the correct behavior should be.
  105276. ** The current implementation interprets "LIMIT 0" to mean
  105277. ** no rows.
  105278. */
  105279. sqlite3ExprCacheClear(pParse);
  105280. assert( p->pOffset==0 || p->pLimit!=0 );
  105281. if( p->pLimit ){
  105282. p->iLimit = iLimit = ++pParse->nMem;
  105283. v = sqlite3GetVdbe(pParse);
  105284. assert( v!=0 );
  105285. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  105286. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  105287. VdbeComment((v, "LIMIT counter"));
  105288. if( n==0 ){
  105289. sqlite3VdbeGoto(v, iBreak);
  105290. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  105291. p->nSelectRow = sqlite3LogEst((u64)n);
  105292. p->selFlags |= SF_FixedLimit;
  105293. }
  105294. }else{
  105295. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  105296. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  105297. VdbeComment((v, "LIMIT counter"));
  105298. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  105299. }
  105300. if( p->pOffset ){
  105301. p->iOffset = iOffset = ++pParse->nMem;
  105302. pParse->nMem++; /* Allocate an extra register for limit+offset */
  105303. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  105304. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  105305. VdbeComment((v, "OFFSET counter"));
  105306. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  105307. VdbeComment((v, "LIMIT+OFFSET"));
  105308. }
  105309. }
  105310. }
  105311. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  105312. /*
  105313. ** Return the appropriate collating sequence for the iCol-th column of
  105314. ** the result set for the compound-select statement "p". Return NULL if
  105315. ** the column has no default collating sequence.
  105316. **
  105317. ** The collating sequence for the compound select is taken from the
  105318. ** left-most term of the select that has a collating sequence.
  105319. */
  105320. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  105321. CollSeq *pRet;
  105322. if( p->pPrior ){
  105323. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  105324. }else{
  105325. pRet = 0;
  105326. }
  105327. assert( iCol>=0 );
  105328. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  105329. ** have been thrown during name resolution and we would not have gotten
  105330. ** this far */
  105331. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  105332. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  105333. }
  105334. return pRet;
  105335. }
  105336. /*
  105337. ** The select statement passed as the second parameter is a compound SELECT
  105338. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  105339. ** structure suitable for implementing the ORDER BY.
  105340. **
  105341. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  105342. ** function is responsible for ensuring that this structure is eventually
  105343. ** freed.
  105344. */
  105345. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  105346. ExprList *pOrderBy = p->pOrderBy;
  105347. int nOrderBy = p->pOrderBy->nExpr;
  105348. sqlite3 *db = pParse->db;
  105349. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  105350. if( pRet ){
  105351. int i;
  105352. for(i=0; i<nOrderBy; i++){
  105353. struct ExprList_item *pItem = &pOrderBy->a[i];
  105354. Expr *pTerm = pItem->pExpr;
  105355. CollSeq *pColl;
  105356. if( pTerm->flags & EP_Collate ){
  105357. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  105358. }else{
  105359. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  105360. if( pColl==0 ) pColl = db->pDfltColl;
  105361. pOrderBy->a[i].pExpr =
  105362. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  105363. }
  105364. assert( sqlite3KeyInfoIsWriteable(pRet) );
  105365. pRet->aColl[i] = pColl;
  105366. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  105367. }
  105368. }
  105369. return pRet;
  105370. }
  105371. #ifndef SQLITE_OMIT_CTE
  105372. /*
  105373. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  105374. ** query of the form:
  105375. **
  105376. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  105377. ** \___________/ \_______________/
  105378. ** p->pPrior p
  105379. **
  105380. **
  105381. ** There is exactly one reference to the recursive-table in the FROM clause
  105382. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  105383. **
  105384. ** The setup-query runs once to generate an initial set of rows that go
  105385. ** into a Queue table. Rows are extracted from the Queue table one by
  105386. ** one. Each row extracted from Queue is output to pDest. Then the single
  105387. ** extracted row (now in the iCurrent table) becomes the content of the
  105388. ** recursive-table for a recursive-query run. The output of the recursive-query
  105389. ** is added back into the Queue table. Then another row is extracted from Queue
  105390. ** and the iteration continues until the Queue table is empty.
  105391. **
  105392. ** If the compound query operator is UNION then no duplicate rows are ever
  105393. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  105394. ** that have ever been inserted into Queue and causes duplicates to be
  105395. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  105396. **
  105397. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  105398. ** ORDER BY order and the first entry is extracted for each cycle. Without
  105399. ** an ORDER BY, the Queue table is just a FIFO.
  105400. **
  105401. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  105402. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  105403. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  105404. ** with a positive value, then the first OFFSET outputs are discarded rather
  105405. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  105406. ** rows have been skipped.
  105407. */
  105408. static void generateWithRecursiveQuery(
  105409. Parse *pParse, /* Parsing context */
  105410. Select *p, /* The recursive SELECT to be coded */
  105411. SelectDest *pDest /* What to do with query results */
  105412. ){
  105413. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  105414. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  105415. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  105416. Select *pSetup = p->pPrior; /* The setup query */
  105417. int addrTop; /* Top of the loop */
  105418. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  105419. int iCurrent = 0; /* The Current table */
  105420. int regCurrent; /* Register holding Current table */
  105421. int iQueue; /* The Queue table */
  105422. int iDistinct = 0; /* To ensure unique results if UNION */
  105423. int eDest = SRT_Fifo; /* How to write to Queue */
  105424. SelectDest destQueue; /* SelectDest targetting the Queue table */
  105425. int i; /* Loop counter */
  105426. int rc; /* Result code */
  105427. ExprList *pOrderBy; /* The ORDER BY clause */
  105428. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  105429. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  105430. /* Obtain authorization to do a recursive query */
  105431. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  105432. /* Process the LIMIT and OFFSET clauses, if they exist */
  105433. addrBreak = sqlite3VdbeMakeLabel(v);
  105434. computeLimitRegisters(pParse, p, addrBreak);
  105435. pLimit = p->pLimit;
  105436. pOffset = p->pOffset;
  105437. regLimit = p->iLimit;
  105438. regOffset = p->iOffset;
  105439. p->pLimit = p->pOffset = 0;
  105440. p->iLimit = p->iOffset = 0;
  105441. pOrderBy = p->pOrderBy;
  105442. /* Locate the cursor number of the Current table */
  105443. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  105444. if( pSrc->a[i].fg.isRecursive ){
  105445. iCurrent = pSrc->a[i].iCursor;
  105446. break;
  105447. }
  105448. }
  105449. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  105450. ** the Distinct table must be exactly one greater than Queue in order
  105451. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  105452. iQueue = pParse->nTab++;
  105453. if( p->op==TK_UNION ){
  105454. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  105455. iDistinct = pParse->nTab++;
  105456. }else{
  105457. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  105458. }
  105459. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  105460. /* Allocate cursors for Current, Queue, and Distinct. */
  105461. regCurrent = ++pParse->nMem;
  105462. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  105463. if( pOrderBy ){
  105464. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  105465. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  105466. (char*)pKeyInfo, P4_KEYINFO);
  105467. destQueue.pOrderBy = pOrderBy;
  105468. }else{
  105469. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  105470. }
  105471. VdbeComment((v, "Queue table"));
  105472. if( iDistinct ){
  105473. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  105474. p->selFlags |= SF_UsesEphemeral;
  105475. }
  105476. /* Detach the ORDER BY clause from the compound SELECT */
  105477. p->pOrderBy = 0;
  105478. /* Store the results of the setup-query in Queue. */
  105479. pSetup->pNext = 0;
  105480. rc = sqlite3Select(pParse, pSetup, &destQueue);
  105481. pSetup->pNext = p;
  105482. if( rc ) goto end_of_recursive_query;
  105483. /* Find the next row in the Queue and output that row */
  105484. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  105485. /* Transfer the next row in Queue over to Current */
  105486. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  105487. if( pOrderBy ){
  105488. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  105489. }else{
  105490. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  105491. }
  105492. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  105493. /* Output the single row in Current */
  105494. addrCont = sqlite3VdbeMakeLabel(v);
  105495. codeOffset(v, regOffset, addrCont);
  105496. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  105497. 0, 0, pDest, addrCont, addrBreak);
  105498. if( regLimit ){
  105499. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  105500. VdbeCoverage(v);
  105501. }
  105502. sqlite3VdbeResolveLabel(v, addrCont);
  105503. /* Execute the recursive SELECT taking the single row in Current as
  105504. ** the value for the recursive-table. Store the results in the Queue.
  105505. */
  105506. if( p->selFlags & SF_Aggregate ){
  105507. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  105508. }else{
  105509. p->pPrior = 0;
  105510. sqlite3Select(pParse, p, &destQueue);
  105511. assert( p->pPrior==0 );
  105512. p->pPrior = pSetup;
  105513. }
  105514. /* Keep running the loop until the Queue is empty */
  105515. sqlite3VdbeGoto(v, addrTop);
  105516. sqlite3VdbeResolveLabel(v, addrBreak);
  105517. end_of_recursive_query:
  105518. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  105519. p->pOrderBy = pOrderBy;
  105520. p->pLimit = pLimit;
  105521. p->pOffset = pOffset;
  105522. return;
  105523. }
  105524. #endif /* SQLITE_OMIT_CTE */
  105525. /* Forward references */
  105526. static int multiSelectOrderBy(
  105527. Parse *pParse, /* Parsing context */
  105528. Select *p, /* The right-most of SELECTs to be coded */
  105529. SelectDest *pDest /* What to do with query results */
  105530. );
  105531. /*
  105532. ** Handle the special case of a compound-select that originates from a
  105533. ** VALUES clause. By handling this as a special case, we avoid deep
  105534. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  105535. ** on a VALUES clause.
  105536. **
  105537. ** Because the Select object originates from a VALUES clause:
  105538. ** (1) It has no LIMIT or OFFSET
  105539. ** (2) All terms are UNION ALL
  105540. ** (3) There is no ORDER BY clause
  105541. */
  105542. static int multiSelectValues(
  105543. Parse *pParse, /* Parsing context */
  105544. Select *p, /* The right-most of SELECTs to be coded */
  105545. SelectDest *pDest /* What to do with query results */
  105546. ){
  105547. Select *pPrior;
  105548. int nRow = 1;
  105549. int rc = 0;
  105550. assert( p->selFlags & SF_MultiValue );
  105551. do{
  105552. assert( p->selFlags & SF_Values );
  105553. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  105554. assert( p->pLimit==0 );
  105555. assert( p->pOffset==0 );
  105556. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  105557. if( p->pPrior==0 ) break;
  105558. assert( p->pPrior->pNext==p );
  105559. p = p->pPrior;
  105560. nRow++;
  105561. }while(1);
  105562. while( p ){
  105563. pPrior = p->pPrior;
  105564. p->pPrior = 0;
  105565. rc = sqlite3Select(pParse, p, pDest);
  105566. p->pPrior = pPrior;
  105567. if( rc ) break;
  105568. p->nSelectRow = nRow;
  105569. p = p->pNext;
  105570. }
  105571. return rc;
  105572. }
  105573. /*
  105574. ** This routine is called to process a compound query form from
  105575. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  105576. ** INTERSECT
  105577. **
  105578. ** "p" points to the right-most of the two queries. the query on the
  105579. ** left is p->pPrior. The left query could also be a compound query
  105580. ** in which case this routine will be called recursively.
  105581. **
  105582. ** The results of the total query are to be written into a destination
  105583. ** of type eDest with parameter iParm.
  105584. **
  105585. ** Example 1: Consider a three-way compound SQL statement.
  105586. **
  105587. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  105588. **
  105589. ** This statement is parsed up as follows:
  105590. **
  105591. ** SELECT c FROM t3
  105592. ** |
  105593. ** `-----> SELECT b FROM t2
  105594. ** |
  105595. ** `------> SELECT a FROM t1
  105596. **
  105597. ** The arrows in the diagram above represent the Select.pPrior pointer.
  105598. ** So if this routine is called with p equal to the t3 query, then
  105599. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  105600. **
  105601. ** Notice that because of the way SQLite parses compound SELECTs, the
  105602. ** individual selects always group from left to right.
  105603. */
  105604. static int multiSelect(
  105605. Parse *pParse, /* Parsing context */
  105606. Select *p, /* The right-most of SELECTs to be coded */
  105607. SelectDest *pDest /* What to do with query results */
  105608. ){
  105609. int rc = SQLITE_OK; /* Success code from a subroutine */
  105610. Select *pPrior; /* Another SELECT immediately to our left */
  105611. Vdbe *v; /* Generate code to this VDBE */
  105612. SelectDest dest; /* Alternative data destination */
  105613. Select *pDelete = 0; /* Chain of simple selects to delete */
  105614. sqlite3 *db; /* Database connection */
  105615. #ifndef SQLITE_OMIT_EXPLAIN
  105616. int iSub1 = 0; /* EQP id of left-hand query */
  105617. int iSub2 = 0; /* EQP id of right-hand query */
  105618. #endif
  105619. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  105620. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  105621. */
  105622. assert( p && p->pPrior ); /* Calling function guarantees this much */
  105623. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  105624. db = pParse->db;
  105625. pPrior = p->pPrior;
  105626. dest = *pDest;
  105627. if( pPrior->pOrderBy ){
  105628. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  105629. selectOpName(p->op));
  105630. rc = 1;
  105631. goto multi_select_end;
  105632. }
  105633. if( pPrior->pLimit ){
  105634. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  105635. selectOpName(p->op));
  105636. rc = 1;
  105637. goto multi_select_end;
  105638. }
  105639. v = sqlite3GetVdbe(pParse);
  105640. assert( v!=0 ); /* The VDBE already created by calling function */
  105641. /* Create the destination temporary table if necessary
  105642. */
  105643. if( dest.eDest==SRT_EphemTab ){
  105644. assert( p->pEList );
  105645. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  105646. dest.eDest = SRT_Table;
  105647. }
  105648. /* Special handling for a compound-select that originates as a VALUES clause.
  105649. */
  105650. if( p->selFlags & SF_MultiValue ){
  105651. rc = multiSelectValues(pParse, p, &dest);
  105652. goto multi_select_end;
  105653. }
  105654. /* Make sure all SELECTs in the statement have the same number of elements
  105655. ** in their result sets.
  105656. */
  105657. assert( p->pEList && pPrior->pEList );
  105658. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  105659. #ifndef SQLITE_OMIT_CTE
  105660. if( p->selFlags & SF_Recursive ){
  105661. generateWithRecursiveQuery(pParse, p, &dest);
  105662. }else
  105663. #endif
  105664. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  105665. */
  105666. if( p->pOrderBy ){
  105667. return multiSelectOrderBy(pParse, p, pDest);
  105668. }else
  105669. /* Generate code for the left and right SELECT statements.
  105670. */
  105671. switch( p->op ){
  105672. case TK_ALL: {
  105673. int addr = 0;
  105674. int nLimit;
  105675. assert( !pPrior->pLimit );
  105676. pPrior->iLimit = p->iLimit;
  105677. pPrior->iOffset = p->iOffset;
  105678. pPrior->pLimit = p->pLimit;
  105679. pPrior->pOffset = p->pOffset;
  105680. explainSetInteger(iSub1, pParse->iNextSelectId);
  105681. rc = sqlite3Select(pParse, pPrior, &dest);
  105682. p->pLimit = 0;
  105683. p->pOffset = 0;
  105684. if( rc ){
  105685. goto multi_select_end;
  105686. }
  105687. p->pPrior = 0;
  105688. p->iLimit = pPrior->iLimit;
  105689. p->iOffset = pPrior->iOffset;
  105690. if( p->iLimit ){
  105691. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  105692. VdbeComment((v, "Jump ahead if LIMIT reached"));
  105693. if( p->iOffset ){
  105694. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  105695. p->iLimit, p->iOffset+1, p->iOffset);
  105696. }
  105697. }
  105698. explainSetInteger(iSub2, pParse->iNextSelectId);
  105699. rc = sqlite3Select(pParse, p, &dest);
  105700. testcase( rc!=SQLITE_OK );
  105701. pDelete = p->pPrior;
  105702. p->pPrior = pPrior;
  105703. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  105704. if( pPrior->pLimit
  105705. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  105706. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  105707. ){
  105708. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  105709. }
  105710. if( addr ){
  105711. sqlite3VdbeJumpHere(v, addr);
  105712. }
  105713. break;
  105714. }
  105715. case TK_EXCEPT:
  105716. case TK_UNION: {
  105717. int unionTab; /* Cursor number of the temporary table holding result */
  105718. u8 op = 0; /* One of the SRT_ operations to apply to self */
  105719. int priorOp; /* The SRT_ operation to apply to prior selects */
  105720. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  105721. int addr;
  105722. SelectDest uniondest;
  105723. testcase( p->op==TK_EXCEPT );
  105724. testcase( p->op==TK_UNION );
  105725. priorOp = SRT_Union;
  105726. if( dest.eDest==priorOp ){
  105727. /* We can reuse a temporary table generated by a SELECT to our
  105728. ** right.
  105729. */
  105730. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  105731. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  105732. unionTab = dest.iSDParm;
  105733. }else{
  105734. /* We will need to create our own temporary table to hold the
  105735. ** intermediate results.
  105736. */
  105737. unionTab = pParse->nTab++;
  105738. assert( p->pOrderBy==0 );
  105739. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  105740. assert( p->addrOpenEphm[0] == -1 );
  105741. p->addrOpenEphm[0] = addr;
  105742. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  105743. assert( p->pEList );
  105744. }
  105745. /* Code the SELECT statements to our left
  105746. */
  105747. assert( !pPrior->pOrderBy );
  105748. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  105749. explainSetInteger(iSub1, pParse->iNextSelectId);
  105750. rc = sqlite3Select(pParse, pPrior, &uniondest);
  105751. if( rc ){
  105752. goto multi_select_end;
  105753. }
  105754. /* Code the current SELECT statement
  105755. */
  105756. if( p->op==TK_EXCEPT ){
  105757. op = SRT_Except;
  105758. }else{
  105759. assert( p->op==TK_UNION );
  105760. op = SRT_Union;
  105761. }
  105762. p->pPrior = 0;
  105763. pLimit = p->pLimit;
  105764. p->pLimit = 0;
  105765. pOffset = p->pOffset;
  105766. p->pOffset = 0;
  105767. uniondest.eDest = op;
  105768. explainSetInteger(iSub2, pParse->iNextSelectId);
  105769. rc = sqlite3Select(pParse, p, &uniondest);
  105770. testcase( rc!=SQLITE_OK );
  105771. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  105772. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  105773. sqlite3ExprListDelete(db, p->pOrderBy);
  105774. pDelete = p->pPrior;
  105775. p->pPrior = pPrior;
  105776. p->pOrderBy = 0;
  105777. if( p->op==TK_UNION ){
  105778. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  105779. }
  105780. sqlite3ExprDelete(db, p->pLimit);
  105781. p->pLimit = pLimit;
  105782. p->pOffset = pOffset;
  105783. p->iLimit = 0;
  105784. p->iOffset = 0;
  105785. /* Convert the data in the temporary table into whatever form
  105786. ** it is that we currently need.
  105787. */
  105788. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  105789. if( dest.eDest!=priorOp ){
  105790. int iCont, iBreak, iStart;
  105791. assert( p->pEList );
  105792. if( dest.eDest==SRT_Output ){
  105793. Select *pFirst = p;
  105794. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  105795. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  105796. }
  105797. iBreak = sqlite3VdbeMakeLabel(v);
  105798. iCont = sqlite3VdbeMakeLabel(v);
  105799. computeLimitRegisters(pParse, p, iBreak);
  105800. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  105801. iStart = sqlite3VdbeCurrentAddr(v);
  105802. selectInnerLoop(pParse, p, p->pEList, unionTab,
  105803. 0, 0, &dest, iCont, iBreak);
  105804. sqlite3VdbeResolveLabel(v, iCont);
  105805. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  105806. sqlite3VdbeResolveLabel(v, iBreak);
  105807. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  105808. }
  105809. break;
  105810. }
  105811. default: assert( p->op==TK_INTERSECT ); {
  105812. int tab1, tab2;
  105813. int iCont, iBreak, iStart;
  105814. Expr *pLimit, *pOffset;
  105815. int addr;
  105816. SelectDest intersectdest;
  105817. int r1;
  105818. /* INTERSECT is different from the others since it requires
  105819. ** two temporary tables. Hence it has its own case. Begin
  105820. ** by allocating the tables we will need.
  105821. */
  105822. tab1 = pParse->nTab++;
  105823. tab2 = pParse->nTab++;
  105824. assert( p->pOrderBy==0 );
  105825. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  105826. assert( p->addrOpenEphm[0] == -1 );
  105827. p->addrOpenEphm[0] = addr;
  105828. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  105829. assert( p->pEList );
  105830. /* Code the SELECTs to our left into temporary table "tab1".
  105831. */
  105832. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  105833. explainSetInteger(iSub1, pParse->iNextSelectId);
  105834. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  105835. if( rc ){
  105836. goto multi_select_end;
  105837. }
  105838. /* Code the current SELECT into temporary table "tab2"
  105839. */
  105840. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  105841. assert( p->addrOpenEphm[1] == -1 );
  105842. p->addrOpenEphm[1] = addr;
  105843. p->pPrior = 0;
  105844. pLimit = p->pLimit;
  105845. p->pLimit = 0;
  105846. pOffset = p->pOffset;
  105847. p->pOffset = 0;
  105848. intersectdest.iSDParm = tab2;
  105849. explainSetInteger(iSub2, pParse->iNextSelectId);
  105850. rc = sqlite3Select(pParse, p, &intersectdest);
  105851. testcase( rc!=SQLITE_OK );
  105852. pDelete = p->pPrior;
  105853. p->pPrior = pPrior;
  105854. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  105855. sqlite3ExprDelete(db, p->pLimit);
  105856. p->pLimit = pLimit;
  105857. p->pOffset = pOffset;
  105858. /* Generate code to take the intersection of the two temporary
  105859. ** tables.
  105860. */
  105861. assert( p->pEList );
  105862. if( dest.eDest==SRT_Output ){
  105863. Select *pFirst = p;
  105864. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  105865. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  105866. }
  105867. iBreak = sqlite3VdbeMakeLabel(v);
  105868. iCont = sqlite3VdbeMakeLabel(v);
  105869. computeLimitRegisters(pParse, p, iBreak);
  105870. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  105871. r1 = sqlite3GetTempReg(pParse);
  105872. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  105873. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  105874. sqlite3ReleaseTempReg(pParse, r1);
  105875. selectInnerLoop(pParse, p, p->pEList, tab1,
  105876. 0, 0, &dest, iCont, iBreak);
  105877. sqlite3VdbeResolveLabel(v, iCont);
  105878. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  105879. sqlite3VdbeResolveLabel(v, iBreak);
  105880. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  105881. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  105882. break;
  105883. }
  105884. }
  105885. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  105886. /* Compute collating sequences used by
  105887. ** temporary tables needed to implement the compound select.
  105888. ** Attach the KeyInfo structure to all temporary tables.
  105889. **
  105890. ** This section is run by the right-most SELECT statement only.
  105891. ** SELECT statements to the left always skip this part. The right-most
  105892. ** SELECT might also skip this part if it has no ORDER BY clause and
  105893. ** no temp tables are required.
  105894. */
  105895. if( p->selFlags & SF_UsesEphemeral ){
  105896. int i; /* Loop counter */
  105897. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  105898. Select *pLoop; /* For looping through SELECT statements */
  105899. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  105900. int nCol; /* Number of columns in result set */
  105901. assert( p->pNext==0 );
  105902. nCol = p->pEList->nExpr;
  105903. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  105904. if( !pKeyInfo ){
  105905. rc = SQLITE_NOMEM_BKPT;
  105906. goto multi_select_end;
  105907. }
  105908. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  105909. *apColl = multiSelectCollSeq(pParse, p, i);
  105910. if( 0==*apColl ){
  105911. *apColl = db->pDfltColl;
  105912. }
  105913. }
  105914. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  105915. for(i=0; i<2; i++){
  105916. int addr = pLoop->addrOpenEphm[i];
  105917. if( addr<0 ){
  105918. /* If [0] is unused then [1] is also unused. So we can
  105919. ** always safely abort as soon as the first unused slot is found */
  105920. assert( pLoop->addrOpenEphm[1]<0 );
  105921. break;
  105922. }
  105923. sqlite3VdbeChangeP2(v, addr, nCol);
  105924. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  105925. P4_KEYINFO);
  105926. pLoop->addrOpenEphm[i] = -1;
  105927. }
  105928. }
  105929. sqlite3KeyInfoUnref(pKeyInfo);
  105930. }
  105931. multi_select_end:
  105932. pDest->iSdst = dest.iSdst;
  105933. pDest->nSdst = dest.nSdst;
  105934. sqlite3SelectDelete(db, pDelete);
  105935. return rc;
  105936. }
  105937. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  105938. /*
  105939. ** Error message for when two or more terms of a compound select have different
  105940. ** size result sets.
  105941. */
  105942. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  105943. if( p->selFlags & SF_Values ){
  105944. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  105945. }else{
  105946. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  105947. " do not have the same number of result columns", selectOpName(p->op));
  105948. }
  105949. }
  105950. /*
  105951. ** Code an output subroutine for a coroutine implementation of a
  105952. ** SELECT statment.
  105953. **
  105954. ** The data to be output is contained in pIn->iSdst. There are
  105955. ** pIn->nSdst columns to be output. pDest is where the output should
  105956. ** be sent.
  105957. **
  105958. ** regReturn is the number of the register holding the subroutine
  105959. ** return address.
  105960. **
  105961. ** If regPrev>0 then it is the first register in a vector that
  105962. ** records the previous output. mem[regPrev] is a flag that is false
  105963. ** if there has been no previous output. If regPrev>0 then code is
  105964. ** generated to suppress duplicates. pKeyInfo is used for comparing
  105965. ** keys.
  105966. **
  105967. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  105968. ** iBreak.
  105969. */
  105970. static int generateOutputSubroutine(
  105971. Parse *pParse, /* Parsing context */
  105972. Select *p, /* The SELECT statement */
  105973. SelectDest *pIn, /* Coroutine supplying data */
  105974. SelectDest *pDest, /* Where to send the data */
  105975. int regReturn, /* The return address register */
  105976. int regPrev, /* Previous result register. No uniqueness if 0 */
  105977. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  105978. int iBreak /* Jump here if we hit the LIMIT */
  105979. ){
  105980. Vdbe *v = pParse->pVdbe;
  105981. int iContinue;
  105982. int addr;
  105983. addr = sqlite3VdbeCurrentAddr(v);
  105984. iContinue = sqlite3VdbeMakeLabel(v);
  105985. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  105986. */
  105987. if( regPrev ){
  105988. int addr1, addr2;
  105989. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  105990. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  105991. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  105992. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  105993. sqlite3VdbeJumpHere(v, addr1);
  105994. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  105995. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  105996. }
  105997. if( pParse->db->mallocFailed ) return 0;
  105998. /* Suppress the first OFFSET entries if there is an OFFSET clause
  105999. */
  106000. codeOffset(v, p->iOffset, iContinue);
  106001. assert( pDest->eDest!=SRT_Exists );
  106002. assert( pDest->eDest!=SRT_Table );
  106003. switch( pDest->eDest ){
  106004. /* Store the result as data using a unique key.
  106005. */
  106006. case SRT_EphemTab: {
  106007. int r1 = sqlite3GetTempReg(pParse);
  106008. int r2 = sqlite3GetTempReg(pParse);
  106009. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  106010. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  106011. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  106012. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  106013. sqlite3ReleaseTempReg(pParse, r2);
  106014. sqlite3ReleaseTempReg(pParse, r1);
  106015. break;
  106016. }
  106017. #ifndef SQLITE_OMIT_SUBQUERY
  106018. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  106019. ** then there should be a single item on the stack. Write this
  106020. ** item into the set table with bogus data.
  106021. */
  106022. case SRT_Set: {
  106023. int r1;
  106024. assert( pIn->nSdst==1 || pParse->nErr>0 );
  106025. pDest->affSdst =
  106026. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  106027. r1 = sqlite3GetTempReg(pParse);
  106028. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  106029. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  106030. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  106031. sqlite3ReleaseTempReg(pParse, r1);
  106032. break;
  106033. }
  106034. /* If this is a scalar select that is part of an expression, then
  106035. ** store the results in the appropriate memory cell and break out
  106036. ** of the scan loop.
  106037. */
  106038. case SRT_Mem: {
  106039. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  106040. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  106041. /* The LIMIT clause will jump out of the loop for us */
  106042. break;
  106043. }
  106044. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  106045. /* The results are stored in a sequence of registers
  106046. ** starting at pDest->iSdst. Then the co-routine yields.
  106047. */
  106048. case SRT_Coroutine: {
  106049. if( pDest->iSdst==0 ){
  106050. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  106051. pDest->nSdst = pIn->nSdst;
  106052. }
  106053. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  106054. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  106055. break;
  106056. }
  106057. /* If none of the above, then the result destination must be
  106058. ** SRT_Output. This routine is never called with any other
  106059. ** destination other than the ones handled above or SRT_Output.
  106060. **
  106061. ** For SRT_Output, results are stored in a sequence of registers.
  106062. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  106063. ** return the next row of result.
  106064. */
  106065. default: {
  106066. assert( pDest->eDest==SRT_Output );
  106067. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  106068. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  106069. break;
  106070. }
  106071. }
  106072. /* Jump to the end of the loop if the LIMIT is reached.
  106073. */
  106074. if( p->iLimit ){
  106075. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  106076. }
  106077. /* Generate the subroutine return
  106078. */
  106079. sqlite3VdbeResolveLabel(v, iContinue);
  106080. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  106081. return addr;
  106082. }
  106083. /*
  106084. ** Alternative compound select code generator for cases when there
  106085. ** is an ORDER BY clause.
  106086. **
  106087. ** We assume a query of the following form:
  106088. **
  106089. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  106090. **
  106091. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  106092. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  106093. ** co-routines. Then run the co-routines in parallel and merge the results
  106094. ** into the output. In addition to the two coroutines (called selectA and
  106095. ** selectB) there are 7 subroutines:
  106096. **
  106097. ** outA: Move the output of the selectA coroutine into the output
  106098. ** of the compound query.
  106099. **
  106100. ** outB: Move the output of the selectB coroutine into the output
  106101. ** of the compound query. (Only generated for UNION and
  106102. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  106103. ** appears only in B.)
  106104. **
  106105. ** AltB: Called when there is data from both coroutines and A<B.
  106106. **
  106107. ** AeqB: Called when there is data from both coroutines and A==B.
  106108. **
  106109. ** AgtB: Called when there is data from both coroutines and A>B.
  106110. **
  106111. ** EofA: Called when data is exhausted from selectA.
  106112. **
  106113. ** EofB: Called when data is exhausted from selectB.
  106114. **
  106115. ** The implementation of the latter five subroutines depend on which
  106116. ** <operator> is used:
  106117. **
  106118. **
  106119. ** UNION ALL UNION EXCEPT INTERSECT
  106120. ** ------------- ----------------- -------------- -----------------
  106121. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  106122. **
  106123. ** AeqB: outA, nextA nextA nextA outA, nextA
  106124. **
  106125. ** AgtB: outB, nextB outB, nextB nextB nextB
  106126. **
  106127. ** EofA: outB, nextB outB, nextB halt halt
  106128. **
  106129. ** EofB: outA, nextA outA, nextA outA, nextA halt
  106130. **
  106131. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  106132. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  106133. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  106134. ** following nextX causes a jump to the end of the select processing.
  106135. **
  106136. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  106137. ** within the output subroutine. The regPrev register set holds the previously
  106138. ** output value. A comparison is made against this value and the output
  106139. ** is skipped if the next results would be the same as the previous.
  106140. **
  106141. ** The implementation plan is to implement the two coroutines and seven
  106142. ** subroutines first, then put the control logic at the bottom. Like this:
  106143. **
  106144. ** goto Init
  106145. ** coA: coroutine for left query (A)
  106146. ** coB: coroutine for right query (B)
  106147. ** outA: output one row of A
  106148. ** outB: output one row of B (UNION and UNION ALL only)
  106149. ** EofA: ...
  106150. ** EofB: ...
  106151. ** AltB: ...
  106152. ** AeqB: ...
  106153. ** AgtB: ...
  106154. ** Init: initialize coroutine registers
  106155. ** yield coA
  106156. ** if eof(A) goto EofA
  106157. ** yield coB
  106158. ** if eof(B) goto EofB
  106159. ** Cmpr: Compare A, B
  106160. ** Jump AltB, AeqB, AgtB
  106161. ** End: ...
  106162. **
  106163. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  106164. ** actually called using Gosub and they do not Return. EofA and EofB loop
  106165. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  106166. ** and AgtB jump to either L2 or to one of EofA or EofB.
  106167. */
  106168. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  106169. static int multiSelectOrderBy(
  106170. Parse *pParse, /* Parsing context */
  106171. Select *p, /* The right-most of SELECTs to be coded */
  106172. SelectDest *pDest /* What to do with query results */
  106173. ){
  106174. int i, j; /* Loop counters */
  106175. Select *pPrior; /* Another SELECT immediately to our left */
  106176. Vdbe *v; /* Generate code to this VDBE */
  106177. SelectDest destA; /* Destination for coroutine A */
  106178. SelectDest destB; /* Destination for coroutine B */
  106179. int regAddrA; /* Address register for select-A coroutine */
  106180. int regAddrB; /* Address register for select-B coroutine */
  106181. int addrSelectA; /* Address of the select-A coroutine */
  106182. int addrSelectB; /* Address of the select-B coroutine */
  106183. int regOutA; /* Address register for the output-A subroutine */
  106184. int regOutB; /* Address register for the output-B subroutine */
  106185. int addrOutA; /* Address of the output-A subroutine */
  106186. int addrOutB = 0; /* Address of the output-B subroutine */
  106187. int addrEofA; /* Address of the select-A-exhausted subroutine */
  106188. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  106189. int addrEofB; /* Address of the select-B-exhausted subroutine */
  106190. int addrAltB; /* Address of the A<B subroutine */
  106191. int addrAeqB; /* Address of the A==B subroutine */
  106192. int addrAgtB; /* Address of the A>B subroutine */
  106193. int regLimitA; /* Limit register for select-A */
  106194. int regLimitB; /* Limit register for select-A */
  106195. int regPrev; /* A range of registers to hold previous output */
  106196. int savedLimit; /* Saved value of p->iLimit */
  106197. int savedOffset; /* Saved value of p->iOffset */
  106198. int labelCmpr; /* Label for the start of the merge algorithm */
  106199. int labelEnd; /* Label for the end of the overall SELECT stmt */
  106200. int addr1; /* Jump instructions that get retargetted */
  106201. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  106202. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  106203. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  106204. sqlite3 *db; /* Database connection */
  106205. ExprList *pOrderBy; /* The ORDER BY clause */
  106206. int nOrderBy; /* Number of terms in the ORDER BY clause */
  106207. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  106208. #ifndef SQLITE_OMIT_EXPLAIN
  106209. int iSub1; /* EQP id of left-hand query */
  106210. int iSub2; /* EQP id of right-hand query */
  106211. #endif
  106212. assert( p->pOrderBy!=0 );
  106213. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  106214. db = pParse->db;
  106215. v = pParse->pVdbe;
  106216. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  106217. labelEnd = sqlite3VdbeMakeLabel(v);
  106218. labelCmpr = sqlite3VdbeMakeLabel(v);
  106219. /* Patch up the ORDER BY clause
  106220. */
  106221. op = p->op;
  106222. pPrior = p->pPrior;
  106223. assert( pPrior->pOrderBy==0 );
  106224. pOrderBy = p->pOrderBy;
  106225. assert( pOrderBy );
  106226. nOrderBy = pOrderBy->nExpr;
  106227. /* For operators other than UNION ALL we have to make sure that
  106228. ** the ORDER BY clause covers every term of the result set. Add
  106229. ** terms to the ORDER BY clause as necessary.
  106230. */
  106231. if( op!=TK_ALL ){
  106232. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  106233. struct ExprList_item *pItem;
  106234. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  106235. assert( pItem->u.x.iOrderByCol>0 );
  106236. if( pItem->u.x.iOrderByCol==i ) break;
  106237. }
  106238. if( j==nOrderBy ){
  106239. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  106240. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  106241. pNew->flags |= EP_IntValue;
  106242. pNew->u.iValue = i;
  106243. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  106244. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  106245. }
  106246. }
  106247. }
  106248. /* Compute the comparison permutation and keyinfo that is used with
  106249. ** the permutation used to determine if the next
  106250. ** row of results comes from selectA or selectB. Also add explicit
  106251. ** collations to the ORDER BY clause terms so that when the subqueries
  106252. ** to the right and the left are evaluated, they use the correct
  106253. ** collation.
  106254. */
  106255. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  106256. if( aPermute ){
  106257. struct ExprList_item *pItem;
  106258. aPermute[0] = nOrderBy;
  106259. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  106260. assert( pItem->u.x.iOrderByCol>0 );
  106261. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  106262. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  106263. }
  106264. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  106265. }else{
  106266. pKeyMerge = 0;
  106267. }
  106268. /* Reattach the ORDER BY clause to the query.
  106269. */
  106270. p->pOrderBy = pOrderBy;
  106271. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  106272. /* Allocate a range of temporary registers and the KeyInfo needed
  106273. ** for the logic that removes duplicate result rows when the
  106274. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  106275. */
  106276. if( op==TK_ALL ){
  106277. regPrev = 0;
  106278. }else{
  106279. int nExpr = p->pEList->nExpr;
  106280. assert( nOrderBy>=nExpr || db->mallocFailed );
  106281. regPrev = pParse->nMem+1;
  106282. pParse->nMem += nExpr+1;
  106283. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  106284. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  106285. if( pKeyDup ){
  106286. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  106287. for(i=0; i<nExpr; i++){
  106288. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  106289. pKeyDup->aSortOrder[i] = 0;
  106290. }
  106291. }
  106292. }
  106293. /* Separate the left and the right query from one another
  106294. */
  106295. p->pPrior = 0;
  106296. pPrior->pNext = 0;
  106297. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  106298. if( pPrior->pPrior==0 ){
  106299. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  106300. }
  106301. /* Compute the limit registers */
  106302. computeLimitRegisters(pParse, p, labelEnd);
  106303. if( p->iLimit && op==TK_ALL ){
  106304. regLimitA = ++pParse->nMem;
  106305. regLimitB = ++pParse->nMem;
  106306. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  106307. regLimitA);
  106308. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  106309. }else{
  106310. regLimitA = regLimitB = 0;
  106311. }
  106312. sqlite3ExprDelete(db, p->pLimit);
  106313. p->pLimit = 0;
  106314. sqlite3ExprDelete(db, p->pOffset);
  106315. p->pOffset = 0;
  106316. regAddrA = ++pParse->nMem;
  106317. regAddrB = ++pParse->nMem;
  106318. regOutA = ++pParse->nMem;
  106319. regOutB = ++pParse->nMem;
  106320. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  106321. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  106322. /* Generate a coroutine to evaluate the SELECT statement to the
  106323. ** left of the compound operator - the "A" select.
  106324. */
  106325. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  106326. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  106327. VdbeComment((v, "left SELECT"));
  106328. pPrior->iLimit = regLimitA;
  106329. explainSetInteger(iSub1, pParse->iNextSelectId);
  106330. sqlite3Select(pParse, pPrior, &destA);
  106331. sqlite3VdbeEndCoroutine(v, regAddrA);
  106332. sqlite3VdbeJumpHere(v, addr1);
  106333. /* Generate a coroutine to evaluate the SELECT statement on
  106334. ** the right - the "B" select
  106335. */
  106336. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  106337. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  106338. VdbeComment((v, "right SELECT"));
  106339. savedLimit = p->iLimit;
  106340. savedOffset = p->iOffset;
  106341. p->iLimit = regLimitB;
  106342. p->iOffset = 0;
  106343. explainSetInteger(iSub2, pParse->iNextSelectId);
  106344. sqlite3Select(pParse, p, &destB);
  106345. p->iLimit = savedLimit;
  106346. p->iOffset = savedOffset;
  106347. sqlite3VdbeEndCoroutine(v, regAddrB);
  106348. /* Generate a subroutine that outputs the current row of the A
  106349. ** select as the next output row of the compound select.
  106350. */
  106351. VdbeNoopComment((v, "Output routine for A"));
  106352. addrOutA = generateOutputSubroutine(pParse,
  106353. p, &destA, pDest, regOutA,
  106354. regPrev, pKeyDup, labelEnd);
  106355. /* Generate a subroutine that outputs the current row of the B
  106356. ** select as the next output row of the compound select.
  106357. */
  106358. if( op==TK_ALL || op==TK_UNION ){
  106359. VdbeNoopComment((v, "Output routine for B"));
  106360. addrOutB = generateOutputSubroutine(pParse,
  106361. p, &destB, pDest, regOutB,
  106362. regPrev, pKeyDup, labelEnd);
  106363. }
  106364. sqlite3KeyInfoUnref(pKeyDup);
  106365. /* Generate a subroutine to run when the results from select A
  106366. ** are exhausted and only data in select B remains.
  106367. */
  106368. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  106369. addrEofA_noB = addrEofA = labelEnd;
  106370. }else{
  106371. VdbeNoopComment((v, "eof-A subroutine"));
  106372. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  106373. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  106374. VdbeCoverage(v);
  106375. sqlite3VdbeGoto(v, addrEofA);
  106376. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  106377. }
  106378. /* Generate a subroutine to run when the results from select B
  106379. ** are exhausted and only data in select A remains.
  106380. */
  106381. if( op==TK_INTERSECT ){
  106382. addrEofB = addrEofA;
  106383. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  106384. }else{
  106385. VdbeNoopComment((v, "eof-B subroutine"));
  106386. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  106387. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  106388. sqlite3VdbeGoto(v, addrEofB);
  106389. }
  106390. /* Generate code to handle the case of A<B
  106391. */
  106392. VdbeNoopComment((v, "A-lt-B subroutine"));
  106393. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  106394. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  106395. sqlite3VdbeGoto(v, labelCmpr);
  106396. /* Generate code to handle the case of A==B
  106397. */
  106398. if( op==TK_ALL ){
  106399. addrAeqB = addrAltB;
  106400. }else if( op==TK_INTERSECT ){
  106401. addrAeqB = addrAltB;
  106402. addrAltB++;
  106403. }else{
  106404. VdbeNoopComment((v, "A-eq-B subroutine"));
  106405. addrAeqB =
  106406. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  106407. sqlite3VdbeGoto(v, labelCmpr);
  106408. }
  106409. /* Generate code to handle the case of A>B
  106410. */
  106411. VdbeNoopComment((v, "A-gt-B subroutine"));
  106412. addrAgtB = sqlite3VdbeCurrentAddr(v);
  106413. if( op==TK_ALL || op==TK_UNION ){
  106414. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  106415. }
  106416. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  106417. sqlite3VdbeGoto(v, labelCmpr);
  106418. /* This code runs once to initialize everything.
  106419. */
  106420. sqlite3VdbeJumpHere(v, addr1);
  106421. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  106422. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  106423. /* Implement the main merge loop
  106424. */
  106425. sqlite3VdbeResolveLabel(v, labelCmpr);
  106426. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  106427. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  106428. (char*)pKeyMerge, P4_KEYINFO);
  106429. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  106430. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  106431. /* Jump to the this point in order to terminate the query.
  106432. */
  106433. sqlite3VdbeResolveLabel(v, labelEnd);
  106434. /* Set the number of output columns
  106435. */
  106436. if( pDest->eDest==SRT_Output ){
  106437. Select *pFirst = pPrior;
  106438. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  106439. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  106440. }
  106441. /* Reassembly the compound query so that it will be freed correctly
  106442. ** by the calling function */
  106443. if( p->pPrior ){
  106444. sqlite3SelectDelete(db, p->pPrior);
  106445. }
  106446. p->pPrior = pPrior;
  106447. pPrior->pNext = p;
  106448. /*** TBD: Insert subroutine calls to close cursors on incomplete
  106449. **** subqueries ****/
  106450. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  106451. return pParse->nErr!=0;
  106452. }
  106453. #endif
  106454. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  106455. /* Forward Declarations */
  106456. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  106457. static void substSelect(sqlite3*, Select *, int, ExprList*, int);
  106458. /*
  106459. ** Scan through the expression pExpr. Replace every reference to
  106460. ** a column in table number iTable with a copy of the iColumn-th
  106461. ** entry in pEList. (But leave references to the ROWID column
  106462. ** unchanged.)
  106463. **
  106464. ** This routine is part of the flattening procedure. A subquery
  106465. ** whose result set is defined by pEList appears as entry in the
  106466. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  106467. ** FORM clause entry is iTable. This routine make the necessary
  106468. ** changes to pExpr so that it refers directly to the source table
  106469. ** of the subquery rather the result set of the subquery.
  106470. */
  106471. static Expr *substExpr(
  106472. sqlite3 *db, /* Report malloc errors to this connection */
  106473. Expr *pExpr, /* Expr in which substitution occurs */
  106474. int iTable, /* Table to be substituted */
  106475. ExprList *pEList /* Substitute expressions */
  106476. ){
  106477. if( pExpr==0 ) return 0;
  106478. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  106479. if( pExpr->iColumn<0 ){
  106480. pExpr->op = TK_NULL;
  106481. }else{
  106482. Expr *pNew;
  106483. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  106484. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  106485. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  106486. sqlite3ExprDelete(db, pExpr);
  106487. pExpr = pNew;
  106488. }
  106489. }else{
  106490. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  106491. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  106492. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  106493. substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
  106494. }else{
  106495. substExprList(db, pExpr->x.pList, iTable, pEList);
  106496. }
  106497. }
  106498. return pExpr;
  106499. }
  106500. static void substExprList(
  106501. sqlite3 *db, /* Report malloc errors here */
  106502. ExprList *pList, /* List to scan and in which to make substitutes */
  106503. int iTable, /* Table to be substituted */
  106504. ExprList *pEList /* Substitute values */
  106505. ){
  106506. int i;
  106507. if( pList==0 ) return;
  106508. for(i=0; i<pList->nExpr; i++){
  106509. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  106510. }
  106511. }
  106512. static void substSelect(
  106513. sqlite3 *db, /* Report malloc errors here */
  106514. Select *p, /* SELECT statement in which to make substitutions */
  106515. int iTable, /* Table to be replaced */
  106516. ExprList *pEList, /* Substitute values */
  106517. int doPrior /* Do substitutes on p->pPrior too */
  106518. ){
  106519. SrcList *pSrc;
  106520. struct SrcList_item *pItem;
  106521. int i;
  106522. if( !p ) return;
  106523. do{
  106524. substExprList(db, p->pEList, iTable, pEList);
  106525. substExprList(db, p->pGroupBy, iTable, pEList);
  106526. substExprList(db, p->pOrderBy, iTable, pEList);
  106527. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  106528. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  106529. pSrc = p->pSrc;
  106530. assert( pSrc!=0 );
  106531. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  106532. substSelect(db, pItem->pSelect, iTable, pEList, 1);
  106533. if( pItem->fg.isTabFunc ){
  106534. substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
  106535. }
  106536. }
  106537. }while( doPrior && (p = p->pPrior)!=0 );
  106538. }
  106539. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  106540. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  106541. /*
  106542. ** This routine attempts to flatten subqueries as a performance optimization.
  106543. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  106544. **
  106545. ** To understand the concept of flattening, consider the following
  106546. ** query:
  106547. **
  106548. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  106549. **
  106550. ** The default way of implementing this query is to execute the
  106551. ** subquery first and store the results in a temporary table, then
  106552. ** run the outer query on that temporary table. This requires two
  106553. ** passes over the data. Furthermore, because the temporary table
  106554. ** has no indices, the WHERE clause on the outer query cannot be
  106555. ** optimized.
  106556. **
  106557. ** This routine attempts to rewrite queries such as the above into
  106558. ** a single flat select, like this:
  106559. **
  106560. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  106561. **
  106562. ** The code generated for this simplification gives the same result
  106563. ** but only has to scan the data once. And because indices might
  106564. ** exist on the table t1, a complete scan of the data might be
  106565. ** avoided.
  106566. **
  106567. ** Flattening is only attempted if all of the following are true:
  106568. **
  106569. ** (1) The subquery and the outer query do not both use aggregates.
  106570. **
  106571. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  106572. ** and (2b) the outer query does not use subqueries other than the one
  106573. ** FROM-clause subquery that is a candidate for flattening. (2b is
  106574. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  106575. **
  106576. ** (3) The subquery is not the right operand of a left outer join
  106577. ** (Originally ticket #306. Strengthened by ticket #3300)
  106578. **
  106579. ** (4) The subquery is not DISTINCT.
  106580. **
  106581. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  106582. ** sub-queries that were excluded from this optimization. Restriction
  106583. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  106584. **
  106585. ** (6) The subquery does not use aggregates or the outer query is not
  106586. ** DISTINCT.
  106587. **
  106588. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  106589. ** A FROM clause, consider adding a FROM close with the special
  106590. ** table sqlite_once that consists of a single row containing a
  106591. ** single NULL.
  106592. **
  106593. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  106594. **
  106595. ** (9) The subquery does not use LIMIT or the outer query does not use
  106596. ** aggregates.
  106597. **
  106598. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  106599. ** accidently carried the comment forward until 2014-09-15. Original
  106600. ** text: "The subquery does not use aggregates or the outer query
  106601. ** does not use LIMIT."
  106602. **
  106603. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  106604. **
  106605. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  106606. ** a separate restriction deriving from ticket #350.
  106607. **
  106608. ** (13) The subquery and outer query do not both use LIMIT.
  106609. **
  106610. ** (14) The subquery does not use OFFSET.
  106611. **
  106612. ** (15) The outer query is not part of a compound select or the
  106613. ** subquery does not have a LIMIT clause.
  106614. ** (See ticket #2339 and ticket [02a8e81d44]).
  106615. **
  106616. ** (16) The outer query is not an aggregate or the subquery does
  106617. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  106618. ** until we introduced the group_concat() function.
  106619. **
  106620. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  106621. ** compound clause made up entirely of non-aggregate queries, and
  106622. ** the parent query:
  106623. **
  106624. ** * is not itself part of a compound select,
  106625. ** * is not an aggregate or DISTINCT query, and
  106626. ** * is not a join
  106627. **
  106628. ** The parent and sub-query may contain WHERE clauses. Subject to
  106629. ** rules (11), (13) and (14), they may also contain ORDER BY,
  106630. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  106631. ** operator other than UNION ALL because all the other compound
  106632. ** operators have an implied DISTINCT which is disallowed by
  106633. ** restriction (4).
  106634. **
  106635. ** Also, each component of the sub-query must return the same number
  106636. ** of result columns. This is actually a requirement for any compound
  106637. ** SELECT statement, but all the code here does is make sure that no
  106638. ** such (illegal) sub-query is flattened. The caller will detect the
  106639. ** syntax error and return a detailed message.
  106640. **
  106641. ** (18) If the sub-query is a compound select, then all terms of the
  106642. ** ORDER by clause of the parent must be simple references to
  106643. ** columns of the sub-query.
  106644. **
  106645. ** (19) The subquery does not use LIMIT or the outer query does not
  106646. ** have a WHERE clause.
  106647. **
  106648. ** (20) If the sub-query is a compound select, then it must not use
  106649. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  106650. ** somewhat by saying that the terms of the ORDER BY clause must
  106651. ** appear as unmodified result columns in the outer query. But we
  106652. ** have other optimizations in mind to deal with that case.
  106653. **
  106654. ** (21) The subquery does not use LIMIT or the outer query is not
  106655. ** DISTINCT. (See ticket [752e1646fc]).
  106656. **
  106657. ** (22) The subquery is not a recursive CTE.
  106658. **
  106659. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  106660. ** compound query. This restriction is because transforming the
  106661. ** parent to a compound query confuses the code that handles
  106662. ** recursive queries in multiSelect().
  106663. **
  106664. ** (24) The subquery is not an aggregate that uses the built-in min() or
  106665. ** or max() functions. (Without this restriction, a query like:
  106666. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  106667. ** return the value X for which Y was maximal.)
  106668. **
  106669. **
  106670. ** In this routine, the "p" parameter is a pointer to the outer query.
  106671. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  106672. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  106673. **
  106674. ** If flattening is not attempted, this routine is a no-op and returns 0.
  106675. ** If flattening is attempted this routine returns 1.
  106676. **
  106677. ** All of the expression analysis must occur on both the outer query and
  106678. ** the subquery before this routine runs.
  106679. */
  106680. static int flattenSubquery(
  106681. Parse *pParse, /* Parsing context */
  106682. Select *p, /* The parent or outer SELECT statement */
  106683. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  106684. int isAgg, /* True if outer SELECT uses aggregate functions */
  106685. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  106686. ){
  106687. const char *zSavedAuthContext = pParse->zAuthContext;
  106688. Select *pParent; /* Current UNION ALL term of the other query */
  106689. Select *pSub; /* The inner query or "subquery" */
  106690. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  106691. SrcList *pSrc; /* The FROM clause of the outer query */
  106692. SrcList *pSubSrc; /* The FROM clause of the subquery */
  106693. ExprList *pList; /* The result set of the outer query */
  106694. int iParent; /* VDBE cursor number of the pSub result set temp table */
  106695. int i; /* Loop counter */
  106696. Expr *pWhere; /* The WHERE clause */
  106697. struct SrcList_item *pSubitem; /* The subquery */
  106698. sqlite3 *db = pParse->db;
  106699. /* Check to see if flattening is permitted. Return 0 if not.
  106700. */
  106701. assert( p!=0 );
  106702. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  106703. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  106704. pSrc = p->pSrc;
  106705. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  106706. pSubitem = &pSrc->a[iFrom];
  106707. iParent = pSubitem->iCursor;
  106708. pSub = pSubitem->pSelect;
  106709. assert( pSub!=0 );
  106710. if( subqueryIsAgg ){
  106711. if( isAgg ) return 0; /* Restriction (1) */
  106712. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  106713. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  106714. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  106715. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  106716. ){
  106717. return 0; /* Restriction (2b) */
  106718. }
  106719. }
  106720. pSubSrc = pSub->pSrc;
  106721. assert( pSubSrc );
  106722. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  106723. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  106724. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  106725. ** became arbitrary expressions, we were forced to add restrictions (13)
  106726. ** and (14). */
  106727. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  106728. if( pSub->pOffset ) return 0; /* Restriction (14) */
  106729. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  106730. return 0; /* Restriction (15) */
  106731. }
  106732. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  106733. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  106734. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  106735. return 0; /* Restrictions (8)(9) */
  106736. }
  106737. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  106738. return 0; /* Restriction (6) */
  106739. }
  106740. if( p->pOrderBy && pSub->pOrderBy ){
  106741. return 0; /* Restriction (11) */
  106742. }
  106743. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  106744. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  106745. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  106746. return 0; /* Restriction (21) */
  106747. }
  106748. testcase( pSub->selFlags & SF_Recursive );
  106749. testcase( pSub->selFlags & SF_MinMaxAgg );
  106750. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  106751. return 0; /* Restrictions (22) and (24) */
  106752. }
  106753. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  106754. return 0; /* Restriction (23) */
  106755. }
  106756. /* OBSOLETE COMMENT 1:
  106757. ** Restriction 3: If the subquery is a join, make sure the subquery is
  106758. ** not used as the right operand of an outer join. Examples of why this
  106759. ** is not allowed:
  106760. **
  106761. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  106762. **
  106763. ** If we flatten the above, we would get
  106764. **
  106765. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  106766. **
  106767. ** which is not at all the same thing.
  106768. **
  106769. ** OBSOLETE COMMENT 2:
  106770. ** Restriction 12: If the subquery is the right operand of a left outer
  106771. ** join, make sure the subquery has no WHERE clause.
  106772. ** An examples of why this is not allowed:
  106773. **
  106774. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  106775. **
  106776. ** If we flatten the above, we would get
  106777. **
  106778. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  106779. **
  106780. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  106781. ** effectively converts the OUTER JOIN into an INNER JOIN.
  106782. **
  106783. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  106784. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  106785. ** is fraught with danger. Best to avoid the whole thing. If the
  106786. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  106787. */
  106788. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  106789. return 0;
  106790. }
  106791. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  106792. ** use only the UNION ALL operator. And none of the simple select queries
  106793. ** that make up the compound SELECT are allowed to be aggregate or distinct
  106794. ** queries.
  106795. */
  106796. if( pSub->pPrior ){
  106797. if( pSub->pOrderBy ){
  106798. return 0; /* Restriction 20 */
  106799. }
  106800. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  106801. return 0;
  106802. }
  106803. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  106804. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  106805. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  106806. assert( pSub->pSrc!=0 );
  106807. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  106808. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  106809. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  106810. || pSub1->pSrc->nSrc<1
  106811. ){
  106812. return 0;
  106813. }
  106814. testcase( pSub1->pSrc->nSrc>1 );
  106815. }
  106816. /* Restriction 18. */
  106817. if( p->pOrderBy ){
  106818. int ii;
  106819. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  106820. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  106821. }
  106822. }
  106823. }
  106824. /***** If we reach this point, flattening is permitted. *****/
  106825. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  106826. pSub->zSelName, pSub, iFrom));
  106827. /* Authorize the subquery */
  106828. pParse->zAuthContext = pSubitem->zName;
  106829. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  106830. testcase( i==SQLITE_DENY );
  106831. pParse->zAuthContext = zSavedAuthContext;
  106832. /* If the sub-query is a compound SELECT statement, then (by restrictions
  106833. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  106834. ** be of the form:
  106835. **
  106836. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  106837. **
  106838. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  106839. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  106840. ** OFFSET clauses and joins them to the left-hand-side of the original
  106841. ** using UNION ALL operators. In this case N is the number of simple
  106842. ** select statements in the compound sub-query.
  106843. **
  106844. ** Example:
  106845. **
  106846. ** SELECT a+1 FROM (
  106847. ** SELECT x FROM tab
  106848. ** UNION ALL
  106849. ** SELECT y FROM tab
  106850. ** UNION ALL
  106851. ** SELECT abs(z*2) FROM tab2
  106852. ** ) WHERE a!=5 ORDER BY 1
  106853. **
  106854. ** Transformed into:
  106855. **
  106856. ** SELECT x+1 FROM tab WHERE x+1!=5
  106857. ** UNION ALL
  106858. ** SELECT y+1 FROM tab WHERE y+1!=5
  106859. ** UNION ALL
  106860. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  106861. ** ORDER BY 1
  106862. **
  106863. ** We call this the "compound-subquery flattening".
  106864. */
  106865. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  106866. Select *pNew;
  106867. ExprList *pOrderBy = p->pOrderBy;
  106868. Expr *pLimit = p->pLimit;
  106869. Expr *pOffset = p->pOffset;
  106870. Select *pPrior = p->pPrior;
  106871. p->pOrderBy = 0;
  106872. p->pSrc = 0;
  106873. p->pPrior = 0;
  106874. p->pLimit = 0;
  106875. p->pOffset = 0;
  106876. pNew = sqlite3SelectDup(db, p, 0);
  106877. sqlite3SelectSetName(pNew, pSub->zSelName);
  106878. p->pOffset = pOffset;
  106879. p->pLimit = pLimit;
  106880. p->pOrderBy = pOrderBy;
  106881. p->pSrc = pSrc;
  106882. p->op = TK_ALL;
  106883. if( pNew==0 ){
  106884. p->pPrior = pPrior;
  106885. }else{
  106886. pNew->pPrior = pPrior;
  106887. if( pPrior ) pPrior->pNext = pNew;
  106888. pNew->pNext = p;
  106889. p->pPrior = pNew;
  106890. SELECTTRACE(2,pParse,p,
  106891. ("compound-subquery flattener creates %s.%p as peer\n",
  106892. pNew->zSelName, pNew));
  106893. }
  106894. if( db->mallocFailed ) return 1;
  106895. }
  106896. /* Begin flattening the iFrom-th entry of the FROM clause
  106897. ** in the outer query.
  106898. */
  106899. pSub = pSub1 = pSubitem->pSelect;
  106900. /* Delete the transient table structure associated with the
  106901. ** subquery
  106902. */
  106903. sqlite3DbFree(db, pSubitem->zDatabase);
  106904. sqlite3DbFree(db, pSubitem->zName);
  106905. sqlite3DbFree(db, pSubitem->zAlias);
  106906. pSubitem->zDatabase = 0;
  106907. pSubitem->zName = 0;
  106908. pSubitem->zAlias = 0;
  106909. pSubitem->pSelect = 0;
  106910. /* Defer deleting the Table object associated with the
  106911. ** subquery until code generation is
  106912. ** complete, since there may still exist Expr.pTab entries that
  106913. ** refer to the subquery even after flattening. Ticket #3346.
  106914. **
  106915. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  106916. */
  106917. if( ALWAYS(pSubitem->pTab!=0) ){
  106918. Table *pTabToDel = pSubitem->pTab;
  106919. if( pTabToDel->nRef==1 ){
  106920. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  106921. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  106922. pToplevel->pZombieTab = pTabToDel;
  106923. }else{
  106924. pTabToDel->nRef--;
  106925. }
  106926. pSubitem->pTab = 0;
  106927. }
  106928. /* The following loop runs once for each term in a compound-subquery
  106929. ** flattening (as described above). If we are doing a different kind
  106930. ** of flattening - a flattening other than a compound-subquery flattening -
  106931. ** then this loop only runs once.
  106932. **
  106933. ** This loop moves all of the FROM elements of the subquery into the
  106934. ** the FROM clause of the outer query. Before doing this, remember
  106935. ** the cursor number for the original outer query FROM element in
  106936. ** iParent. The iParent cursor will never be used. Subsequent code
  106937. ** will scan expressions looking for iParent references and replace
  106938. ** those references with expressions that resolve to the subquery FROM
  106939. ** elements we are now copying in.
  106940. */
  106941. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  106942. int nSubSrc;
  106943. u8 jointype = 0;
  106944. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  106945. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  106946. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  106947. if( pSrc ){
  106948. assert( pParent==p ); /* First time through the loop */
  106949. jointype = pSubitem->fg.jointype;
  106950. }else{
  106951. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  106952. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  106953. if( pSrc==0 ){
  106954. assert( db->mallocFailed );
  106955. break;
  106956. }
  106957. }
  106958. /* The subquery uses a single slot of the FROM clause of the outer
  106959. ** query. If the subquery has more than one element in its FROM clause,
  106960. ** then expand the outer query to make space for it to hold all elements
  106961. ** of the subquery.
  106962. **
  106963. ** Example:
  106964. **
  106965. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  106966. **
  106967. ** The outer query has 3 slots in its FROM clause. One slot of the
  106968. ** outer query (the middle slot) is used by the subquery. The next
  106969. ** block of code will expand the outer query FROM clause to 4 slots.
  106970. ** The middle slot is expanded to two slots in order to make space
  106971. ** for the two elements in the FROM clause of the subquery.
  106972. */
  106973. if( nSubSrc>1 ){
  106974. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  106975. if( db->mallocFailed ){
  106976. break;
  106977. }
  106978. }
  106979. /* Transfer the FROM clause terms from the subquery into the
  106980. ** outer query.
  106981. */
  106982. for(i=0; i<nSubSrc; i++){
  106983. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  106984. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  106985. pSrc->a[i+iFrom] = pSubSrc->a[i];
  106986. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  106987. }
  106988. pSrc->a[iFrom].fg.jointype = jointype;
  106989. /* Now begin substituting subquery result set expressions for
  106990. ** references to the iParent in the outer query.
  106991. **
  106992. ** Example:
  106993. **
  106994. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  106995. ** \ \_____________ subquery __________/ /
  106996. ** \_____________________ outer query ______________________________/
  106997. **
  106998. ** We look at every expression in the outer query and every place we see
  106999. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  107000. */
  107001. pList = pParent->pEList;
  107002. for(i=0; i<pList->nExpr; i++){
  107003. if( pList->a[i].zName==0 ){
  107004. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  107005. sqlite3Dequote(zName);
  107006. pList->a[i].zName = zName;
  107007. }
  107008. }
  107009. if( pSub->pOrderBy ){
  107010. /* At this point, any non-zero iOrderByCol values indicate that the
  107011. ** ORDER BY column expression is identical to the iOrderByCol'th
  107012. ** expression returned by SELECT statement pSub. Since these values
  107013. ** do not necessarily correspond to columns in SELECT statement pParent,
  107014. ** zero them before transfering the ORDER BY clause.
  107015. **
  107016. ** Not doing this may cause an error if a subsequent call to this
  107017. ** function attempts to flatten a compound sub-query into pParent
  107018. ** (the only way this can happen is if the compound sub-query is
  107019. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  107020. ExprList *pOrderBy = pSub->pOrderBy;
  107021. for(i=0; i<pOrderBy->nExpr; i++){
  107022. pOrderBy->a[i].u.x.iOrderByCol = 0;
  107023. }
  107024. assert( pParent->pOrderBy==0 );
  107025. assert( pSub->pPrior==0 );
  107026. pParent->pOrderBy = pOrderBy;
  107027. pSub->pOrderBy = 0;
  107028. }
  107029. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  107030. if( subqueryIsAgg ){
  107031. assert( pParent->pHaving==0 );
  107032. pParent->pHaving = pParent->pWhere;
  107033. pParent->pWhere = pWhere;
  107034. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  107035. sqlite3ExprDup(db, pSub->pHaving, 0));
  107036. assert( pParent->pGroupBy==0 );
  107037. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  107038. }else{
  107039. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  107040. }
  107041. substSelect(db, pParent, iParent, pSub->pEList, 0);
  107042. /* The flattened query is distinct if either the inner or the
  107043. ** outer query is distinct.
  107044. */
  107045. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  107046. /*
  107047. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  107048. **
  107049. ** One is tempted to try to add a and b to combine the limits. But this
  107050. ** does not work if either limit is negative.
  107051. */
  107052. if( pSub->pLimit ){
  107053. pParent->pLimit = pSub->pLimit;
  107054. pSub->pLimit = 0;
  107055. }
  107056. }
  107057. /* Finially, delete what is left of the subquery and return
  107058. ** success.
  107059. */
  107060. sqlite3SelectDelete(db, pSub1);
  107061. #if SELECTTRACE_ENABLED
  107062. if( sqlite3SelectTrace & 0x100 ){
  107063. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  107064. sqlite3TreeViewSelect(0, p, 0);
  107065. }
  107066. #endif
  107067. return 1;
  107068. }
  107069. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  107070. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  107071. /*
  107072. ** Make copies of relevant WHERE clause terms of the outer query into
  107073. ** the WHERE clause of subquery. Example:
  107074. **
  107075. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  107076. **
  107077. ** Transformed into:
  107078. **
  107079. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  107080. ** WHERE x=5 AND y=10;
  107081. **
  107082. ** The hope is that the terms added to the inner query will make it more
  107083. ** efficient.
  107084. **
  107085. ** Do not attempt this optimization if:
  107086. **
  107087. ** (1) The inner query is an aggregate. (In that case, we'd really want
  107088. ** to copy the outer WHERE-clause terms onto the HAVING clause of the
  107089. ** inner query. But they probably won't help there so do not bother.)
  107090. **
  107091. ** (2) The inner query is the recursive part of a common table expression.
  107092. **
  107093. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  107094. ** close would change the meaning of the LIMIT).
  107095. **
  107096. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  107097. ** enforces this restriction since this routine does not have enough
  107098. ** information to know.)
  107099. **
  107100. ** (5) The WHERE clause expression originates in the ON or USING clause
  107101. ** of a LEFT JOIN.
  107102. **
  107103. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  107104. ** terms are duplicated into the subquery.
  107105. */
  107106. static int pushDownWhereTerms(
  107107. sqlite3 *db, /* The database connection (for malloc()) */
  107108. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  107109. Expr *pWhere, /* The WHERE clause of the outer query */
  107110. int iCursor /* Cursor number of the subquery */
  107111. ){
  107112. Expr *pNew;
  107113. int nChng = 0;
  107114. if( pWhere==0 ) return 0;
  107115. if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
  107116. return 0; /* restrictions (1) and (2) */
  107117. }
  107118. if( pSubq->pLimit!=0 ){
  107119. return 0; /* restriction (3) */
  107120. }
  107121. while( pWhere->op==TK_AND ){
  107122. nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
  107123. pWhere = pWhere->pLeft;
  107124. }
  107125. if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
  107126. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  107127. nChng++;
  107128. while( pSubq ){
  107129. pNew = sqlite3ExprDup(db, pWhere, 0);
  107130. pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
  107131. pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
  107132. pSubq = pSubq->pPrior;
  107133. }
  107134. }
  107135. return nChng;
  107136. }
  107137. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  107138. /*
  107139. ** Based on the contents of the AggInfo structure indicated by the first
  107140. ** argument, this function checks if the following are true:
  107141. **
  107142. ** * the query contains just a single aggregate function,
  107143. ** * the aggregate function is either min() or max(), and
  107144. ** * the argument to the aggregate function is a column value.
  107145. **
  107146. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  107147. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  107148. ** list of arguments passed to the aggregate before returning.
  107149. **
  107150. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  107151. ** WHERE_ORDERBY_NORMAL is returned.
  107152. */
  107153. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  107154. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  107155. *ppMinMax = 0;
  107156. if( pAggInfo->nFunc==1 ){
  107157. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  107158. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  107159. assert( pExpr->op==TK_AGG_FUNCTION );
  107160. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  107161. const char *zFunc = pExpr->u.zToken;
  107162. if( sqlite3StrICmp(zFunc, "min")==0 ){
  107163. eRet = WHERE_ORDERBY_MIN;
  107164. *ppMinMax = pEList;
  107165. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  107166. eRet = WHERE_ORDERBY_MAX;
  107167. *ppMinMax = pEList;
  107168. }
  107169. }
  107170. }
  107171. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  107172. return eRet;
  107173. }
  107174. /*
  107175. ** The select statement passed as the first argument is an aggregate query.
  107176. ** The second argument is the associated aggregate-info object. This
  107177. ** function tests if the SELECT is of the form:
  107178. **
  107179. ** SELECT count(*) FROM <tbl>
  107180. **
  107181. ** where table is a database table, not a sub-select or view. If the query
  107182. ** does match this pattern, then a pointer to the Table object representing
  107183. ** <tbl> is returned. Otherwise, 0 is returned.
  107184. */
  107185. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  107186. Table *pTab;
  107187. Expr *pExpr;
  107188. assert( !p->pGroupBy );
  107189. if( p->pWhere || p->pEList->nExpr!=1
  107190. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  107191. ){
  107192. return 0;
  107193. }
  107194. pTab = p->pSrc->a[0].pTab;
  107195. pExpr = p->pEList->a[0].pExpr;
  107196. assert( pTab && !pTab->pSelect && pExpr );
  107197. if( IsVirtual(pTab) ) return 0;
  107198. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  107199. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  107200. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  107201. if( pExpr->flags&EP_Distinct ) return 0;
  107202. return pTab;
  107203. }
  107204. /*
  107205. ** If the source-list item passed as an argument was augmented with an
  107206. ** INDEXED BY clause, then try to locate the specified index. If there
  107207. ** was such a clause and the named index cannot be found, return
  107208. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  107209. ** pFrom->pIndex and return SQLITE_OK.
  107210. */
  107211. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  107212. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  107213. Table *pTab = pFrom->pTab;
  107214. char *zIndexedBy = pFrom->u1.zIndexedBy;
  107215. Index *pIdx;
  107216. for(pIdx=pTab->pIndex;
  107217. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  107218. pIdx=pIdx->pNext
  107219. );
  107220. if( !pIdx ){
  107221. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  107222. pParse->checkSchema = 1;
  107223. return SQLITE_ERROR;
  107224. }
  107225. pFrom->pIBIndex = pIdx;
  107226. }
  107227. return SQLITE_OK;
  107228. }
  107229. /*
  107230. ** Detect compound SELECT statements that use an ORDER BY clause with
  107231. ** an alternative collating sequence.
  107232. **
  107233. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  107234. **
  107235. ** These are rewritten as a subquery:
  107236. **
  107237. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  107238. ** ORDER BY ... COLLATE ...
  107239. **
  107240. ** This transformation is necessary because the multiSelectOrderBy() routine
  107241. ** above that generates the code for a compound SELECT with an ORDER BY clause
  107242. ** uses a merge algorithm that requires the same collating sequence on the
  107243. ** result columns as on the ORDER BY clause. See ticket
  107244. ** http://www.sqlite.org/src/info/6709574d2a
  107245. **
  107246. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  107247. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  107248. ** there are COLLATE terms in the ORDER BY.
  107249. */
  107250. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  107251. int i;
  107252. Select *pNew;
  107253. Select *pX;
  107254. sqlite3 *db;
  107255. struct ExprList_item *a;
  107256. SrcList *pNewSrc;
  107257. Parse *pParse;
  107258. Token dummy;
  107259. if( p->pPrior==0 ) return WRC_Continue;
  107260. if( p->pOrderBy==0 ) return WRC_Continue;
  107261. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  107262. if( pX==0 ) return WRC_Continue;
  107263. a = p->pOrderBy->a;
  107264. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  107265. if( a[i].pExpr->flags & EP_Collate ) break;
  107266. }
  107267. if( i<0 ) return WRC_Continue;
  107268. /* If we reach this point, that means the transformation is required. */
  107269. pParse = pWalker->pParse;
  107270. db = pParse->db;
  107271. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  107272. if( pNew==0 ) return WRC_Abort;
  107273. memset(&dummy, 0, sizeof(dummy));
  107274. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  107275. if( pNewSrc==0 ) return WRC_Abort;
  107276. *pNew = *p;
  107277. p->pSrc = pNewSrc;
  107278. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  107279. p->op = TK_SELECT;
  107280. p->pWhere = 0;
  107281. pNew->pGroupBy = 0;
  107282. pNew->pHaving = 0;
  107283. pNew->pOrderBy = 0;
  107284. p->pPrior = 0;
  107285. p->pNext = 0;
  107286. p->pWith = 0;
  107287. p->selFlags &= ~SF_Compound;
  107288. assert( (p->selFlags & SF_Converted)==0 );
  107289. p->selFlags |= SF_Converted;
  107290. assert( pNew->pPrior!=0 );
  107291. pNew->pPrior->pNext = pNew;
  107292. pNew->pLimit = 0;
  107293. pNew->pOffset = 0;
  107294. return WRC_Continue;
  107295. }
  107296. /*
  107297. ** Check to see if the FROM clause term pFrom has table-valued function
  107298. ** arguments. If it does, leave an error message in pParse and return
  107299. ** non-zero, since pFrom is not allowed to be a table-valued function.
  107300. */
  107301. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  107302. if( pFrom->fg.isTabFunc ){
  107303. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  107304. return 1;
  107305. }
  107306. return 0;
  107307. }
  107308. #ifndef SQLITE_OMIT_CTE
  107309. /*
  107310. ** Argument pWith (which may be NULL) points to a linked list of nested
  107311. ** WITH contexts, from inner to outermost. If the table identified by
  107312. ** FROM clause element pItem is really a common-table-expression (CTE)
  107313. ** then return a pointer to the CTE definition for that table. Otherwise
  107314. ** return NULL.
  107315. **
  107316. ** If a non-NULL value is returned, set *ppContext to point to the With
  107317. ** object that the returned CTE belongs to.
  107318. */
  107319. static struct Cte *searchWith(
  107320. With *pWith, /* Current innermost WITH clause */
  107321. struct SrcList_item *pItem, /* FROM clause element to resolve */
  107322. With **ppContext /* OUT: WITH clause return value belongs to */
  107323. ){
  107324. const char *zName;
  107325. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  107326. With *p;
  107327. for(p=pWith; p; p=p->pOuter){
  107328. int i;
  107329. for(i=0; i<p->nCte; i++){
  107330. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  107331. *ppContext = p;
  107332. return &p->a[i];
  107333. }
  107334. }
  107335. }
  107336. }
  107337. return 0;
  107338. }
  107339. /* The code generator maintains a stack of active WITH clauses
  107340. ** with the inner-most WITH clause being at the top of the stack.
  107341. **
  107342. ** This routine pushes the WITH clause passed as the second argument
  107343. ** onto the top of the stack. If argument bFree is true, then this
  107344. ** WITH clause will never be popped from the stack. In this case it
  107345. ** should be freed along with the Parse object. In other cases, when
  107346. ** bFree==0, the With object will be freed along with the SELECT
  107347. ** statement with which it is associated.
  107348. */
  107349. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  107350. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  107351. if( pWith ){
  107352. assert( pParse->pWith!=pWith );
  107353. pWith->pOuter = pParse->pWith;
  107354. pParse->pWith = pWith;
  107355. if( bFree ) pParse->pWithToFree = pWith;
  107356. }
  107357. }
  107358. /*
  107359. ** This function checks if argument pFrom refers to a CTE declared by
  107360. ** a WITH clause on the stack currently maintained by the parser. And,
  107361. ** if currently processing a CTE expression, if it is a recursive
  107362. ** reference to the current CTE.
  107363. **
  107364. ** If pFrom falls into either of the two categories above, pFrom->pTab
  107365. ** and other fields are populated accordingly. The caller should check
  107366. ** (pFrom->pTab!=0) to determine whether or not a successful match
  107367. ** was found.
  107368. **
  107369. ** Whether or not a match is found, SQLITE_OK is returned if no error
  107370. ** occurs. If an error does occur, an error message is stored in the
  107371. ** parser and some error code other than SQLITE_OK returned.
  107372. */
  107373. static int withExpand(
  107374. Walker *pWalker,
  107375. struct SrcList_item *pFrom
  107376. ){
  107377. Parse *pParse = pWalker->pParse;
  107378. sqlite3 *db = pParse->db;
  107379. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  107380. With *pWith; /* WITH clause that pCte belongs to */
  107381. assert( pFrom->pTab==0 );
  107382. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  107383. if( pCte ){
  107384. Table *pTab;
  107385. ExprList *pEList;
  107386. Select *pSel;
  107387. Select *pLeft; /* Left-most SELECT statement */
  107388. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  107389. With *pSavedWith; /* Initial value of pParse->pWith */
  107390. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  107391. ** recursive reference to CTE pCte. Leave an error in pParse and return
  107392. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  107393. ** In this case, proceed. */
  107394. if( pCte->zCteErr ){
  107395. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  107396. return SQLITE_ERROR;
  107397. }
  107398. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  107399. assert( pFrom->pTab==0 );
  107400. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  107401. if( pTab==0 ) return WRC_Abort;
  107402. pTab->nRef = 1;
  107403. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  107404. pTab->iPKey = -1;
  107405. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  107406. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  107407. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  107408. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  107409. assert( pFrom->pSelect );
  107410. /* Check if this is a recursive CTE. */
  107411. pSel = pFrom->pSelect;
  107412. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  107413. if( bMayRecursive ){
  107414. int i;
  107415. SrcList *pSrc = pFrom->pSelect->pSrc;
  107416. for(i=0; i<pSrc->nSrc; i++){
  107417. struct SrcList_item *pItem = &pSrc->a[i];
  107418. if( pItem->zDatabase==0
  107419. && pItem->zName!=0
  107420. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  107421. ){
  107422. pItem->pTab = pTab;
  107423. pItem->fg.isRecursive = 1;
  107424. pTab->nRef++;
  107425. pSel->selFlags |= SF_Recursive;
  107426. }
  107427. }
  107428. }
  107429. /* Only one recursive reference is permitted. */
  107430. if( pTab->nRef>2 ){
  107431. sqlite3ErrorMsg(
  107432. pParse, "multiple references to recursive table: %s", pCte->zName
  107433. );
  107434. return SQLITE_ERROR;
  107435. }
  107436. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  107437. pCte->zCteErr = "circular reference: %s";
  107438. pSavedWith = pParse->pWith;
  107439. pParse->pWith = pWith;
  107440. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  107441. pParse->pWith = pWith;
  107442. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  107443. pEList = pLeft->pEList;
  107444. if( pCte->pCols ){
  107445. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  107446. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  107447. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  107448. );
  107449. pParse->pWith = pSavedWith;
  107450. return SQLITE_ERROR;
  107451. }
  107452. pEList = pCte->pCols;
  107453. }
  107454. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  107455. if( bMayRecursive ){
  107456. if( pSel->selFlags & SF_Recursive ){
  107457. pCte->zCteErr = "multiple recursive references: %s";
  107458. }else{
  107459. pCte->zCteErr = "recursive reference in a subquery: %s";
  107460. }
  107461. sqlite3WalkSelect(pWalker, pSel);
  107462. }
  107463. pCte->zCteErr = 0;
  107464. pParse->pWith = pSavedWith;
  107465. }
  107466. return SQLITE_OK;
  107467. }
  107468. #endif
  107469. #ifndef SQLITE_OMIT_CTE
  107470. /*
  107471. ** If the SELECT passed as the second argument has an associated WITH
  107472. ** clause, pop it from the stack stored as part of the Parse object.
  107473. **
  107474. ** This function is used as the xSelectCallback2() callback by
  107475. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  107476. ** names and other FROM clause elements.
  107477. */
  107478. static void selectPopWith(Walker *pWalker, Select *p){
  107479. Parse *pParse = pWalker->pParse;
  107480. With *pWith = findRightmost(p)->pWith;
  107481. if( pWith!=0 ){
  107482. assert( pParse->pWith==pWith );
  107483. pParse->pWith = pWith->pOuter;
  107484. }
  107485. }
  107486. #else
  107487. #define selectPopWith 0
  107488. #endif
  107489. /*
  107490. ** This routine is a Walker callback for "expanding" a SELECT statement.
  107491. ** "Expanding" means to do the following:
  107492. **
  107493. ** (1) Make sure VDBE cursor numbers have been assigned to every
  107494. ** element of the FROM clause.
  107495. **
  107496. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  107497. ** defines FROM clause. When views appear in the FROM clause,
  107498. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  107499. ** that implements the view. A copy is made of the view's SELECT
  107500. ** statement so that we can freely modify or delete that statement
  107501. ** without worrying about messing up the persistent representation
  107502. ** of the view.
  107503. **
  107504. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  107505. ** on joins and the ON and USING clause of joins.
  107506. **
  107507. ** (4) Scan the list of columns in the result set (pEList) looking
  107508. ** for instances of the "*" operator or the TABLE.* operator.
  107509. ** If found, expand each "*" to be every column in every table
  107510. ** and TABLE.* to be every column in TABLE.
  107511. **
  107512. */
  107513. static int selectExpander(Walker *pWalker, Select *p){
  107514. Parse *pParse = pWalker->pParse;
  107515. int i, j, k;
  107516. SrcList *pTabList;
  107517. ExprList *pEList;
  107518. struct SrcList_item *pFrom;
  107519. sqlite3 *db = pParse->db;
  107520. Expr *pE, *pRight, *pExpr;
  107521. u16 selFlags = p->selFlags;
  107522. p->selFlags |= SF_Expanded;
  107523. if( db->mallocFailed ){
  107524. return WRC_Abort;
  107525. }
  107526. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  107527. return WRC_Prune;
  107528. }
  107529. pTabList = p->pSrc;
  107530. pEList = p->pEList;
  107531. if( pWalker->xSelectCallback2==selectPopWith ){
  107532. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  107533. }
  107534. /* Make sure cursor numbers have been assigned to all entries in
  107535. ** the FROM clause of the SELECT statement.
  107536. */
  107537. sqlite3SrcListAssignCursors(pParse, pTabList);
  107538. /* Look up every table named in the FROM clause of the select. If
  107539. ** an entry of the FROM clause is a subquery instead of a table or view,
  107540. ** then create a transient table structure to describe the subquery.
  107541. */
  107542. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  107543. Table *pTab;
  107544. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  107545. if( pFrom->fg.isRecursive ) continue;
  107546. assert( pFrom->pTab==0 );
  107547. #ifndef SQLITE_OMIT_CTE
  107548. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  107549. if( pFrom->pTab ) {} else
  107550. #endif
  107551. if( pFrom->zName==0 ){
  107552. #ifndef SQLITE_OMIT_SUBQUERY
  107553. Select *pSel = pFrom->pSelect;
  107554. /* A sub-query in the FROM clause of a SELECT */
  107555. assert( pSel!=0 );
  107556. assert( pFrom->pTab==0 );
  107557. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  107558. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  107559. if( pTab==0 ) return WRC_Abort;
  107560. pTab->nRef = 1;
  107561. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  107562. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  107563. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  107564. pTab->iPKey = -1;
  107565. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  107566. pTab->tabFlags |= TF_Ephemeral;
  107567. #endif
  107568. }else{
  107569. /* An ordinary table or view name in the FROM clause */
  107570. assert( pFrom->pTab==0 );
  107571. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  107572. if( pTab==0 ) return WRC_Abort;
  107573. if( pTab->nRef==0xffff ){
  107574. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  107575. pTab->zName);
  107576. pFrom->pTab = 0;
  107577. return WRC_Abort;
  107578. }
  107579. pTab->nRef++;
  107580. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  107581. return WRC_Abort;
  107582. }
  107583. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  107584. if( IsVirtual(pTab) || pTab->pSelect ){
  107585. i16 nCol;
  107586. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  107587. assert( pFrom->pSelect==0 );
  107588. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  107589. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  107590. nCol = pTab->nCol;
  107591. pTab->nCol = -1;
  107592. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  107593. pTab->nCol = nCol;
  107594. }
  107595. #endif
  107596. }
  107597. /* Locate the index named by the INDEXED BY clause, if any. */
  107598. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  107599. return WRC_Abort;
  107600. }
  107601. }
  107602. /* Process NATURAL keywords, and ON and USING clauses of joins.
  107603. */
  107604. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  107605. return WRC_Abort;
  107606. }
  107607. /* For every "*" that occurs in the column list, insert the names of
  107608. ** all columns in all tables. And for every TABLE.* insert the names
  107609. ** of all columns in TABLE. The parser inserted a special expression
  107610. ** with the TK_ASTERISK operator for each "*" that it found in the column
  107611. ** list. The following code just has to locate the TK_ASTERISK
  107612. ** expressions and expand each one to the list of all columns in
  107613. ** all tables.
  107614. **
  107615. ** The first loop just checks to see if there are any "*" operators
  107616. ** that need expanding.
  107617. */
  107618. for(k=0; k<pEList->nExpr; k++){
  107619. pE = pEList->a[k].pExpr;
  107620. if( pE->op==TK_ASTERISK ) break;
  107621. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  107622. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  107623. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  107624. }
  107625. if( k<pEList->nExpr ){
  107626. /*
  107627. ** If we get here it means the result set contains one or more "*"
  107628. ** operators that need to be expanded. Loop through each expression
  107629. ** in the result set and expand them one by one.
  107630. */
  107631. struct ExprList_item *a = pEList->a;
  107632. ExprList *pNew = 0;
  107633. int flags = pParse->db->flags;
  107634. int longNames = (flags & SQLITE_FullColNames)!=0
  107635. && (flags & SQLITE_ShortColNames)==0;
  107636. for(k=0; k<pEList->nExpr; k++){
  107637. pE = a[k].pExpr;
  107638. pRight = pE->pRight;
  107639. assert( pE->op!=TK_DOT || pRight!=0 );
  107640. if( pE->op!=TK_ASTERISK
  107641. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  107642. ){
  107643. /* This particular expression does not need to be expanded.
  107644. */
  107645. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  107646. if( pNew ){
  107647. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  107648. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  107649. a[k].zName = 0;
  107650. a[k].zSpan = 0;
  107651. }
  107652. a[k].pExpr = 0;
  107653. }else{
  107654. /* This expression is a "*" or a "TABLE.*" and needs to be
  107655. ** expanded. */
  107656. int tableSeen = 0; /* Set to 1 when TABLE matches */
  107657. char *zTName = 0; /* text of name of TABLE */
  107658. if( pE->op==TK_DOT ){
  107659. assert( pE->pLeft!=0 );
  107660. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  107661. zTName = pE->pLeft->u.zToken;
  107662. }
  107663. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  107664. Table *pTab = pFrom->pTab;
  107665. Select *pSub = pFrom->pSelect;
  107666. char *zTabName = pFrom->zAlias;
  107667. const char *zSchemaName = 0;
  107668. int iDb;
  107669. if( zTabName==0 ){
  107670. zTabName = pTab->zName;
  107671. }
  107672. if( db->mallocFailed ) break;
  107673. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  107674. pSub = 0;
  107675. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  107676. continue;
  107677. }
  107678. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  107679. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  107680. }
  107681. for(j=0; j<pTab->nCol; j++){
  107682. char *zName = pTab->aCol[j].zName;
  107683. char *zColname; /* The computed column name */
  107684. char *zToFree; /* Malloced string that needs to be freed */
  107685. Token sColname; /* Computed column name as a token */
  107686. assert( zName );
  107687. if( zTName && pSub
  107688. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  107689. ){
  107690. continue;
  107691. }
  107692. /* If a column is marked as 'hidden', omit it from the expanded
  107693. ** result-set list unless the SELECT has the SF_IncludeHidden
  107694. ** bit set.
  107695. */
  107696. if( (p->selFlags & SF_IncludeHidden)==0
  107697. && IsHiddenColumn(&pTab->aCol[j])
  107698. ){
  107699. continue;
  107700. }
  107701. tableSeen = 1;
  107702. if( i>0 && zTName==0 ){
  107703. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  107704. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  107705. ){
  107706. /* In a NATURAL join, omit the join columns from the
  107707. ** table to the right of the join */
  107708. continue;
  107709. }
  107710. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  107711. /* In a join with a USING clause, omit columns in the
  107712. ** using clause from the table on the right. */
  107713. continue;
  107714. }
  107715. }
  107716. pRight = sqlite3Expr(db, TK_ID, zName);
  107717. zColname = zName;
  107718. zToFree = 0;
  107719. if( longNames || pTabList->nSrc>1 ){
  107720. Expr *pLeft;
  107721. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  107722. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  107723. if( zSchemaName ){
  107724. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  107725. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  107726. }
  107727. if( longNames ){
  107728. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  107729. zToFree = zColname;
  107730. }
  107731. }else{
  107732. pExpr = pRight;
  107733. }
  107734. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  107735. sqlite3TokenInit(&sColname, zColname);
  107736. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  107737. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  107738. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  107739. if( pSub ){
  107740. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  107741. testcase( pX->zSpan==0 );
  107742. }else{
  107743. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  107744. zSchemaName, zTabName, zColname);
  107745. testcase( pX->zSpan==0 );
  107746. }
  107747. pX->bSpanIsTab = 1;
  107748. }
  107749. sqlite3DbFree(db, zToFree);
  107750. }
  107751. }
  107752. if( !tableSeen ){
  107753. if( zTName ){
  107754. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  107755. }else{
  107756. sqlite3ErrorMsg(pParse, "no tables specified");
  107757. }
  107758. }
  107759. }
  107760. }
  107761. sqlite3ExprListDelete(db, pEList);
  107762. p->pEList = pNew;
  107763. }
  107764. #if SQLITE_MAX_COLUMN
  107765. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  107766. sqlite3ErrorMsg(pParse, "too many columns in result set");
  107767. return WRC_Abort;
  107768. }
  107769. #endif
  107770. return WRC_Continue;
  107771. }
  107772. /*
  107773. ** No-op routine for the parse-tree walker.
  107774. **
  107775. ** When this routine is the Walker.xExprCallback then expression trees
  107776. ** are walked without any actions being taken at each node. Presumably,
  107777. ** when this routine is used for Walker.xExprCallback then
  107778. ** Walker.xSelectCallback is set to do something useful for every
  107779. ** subquery in the parser tree.
  107780. */
  107781. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  107782. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  107783. return WRC_Continue;
  107784. }
  107785. /*
  107786. ** This routine "expands" a SELECT statement and all of its subqueries.
  107787. ** For additional information on what it means to "expand" a SELECT
  107788. ** statement, see the comment on the selectExpand worker callback above.
  107789. **
  107790. ** Expanding a SELECT statement is the first step in processing a
  107791. ** SELECT statement. The SELECT statement must be expanded before
  107792. ** name resolution is performed.
  107793. **
  107794. ** If anything goes wrong, an error message is written into pParse.
  107795. ** The calling function can detect the problem by looking at pParse->nErr
  107796. ** and/or pParse->db->mallocFailed.
  107797. */
  107798. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  107799. Walker w;
  107800. memset(&w, 0, sizeof(w));
  107801. w.xExprCallback = sqlite3ExprWalkNoop;
  107802. w.pParse = pParse;
  107803. if( pParse->hasCompound ){
  107804. w.xSelectCallback = convertCompoundSelectToSubquery;
  107805. sqlite3WalkSelect(&w, pSelect);
  107806. }
  107807. w.xSelectCallback = selectExpander;
  107808. if( (pSelect->selFlags & SF_MultiValue)==0 ){
  107809. w.xSelectCallback2 = selectPopWith;
  107810. }
  107811. sqlite3WalkSelect(&w, pSelect);
  107812. }
  107813. #ifndef SQLITE_OMIT_SUBQUERY
  107814. /*
  107815. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  107816. ** interface.
  107817. **
  107818. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  107819. ** information to the Table structure that represents the result set
  107820. ** of that subquery.
  107821. **
  107822. ** The Table structure that represents the result set was constructed
  107823. ** by selectExpander() but the type and collation information was omitted
  107824. ** at that point because identifiers had not yet been resolved. This
  107825. ** routine is called after identifier resolution.
  107826. */
  107827. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  107828. Parse *pParse;
  107829. int i;
  107830. SrcList *pTabList;
  107831. struct SrcList_item *pFrom;
  107832. assert( p->selFlags & SF_Resolved );
  107833. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  107834. p->selFlags |= SF_HasTypeInfo;
  107835. pParse = pWalker->pParse;
  107836. pTabList = p->pSrc;
  107837. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  107838. Table *pTab = pFrom->pTab;
  107839. assert( pTab!=0 );
  107840. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  107841. /* A sub-query in the FROM clause of a SELECT */
  107842. Select *pSel = pFrom->pSelect;
  107843. if( pSel ){
  107844. while( pSel->pPrior ) pSel = pSel->pPrior;
  107845. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  107846. }
  107847. }
  107848. }
  107849. }
  107850. #endif
  107851. /*
  107852. ** This routine adds datatype and collating sequence information to
  107853. ** the Table structures of all FROM-clause subqueries in a
  107854. ** SELECT statement.
  107855. **
  107856. ** Use this routine after name resolution.
  107857. */
  107858. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  107859. #ifndef SQLITE_OMIT_SUBQUERY
  107860. Walker w;
  107861. memset(&w, 0, sizeof(w));
  107862. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  107863. w.xExprCallback = sqlite3ExprWalkNoop;
  107864. w.pParse = pParse;
  107865. sqlite3WalkSelect(&w, pSelect);
  107866. #endif
  107867. }
  107868. /*
  107869. ** This routine sets up a SELECT statement for processing. The
  107870. ** following is accomplished:
  107871. **
  107872. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  107873. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  107874. ** * ON and USING clauses are shifted into WHERE statements
  107875. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  107876. ** * Identifiers in expression are matched to tables.
  107877. **
  107878. ** This routine acts recursively on all subqueries within the SELECT.
  107879. */
  107880. SQLITE_PRIVATE void sqlite3SelectPrep(
  107881. Parse *pParse, /* The parser context */
  107882. Select *p, /* The SELECT statement being coded. */
  107883. NameContext *pOuterNC /* Name context for container */
  107884. ){
  107885. sqlite3 *db;
  107886. if( NEVER(p==0) ) return;
  107887. db = pParse->db;
  107888. if( db->mallocFailed ) return;
  107889. if( p->selFlags & SF_HasTypeInfo ) return;
  107890. sqlite3SelectExpand(pParse, p);
  107891. if( pParse->nErr || db->mallocFailed ) return;
  107892. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  107893. if( pParse->nErr || db->mallocFailed ) return;
  107894. sqlite3SelectAddTypeInfo(pParse, p);
  107895. }
  107896. /*
  107897. ** Reset the aggregate accumulator.
  107898. **
  107899. ** The aggregate accumulator is a set of memory cells that hold
  107900. ** intermediate results while calculating an aggregate. This
  107901. ** routine generates code that stores NULLs in all of those memory
  107902. ** cells.
  107903. */
  107904. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  107905. Vdbe *v = pParse->pVdbe;
  107906. int i;
  107907. struct AggInfo_func *pFunc;
  107908. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  107909. if( nReg==0 ) return;
  107910. #ifdef SQLITE_DEBUG
  107911. /* Verify that all AggInfo registers are within the range specified by
  107912. ** AggInfo.mnReg..AggInfo.mxReg */
  107913. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  107914. for(i=0; i<pAggInfo->nColumn; i++){
  107915. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  107916. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  107917. }
  107918. for(i=0; i<pAggInfo->nFunc; i++){
  107919. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  107920. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  107921. }
  107922. #endif
  107923. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  107924. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  107925. if( pFunc->iDistinct>=0 ){
  107926. Expr *pE = pFunc->pExpr;
  107927. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  107928. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  107929. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  107930. "argument");
  107931. pFunc->iDistinct = -1;
  107932. }else{
  107933. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  107934. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  107935. (char*)pKeyInfo, P4_KEYINFO);
  107936. }
  107937. }
  107938. }
  107939. }
  107940. /*
  107941. ** Invoke the OP_AggFinalize opcode for every aggregate function
  107942. ** in the AggInfo structure.
  107943. */
  107944. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  107945. Vdbe *v = pParse->pVdbe;
  107946. int i;
  107947. struct AggInfo_func *pF;
  107948. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  107949. ExprList *pList = pF->pExpr->x.pList;
  107950. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  107951. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  107952. (void*)pF->pFunc, P4_FUNCDEF);
  107953. }
  107954. }
  107955. /*
  107956. ** Update the accumulator memory cells for an aggregate based on
  107957. ** the current cursor position.
  107958. */
  107959. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  107960. Vdbe *v = pParse->pVdbe;
  107961. int i;
  107962. int regHit = 0;
  107963. int addrHitTest = 0;
  107964. struct AggInfo_func *pF;
  107965. struct AggInfo_col *pC;
  107966. pAggInfo->directMode = 1;
  107967. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  107968. int nArg;
  107969. int addrNext = 0;
  107970. int regAgg;
  107971. ExprList *pList = pF->pExpr->x.pList;
  107972. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  107973. if( pList ){
  107974. nArg = pList->nExpr;
  107975. regAgg = sqlite3GetTempRange(pParse, nArg);
  107976. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  107977. }else{
  107978. nArg = 0;
  107979. regAgg = 0;
  107980. }
  107981. if( pF->iDistinct>=0 ){
  107982. addrNext = sqlite3VdbeMakeLabel(v);
  107983. testcase( nArg==0 ); /* Error condition */
  107984. testcase( nArg>1 ); /* Also an error */
  107985. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  107986. }
  107987. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  107988. CollSeq *pColl = 0;
  107989. struct ExprList_item *pItem;
  107990. int j;
  107991. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  107992. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  107993. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  107994. }
  107995. if( !pColl ){
  107996. pColl = pParse->db->pDfltColl;
  107997. }
  107998. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  107999. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  108000. }
  108001. sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
  108002. (void*)pF->pFunc, P4_FUNCDEF);
  108003. sqlite3VdbeChangeP5(v, (u8)nArg);
  108004. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  108005. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  108006. if( addrNext ){
  108007. sqlite3VdbeResolveLabel(v, addrNext);
  108008. sqlite3ExprCacheClear(pParse);
  108009. }
  108010. }
  108011. /* Before populating the accumulator registers, clear the column cache.
  108012. ** Otherwise, if any of the required column values are already present
  108013. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  108014. ** to pC->iMem. But by the time the value is used, the original register
  108015. ** may have been used, invalidating the underlying buffer holding the
  108016. ** text or blob value. See ticket [883034dcb5].
  108017. **
  108018. ** Another solution would be to change the OP_SCopy used to copy cached
  108019. ** values to an OP_Copy.
  108020. */
  108021. if( regHit ){
  108022. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  108023. }
  108024. sqlite3ExprCacheClear(pParse);
  108025. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  108026. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  108027. }
  108028. pAggInfo->directMode = 0;
  108029. sqlite3ExprCacheClear(pParse);
  108030. if( addrHitTest ){
  108031. sqlite3VdbeJumpHere(v, addrHitTest);
  108032. }
  108033. }
  108034. /*
  108035. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  108036. ** count(*) query ("SELECT count(*) FROM pTab").
  108037. */
  108038. #ifndef SQLITE_OMIT_EXPLAIN
  108039. static void explainSimpleCount(
  108040. Parse *pParse, /* Parse context */
  108041. Table *pTab, /* Table being queried */
  108042. Index *pIdx /* Index used to optimize scan, or NULL */
  108043. ){
  108044. if( pParse->explain==2 ){
  108045. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  108046. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  108047. pTab->zName,
  108048. bCover ? " USING COVERING INDEX " : "",
  108049. bCover ? pIdx->zName : ""
  108050. );
  108051. sqlite3VdbeAddOp4(
  108052. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  108053. );
  108054. }
  108055. }
  108056. #else
  108057. # define explainSimpleCount(a,b,c)
  108058. #endif
  108059. /*
  108060. ** Generate code for the SELECT statement given in the p argument.
  108061. **
  108062. ** The results are returned according to the SelectDest structure.
  108063. ** See comments in sqliteInt.h for further information.
  108064. **
  108065. ** This routine returns the number of errors. If any errors are
  108066. ** encountered, then an appropriate error message is left in
  108067. ** pParse->zErrMsg.
  108068. **
  108069. ** This routine does NOT free the Select structure passed in. The
  108070. ** calling function needs to do that.
  108071. */
  108072. SQLITE_PRIVATE int sqlite3Select(
  108073. Parse *pParse, /* The parser context */
  108074. Select *p, /* The SELECT statement being coded. */
  108075. SelectDest *pDest /* What to do with the query results */
  108076. ){
  108077. int i, j; /* Loop counters */
  108078. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  108079. Vdbe *v; /* The virtual machine under construction */
  108080. int isAgg; /* True for select lists like "count(*)" */
  108081. ExprList *pEList = 0; /* List of columns to extract. */
  108082. SrcList *pTabList; /* List of tables to select from */
  108083. Expr *pWhere; /* The WHERE clause. May be NULL */
  108084. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  108085. Expr *pHaving; /* The HAVING clause. May be NULL */
  108086. int rc = 1; /* Value to return from this function */
  108087. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  108088. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  108089. AggInfo sAggInfo; /* Information used by aggregate queries */
  108090. int iEnd; /* Address of the end of the query */
  108091. sqlite3 *db; /* The database connection */
  108092. #ifndef SQLITE_OMIT_EXPLAIN
  108093. int iRestoreSelectId = pParse->iSelectId;
  108094. pParse->iSelectId = pParse->iNextSelectId++;
  108095. #endif
  108096. db = pParse->db;
  108097. if( p==0 || db->mallocFailed || pParse->nErr ){
  108098. return 1;
  108099. }
  108100. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  108101. memset(&sAggInfo, 0, sizeof(sAggInfo));
  108102. #if SELECTTRACE_ENABLED
  108103. pParse->nSelectIndent++;
  108104. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  108105. if( sqlite3SelectTrace & 0x100 ){
  108106. sqlite3TreeViewSelect(0, p, 0);
  108107. }
  108108. #endif
  108109. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  108110. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  108111. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  108112. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  108113. if( IgnorableOrderby(pDest) ){
  108114. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  108115. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  108116. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  108117. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  108118. /* If ORDER BY makes no difference in the output then neither does
  108119. ** DISTINCT so it can be removed too. */
  108120. sqlite3ExprListDelete(db, p->pOrderBy);
  108121. p->pOrderBy = 0;
  108122. p->selFlags &= ~SF_Distinct;
  108123. }
  108124. sqlite3SelectPrep(pParse, p, 0);
  108125. memset(&sSort, 0, sizeof(sSort));
  108126. sSort.pOrderBy = p->pOrderBy;
  108127. pTabList = p->pSrc;
  108128. if( pParse->nErr || db->mallocFailed ){
  108129. goto select_end;
  108130. }
  108131. assert( p->pEList!=0 );
  108132. isAgg = (p->selFlags & SF_Aggregate)!=0;
  108133. #if SELECTTRACE_ENABLED
  108134. if( sqlite3SelectTrace & 0x100 ){
  108135. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  108136. sqlite3TreeViewSelect(0, p, 0);
  108137. }
  108138. #endif
  108139. /* If writing to memory or generating a set
  108140. ** only a single column may be output.
  108141. */
  108142. #ifndef SQLITE_OMIT_SUBQUERY
  108143. if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
  108144. goto select_end;
  108145. }
  108146. #endif
  108147. /* Try to flatten subqueries in the FROM clause up into the main query
  108148. */
  108149. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  108150. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  108151. struct SrcList_item *pItem = &pTabList->a[i];
  108152. Select *pSub = pItem->pSelect;
  108153. int isAggSub;
  108154. Table *pTab = pItem->pTab;
  108155. if( pSub==0 ) continue;
  108156. /* Catch mismatch in the declared columns of a view and the number of
  108157. ** columns in the SELECT on the RHS */
  108158. if( pTab->nCol!=pSub->pEList->nExpr ){
  108159. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  108160. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  108161. goto select_end;
  108162. }
  108163. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  108164. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  108165. /* This subquery can be absorbed into its parent. */
  108166. if( isAggSub ){
  108167. isAgg = 1;
  108168. p->selFlags |= SF_Aggregate;
  108169. }
  108170. i = -1;
  108171. }
  108172. pTabList = p->pSrc;
  108173. if( db->mallocFailed ) goto select_end;
  108174. if( !IgnorableOrderby(pDest) ){
  108175. sSort.pOrderBy = p->pOrderBy;
  108176. }
  108177. }
  108178. #endif
  108179. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  108180. ** does not already exist */
  108181. v = sqlite3GetVdbe(pParse);
  108182. if( v==0 ) goto select_end;
  108183. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  108184. /* Handle compound SELECT statements using the separate multiSelect()
  108185. ** procedure.
  108186. */
  108187. if( p->pPrior ){
  108188. rc = multiSelect(pParse, p, pDest);
  108189. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  108190. #if SELECTTRACE_ENABLED
  108191. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  108192. pParse->nSelectIndent--;
  108193. #endif
  108194. return rc;
  108195. }
  108196. #endif
  108197. /* Generate code for all sub-queries in the FROM clause
  108198. */
  108199. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  108200. for(i=0; i<pTabList->nSrc; i++){
  108201. struct SrcList_item *pItem = &pTabList->a[i];
  108202. SelectDest dest;
  108203. Select *pSub = pItem->pSelect;
  108204. if( pSub==0 ) continue;
  108205. /* Sometimes the code for a subquery will be generated more than
  108206. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  108207. ** for example. In that case, do not regenerate the code to manifest
  108208. ** a view or the co-routine to implement a view. The first instance
  108209. ** is sufficient, though the subroutine to manifest the view does need
  108210. ** to be invoked again. */
  108211. if( pItem->addrFillSub ){
  108212. if( pItem->fg.viaCoroutine==0 ){
  108213. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  108214. }
  108215. continue;
  108216. }
  108217. /* Increment Parse.nHeight by the height of the largest expression
  108218. ** tree referred to by this, the parent select. The child select
  108219. ** may contain expression trees of at most
  108220. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  108221. ** more conservative than necessary, but much easier than enforcing
  108222. ** an exact limit.
  108223. */
  108224. pParse->nHeight += sqlite3SelectExprHeight(p);
  108225. /* Make copies of constant WHERE-clause terms in the outer query down
  108226. ** inside the subquery. This can help the subquery to run more efficiently.
  108227. */
  108228. if( (pItem->fg.jointype & JT_OUTER)==0
  108229. && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
  108230. ){
  108231. #if SELECTTRACE_ENABLED
  108232. if( sqlite3SelectTrace & 0x100 ){
  108233. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  108234. sqlite3TreeViewSelect(0, p, 0);
  108235. }
  108236. #endif
  108237. }
  108238. /* Generate code to implement the subquery
  108239. **
  108240. ** The subquery is implemented as a co-routine if all of these are true:
  108241. ** (1) The subquery is guaranteed to be the outer loop (so that it
  108242. ** does not need to be computed more than once)
  108243. ** (2) The ALL keyword after SELECT is omitted. (Applications are
  108244. ** allowed to say "SELECT ALL" instead of just "SELECT" to disable
  108245. ** the use of co-routines.)
  108246. ** (3) Co-routines are not disabled using sqlite3_test_control()
  108247. ** with SQLITE_TESTCTRL_OPTIMIZATIONS.
  108248. **
  108249. ** TODO: Are there other reasons beside (1) to use a co-routine
  108250. ** implementation?
  108251. */
  108252. if( i==0
  108253. && (pTabList->nSrc==1
  108254. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  108255. && (p->selFlags & SF_All)==0 /* (2) */
  108256. && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */
  108257. ){
  108258. /* Implement a co-routine that will return a single row of the result
  108259. ** set on each invocation.
  108260. */
  108261. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  108262. pItem->regReturn = ++pParse->nMem;
  108263. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  108264. VdbeComment((v, "%s", pItem->pTab->zName));
  108265. pItem->addrFillSub = addrTop;
  108266. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  108267. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  108268. sqlite3Select(pParse, pSub, &dest);
  108269. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  108270. pItem->fg.viaCoroutine = 1;
  108271. pItem->regResult = dest.iSdst;
  108272. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  108273. sqlite3VdbeJumpHere(v, addrTop-1);
  108274. sqlite3ClearTempRegCache(pParse);
  108275. }else{
  108276. /* Generate a subroutine that will fill an ephemeral table with
  108277. ** the content of this subquery. pItem->addrFillSub will point
  108278. ** to the address of the generated subroutine. pItem->regReturn
  108279. ** is a register allocated to hold the subroutine return address
  108280. */
  108281. int topAddr;
  108282. int onceAddr = 0;
  108283. int retAddr;
  108284. assert( pItem->addrFillSub==0 );
  108285. pItem->regReturn = ++pParse->nMem;
  108286. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  108287. pItem->addrFillSub = topAddr+1;
  108288. if( pItem->fg.isCorrelated==0 ){
  108289. /* If the subquery is not correlated and if we are not inside of
  108290. ** a trigger, then we only need to compute the value of the subquery
  108291. ** once. */
  108292. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  108293. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  108294. }else{
  108295. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  108296. }
  108297. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  108298. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  108299. sqlite3Select(pParse, pSub, &dest);
  108300. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  108301. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  108302. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  108303. VdbeComment((v, "end %s", pItem->pTab->zName));
  108304. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  108305. sqlite3ClearTempRegCache(pParse);
  108306. }
  108307. if( db->mallocFailed ) goto select_end;
  108308. pParse->nHeight -= sqlite3SelectExprHeight(p);
  108309. }
  108310. #endif
  108311. /* Various elements of the SELECT copied into local variables for
  108312. ** convenience */
  108313. pEList = p->pEList;
  108314. pWhere = p->pWhere;
  108315. pGroupBy = p->pGroupBy;
  108316. pHaving = p->pHaving;
  108317. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  108318. #if SELECTTRACE_ENABLED
  108319. if( sqlite3SelectTrace & 0x400 ){
  108320. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  108321. sqlite3TreeViewSelect(0, p, 0);
  108322. }
  108323. #endif
  108324. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  108325. ** if the select-list is the same as the ORDER BY list, then this query
  108326. ** can be rewritten as a GROUP BY. In other words, this:
  108327. **
  108328. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  108329. **
  108330. ** is transformed to:
  108331. **
  108332. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  108333. **
  108334. ** The second form is preferred as a single index (or temp-table) may be
  108335. ** used for both the ORDER BY and DISTINCT processing. As originally
  108336. ** written the query must use a temp-table for at least one of the ORDER
  108337. ** BY and DISTINCT, and an index or separate temp-table for the other.
  108338. */
  108339. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  108340. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  108341. ){
  108342. p->selFlags &= ~SF_Distinct;
  108343. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  108344. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  108345. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  108346. ** original setting of the SF_Distinct flag, not the current setting */
  108347. assert( sDistinct.isTnct );
  108348. }
  108349. /* If there is an ORDER BY clause, then create an ephemeral index to
  108350. ** do the sorting. But this sorting ephemeral index might end up
  108351. ** being unused if the data can be extracted in pre-sorted order.
  108352. ** If that is the case, then the OP_OpenEphemeral instruction will be
  108353. ** changed to an OP_Noop once we figure out that the sorting index is
  108354. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  108355. ** that change.
  108356. */
  108357. if( sSort.pOrderBy ){
  108358. KeyInfo *pKeyInfo;
  108359. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  108360. sSort.iECursor = pParse->nTab++;
  108361. sSort.addrSortIndex =
  108362. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  108363. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  108364. (char*)pKeyInfo, P4_KEYINFO
  108365. );
  108366. }else{
  108367. sSort.addrSortIndex = -1;
  108368. }
  108369. /* If the output is destined for a temporary table, open that table.
  108370. */
  108371. if( pDest->eDest==SRT_EphemTab ){
  108372. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  108373. }
  108374. /* Set the limiter.
  108375. */
  108376. iEnd = sqlite3VdbeMakeLabel(v);
  108377. p->nSelectRow = 320; /* 4 billion rows */
  108378. computeLimitRegisters(pParse, p, iEnd);
  108379. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  108380. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  108381. sSort.sortFlags |= SORTFLAG_UseSorter;
  108382. }
  108383. /* Open an ephemeral index to use for the distinct set.
  108384. */
  108385. if( p->selFlags & SF_Distinct ){
  108386. sDistinct.tabTnct = pParse->nTab++;
  108387. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  108388. sDistinct.tabTnct, 0, 0,
  108389. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  108390. P4_KEYINFO);
  108391. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  108392. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  108393. }else{
  108394. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  108395. }
  108396. if( !isAgg && pGroupBy==0 ){
  108397. /* No aggregate functions and no GROUP BY clause */
  108398. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  108399. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  108400. wctrlFlags |= p->selFlags & SF_FixedLimit;
  108401. /* Begin the database scan. */
  108402. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  108403. p->pEList, wctrlFlags, p->nSelectRow);
  108404. if( pWInfo==0 ) goto select_end;
  108405. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  108406. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  108407. }
  108408. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  108409. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  108410. }
  108411. if( sSort.pOrderBy ){
  108412. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  108413. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  108414. sSort.pOrderBy = 0;
  108415. }
  108416. }
  108417. /* If sorting index that was created by a prior OP_OpenEphemeral
  108418. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  108419. ** into an OP_Noop.
  108420. */
  108421. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  108422. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  108423. }
  108424. /* Use the standard inner loop. */
  108425. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  108426. sqlite3WhereContinueLabel(pWInfo),
  108427. sqlite3WhereBreakLabel(pWInfo));
  108428. /* End the database scan loop.
  108429. */
  108430. sqlite3WhereEnd(pWInfo);
  108431. }else{
  108432. /* This case when there exist aggregate functions or a GROUP BY clause
  108433. ** or both */
  108434. NameContext sNC; /* Name context for processing aggregate information */
  108435. int iAMem; /* First Mem address for storing current GROUP BY */
  108436. int iBMem; /* First Mem address for previous GROUP BY */
  108437. int iUseFlag; /* Mem address holding flag indicating that at least
  108438. ** one row of the input to the aggregator has been
  108439. ** processed */
  108440. int iAbortFlag; /* Mem address which causes query abort if positive */
  108441. int groupBySort; /* Rows come from source in GROUP BY order */
  108442. int addrEnd; /* End of processing for this SELECT */
  108443. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  108444. int sortOut = 0; /* Output register from the sorter */
  108445. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  108446. /* Remove any and all aliases between the result set and the
  108447. ** GROUP BY clause.
  108448. */
  108449. if( pGroupBy ){
  108450. int k; /* Loop counter */
  108451. struct ExprList_item *pItem; /* For looping over expression in a list */
  108452. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  108453. pItem->u.x.iAlias = 0;
  108454. }
  108455. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  108456. pItem->u.x.iAlias = 0;
  108457. }
  108458. assert( 66==sqlite3LogEst(100) );
  108459. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  108460. }else{
  108461. assert( 0==sqlite3LogEst(1) );
  108462. p->nSelectRow = 0;
  108463. }
  108464. /* If there is both a GROUP BY and an ORDER BY clause and they are
  108465. ** identical, then it may be possible to disable the ORDER BY clause
  108466. ** on the grounds that the GROUP BY will cause elements to come out
  108467. ** in the correct order. It also may not - the GROUP BY might use a
  108468. ** database index that causes rows to be grouped together as required
  108469. ** but not actually sorted. Either way, record the fact that the
  108470. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  108471. ** variable. */
  108472. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  108473. orderByGrp = 1;
  108474. }
  108475. /* Create a label to jump to when we want to abort the query */
  108476. addrEnd = sqlite3VdbeMakeLabel(v);
  108477. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  108478. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  108479. ** SELECT statement.
  108480. */
  108481. memset(&sNC, 0, sizeof(sNC));
  108482. sNC.pParse = pParse;
  108483. sNC.pSrcList = pTabList;
  108484. sNC.pAggInfo = &sAggInfo;
  108485. sAggInfo.mnReg = pParse->nMem+1;
  108486. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  108487. sAggInfo.pGroupBy = pGroupBy;
  108488. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  108489. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  108490. if( pHaving ){
  108491. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  108492. }
  108493. sAggInfo.nAccumulator = sAggInfo.nColumn;
  108494. for(i=0; i<sAggInfo.nFunc; i++){
  108495. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  108496. sNC.ncFlags |= NC_InAggFunc;
  108497. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  108498. sNC.ncFlags &= ~NC_InAggFunc;
  108499. }
  108500. sAggInfo.mxReg = pParse->nMem;
  108501. if( db->mallocFailed ) goto select_end;
  108502. /* Processing for aggregates with GROUP BY is very different and
  108503. ** much more complex than aggregates without a GROUP BY.
  108504. */
  108505. if( pGroupBy ){
  108506. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  108507. int addr1; /* A-vs-B comparision jump */
  108508. int addrOutputRow; /* Start of subroutine that outputs a result row */
  108509. int regOutputRow; /* Return address register for output subroutine */
  108510. int addrSetAbort; /* Set the abort flag and return */
  108511. int addrTopOfLoop; /* Top of the input loop */
  108512. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  108513. int addrReset; /* Subroutine for resetting the accumulator */
  108514. int regReset; /* Return address register for reset subroutine */
  108515. /* If there is a GROUP BY clause we might need a sorting index to
  108516. ** implement it. Allocate that sorting index now. If it turns out
  108517. ** that we do not need it after all, the OP_SorterOpen instruction
  108518. ** will be converted into a Noop.
  108519. */
  108520. sAggInfo.sortingIdx = pParse->nTab++;
  108521. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  108522. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  108523. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  108524. 0, (char*)pKeyInfo, P4_KEYINFO);
  108525. /* Initialize memory locations used by GROUP BY aggregate processing
  108526. */
  108527. iUseFlag = ++pParse->nMem;
  108528. iAbortFlag = ++pParse->nMem;
  108529. regOutputRow = ++pParse->nMem;
  108530. addrOutputRow = sqlite3VdbeMakeLabel(v);
  108531. regReset = ++pParse->nMem;
  108532. addrReset = sqlite3VdbeMakeLabel(v);
  108533. iAMem = pParse->nMem + 1;
  108534. pParse->nMem += pGroupBy->nExpr;
  108535. iBMem = pParse->nMem + 1;
  108536. pParse->nMem += pGroupBy->nExpr;
  108537. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  108538. VdbeComment((v, "clear abort flag"));
  108539. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  108540. VdbeComment((v, "indicate accumulator empty"));
  108541. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  108542. /* Begin a loop that will extract all source rows in GROUP BY order.
  108543. ** This might involve two separate loops with an OP_Sort in between, or
  108544. ** it might be a single loop that uses an index to extract information
  108545. ** in the right order to begin with.
  108546. */
  108547. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  108548. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  108549. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  108550. );
  108551. if( pWInfo==0 ) goto select_end;
  108552. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  108553. /* The optimizer is able to deliver rows in group by order so
  108554. ** we do not have to sort. The OP_OpenEphemeral table will be
  108555. ** cancelled later because we still need to use the pKeyInfo
  108556. */
  108557. groupBySort = 0;
  108558. }else{
  108559. /* Rows are coming out in undetermined order. We have to push
  108560. ** each row into a sorting index, terminate the first loop,
  108561. ** then loop over the sorting index in order to get the output
  108562. ** in sorted order
  108563. */
  108564. int regBase;
  108565. int regRecord;
  108566. int nCol;
  108567. int nGroupBy;
  108568. explainTempTable(pParse,
  108569. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  108570. "DISTINCT" : "GROUP BY");
  108571. groupBySort = 1;
  108572. nGroupBy = pGroupBy->nExpr;
  108573. nCol = nGroupBy;
  108574. j = nGroupBy;
  108575. for(i=0; i<sAggInfo.nColumn; i++){
  108576. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  108577. nCol++;
  108578. j++;
  108579. }
  108580. }
  108581. regBase = sqlite3GetTempRange(pParse, nCol);
  108582. sqlite3ExprCacheClear(pParse);
  108583. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  108584. j = nGroupBy;
  108585. for(i=0; i<sAggInfo.nColumn; i++){
  108586. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  108587. if( pCol->iSorterColumn>=j ){
  108588. int r1 = j + regBase;
  108589. sqlite3ExprCodeGetColumnToReg(pParse,
  108590. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  108591. j++;
  108592. }
  108593. }
  108594. regRecord = sqlite3GetTempReg(pParse);
  108595. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  108596. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  108597. sqlite3ReleaseTempReg(pParse, regRecord);
  108598. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  108599. sqlite3WhereEnd(pWInfo);
  108600. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  108601. sortOut = sqlite3GetTempReg(pParse);
  108602. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  108603. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  108604. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  108605. sAggInfo.useSortingIdx = 1;
  108606. sqlite3ExprCacheClear(pParse);
  108607. }
  108608. /* If the index or temporary table used by the GROUP BY sort
  108609. ** will naturally deliver rows in the order required by the ORDER BY
  108610. ** clause, cancel the ephemeral table open coded earlier.
  108611. **
  108612. ** This is an optimization - the correct answer should result regardless.
  108613. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  108614. ** disable this optimization for testing purposes. */
  108615. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  108616. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  108617. ){
  108618. sSort.pOrderBy = 0;
  108619. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  108620. }
  108621. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  108622. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  108623. ** Then compare the current GROUP BY terms against the GROUP BY terms
  108624. ** from the previous row currently stored in a0, a1, a2...
  108625. */
  108626. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  108627. sqlite3ExprCacheClear(pParse);
  108628. if( groupBySort ){
  108629. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  108630. sortOut, sortPTab);
  108631. }
  108632. for(j=0; j<pGroupBy->nExpr; j++){
  108633. if( groupBySort ){
  108634. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  108635. }else{
  108636. sAggInfo.directMode = 1;
  108637. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  108638. }
  108639. }
  108640. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  108641. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  108642. addr1 = sqlite3VdbeCurrentAddr(v);
  108643. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  108644. /* Generate code that runs whenever the GROUP BY changes.
  108645. ** Changes in the GROUP BY are detected by the previous code
  108646. ** block. If there were no changes, this block is skipped.
  108647. **
  108648. ** This code copies current group by terms in b0,b1,b2,...
  108649. ** over to a0,a1,a2. It then calls the output subroutine
  108650. ** and resets the aggregate accumulator registers in preparation
  108651. ** for the next GROUP BY batch.
  108652. */
  108653. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  108654. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  108655. VdbeComment((v, "output one row"));
  108656. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  108657. VdbeComment((v, "check abort flag"));
  108658. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  108659. VdbeComment((v, "reset accumulator"));
  108660. /* Update the aggregate accumulators based on the content of
  108661. ** the current row
  108662. */
  108663. sqlite3VdbeJumpHere(v, addr1);
  108664. updateAccumulator(pParse, &sAggInfo);
  108665. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  108666. VdbeComment((v, "indicate data in accumulator"));
  108667. /* End of the loop
  108668. */
  108669. if( groupBySort ){
  108670. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  108671. VdbeCoverage(v);
  108672. }else{
  108673. sqlite3WhereEnd(pWInfo);
  108674. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  108675. }
  108676. /* Output the final row of result
  108677. */
  108678. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  108679. VdbeComment((v, "output final row"));
  108680. /* Jump over the subroutines
  108681. */
  108682. sqlite3VdbeGoto(v, addrEnd);
  108683. /* Generate a subroutine that outputs a single row of the result
  108684. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  108685. ** is less than or equal to zero, the subroutine is a no-op. If
  108686. ** the processing calls for the query to abort, this subroutine
  108687. ** increments the iAbortFlag memory location before returning in
  108688. ** order to signal the caller to abort.
  108689. */
  108690. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  108691. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  108692. VdbeComment((v, "set abort flag"));
  108693. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  108694. sqlite3VdbeResolveLabel(v, addrOutputRow);
  108695. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  108696. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  108697. VdbeCoverage(v);
  108698. VdbeComment((v, "Groupby result generator entry point"));
  108699. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  108700. finalizeAggFunctions(pParse, &sAggInfo);
  108701. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  108702. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  108703. &sDistinct, pDest,
  108704. addrOutputRow+1, addrSetAbort);
  108705. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  108706. VdbeComment((v, "end groupby result generator"));
  108707. /* Generate a subroutine that will reset the group-by accumulator
  108708. */
  108709. sqlite3VdbeResolveLabel(v, addrReset);
  108710. resetAccumulator(pParse, &sAggInfo);
  108711. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  108712. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  108713. else {
  108714. ExprList *pDel = 0;
  108715. #ifndef SQLITE_OMIT_BTREECOUNT
  108716. Table *pTab;
  108717. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  108718. /* If isSimpleCount() returns a pointer to a Table structure, then
  108719. ** the SQL statement is of the form:
  108720. **
  108721. ** SELECT count(*) FROM <tbl>
  108722. **
  108723. ** where the Table structure returned represents table <tbl>.
  108724. **
  108725. ** This statement is so common that it is optimized specially. The
  108726. ** OP_Count instruction is executed either on the intkey table that
  108727. ** contains the data for table <tbl> or on one of its indexes. It
  108728. ** is better to execute the op on an index, as indexes are almost
  108729. ** always spread across less pages than their corresponding tables.
  108730. */
  108731. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  108732. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  108733. Index *pIdx; /* Iterator variable */
  108734. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  108735. Index *pBest = 0; /* Best index found so far */
  108736. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  108737. sqlite3CodeVerifySchema(pParse, iDb);
  108738. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  108739. /* Search for the index that has the lowest scan cost.
  108740. **
  108741. ** (2011-04-15) Do not do a full scan of an unordered index.
  108742. **
  108743. ** (2013-10-03) Do not count the entries in a partial index.
  108744. **
  108745. ** In practice the KeyInfo structure will not be used. It is only
  108746. ** passed to keep OP_OpenRead happy.
  108747. */
  108748. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  108749. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108750. if( pIdx->bUnordered==0
  108751. && pIdx->szIdxRow<pTab->szTabRow
  108752. && pIdx->pPartIdxWhere==0
  108753. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  108754. ){
  108755. pBest = pIdx;
  108756. }
  108757. }
  108758. if( pBest ){
  108759. iRoot = pBest->tnum;
  108760. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  108761. }
  108762. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  108763. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  108764. if( pKeyInfo ){
  108765. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  108766. }
  108767. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  108768. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  108769. explainSimpleCount(pParse, pTab, pBest);
  108770. }else
  108771. #endif /* SQLITE_OMIT_BTREECOUNT */
  108772. {
  108773. /* Check if the query is of one of the following forms:
  108774. **
  108775. ** SELECT min(x) FROM ...
  108776. ** SELECT max(x) FROM ...
  108777. **
  108778. ** If it is, then ask the code in where.c to attempt to sort results
  108779. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  108780. ** If where.c is able to produce results sorted in this order, then
  108781. ** add vdbe code to break out of the processing loop after the
  108782. ** first iteration (since the first iteration of the loop is
  108783. ** guaranteed to operate on the row with the minimum or maximum
  108784. ** value of x, the only row required).
  108785. **
  108786. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  108787. ** modify behavior as follows:
  108788. **
  108789. ** + If the query is a "SELECT min(x)", then the loop coded by
  108790. ** where.c should not iterate over any values with a NULL value
  108791. ** for x.
  108792. **
  108793. ** + The optimizer code in where.c (the thing that decides which
  108794. ** index or indices to use) should place a different priority on
  108795. ** satisfying the 'ORDER BY' clause than it does in other cases.
  108796. ** Refer to code and comments in where.c for details.
  108797. */
  108798. ExprList *pMinMax = 0;
  108799. u8 flag = WHERE_ORDERBY_NORMAL;
  108800. assert( p->pGroupBy==0 );
  108801. assert( flag==0 );
  108802. if( p->pHaving==0 ){
  108803. flag = minMaxQuery(&sAggInfo, &pMinMax);
  108804. }
  108805. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  108806. if( flag ){
  108807. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  108808. pDel = pMinMax;
  108809. assert( db->mallocFailed || pMinMax!=0 );
  108810. if( !db->mallocFailed ){
  108811. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  108812. pMinMax->a[0].pExpr->op = TK_COLUMN;
  108813. }
  108814. }
  108815. /* This case runs if the aggregate has no GROUP BY clause. The
  108816. ** processing is much simpler since there is only a single row
  108817. ** of output.
  108818. */
  108819. resetAccumulator(pParse, &sAggInfo);
  108820. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  108821. if( pWInfo==0 ){
  108822. sqlite3ExprListDelete(db, pDel);
  108823. goto select_end;
  108824. }
  108825. updateAccumulator(pParse, &sAggInfo);
  108826. assert( pMinMax==0 || pMinMax->nExpr==1 );
  108827. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  108828. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  108829. VdbeComment((v, "%s() by index",
  108830. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  108831. }
  108832. sqlite3WhereEnd(pWInfo);
  108833. finalizeAggFunctions(pParse, &sAggInfo);
  108834. }
  108835. sSort.pOrderBy = 0;
  108836. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  108837. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  108838. pDest, addrEnd, addrEnd);
  108839. sqlite3ExprListDelete(db, pDel);
  108840. }
  108841. sqlite3VdbeResolveLabel(v, addrEnd);
  108842. } /* endif aggregate query */
  108843. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  108844. explainTempTable(pParse, "DISTINCT");
  108845. }
  108846. /* If there is an ORDER BY clause, then we need to sort the results
  108847. ** and send them to the callback one by one.
  108848. */
  108849. if( sSort.pOrderBy ){
  108850. explainTempTable(pParse,
  108851. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  108852. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  108853. }
  108854. /* Jump here to skip this query
  108855. */
  108856. sqlite3VdbeResolveLabel(v, iEnd);
  108857. /* The SELECT has been coded. If there is an error in the Parse structure,
  108858. ** set the return code to 1. Otherwise 0. */
  108859. rc = (pParse->nErr>0);
  108860. /* Control jumps to here if an error is encountered above, or upon
  108861. ** successful coding of the SELECT.
  108862. */
  108863. select_end:
  108864. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  108865. /* Identify column names if results of the SELECT are to be output.
  108866. */
  108867. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  108868. generateColumnNames(pParse, pTabList, pEList);
  108869. }
  108870. sqlite3DbFree(db, sAggInfo.aCol);
  108871. sqlite3DbFree(db, sAggInfo.aFunc);
  108872. #if SELECTTRACE_ENABLED
  108873. SELECTTRACE(1,pParse,p,("end processing\n"));
  108874. pParse->nSelectIndent--;
  108875. #endif
  108876. return rc;
  108877. }
  108878. /************** End of select.c **********************************************/
  108879. /************** Begin file table.c *******************************************/
  108880. /*
  108881. ** 2001 September 15
  108882. **
  108883. ** The author disclaims copyright to this source code. In place of
  108884. ** a legal notice, here is a blessing:
  108885. **
  108886. ** May you do good and not evil.
  108887. ** May you find forgiveness for yourself and forgive others.
  108888. ** May you share freely, never taking more than you give.
  108889. **
  108890. *************************************************************************
  108891. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  108892. ** interface routines. These are just wrappers around the main
  108893. ** interface routine of sqlite3_exec().
  108894. **
  108895. ** These routines are in a separate files so that they will not be linked
  108896. ** if they are not used.
  108897. */
  108898. /* #include "sqliteInt.h" */
  108899. /* #include <stdlib.h> */
  108900. /* #include <string.h> */
  108901. #ifndef SQLITE_OMIT_GET_TABLE
  108902. /*
  108903. ** This structure is used to pass data from sqlite3_get_table() through
  108904. ** to the callback function is uses to build the result.
  108905. */
  108906. typedef struct TabResult {
  108907. char **azResult; /* Accumulated output */
  108908. char *zErrMsg; /* Error message text, if an error occurs */
  108909. u32 nAlloc; /* Slots allocated for azResult[] */
  108910. u32 nRow; /* Number of rows in the result */
  108911. u32 nColumn; /* Number of columns in the result */
  108912. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  108913. int rc; /* Return code from sqlite3_exec() */
  108914. } TabResult;
  108915. /*
  108916. ** This routine is called once for each row in the result table. Its job
  108917. ** is to fill in the TabResult structure appropriately, allocating new
  108918. ** memory as necessary.
  108919. */
  108920. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  108921. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  108922. int need; /* Slots needed in p->azResult[] */
  108923. int i; /* Loop counter */
  108924. char *z; /* A single column of result */
  108925. /* Make sure there is enough space in p->azResult to hold everything
  108926. ** we need to remember from this invocation of the callback.
  108927. */
  108928. if( p->nRow==0 && argv!=0 ){
  108929. need = nCol*2;
  108930. }else{
  108931. need = nCol;
  108932. }
  108933. if( p->nData + need > p->nAlloc ){
  108934. char **azNew;
  108935. p->nAlloc = p->nAlloc*2 + need;
  108936. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  108937. if( azNew==0 ) goto malloc_failed;
  108938. p->azResult = azNew;
  108939. }
  108940. /* If this is the first row, then generate an extra row containing
  108941. ** the names of all columns.
  108942. */
  108943. if( p->nRow==0 ){
  108944. p->nColumn = nCol;
  108945. for(i=0; i<nCol; i++){
  108946. z = sqlite3_mprintf("%s", colv[i]);
  108947. if( z==0 ) goto malloc_failed;
  108948. p->azResult[p->nData++] = z;
  108949. }
  108950. }else if( (int)p->nColumn!=nCol ){
  108951. sqlite3_free(p->zErrMsg);
  108952. p->zErrMsg = sqlite3_mprintf(
  108953. "sqlite3_get_table() called with two or more incompatible queries"
  108954. );
  108955. p->rc = SQLITE_ERROR;
  108956. return 1;
  108957. }
  108958. /* Copy over the row data
  108959. */
  108960. if( argv!=0 ){
  108961. for(i=0; i<nCol; i++){
  108962. if( argv[i]==0 ){
  108963. z = 0;
  108964. }else{
  108965. int n = sqlite3Strlen30(argv[i])+1;
  108966. z = sqlite3_malloc64( n );
  108967. if( z==0 ) goto malloc_failed;
  108968. memcpy(z, argv[i], n);
  108969. }
  108970. p->azResult[p->nData++] = z;
  108971. }
  108972. p->nRow++;
  108973. }
  108974. return 0;
  108975. malloc_failed:
  108976. p->rc = SQLITE_NOMEM_BKPT;
  108977. return 1;
  108978. }
  108979. /*
  108980. ** Query the database. But instead of invoking a callback for each row,
  108981. ** malloc() for space to hold the result and return the entire results
  108982. ** at the conclusion of the call.
  108983. **
  108984. ** The result that is written to ***pazResult is held in memory obtained
  108985. ** from malloc(). But the caller cannot free this memory directly.
  108986. ** Instead, the entire table should be passed to sqlite3_free_table() when
  108987. ** the calling procedure is finished using it.
  108988. */
  108989. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  108990. sqlite3 *db, /* The database on which the SQL executes */
  108991. const char *zSql, /* The SQL to be executed */
  108992. char ***pazResult, /* Write the result table here */
  108993. int *pnRow, /* Write the number of rows in the result here */
  108994. int *pnColumn, /* Write the number of columns of result here */
  108995. char **pzErrMsg /* Write error messages here */
  108996. ){
  108997. int rc;
  108998. TabResult res;
  108999. #ifdef SQLITE_ENABLE_API_ARMOR
  109000. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  109001. #endif
  109002. *pazResult = 0;
  109003. if( pnColumn ) *pnColumn = 0;
  109004. if( pnRow ) *pnRow = 0;
  109005. if( pzErrMsg ) *pzErrMsg = 0;
  109006. res.zErrMsg = 0;
  109007. res.nRow = 0;
  109008. res.nColumn = 0;
  109009. res.nData = 1;
  109010. res.nAlloc = 20;
  109011. res.rc = SQLITE_OK;
  109012. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  109013. if( res.azResult==0 ){
  109014. db->errCode = SQLITE_NOMEM;
  109015. return SQLITE_NOMEM_BKPT;
  109016. }
  109017. res.azResult[0] = 0;
  109018. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  109019. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  109020. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  109021. if( (rc&0xff)==SQLITE_ABORT ){
  109022. sqlite3_free_table(&res.azResult[1]);
  109023. if( res.zErrMsg ){
  109024. if( pzErrMsg ){
  109025. sqlite3_free(*pzErrMsg);
  109026. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  109027. }
  109028. sqlite3_free(res.zErrMsg);
  109029. }
  109030. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  109031. return res.rc;
  109032. }
  109033. sqlite3_free(res.zErrMsg);
  109034. if( rc!=SQLITE_OK ){
  109035. sqlite3_free_table(&res.azResult[1]);
  109036. return rc;
  109037. }
  109038. if( res.nAlloc>res.nData ){
  109039. char **azNew;
  109040. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  109041. if( azNew==0 ){
  109042. sqlite3_free_table(&res.azResult[1]);
  109043. db->errCode = SQLITE_NOMEM;
  109044. return SQLITE_NOMEM_BKPT;
  109045. }
  109046. res.azResult = azNew;
  109047. }
  109048. *pazResult = &res.azResult[1];
  109049. if( pnColumn ) *pnColumn = res.nColumn;
  109050. if( pnRow ) *pnRow = res.nRow;
  109051. return rc;
  109052. }
  109053. /*
  109054. ** This routine frees the space the sqlite3_get_table() malloced.
  109055. */
  109056. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
  109057. char **azResult /* Result returned from sqlite3_get_table() */
  109058. ){
  109059. if( azResult ){
  109060. int i, n;
  109061. azResult--;
  109062. assert( azResult!=0 );
  109063. n = SQLITE_PTR_TO_INT(azResult[0]);
  109064. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  109065. sqlite3_free(azResult);
  109066. }
  109067. }
  109068. #endif /* SQLITE_OMIT_GET_TABLE */
  109069. /************** End of table.c ***********************************************/
  109070. /************** Begin file trigger.c *****************************************/
  109071. /*
  109072. **
  109073. ** The author disclaims copyright to this source code. In place of
  109074. ** a legal notice, here is a blessing:
  109075. **
  109076. ** May you do good and not evil.
  109077. ** May you find forgiveness for yourself and forgive others.
  109078. ** May you share freely, never taking more than you give.
  109079. **
  109080. *************************************************************************
  109081. ** This file contains the implementation for TRIGGERs
  109082. */
  109083. /* #include "sqliteInt.h" */
  109084. #ifndef SQLITE_OMIT_TRIGGER
  109085. /*
  109086. ** Delete a linked list of TriggerStep structures.
  109087. */
  109088. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  109089. while( pTriggerStep ){
  109090. TriggerStep * pTmp = pTriggerStep;
  109091. pTriggerStep = pTriggerStep->pNext;
  109092. sqlite3ExprDelete(db, pTmp->pWhere);
  109093. sqlite3ExprListDelete(db, pTmp->pExprList);
  109094. sqlite3SelectDelete(db, pTmp->pSelect);
  109095. sqlite3IdListDelete(db, pTmp->pIdList);
  109096. sqlite3DbFree(db, pTmp);
  109097. }
  109098. }
  109099. /*
  109100. ** Given table pTab, return a list of all the triggers attached to
  109101. ** the table. The list is connected by Trigger.pNext pointers.
  109102. **
  109103. ** All of the triggers on pTab that are in the same database as pTab
  109104. ** are already attached to pTab->pTrigger. But there might be additional
  109105. ** triggers on pTab in the TEMP schema. This routine prepends all
  109106. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  109107. ** and returns the combined list.
  109108. **
  109109. ** To state it another way: This routine returns a list of all triggers
  109110. ** that fire off of pTab. The list will include any TEMP triggers on
  109111. ** pTab as well as the triggers lised in pTab->pTrigger.
  109112. */
  109113. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  109114. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  109115. Trigger *pList = 0; /* List of triggers to return */
  109116. if( pParse->disableTriggers ){
  109117. return 0;
  109118. }
  109119. if( pTmpSchema!=pTab->pSchema ){
  109120. HashElem *p;
  109121. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  109122. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  109123. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  109124. if( pTrig->pTabSchema==pTab->pSchema
  109125. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  109126. ){
  109127. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  109128. pList = pTrig;
  109129. }
  109130. }
  109131. }
  109132. return (pList ? pList : pTab->pTrigger);
  109133. }
  109134. /*
  109135. ** This is called by the parser when it sees a CREATE TRIGGER statement
  109136. ** up to the point of the BEGIN before the trigger actions. A Trigger
  109137. ** structure is generated based on the information available and stored
  109138. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  109139. ** sqlite3FinishTrigger() function is called to complete the trigger
  109140. ** construction process.
  109141. */
  109142. SQLITE_PRIVATE void sqlite3BeginTrigger(
  109143. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  109144. Token *pName1, /* The name of the trigger */
  109145. Token *pName2, /* The name of the trigger */
  109146. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  109147. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  109148. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  109149. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  109150. Expr *pWhen, /* WHEN clause */
  109151. int isTemp, /* True if the TEMPORARY keyword is present */
  109152. int noErr /* Suppress errors if the trigger already exists */
  109153. ){
  109154. Trigger *pTrigger = 0; /* The new trigger */
  109155. Table *pTab; /* Table that the trigger fires off of */
  109156. char *zName = 0; /* Name of the trigger */
  109157. sqlite3 *db = pParse->db; /* The database connection */
  109158. int iDb; /* The database to store the trigger in */
  109159. Token *pName; /* The unqualified db name */
  109160. DbFixer sFix; /* State vector for the DB fixer */
  109161. int iTabDb; /* Index of the database holding pTab */
  109162. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  109163. assert( pName2!=0 );
  109164. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  109165. assert( op>0 && op<0xff );
  109166. if( isTemp ){
  109167. /* If TEMP was specified, then the trigger name may not be qualified. */
  109168. if( pName2->n>0 ){
  109169. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  109170. goto trigger_cleanup;
  109171. }
  109172. iDb = 1;
  109173. pName = pName1;
  109174. }else{
  109175. /* Figure out the db that the trigger will be created in */
  109176. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  109177. if( iDb<0 ){
  109178. goto trigger_cleanup;
  109179. }
  109180. }
  109181. if( !pTableName || db->mallocFailed ){
  109182. goto trigger_cleanup;
  109183. }
  109184. /* A long-standing parser bug is that this syntax was allowed:
  109185. **
  109186. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  109187. ** ^^^^^^^^
  109188. **
  109189. ** To maintain backwards compatibility, ignore the database
  109190. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  109191. */
  109192. if( db->init.busy && iDb!=1 ){
  109193. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  109194. pTableName->a[0].zDatabase = 0;
  109195. }
  109196. /* If the trigger name was unqualified, and the table is a temp table,
  109197. ** then set iDb to 1 to create the trigger in the temporary database.
  109198. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  109199. ** exist, the error is caught by the block below.
  109200. */
  109201. pTab = sqlite3SrcListLookup(pParse, pTableName);
  109202. if( db->init.busy==0 && pName2->n==0 && pTab
  109203. && pTab->pSchema==db->aDb[1].pSchema ){
  109204. iDb = 1;
  109205. }
  109206. /* Ensure the table name matches database name and that the table exists */
  109207. if( db->mallocFailed ) goto trigger_cleanup;
  109208. assert( pTableName->nSrc==1 );
  109209. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  109210. if( sqlite3FixSrcList(&sFix, pTableName) ){
  109211. goto trigger_cleanup;
  109212. }
  109213. pTab = sqlite3SrcListLookup(pParse, pTableName);
  109214. if( !pTab ){
  109215. /* The table does not exist. */
  109216. if( db->init.iDb==1 ){
  109217. /* Ticket #3810.
  109218. ** Normally, whenever a table is dropped, all associated triggers are
  109219. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  109220. ** and the table is dropped by a different database connection, the
  109221. ** trigger is not visible to the database connection that does the
  109222. ** drop so the trigger cannot be dropped. This results in an
  109223. ** "orphaned trigger" - a trigger whose associated table is missing.
  109224. */
  109225. db->init.orphanTrigger = 1;
  109226. }
  109227. goto trigger_cleanup;
  109228. }
  109229. if( IsVirtual(pTab) ){
  109230. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  109231. goto trigger_cleanup;
  109232. }
  109233. /* Check that the trigger name is not reserved and that no trigger of the
  109234. ** specified name exists */
  109235. zName = sqlite3NameFromToken(db, pName);
  109236. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  109237. goto trigger_cleanup;
  109238. }
  109239. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  109240. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  109241. if( !noErr ){
  109242. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  109243. }else{
  109244. assert( !db->init.busy );
  109245. sqlite3CodeVerifySchema(pParse, iDb);
  109246. }
  109247. goto trigger_cleanup;
  109248. }
  109249. /* Do not create a trigger on a system table */
  109250. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  109251. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  109252. goto trigger_cleanup;
  109253. }
  109254. /* INSTEAD of triggers are only for views and views only support INSTEAD
  109255. ** of triggers.
  109256. */
  109257. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  109258. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  109259. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  109260. goto trigger_cleanup;
  109261. }
  109262. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  109263. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  109264. " trigger on table: %S", pTableName, 0);
  109265. goto trigger_cleanup;
  109266. }
  109267. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  109268. #ifndef SQLITE_OMIT_AUTHORIZATION
  109269. {
  109270. int code = SQLITE_CREATE_TRIGGER;
  109271. const char *zDb = db->aDb[iTabDb].zName;
  109272. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  109273. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  109274. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  109275. goto trigger_cleanup;
  109276. }
  109277. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  109278. goto trigger_cleanup;
  109279. }
  109280. }
  109281. #endif
  109282. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  109283. ** cannot appear on views. So we might as well translate every
  109284. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  109285. ** elsewhere.
  109286. */
  109287. if (tr_tm == TK_INSTEAD){
  109288. tr_tm = TK_BEFORE;
  109289. }
  109290. /* Build the Trigger object */
  109291. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  109292. if( pTrigger==0 ) goto trigger_cleanup;
  109293. pTrigger->zName = zName;
  109294. zName = 0;
  109295. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  109296. pTrigger->pSchema = db->aDb[iDb].pSchema;
  109297. pTrigger->pTabSchema = pTab->pSchema;
  109298. pTrigger->op = (u8)op;
  109299. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  109300. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  109301. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  109302. assert( pParse->pNewTrigger==0 );
  109303. pParse->pNewTrigger = pTrigger;
  109304. trigger_cleanup:
  109305. sqlite3DbFree(db, zName);
  109306. sqlite3SrcListDelete(db, pTableName);
  109307. sqlite3IdListDelete(db, pColumns);
  109308. sqlite3ExprDelete(db, pWhen);
  109309. if( !pParse->pNewTrigger ){
  109310. sqlite3DeleteTrigger(db, pTrigger);
  109311. }else{
  109312. assert( pParse->pNewTrigger==pTrigger );
  109313. }
  109314. }
  109315. /*
  109316. ** This routine is called after all of the trigger actions have been parsed
  109317. ** in order to complete the process of building the trigger.
  109318. */
  109319. SQLITE_PRIVATE void sqlite3FinishTrigger(
  109320. Parse *pParse, /* Parser context */
  109321. TriggerStep *pStepList, /* The triggered program */
  109322. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  109323. ){
  109324. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  109325. char *zName; /* Name of trigger */
  109326. sqlite3 *db = pParse->db; /* The database */
  109327. DbFixer sFix; /* Fixer object */
  109328. int iDb; /* Database containing the trigger */
  109329. Token nameToken; /* Trigger name for error reporting */
  109330. pParse->pNewTrigger = 0;
  109331. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  109332. zName = pTrig->zName;
  109333. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  109334. pTrig->step_list = pStepList;
  109335. while( pStepList ){
  109336. pStepList->pTrig = pTrig;
  109337. pStepList = pStepList->pNext;
  109338. }
  109339. sqlite3TokenInit(&nameToken, pTrig->zName);
  109340. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  109341. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  109342. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  109343. ){
  109344. goto triggerfinish_cleanup;
  109345. }
  109346. /* if we are not initializing,
  109347. ** build the sqlite_master entry
  109348. */
  109349. if( !db->init.busy ){
  109350. Vdbe *v;
  109351. char *z;
  109352. /* Make an entry in the sqlite_master table */
  109353. v = sqlite3GetVdbe(pParse);
  109354. if( v==0 ) goto triggerfinish_cleanup;
  109355. sqlite3BeginWriteOperation(pParse, 0, iDb);
  109356. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  109357. sqlite3NestedParse(pParse,
  109358. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  109359. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  109360. pTrig->table, z);
  109361. sqlite3DbFree(db, z);
  109362. sqlite3ChangeCookie(pParse, iDb);
  109363. sqlite3VdbeAddParseSchemaOp(v, iDb,
  109364. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  109365. }
  109366. if( db->init.busy ){
  109367. Trigger *pLink = pTrig;
  109368. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  109369. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  109370. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  109371. if( pTrig ){
  109372. sqlite3OomFault(db);
  109373. }else if( pLink->pSchema==pLink->pTabSchema ){
  109374. Table *pTab;
  109375. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  109376. assert( pTab!=0 );
  109377. pLink->pNext = pTab->pTrigger;
  109378. pTab->pTrigger = pLink;
  109379. }
  109380. }
  109381. triggerfinish_cleanup:
  109382. sqlite3DeleteTrigger(db, pTrig);
  109383. assert( !pParse->pNewTrigger );
  109384. sqlite3DeleteTriggerStep(db, pStepList);
  109385. }
  109386. /*
  109387. ** Turn a SELECT statement (that the pSelect parameter points to) into
  109388. ** a trigger step. Return a pointer to a TriggerStep structure.
  109389. **
  109390. ** The parser calls this routine when it finds a SELECT statement in
  109391. ** body of a TRIGGER.
  109392. */
  109393. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  109394. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  109395. if( pTriggerStep==0 ) {
  109396. sqlite3SelectDelete(db, pSelect);
  109397. return 0;
  109398. }
  109399. pTriggerStep->op = TK_SELECT;
  109400. pTriggerStep->pSelect = pSelect;
  109401. pTriggerStep->orconf = OE_Default;
  109402. return pTriggerStep;
  109403. }
  109404. /*
  109405. ** Allocate space to hold a new trigger step. The allocated space
  109406. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  109407. **
  109408. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  109409. */
  109410. static TriggerStep *triggerStepAllocate(
  109411. sqlite3 *db, /* Database connection */
  109412. u8 op, /* Trigger opcode */
  109413. Token *pName /* The target name */
  109414. ){
  109415. TriggerStep *pTriggerStep;
  109416. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  109417. if( pTriggerStep ){
  109418. char *z = (char*)&pTriggerStep[1];
  109419. memcpy(z, pName->z, pName->n);
  109420. sqlite3Dequote(z);
  109421. pTriggerStep->zTarget = z;
  109422. pTriggerStep->op = op;
  109423. }
  109424. return pTriggerStep;
  109425. }
  109426. /*
  109427. ** Build a trigger step out of an INSERT statement. Return a pointer
  109428. ** to the new trigger step.
  109429. **
  109430. ** The parser calls this routine when it sees an INSERT inside the
  109431. ** body of a trigger.
  109432. */
  109433. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  109434. sqlite3 *db, /* The database connection */
  109435. Token *pTableName, /* Name of the table into which we insert */
  109436. IdList *pColumn, /* List of columns in pTableName to insert into */
  109437. Select *pSelect, /* A SELECT statement that supplies values */
  109438. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  109439. ){
  109440. TriggerStep *pTriggerStep;
  109441. assert(pSelect != 0 || db->mallocFailed);
  109442. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  109443. if( pTriggerStep ){
  109444. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  109445. pTriggerStep->pIdList = pColumn;
  109446. pTriggerStep->orconf = orconf;
  109447. }else{
  109448. sqlite3IdListDelete(db, pColumn);
  109449. }
  109450. sqlite3SelectDelete(db, pSelect);
  109451. return pTriggerStep;
  109452. }
  109453. /*
  109454. ** Construct a trigger step that implements an UPDATE statement and return
  109455. ** a pointer to that trigger step. The parser calls this routine when it
  109456. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  109457. */
  109458. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  109459. sqlite3 *db, /* The database connection */
  109460. Token *pTableName, /* Name of the table to be updated */
  109461. ExprList *pEList, /* The SET clause: list of column and new values */
  109462. Expr *pWhere, /* The WHERE clause */
  109463. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  109464. ){
  109465. TriggerStep *pTriggerStep;
  109466. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  109467. if( pTriggerStep ){
  109468. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  109469. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  109470. pTriggerStep->orconf = orconf;
  109471. }
  109472. sqlite3ExprListDelete(db, pEList);
  109473. sqlite3ExprDelete(db, pWhere);
  109474. return pTriggerStep;
  109475. }
  109476. /*
  109477. ** Construct a trigger step that implements a DELETE statement and return
  109478. ** a pointer to that trigger step. The parser calls this routine when it
  109479. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  109480. */
  109481. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  109482. sqlite3 *db, /* Database connection */
  109483. Token *pTableName, /* The table from which rows are deleted */
  109484. Expr *pWhere /* The WHERE clause */
  109485. ){
  109486. TriggerStep *pTriggerStep;
  109487. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  109488. if( pTriggerStep ){
  109489. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  109490. pTriggerStep->orconf = OE_Default;
  109491. }
  109492. sqlite3ExprDelete(db, pWhere);
  109493. return pTriggerStep;
  109494. }
  109495. /*
  109496. ** Recursively delete a Trigger structure
  109497. */
  109498. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  109499. if( pTrigger==0 ) return;
  109500. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  109501. sqlite3DbFree(db, pTrigger->zName);
  109502. sqlite3DbFree(db, pTrigger->table);
  109503. sqlite3ExprDelete(db, pTrigger->pWhen);
  109504. sqlite3IdListDelete(db, pTrigger->pColumns);
  109505. sqlite3DbFree(db, pTrigger);
  109506. }
  109507. /*
  109508. ** This function is called to drop a trigger from the database schema.
  109509. **
  109510. ** This may be called directly from the parser and therefore identifies
  109511. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  109512. ** same job as this routine except it takes a pointer to the trigger
  109513. ** instead of the trigger name.
  109514. **/
  109515. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  109516. Trigger *pTrigger = 0;
  109517. int i;
  109518. const char *zDb;
  109519. const char *zName;
  109520. sqlite3 *db = pParse->db;
  109521. if( db->mallocFailed ) goto drop_trigger_cleanup;
  109522. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  109523. goto drop_trigger_cleanup;
  109524. }
  109525. assert( pName->nSrc==1 );
  109526. zDb = pName->a[0].zDatabase;
  109527. zName = pName->a[0].zName;
  109528. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  109529. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  109530. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  109531. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  109532. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  109533. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  109534. if( pTrigger ) break;
  109535. }
  109536. if( !pTrigger ){
  109537. if( !noErr ){
  109538. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  109539. }else{
  109540. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  109541. }
  109542. pParse->checkSchema = 1;
  109543. goto drop_trigger_cleanup;
  109544. }
  109545. sqlite3DropTriggerPtr(pParse, pTrigger);
  109546. drop_trigger_cleanup:
  109547. sqlite3SrcListDelete(db, pName);
  109548. }
  109549. /*
  109550. ** Return a pointer to the Table structure for the table that a trigger
  109551. ** is set on.
  109552. */
  109553. static Table *tableOfTrigger(Trigger *pTrigger){
  109554. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  109555. }
  109556. /*
  109557. ** Drop a trigger given a pointer to that trigger.
  109558. */
  109559. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  109560. Table *pTable;
  109561. Vdbe *v;
  109562. sqlite3 *db = pParse->db;
  109563. int iDb;
  109564. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  109565. assert( iDb>=0 && iDb<db->nDb );
  109566. pTable = tableOfTrigger(pTrigger);
  109567. assert( pTable );
  109568. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  109569. #ifndef SQLITE_OMIT_AUTHORIZATION
  109570. {
  109571. int code = SQLITE_DROP_TRIGGER;
  109572. const char *zDb = db->aDb[iDb].zName;
  109573. const char *zTab = SCHEMA_TABLE(iDb);
  109574. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  109575. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  109576. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  109577. return;
  109578. }
  109579. }
  109580. #endif
  109581. /* Generate code to destroy the database record of the trigger.
  109582. */
  109583. assert( pTable!=0 );
  109584. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  109585. sqlite3NestedParse(pParse,
  109586. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  109587. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
  109588. );
  109589. sqlite3ChangeCookie(pParse, iDb);
  109590. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  109591. }
  109592. }
  109593. /*
  109594. ** Remove a trigger from the hash tables of the sqlite* pointer.
  109595. */
  109596. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  109597. Trigger *pTrigger;
  109598. Hash *pHash;
  109599. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  109600. pHash = &(db->aDb[iDb].pSchema->trigHash);
  109601. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  109602. if( ALWAYS(pTrigger) ){
  109603. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  109604. Table *pTab = tableOfTrigger(pTrigger);
  109605. Trigger **pp;
  109606. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  109607. *pp = (*pp)->pNext;
  109608. }
  109609. sqlite3DeleteTrigger(db, pTrigger);
  109610. db->flags |= SQLITE_InternChanges;
  109611. }
  109612. }
  109613. /*
  109614. ** pEList is the SET clause of an UPDATE statement. Each entry
  109615. ** in pEList is of the format <id>=<expr>. If any of the entries
  109616. ** in pEList have an <id> which matches an identifier in pIdList,
  109617. ** then return TRUE. If pIdList==NULL, then it is considered a
  109618. ** wildcard that matches anything. Likewise if pEList==NULL then
  109619. ** it matches anything so always return true. Return false only
  109620. ** if there is no match.
  109621. */
  109622. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  109623. int e;
  109624. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  109625. for(e=0; e<pEList->nExpr; e++){
  109626. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  109627. }
  109628. return 0;
  109629. }
  109630. /*
  109631. ** Return a list of all triggers on table pTab if there exists at least
  109632. ** one trigger that must be fired when an operation of type 'op' is
  109633. ** performed on the table, and, if that operation is an UPDATE, if at
  109634. ** least one of the columns in pChanges is being modified.
  109635. */
  109636. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  109637. Parse *pParse, /* Parse context */
  109638. Table *pTab, /* The table the contains the triggers */
  109639. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  109640. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  109641. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  109642. ){
  109643. int mask = 0;
  109644. Trigger *pList = 0;
  109645. Trigger *p;
  109646. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  109647. pList = sqlite3TriggerList(pParse, pTab);
  109648. }
  109649. assert( pList==0 || IsVirtual(pTab)==0 );
  109650. for(p=pList; p; p=p->pNext){
  109651. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  109652. mask |= p->tr_tm;
  109653. }
  109654. }
  109655. if( pMask ){
  109656. *pMask = mask;
  109657. }
  109658. return (mask ? pList : 0);
  109659. }
  109660. /*
  109661. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  109662. ** to that SrcList.
  109663. **
  109664. ** This routine adds a specific database name, if needed, to the target when
  109665. ** forming the SrcList. This prevents a trigger in one database from
  109666. ** referring to a target in another database. An exception is when the
  109667. ** trigger is in TEMP in which case it can refer to any other database it
  109668. ** wants.
  109669. */
  109670. static SrcList *targetSrcList(
  109671. Parse *pParse, /* The parsing context */
  109672. TriggerStep *pStep /* The trigger containing the target token */
  109673. ){
  109674. sqlite3 *db = pParse->db;
  109675. int iDb; /* Index of the database to use */
  109676. SrcList *pSrc; /* SrcList to be returned */
  109677. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  109678. if( pSrc ){
  109679. assert( pSrc->nSrc>0 );
  109680. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  109681. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  109682. if( iDb==0 || iDb>=2 ){
  109683. assert( iDb<db->nDb );
  109684. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  109685. }
  109686. }
  109687. return pSrc;
  109688. }
  109689. /*
  109690. ** Generate VDBE code for the statements inside the body of a single
  109691. ** trigger.
  109692. */
  109693. static int codeTriggerProgram(
  109694. Parse *pParse, /* The parser context */
  109695. TriggerStep *pStepList, /* List of statements inside the trigger body */
  109696. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  109697. ){
  109698. TriggerStep *pStep;
  109699. Vdbe *v = pParse->pVdbe;
  109700. sqlite3 *db = pParse->db;
  109701. assert( pParse->pTriggerTab && pParse->pToplevel );
  109702. assert( pStepList );
  109703. assert( v!=0 );
  109704. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  109705. /* Figure out the ON CONFLICT policy that will be used for this step
  109706. ** of the trigger program. If the statement that caused this trigger
  109707. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  109708. ** the ON CONFLICT policy that was specified as part of the trigger
  109709. ** step statement. Example:
  109710. **
  109711. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  109712. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  109713. ** END;
  109714. **
  109715. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  109716. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  109717. */
  109718. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  109719. assert( pParse->okConstFactor==0 );
  109720. switch( pStep->op ){
  109721. case TK_UPDATE: {
  109722. sqlite3Update(pParse,
  109723. targetSrcList(pParse, pStep),
  109724. sqlite3ExprListDup(db, pStep->pExprList, 0),
  109725. sqlite3ExprDup(db, pStep->pWhere, 0),
  109726. pParse->eOrconf
  109727. );
  109728. break;
  109729. }
  109730. case TK_INSERT: {
  109731. sqlite3Insert(pParse,
  109732. targetSrcList(pParse, pStep),
  109733. sqlite3SelectDup(db, pStep->pSelect, 0),
  109734. sqlite3IdListDup(db, pStep->pIdList),
  109735. pParse->eOrconf
  109736. );
  109737. break;
  109738. }
  109739. case TK_DELETE: {
  109740. sqlite3DeleteFrom(pParse,
  109741. targetSrcList(pParse, pStep),
  109742. sqlite3ExprDup(db, pStep->pWhere, 0)
  109743. );
  109744. break;
  109745. }
  109746. default: assert( pStep->op==TK_SELECT ); {
  109747. SelectDest sDest;
  109748. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  109749. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  109750. sqlite3Select(pParse, pSelect, &sDest);
  109751. sqlite3SelectDelete(db, pSelect);
  109752. break;
  109753. }
  109754. }
  109755. if( pStep->op!=TK_SELECT ){
  109756. sqlite3VdbeAddOp0(v, OP_ResetCount);
  109757. }
  109758. }
  109759. return 0;
  109760. }
  109761. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  109762. /*
  109763. ** This function is used to add VdbeComment() annotations to a VDBE
  109764. ** program. It is not used in production code, only for debugging.
  109765. */
  109766. static const char *onErrorText(int onError){
  109767. switch( onError ){
  109768. case OE_Abort: return "abort";
  109769. case OE_Rollback: return "rollback";
  109770. case OE_Fail: return "fail";
  109771. case OE_Replace: return "replace";
  109772. case OE_Ignore: return "ignore";
  109773. case OE_Default: return "default";
  109774. }
  109775. return "n/a";
  109776. }
  109777. #endif
  109778. /*
  109779. ** Parse context structure pFrom has just been used to create a sub-vdbe
  109780. ** (trigger program). If an error has occurred, transfer error information
  109781. ** from pFrom to pTo.
  109782. */
  109783. static void transferParseError(Parse *pTo, Parse *pFrom){
  109784. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  109785. assert( pTo->zErrMsg==0 || pTo->nErr );
  109786. if( pTo->nErr==0 ){
  109787. pTo->zErrMsg = pFrom->zErrMsg;
  109788. pTo->nErr = pFrom->nErr;
  109789. pTo->rc = pFrom->rc;
  109790. }else{
  109791. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  109792. }
  109793. }
  109794. /*
  109795. ** Create and populate a new TriggerPrg object with a sub-program
  109796. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  109797. */
  109798. static TriggerPrg *codeRowTrigger(
  109799. Parse *pParse, /* Current parse context */
  109800. Trigger *pTrigger, /* Trigger to code */
  109801. Table *pTab, /* The table pTrigger is attached to */
  109802. int orconf /* ON CONFLICT policy to code trigger program with */
  109803. ){
  109804. Parse *pTop = sqlite3ParseToplevel(pParse);
  109805. sqlite3 *db = pParse->db; /* Database handle */
  109806. TriggerPrg *pPrg; /* Value to return */
  109807. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  109808. Vdbe *v; /* Temporary VM */
  109809. NameContext sNC; /* Name context for sub-vdbe */
  109810. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  109811. Parse *pSubParse; /* Parse context for sub-vdbe */
  109812. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  109813. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  109814. assert( pTop->pVdbe );
  109815. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  109816. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  109817. ** list of the top-level Parse object sooner rather than later. */
  109818. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  109819. if( !pPrg ) return 0;
  109820. pPrg->pNext = pTop->pTriggerPrg;
  109821. pTop->pTriggerPrg = pPrg;
  109822. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  109823. if( !pProgram ) return 0;
  109824. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  109825. pPrg->pTrigger = pTrigger;
  109826. pPrg->orconf = orconf;
  109827. pPrg->aColmask[0] = 0xffffffff;
  109828. pPrg->aColmask[1] = 0xffffffff;
  109829. /* Allocate and populate a new Parse context to use for coding the
  109830. ** trigger sub-program. */
  109831. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  109832. if( !pSubParse ) return 0;
  109833. memset(&sNC, 0, sizeof(sNC));
  109834. sNC.pParse = pSubParse;
  109835. pSubParse->db = db;
  109836. pSubParse->pTriggerTab = pTab;
  109837. pSubParse->pToplevel = pTop;
  109838. pSubParse->zAuthContext = pTrigger->zName;
  109839. pSubParse->eTriggerOp = pTrigger->op;
  109840. pSubParse->nQueryLoop = pParse->nQueryLoop;
  109841. v = sqlite3GetVdbe(pSubParse);
  109842. if( v ){
  109843. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  109844. pTrigger->zName, onErrorText(orconf),
  109845. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  109846. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  109847. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  109848. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  109849. pTab->zName
  109850. ));
  109851. #ifndef SQLITE_OMIT_TRACE
  109852. sqlite3VdbeChangeP4(v, -1,
  109853. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  109854. );
  109855. #endif
  109856. /* If one was specified, code the WHEN clause. If it evaluates to false
  109857. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  109858. ** OP_Halt inserted at the end of the program. */
  109859. if( pTrigger->pWhen ){
  109860. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  109861. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  109862. && db->mallocFailed==0
  109863. ){
  109864. iEndTrigger = sqlite3VdbeMakeLabel(v);
  109865. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  109866. }
  109867. sqlite3ExprDelete(db, pWhen);
  109868. }
  109869. /* Code the trigger program into the sub-vdbe. */
  109870. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  109871. /* Insert an OP_Halt at the end of the sub-program. */
  109872. if( iEndTrigger ){
  109873. sqlite3VdbeResolveLabel(v, iEndTrigger);
  109874. }
  109875. sqlite3VdbeAddOp0(v, OP_Halt);
  109876. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  109877. transferParseError(pParse, pSubParse);
  109878. if( db->mallocFailed==0 ){
  109879. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  109880. }
  109881. pProgram->nMem = pSubParse->nMem;
  109882. pProgram->nCsr = pSubParse->nTab;
  109883. pProgram->nOnce = pSubParse->nOnce;
  109884. pProgram->token = (void *)pTrigger;
  109885. pPrg->aColmask[0] = pSubParse->oldmask;
  109886. pPrg->aColmask[1] = pSubParse->newmask;
  109887. sqlite3VdbeDelete(v);
  109888. }
  109889. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  109890. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  109891. sqlite3ParserReset(pSubParse);
  109892. sqlite3StackFree(db, pSubParse);
  109893. return pPrg;
  109894. }
  109895. /*
  109896. ** Return a pointer to a TriggerPrg object containing the sub-program for
  109897. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  109898. ** TriggerPrg object exists, a new object is allocated and populated before
  109899. ** being returned.
  109900. */
  109901. static TriggerPrg *getRowTrigger(
  109902. Parse *pParse, /* Current parse context */
  109903. Trigger *pTrigger, /* Trigger to code */
  109904. Table *pTab, /* The table trigger pTrigger is attached to */
  109905. int orconf /* ON CONFLICT algorithm. */
  109906. ){
  109907. Parse *pRoot = sqlite3ParseToplevel(pParse);
  109908. TriggerPrg *pPrg;
  109909. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  109910. /* It may be that this trigger has already been coded (or is in the
  109911. ** process of being coded). If this is the case, then an entry with
  109912. ** a matching TriggerPrg.pTrigger field will be present somewhere
  109913. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  109914. for(pPrg=pRoot->pTriggerPrg;
  109915. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  109916. pPrg=pPrg->pNext
  109917. );
  109918. /* If an existing TriggerPrg could not be located, create a new one. */
  109919. if( !pPrg ){
  109920. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  109921. }
  109922. return pPrg;
  109923. }
  109924. /*
  109925. ** Generate code for the trigger program associated with trigger p on
  109926. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  109927. ** function are the same as those described in the header function for
  109928. ** sqlite3CodeRowTrigger()
  109929. */
  109930. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  109931. Parse *pParse, /* Parse context */
  109932. Trigger *p, /* Trigger to code */
  109933. Table *pTab, /* The table to code triggers from */
  109934. int reg, /* Reg array containing OLD.* and NEW.* values */
  109935. int orconf, /* ON CONFLICT policy */
  109936. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  109937. ){
  109938. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  109939. TriggerPrg *pPrg;
  109940. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  109941. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  109942. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  109943. ** is a pointer to the sub-vdbe containing the trigger program. */
  109944. if( pPrg ){
  109945. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  109946. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  109947. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  109948. VdbeComment(
  109949. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  109950. /* Set the P5 operand of the OP_Program instruction to non-zero if
  109951. ** recursive invocation of this trigger program is disallowed. Recursive
  109952. ** invocation is disallowed if (a) the sub-program is really a trigger,
  109953. ** not a foreign key action, and (b) the flag to enable recursive triggers
  109954. ** is clear. */
  109955. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  109956. }
  109957. }
  109958. /*
  109959. ** This is called to code the required FOR EACH ROW triggers for an operation
  109960. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  109961. ** is given by the op parameter. The tr_tm parameter determines whether the
  109962. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  109963. ** parameter pChanges is passed the list of columns being modified.
  109964. **
  109965. ** If there are no triggers that fire at the specified time for the specified
  109966. ** operation on pTab, this function is a no-op.
  109967. **
  109968. ** The reg argument is the address of the first in an array of registers
  109969. ** that contain the values substituted for the new.* and old.* references
  109970. ** in the trigger program. If N is the number of columns in table pTab
  109971. ** (a copy of pTab->nCol), then registers are populated as follows:
  109972. **
  109973. ** Register Contains
  109974. ** ------------------------------------------------------
  109975. ** reg+0 OLD.rowid
  109976. ** reg+1 OLD.* value of left-most column of pTab
  109977. ** ... ...
  109978. ** reg+N OLD.* value of right-most column of pTab
  109979. ** reg+N+1 NEW.rowid
  109980. ** reg+N+2 OLD.* value of left-most column of pTab
  109981. ** ... ...
  109982. ** reg+N+N+1 NEW.* value of right-most column of pTab
  109983. **
  109984. ** For ON DELETE triggers, the registers containing the NEW.* values will
  109985. ** never be accessed by the trigger program, so they are not allocated or
  109986. ** populated by the caller (there is no data to populate them with anyway).
  109987. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  109988. ** are never accessed, and so are not allocated by the caller. So, for an
  109989. ** ON INSERT trigger, the value passed to this function as parameter reg
  109990. ** is not a readable register, although registers (reg+N) through
  109991. ** (reg+N+N+1) are.
  109992. **
  109993. ** Parameter orconf is the default conflict resolution algorithm for the
  109994. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  109995. ** is the instruction that control should jump to if a trigger program
  109996. ** raises an IGNORE exception.
  109997. */
  109998. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  109999. Parse *pParse, /* Parse context */
  110000. Trigger *pTrigger, /* List of triggers on table pTab */
  110001. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  110002. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  110003. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  110004. Table *pTab, /* The table to code triggers from */
  110005. int reg, /* The first in an array of registers (see above) */
  110006. int orconf, /* ON CONFLICT policy */
  110007. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  110008. ){
  110009. Trigger *p; /* Used to iterate through pTrigger list */
  110010. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  110011. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  110012. assert( (op==TK_UPDATE)==(pChanges!=0) );
  110013. for(p=pTrigger; p; p=p->pNext){
  110014. /* Sanity checking: The schema for the trigger and for the table are
  110015. ** always defined. The trigger must be in the same schema as the table
  110016. ** or else it must be a TEMP trigger. */
  110017. assert( p->pSchema!=0 );
  110018. assert( p->pTabSchema!=0 );
  110019. assert( p->pSchema==p->pTabSchema
  110020. || p->pSchema==pParse->db->aDb[1].pSchema );
  110021. /* Determine whether we should code this trigger */
  110022. if( p->op==op
  110023. && p->tr_tm==tr_tm
  110024. && checkColumnOverlap(p->pColumns, pChanges)
  110025. ){
  110026. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  110027. }
  110028. }
  110029. }
  110030. /*
  110031. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  110032. ** This function returns a 32-bit bitmask indicating which columns of the
  110033. ** old.* or new.* tables actually are used by triggers. This information
  110034. ** may be used by the caller, for example, to avoid having to load the entire
  110035. ** old.* record into memory when executing an UPDATE or DELETE command.
  110036. **
  110037. ** Bit 0 of the returned mask is set if the left-most column of the
  110038. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  110039. ** the second leftmost column value is required, and so on. If there
  110040. ** are more than 32 columns in the table, and at least one of the columns
  110041. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  110042. **
  110043. ** It is not possible to determine if the old.rowid or new.rowid column is
  110044. ** accessed by triggers. The caller must always assume that it is.
  110045. **
  110046. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  110047. ** applies to the old.* table. If 1, the new.* table.
  110048. **
  110049. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  110050. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  110051. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  110052. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  110053. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  110054. */
  110055. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  110056. Parse *pParse, /* Parse context */
  110057. Trigger *pTrigger, /* List of triggers on table pTab */
  110058. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  110059. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  110060. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  110061. Table *pTab, /* The table to code triggers from */
  110062. int orconf /* Default ON CONFLICT policy for trigger steps */
  110063. ){
  110064. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  110065. u32 mask = 0;
  110066. Trigger *p;
  110067. assert( isNew==1 || isNew==0 );
  110068. for(p=pTrigger; p; p=p->pNext){
  110069. if( p->op==op && (tr_tm&p->tr_tm)
  110070. && checkColumnOverlap(p->pColumns,pChanges)
  110071. ){
  110072. TriggerPrg *pPrg;
  110073. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  110074. if( pPrg ){
  110075. mask |= pPrg->aColmask[isNew];
  110076. }
  110077. }
  110078. }
  110079. return mask;
  110080. }
  110081. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  110082. /************** End of trigger.c *********************************************/
  110083. /************** Begin file update.c ******************************************/
  110084. /*
  110085. ** 2001 September 15
  110086. **
  110087. ** The author disclaims copyright to this source code. In place of
  110088. ** a legal notice, here is a blessing:
  110089. **
  110090. ** May you do good and not evil.
  110091. ** May you find forgiveness for yourself and forgive others.
  110092. ** May you share freely, never taking more than you give.
  110093. **
  110094. *************************************************************************
  110095. ** This file contains C code routines that are called by the parser
  110096. ** to handle UPDATE statements.
  110097. */
  110098. /* #include "sqliteInt.h" */
  110099. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110100. /* Forward declaration */
  110101. static void updateVirtualTable(
  110102. Parse *pParse, /* The parsing context */
  110103. SrcList *pSrc, /* The virtual table to be modified */
  110104. Table *pTab, /* The virtual table */
  110105. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  110106. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  110107. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  110108. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  110109. int onError /* ON CONFLICT strategy */
  110110. );
  110111. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110112. /*
  110113. ** The most recently coded instruction was an OP_Column to retrieve the
  110114. ** i-th column of table pTab. This routine sets the P4 parameter of the
  110115. ** OP_Column to the default value, if any.
  110116. **
  110117. ** The default value of a column is specified by a DEFAULT clause in the
  110118. ** column definition. This was either supplied by the user when the table
  110119. ** was created, or added later to the table definition by an ALTER TABLE
  110120. ** command. If the latter, then the row-records in the table btree on disk
  110121. ** may not contain a value for the column and the default value, taken
  110122. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  110123. ** If the former, then all row-records are guaranteed to include a value
  110124. ** for the column and the P4 value is not required.
  110125. **
  110126. ** Column definitions created by an ALTER TABLE command may only have
  110127. ** literal default values specified: a number, null or a string. (If a more
  110128. ** complicated default expression value was provided, it is evaluated
  110129. ** when the ALTER TABLE is executed and one of the literal values written
  110130. ** into the sqlite_master table.)
  110131. **
  110132. ** Therefore, the P4 parameter is only required if the default value for
  110133. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  110134. ** function is capable of transforming these types of expressions into
  110135. ** sqlite3_value objects.
  110136. **
  110137. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  110138. ** on register iReg. This is used when an equivalent integer value is
  110139. ** stored in place of an 8-byte floating point value in order to save
  110140. ** space.
  110141. */
  110142. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  110143. assert( pTab!=0 );
  110144. if( !pTab->pSelect ){
  110145. sqlite3_value *pValue = 0;
  110146. u8 enc = ENC(sqlite3VdbeDb(v));
  110147. Column *pCol = &pTab->aCol[i];
  110148. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  110149. assert( i<pTab->nCol );
  110150. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  110151. pCol->affinity, &pValue);
  110152. if( pValue ){
  110153. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  110154. }
  110155. #ifndef SQLITE_OMIT_FLOATING_POINT
  110156. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  110157. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  110158. }
  110159. #endif
  110160. }
  110161. }
  110162. /*
  110163. ** Process an UPDATE statement.
  110164. **
  110165. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  110166. ** \_______/ \________/ \______/ \________________/
  110167. * onError pTabList pChanges pWhere
  110168. */
  110169. SQLITE_PRIVATE void sqlite3Update(
  110170. Parse *pParse, /* The parser context */
  110171. SrcList *pTabList, /* The table in which we should change things */
  110172. ExprList *pChanges, /* Things to be changed */
  110173. Expr *pWhere, /* The WHERE clause. May be null */
  110174. int onError /* How to handle constraint errors */
  110175. ){
  110176. int i, j; /* Loop counters */
  110177. Table *pTab; /* The table to be updated */
  110178. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  110179. WhereInfo *pWInfo; /* Information about the WHERE clause */
  110180. Vdbe *v; /* The virtual database engine */
  110181. Index *pIdx; /* For looping over indices */
  110182. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  110183. int nIdx; /* Number of indices that need updating */
  110184. int iBaseCur; /* Base cursor number */
  110185. int iDataCur; /* Cursor for the canonical data btree */
  110186. int iIdxCur; /* Cursor for the first index */
  110187. sqlite3 *db; /* The database structure */
  110188. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  110189. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  110190. ** an expression for the i-th column of the table.
  110191. ** aXRef[i]==-1 if the i-th column is not changed. */
  110192. u8 *aToOpen; /* 1 for tables and indices to be opened */
  110193. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  110194. u8 chngRowid; /* Rowid changed in a normal table */
  110195. u8 chngKey; /* Either chngPk or chngRowid */
  110196. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  110197. AuthContext sContext; /* The authorization context */
  110198. NameContext sNC; /* The name-context to resolve expressions in */
  110199. int iDb; /* Database containing the table being updated */
  110200. int okOnePass; /* True for one-pass algorithm without the FIFO */
  110201. int hasFK; /* True if foreign key processing is required */
  110202. int labelBreak; /* Jump here to break out of UPDATE loop */
  110203. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  110204. #ifndef SQLITE_OMIT_TRIGGER
  110205. int isView; /* True when updating a view (INSTEAD OF trigger) */
  110206. Trigger *pTrigger; /* List of triggers on pTab, if required */
  110207. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  110208. #endif
  110209. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  110210. int iEph = 0; /* Ephemeral table holding all primary key values */
  110211. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  110212. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  110213. /* Register Allocations */
  110214. int regRowCount = 0; /* A count of rows changed */
  110215. int regOldRowid = 0; /* The old rowid */
  110216. int regNewRowid = 0; /* The new rowid */
  110217. int regNew = 0; /* Content of the NEW.* table in triggers */
  110218. int regOld = 0; /* Content of OLD.* table in triggers */
  110219. int regRowSet = 0; /* Rowset of rows to be updated */
  110220. int regKey = 0; /* composite PRIMARY KEY value */
  110221. memset(&sContext, 0, sizeof(sContext));
  110222. db = pParse->db;
  110223. if( pParse->nErr || db->mallocFailed ){
  110224. goto update_cleanup;
  110225. }
  110226. assert( pTabList->nSrc==1 );
  110227. /* Locate the table which we want to update.
  110228. */
  110229. pTab = sqlite3SrcListLookup(pParse, pTabList);
  110230. if( pTab==0 ) goto update_cleanup;
  110231. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  110232. /* Figure out if we have any triggers and if the table being
  110233. ** updated is a view.
  110234. */
  110235. #ifndef SQLITE_OMIT_TRIGGER
  110236. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  110237. isView = pTab->pSelect!=0;
  110238. assert( pTrigger || tmask==0 );
  110239. #else
  110240. # define pTrigger 0
  110241. # define isView 0
  110242. # define tmask 0
  110243. #endif
  110244. #ifdef SQLITE_OMIT_VIEW
  110245. # undef isView
  110246. # define isView 0
  110247. #endif
  110248. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  110249. goto update_cleanup;
  110250. }
  110251. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  110252. goto update_cleanup;
  110253. }
  110254. /* Allocate a cursors for the main database table and for all indices.
  110255. ** The index cursors might not be used, but if they are used they
  110256. ** need to occur right after the database cursor. So go ahead and
  110257. ** allocate enough space, just in case.
  110258. */
  110259. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  110260. iIdxCur = iDataCur+1;
  110261. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  110262. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  110263. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  110264. iDataCur = pParse->nTab;
  110265. pTabList->a[0].iCursor = iDataCur;
  110266. }
  110267. pParse->nTab++;
  110268. }
  110269. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  110270. ** Initialize aXRef[] and aToOpen[] to their default values.
  110271. */
  110272. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  110273. if( aXRef==0 ) goto update_cleanup;
  110274. aRegIdx = aXRef+pTab->nCol;
  110275. aToOpen = (u8*)(aRegIdx+nIdx);
  110276. memset(aToOpen, 1, nIdx+1);
  110277. aToOpen[nIdx+1] = 0;
  110278. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  110279. /* Initialize the name-context */
  110280. memset(&sNC, 0, sizeof(sNC));
  110281. sNC.pParse = pParse;
  110282. sNC.pSrcList = pTabList;
  110283. /* Resolve the column names in all the expressions of the
  110284. ** of the UPDATE statement. Also find the column index
  110285. ** for each column to be updated in the pChanges array. For each
  110286. ** column to be updated, make sure we have authorization to change
  110287. ** that column.
  110288. */
  110289. chngRowid = chngPk = 0;
  110290. for(i=0; i<pChanges->nExpr; i++){
  110291. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  110292. goto update_cleanup;
  110293. }
  110294. for(j=0; j<pTab->nCol; j++){
  110295. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  110296. if( j==pTab->iPKey ){
  110297. chngRowid = 1;
  110298. pRowidExpr = pChanges->a[i].pExpr;
  110299. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  110300. chngPk = 1;
  110301. }
  110302. aXRef[j] = i;
  110303. break;
  110304. }
  110305. }
  110306. if( j>=pTab->nCol ){
  110307. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  110308. j = -1;
  110309. chngRowid = 1;
  110310. pRowidExpr = pChanges->a[i].pExpr;
  110311. }else{
  110312. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  110313. pParse->checkSchema = 1;
  110314. goto update_cleanup;
  110315. }
  110316. }
  110317. #ifndef SQLITE_OMIT_AUTHORIZATION
  110318. {
  110319. int rc;
  110320. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  110321. j<0 ? "ROWID" : pTab->aCol[j].zName,
  110322. db->aDb[iDb].zName);
  110323. if( rc==SQLITE_DENY ){
  110324. goto update_cleanup;
  110325. }else if( rc==SQLITE_IGNORE ){
  110326. aXRef[j] = -1;
  110327. }
  110328. }
  110329. #endif
  110330. }
  110331. assert( (chngRowid & chngPk)==0 );
  110332. assert( chngRowid==0 || chngRowid==1 );
  110333. assert( chngPk==0 || chngPk==1 );
  110334. chngKey = chngRowid + chngPk;
  110335. /* The SET expressions are not actually used inside the WHERE loop.
  110336. ** So reset the colUsed mask. Unless this is a virtual table. In that
  110337. ** case, set all bits of the colUsed mask (to ensure that the virtual
  110338. ** table implementation makes all columns available).
  110339. */
  110340. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  110341. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  110342. /* There is one entry in the aRegIdx[] array for each index on the table
  110343. ** being updated. Fill in aRegIdx[] with a register number that will hold
  110344. ** the key for accessing each index.
  110345. **
  110346. ** FIXME: Be smarter about omitting indexes that use expressions.
  110347. */
  110348. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  110349. int reg;
  110350. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  110351. reg = ++pParse->nMem;
  110352. }else{
  110353. reg = 0;
  110354. for(i=0; i<pIdx->nKeyCol; i++){
  110355. i16 iIdxCol = pIdx->aiColumn[i];
  110356. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  110357. reg = ++pParse->nMem;
  110358. break;
  110359. }
  110360. }
  110361. }
  110362. if( reg==0 ) aToOpen[j+1] = 0;
  110363. aRegIdx[j] = reg;
  110364. }
  110365. /* Begin generating code. */
  110366. v = sqlite3GetVdbe(pParse);
  110367. if( v==0 ) goto update_cleanup;
  110368. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  110369. sqlite3BeginWriteOperation(pParse, 1, iDb);
  110370. /* Allocate required registers. */
  110371. if( !IsVirtual(pTab) ){
  110372. regRowSet = ++pParse->nMem;
  110373. regOldRowid = regNewRowid = ++pParse->nMem;
  110374. if( chngPk || pTrigger || hasFK ){
  110375. regOld = pParse->nMem + 1;
  110376. pParse->nMem += pTab->nCol;
  110377. }
  110378. if( chngKey || pTrigger || hasFK ){
  110379. regNewRowid = ++pParse->nMem;
  110380. }
  110381. regNew = pParse->nMem + 1;
  110382. pParse->nMem += pTab->nCol;
  110383. }
  110384. /* Start the view context. */
  110385. if( isView ){
  110386. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  110387. }
  110388. /* If we are trying to update a view, realize that view into
  110389. ** an ephemeral table.
  110390. */
  110391. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  110392. if( isView ){
  110393. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  110394. }
  110395. #endif
  110396. /* Resolve the column names in all the expressions in the
  110397. ** WHERE clause.
  110398. */
  110399. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  110400. goto update_cleanup;
  110401. }
  110402. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110403. /* Virtual tables must be handled separately */
  110404. if( IsVirtual(pTab) ){
  110405. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  110406. pWhere, onError);
  110407. goto update_cleanup;
  110408. }
  110409. #endif
  110410. /* Begin the database scan
  110411. */
  110412. if( HasRowid(pTab) ){
  110413. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  110414. pWInfo = sqlite3WhereBegin(
  110415. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  110416. );
  110417. if( pWInfo==0 ) goto update_cleanup;
  110418. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  110419. /* Remember the rowid of every item to be updated.
  110420. */
  110421. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  110422. if( !okOnePass ){
  110423. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  110424. }
  110425. /* End the database scan loop.
  110426. */
  110427. sqlite3WhereEnd(pWInfo);
  110428. }else{
  110429. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  110430. i16 nPk; /* Number of components of the PRIMARY KEY */
  110431. int addrOpen; /* Address of the OpenEphemeral instruction */
  110432. assert( pPk!=0 );
  110433. nPk = pPk->nKeyCol;
  110434. iPk = pParse->nMem+1;
  110435. pParse->nMem += nPk;
  110436. regKey = ++pParse->nMem;
  110437. iEph = pParse->nTab++;
  110438. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  110439. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  110440. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  110441. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  110442. WHERE_ONEPASS_DESIRED, iIdxCur);
  110443. if( pWInfo==0 ) goto update_cleanup;
  110444. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  110445. for(i=0; i<nPk; i++){
  110446. assert( pPk->aiColumn[i]>=0 );
  110447. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  110448. iPk+i);
  110449. }
  110450. if( okOnePass ){
  110451. sqlite3VdbeChangeToNoop(v, addrOpen);
  110452. nKey = nPk;
  110453. regKey = iPk;
  110454. }else{
  110455. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  110456. sqlite3IndexAffinityStr(db, pPk), nPk);
  110457. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  110458. }
  110459. sqlite3WhereEnd(pWInfo);
  110460. }
  110461. /* Initialize the count of updated rows
  110462. */
  110463. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  110464. regRowCount = ++pParse->nMem;
  110465. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  110466. }
  110467. labelBreak = sqlite3VdbeMakeLabel(v);
  110468. if( !isView ){
  110469. /*
  110470. ** Open every index that needs updating. Note that if any
  110471. ** index could potentially invoke a REPLACE conflict resolution
  110472. ** action, then we need to open all indices because we might need
  110473. ** to be deleting some records.
  110474. */
  110475. if( onError==OE_Replace ){
  110476. memset(aToOpen, 1, nIdx+1);
  110477. }else{
  110478. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  110479. if( pIdx->onError==OE_Replace ){
  110480. memset(aToOpen, 1, nIdx+1);
  110481. break;
  110482. }
  110483. }
  110484. }
  110485. if( okOnePass ){
  110486. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  110487. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  110488. }
  110489. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
  110490. 0, 0);
  110491. }
  110492. /* Top of the update loop */
  110493. if( okOnePass ){
  110494. if( aToOpen[iDataCur-iBaseCur] && !isView ){
  110495. assert( pPk );
  110496. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  110497. VdbeCoverageNeverTaken(v);
  110498. }
  110499. labelContinue = labelBreak;
  110500. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  110501. VdbeCoverageIf(v, pPk==0);
  110502. VdbeCoverageIf(v, pPk!=0);
  110503. }else if( pPk ){
  110504. labelContinue = sqlite3VdbeMakeLabel(v);
  110505. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  110506. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  110507. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  110508. VdbeCoverage(v);
  110509. }else{
  110510. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  110511. regOldRowid);
  110512. VdbeCoverage(v);
  110513. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  110514. VdbeCoverage(v);
  110515. }
  110516. /* If the record number will change, set register regNewRowid to
  110517. ** contain the new value. If the record number is not being modified,
  110518. ** then regNewRowid is the same register as regOldRowid, which is
  110519. ** already populated. */
  110520. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  110521. if( chngRowid ){
  110522. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  110523. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  110524. }
  110525. /* Compute the old pre-UPDATE content of the row being changed, if that
  110526. ** information is needed */
  110527. if( chngPk || hasFK || pTrigger ){
  110528. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  110529. oldmask |= sqlite3TriggerColmask(pParse,
  110530. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  110531. );
  110532. for(i=0; i<pTab->nCol; i++){
  110533. if( oldmask==0xffffffff
  110534. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  110535. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  110536. ){
  110537. testcase( oldmask!=0xffffffff && i==31 );
  110538. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  110539. }else{
  110540. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  110541. }
  110542. }
  110543. if( chngRowid==0 && pPk==0 ){
  110544. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  110545. }
  110546. }
  110547. /* Populate the array of registers beginning at regNew with the new
  110548. ** row data. This array is used to check constants, create the new
  110549. ** table and index records, and as the values for any new.* references
  110550. ** made by triggers.
  110551. **
  110552. ** If there are one or more BEFORE triggers, then do not populate the
  110553. ** registers associated with columns that are (a) not modified by
  110554. ** this UPDATE statement and (b) not accessed by new.* references. The
  110555. ** values for registers not modified by the UPDATE must be reloaded from
  110556. ** the database after the BEFORE triggers are fired anyway (as the trigger
  110557. ** may have modified them). So not loading those that are not going to
  110558. ** be used eliminates some redundant opcodes.
  110559. */
  110560. newmask = sqlite3TriggerColmask(
  110561. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  110562. );
  110563. for(i=0; i<pTab->nCol; i++){
  110564. if( i==pTab->iPKey ){
  110565. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  110566. }else{
  110567. j = aXRef[i];
  110568. if( j>=0 ){
  110569. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  110570. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  110571. /* This branch loads the value of a column that will not be changed
  110572. ** into a register. This is done if there are no BEFORE triggers, or
  110573. ** if there are one or more BEFORE triggers that use this value via
  110574. ** a new.* reference in a trigger program.
  110575. */
  110576. testcase( i==31 );
  110577. testcase( i==32 );
  110578. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  110579. }else{
  110580. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  110581. }
  110582. }
  110583. }
  110584. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  110585. ** verified. One could argue that this is wrong.
  110586. */
  110587. if( tmask&TRIGGER_BEFORE ){
  110588. sqlite3TableAffinity(v, pTab, regNew);
  110589. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  110590. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  110591. /* The row-trigger may have deleted the row being updated. In this
  110592. ** case, jump to the next row. No updates or AFTER triggers are
  110593. ** required. This behavior - what happens when the row being updated
  110594. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  110595. ** documentation.
  110596. */
  110597. if( pPk ){
  110598. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  110599. VdbeCoverage(v);
  110600. }else{
  110601. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  110602. VdbeCoverage(v);
  110603. }
  110604. /* If it did not delete it, the row-trigger may still have modified
  110605. ** some of the columns of the row being updated. Load the values for
  110606. ** all columns not modified by the update statement into their
  110607. ** registers in case this has happened.
  110608. */
  110609. for(i=0; i<pTab->nCol; i++){
  110610. if( aXRef[i]<0 && i!=pTab->iPKey ){
  110611. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  110612. }
  110613. }
  110614. }
  110615. if( !isView ){
  110616. int addr1 = 0; /* Address of jump instruction */
  110617. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  110618. /* Do constraint checks. */
  110619. assert( regOldRowid>0 );
  110620. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  110621. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  110622. aXRef);
  110623. /* Do FK constraint checks. */
  110624. if( hasFK ){
  110625. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  110626. }
  110627. /* Delete the index entries associated with the current record. */
  110628. if( bReplace || chngKey ){
  110629. if( pPk ){
  110630. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  110631. }else{
  110632. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  110633. }
  110634. VdbeCoverageNeverTaken(v);
  110635. }
  110636. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  110637. /* If changing the record number, delete the old record. */
  110638. if( hasFK || chngKey || pPk!=0 ){
  110639. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  110640. }
  110641. if( bReplace || chngKey ){
  110642. sqlite3VdbeJumpHere(v, addr1);
  110643. }
  110644. if( hasFK ){
  110645. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  110646. }
  110647. /* Insert the new index entries and the new record. */
  110648. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  110649. regNewRowid, aRegIdx, 1, 0, 0);
  110650. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  110651. ** handle rows (possibly in other tables) that refer via a foreign key
  110652. ** to the row just updated. */
  110653. if( hasFK ){
  110654. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  110655. }
  110656. }
  110657. /* Increment the row counter
  110658. */
  110659. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  110660. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  110661. }
  110662. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  110663. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  110664. /* Repeat the above with the next record to be updated, until
  110665. ** all record selected by the WHERE clause have been updated.
  110666. */
  110667. if( okOnePass ){
  110668. /* Nothing to do at end-of-loop for a single-pass */
  110669. }else if( pPk ){
  110670. sqlite3VdbeResolveLabel(v, labelContinue);
  110671. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  110672. }else{
  110673. sqlite3VdbeGoto(v, labelContinue);
  110674. }
  110675. sqlite3VdbeResolveLabel(v, labelBreak);
  110676. /* Close all tables */
  110677. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  110678. assert( aRegIdx );
  110679. if( aToOpen[i+1] ){
  110680. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  110681. }
  110682. }
  110683. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  110684. /* Update the sqlite_sequence table by storing the content of the
  110685. ** maximum rowid counter values recorded while inserting into
  110686. ** autoincrement tables.
  110687. */
  110688. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  110689. sqlite3AutoincrementEnd(pParse);
  110690. }
  110691. /*
  110692. ** Return the number of rows that were changed. If this routine is
  110693. ** generating code because of a call to sqlite3NestedParse(), do not
  110694. ** invoke the callback function.
  110695. */
  110696. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  110697. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  110698. sqlite3VdbeSetNumCols(v, 1);
  110699. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  110700. }
  110701. update_cleanup:
  110702. sqlite3AuthContextPop(&sContext);
  110703. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  110704. sqlite3SrcListDelete(db, pTabList);
  110705. sqlite3ExprListDelete(db, pChanges);
  110706. sqlite3ExprDelete(db, pWhere);
  110707. return;
  110708. }
  110709. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  110710. ** they may interfere with compilation of other functions in this file
  110711. ** (or in another file, if this file becomes part of the amalgamation). */
  110712. #ifdef isView
  110713. #undef isView
  110714. #endif
  110715. #ifdef pTrigger
  110716. #undef pTrigger
  110717. #endif
  110718. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110719. /*
  110720. ** Generate code for an UPDATE of a virtual table.
  110721. **
  110722. ** There are two possible strategies - the default and the special
  110723. ** "onepass" strategy. Onepass is only used if the virtual table
  110724. ** implementation indicates that pWhere may match at most one row.
  110725. **
  110726. ** The default strategy is to create an ephemeral table that contains
  110727. ** for each row to be changed:
  110728. **
  110729. ** (A) The original rowid of that row.
  110730. ** (B) The revised rowid for the row.
  110731. ** (C) The content of every column in the row.
  110732. **
  110733. ** Then loop through the contents of this ephemeral table executing a
  110734. ** VUpdate for each row. When finished, drop the ephemeral table.
  110735. **
  110736. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  110737. ** stores the same values (A, B and C above) in a register array and
  110738. ** makes a single invocation of VUpdate.
  110739. */
  110740. static void updateVirtualTable(
  110741. Parse *pParse, /* The parsing context */
  110742. SrcList *pSrc, /* The virtual table to be modified */
  110743. Table *pTab, /* The virtual table */
  110744. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  110745. Expr *pRowid, /* Expression used to recompute the rowid */
  110746. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  110747. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  110748. int onError /* ON CONFLICT strategy */
  110749. ){
  110750. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  110751. int ephemTab; /* Table holding the result of the SELECT */
  110752. int i; /* Loop counter */
  110753. sqlite3 *db = pParse->db; /* Database connection */
  110754. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  110755. WhereInfo *pWInfo;
  110756. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  110757. int regArg; /* First register in VUpdate arg array */
  110758. int regRec; /* Register in which to assemble record */
  110759. int regRowid; /* Register for ephem table rowid */
  110760. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  110761. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  110762. int bOnePass; /* True to use onepass strategy */
  110763. int addr; /* Address of OP_OpenEphemeral */
  110764. /* Allocate nArg registers to martial the arguments to VUpdate. Then
  110765. ** create and open the ephemeral table in which the records created from
  110766. ** these arguments will be temporarily stored. */
  110767. assert( v );
  110768. ephemTab = pParse->nTab++;
  110769. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  110770. regArg = pParse->nMem + 1;
  110771. pParse->nMem += nArg;
  110772. regRec = ++pParse->nMem;
  110773. regRowid = ++pParse->nMem;
  110774. /* Start scanning the virtual table */
  110775. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  110776. if( pWInfo==0 ) return;
  110777. /* Populate the argument registers. */
  110778. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  110779. if( pRowid ){
  110780. sqlite3ExprCode(pParse, pRowid, regArg+1);
  110781. }else{
  110782. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  110783. }
  110784. for(i=0; i<pTab->nCol; i++){
  110785. if( aXRef[i]>=0 ){
  110786. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  110787. }else{
  110788. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  110789. }
  110790. }
  110791. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  110792. if( bOnePass ){
  110793. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  110794. ** above. Also, if this is a top-level parse (not a trigger), clear the
  110795. ** multi-write flag so that the VM does not open a statement journal */
  110796. sqlite3VdbeChangeToNoop(v, addr);
  110797. if( sqlite3IsToplevel(pParse) ){
  110798. pParse->isMultiWrite = 0;
  110799. }
  110800. }else{
  110801. /* Create a record from the argument register contents and insert it into
  110802. ** the ephemeral table. */
  110803. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  110804. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  110805. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  110806. }
  110807. if( bOnePass==0 ){
  110808. /* End the virtual table scan */
  110809. sqlite3WhereEnd(pWInfo);
  110810. /* Begin scannning through the ephemeral table. */
  110811. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  110812. /* Extract arguments from the current row of the ephemeral table and
  110813. ** invoke the VUpdate method. */
  110814. for(i=0; i<nArg; i++){
  110815. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  110816. }
  110817. }
  110818. sqlite3VtabMakeWritable(pParse, pTab);
  110819. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  110820. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  110821. sqlite3MayAbort(pParse);
  110822. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  110823. ** jump to here if the scan visited zero rows. */
  110824. if( bOnePass==0 ){
  110825. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  110826. sqlite3VdbeJumpHere(v, addr);
  110827. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  110828. }else{
  110829. sqlite3WhereEnd(pWInfo);
  110830. }
  110831. }
  110832. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110833. /************** End of update.c **********************************************/
  110834. /************** Begin file vacuum.c ******************************************/
  110835. /*
  110836. ** 2003 April 6
  110837. **
  110838. ** The author disclaims copyright to this source code. In place of
  110839. ** a legal notice, here is a blessing:
  110840. **
  110841. ** May you do good and not evil.
  110842. ** May you find forgiveness for yourself and forgive others.
  110843. ** May you share freely, never taking more than you give.
  110844. **
  110845. *************************************************************************
  110846. ** This file contains code used to implement the VACUUM command.
  110847. **
  110848. ** Most of the code in this file may be omitted by defining the
  110849. ** SQLITE_OMIT_VACUUM macro.
  110850. */
  110851. /* #include "sqliteInt.h" */
  110852. /* #include "vdbeInt.h" */
  110853. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  110854. /*
  110855. ** Finalize a prepared statement. If there was an error, store the
  110856. ** text of the error message in *pzErrMsg. Return the result code.
  110857. */
  110858. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  110859. int rc;
  110860. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  110861. if( rc ){
  110862. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  110863. }
  110864. return rc;
  110865. }
  110866. /*
  110867. ** Execute zSql on database db. Return an error code.
  110868. */
  110869. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  110870. sqlite3_stmt *pStmt;
  110871. VVA_ONLY( int rc; )
  110872. if( !zSql ){
  110873. return SQLITE_NOMEM_BKPT;
  110874. }
  110875. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  110876. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  110877. return sqlite3_errcode(db);
  110878. }
  110879. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  110880. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  110881. return vacuumFinalize(db, pStmt, pzErrMsg);
  110882. }
  110883. /*
  110884. ** Execute zSql on database db. The statement returns exactly
  110885. ** one column. Execute this as SQL on the same database.
  110886. */
  110887. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  110888. sqlite3_stmt *pStmt;
  110889. int rc;
  110890. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  110891. if( rc!=SQLITE_OK ) return rc;
  110892. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  110893. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  110894. if( rc!=SQLITE_OK ){
  110895. vacuumFinalize(db, pStmt, pzErrMsg);
  110896. return rc;
  110897. }
  110898. }
  110899. return vacuumFinalize(db, pStmt, pzErrMsg);
  110900. }
  110901. /*
  110902. ** The VACUUM command is used to clean up the database,
  110903. ** collapse free space, etc. It is modelled after the VACUUM command
  110904. ** in PostgreSQL. The VACUUM command works as follows:
  110905. **
  110906. ** (1) Create a new transient database file
  110907. ** (2) Copy all content from the database being vacuumed into
  110908. ** the new transient database file
  110909. ** (3) Copy content from the transient database back into the
  110910. ** original database.
  110911. **
  110912. ** The transient database requires temporary disk space approximately
  110913. ** equal to the size of the original database. The copy operation of
  110914. ** step (3) requires additional temporary disk space approximately equal
  110915. ** to the size of the original database for the rollback journal.
  110916. ** Hence, temporary disk space that is approximately 2x the size of the
  110917. ** original database is required. Every page of the database is written
  110918. ** approximately 3 times: Once for step (2) and twice for step (3).
  110919. ** Two writes per page are required in step (3) because the original
  110920. ** database content must be written into the rollback journal prior to
  110921. ** overwriting the database with the vacuumed content.
  110922. **
  110923. ** Only 1x temporary space and only 1x writes would be required if
  110924. ** the copy of step (3) were replaced by deleting the original database
  110925. ** and renaming the transient database as the original. But that will
  110926. ** not work if other processes are attached to the original database.
  110927. ** And a power loss in between deleting the original and renaming the
  110928. ** transient would cause the database file to appear to be deleted
  110929. ** following reboot.
  110930. */
  110931. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  110932. Vdbe *v = sqlite3GetVdbe(pParse);
  110933. if( v ){
  110934. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  110935. sqlite3VdbeUsesBtree(v, 0);
  110936. }
  110937. return;
  110938. }
  110939. /*
  110940. ** This routine implements the OP_Vacuum opcode of the VDBE.
  110941. */
  110942. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  110943. int rc = SQLITE_OK; /* Return code from service routines */
  110944. Btree *pMain; /* The database being vacuumed */
  110945. Btree *pTemp; /* The temporary database we vacuum into */
  110946. char *zSql = 0; /* SQL statements */
  110947. int saved_flags; /* Saved value of the db->flags */
  110948. int saved_nChange; /* Saved value of db->nChange */
  110949. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  110950. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  110951. Db *pDb = 0; /* Database to detach at end of vacuum */
  110952. int isMemDb; /* True if vacuuming a :memory: database */
  110953. int nRes; /* Bytes of reserved space at the end of each page */
  110954. int nDb; /* Number of attached databases */
  110955. if( !db->autoCommit ){
  110956. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  110957. return SQLITE_ERROR;
  110958. }
  110959. if( db->nVdbeActive>1 ){
  110960. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  110961. return SQLITE_ERROR;
  110962. }
  110963. /* Save the current value of the database flags so that it can be
  110964. ** restored before returning. Then set the writable-schema flag, and
  110965. ** disable CHECK and foreign key constraints. */
  110966. saved_flags = db->flags;
  110967. saved_nChange = db->nChange;
  110968. saved_nTotalChange = db->nTotalChange;
  110969. saved_xTrace = db->xTrace;
  110970. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  110971. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  110972. db->xTrace = 0;
  110973. pMain = db->aDb[0].pBt;
  110974. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  110975. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  110976. ** can be set to 'off' for this file, as it is not recovered if a crash
  110977. ** occurs anyway. The integrity of the database is maintained by a
  110978. ** (possibly synchronous) transaction opened on the main database before
  110979. ** sqlite3BtreeCopyFile() is called.
  110980. **
  110981. ** An optimisation would be to use a non-journaled pager.
  110982. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  110983. ** that actually made the VACUUM run slower. Very little journalling
  110984. ** actually occurs when doing a vacuum since the vacuum_db is initially
  110985. ** empty. Only the journal header is written. Apparently it takes more
  110986. ** time to parse and run the PRAGMA to turn journalling off than it does
  110987. ** to write the journal header file.
  110988. */
  110989. nDb = db->nDb;
  110990. if( sqlite3TempInMemory(db) ){
  110991. zSql = "ATTACH ':memory:' AS vacuum_db;";
  110992. }else{
  110993. zSql = "ATTACH '' AS vacuum_db;";
  110994. }
  110995. rc = execSql(db, pzErrMsg, zSql);
  110996. if( db->nDb>nDb ){
  110997. pDb = &db->aDb[db->nDb-1];
  110998. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  110999. }
  111000. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111001. pTemp = db->aDb[db->nDb-1].pBt;
  111002. /* The call to execSql() to attach the temp database has left the file
  111003. ** locked (as there was more than one active statement when the transaction
  111004. ** to read the schema was concluded. Unlock it here so that this doesn't
  111005. ** cause problems for the call to BtreeSetPageSize() below. */
  111006. sqlite3BtreeCommit(pTemp);
  111007. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  111008. /* A VACUUM cannot change the pagesize of an encrypted database. */
  111009. #ifdef SQLITE_HAS_CODEC
  111010. if( db->nextPagesize ){
  111011. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  111012. int nKey;
  111013. char *zKey;
  111014. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  111015. if( nKey ) db->nextPagesize = 0;
  111016. }
  111017. #endif
  111018. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  111019. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111020. /* Begin a transaction and take an exclusive lock on the main database
  111021. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  111022. ** to ensure that we do not try to change the page-size on a WAL database.
  111023. */
  111024. rc = execSql(db, pzErrMsg, "BEGIN;");
  111025. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111026. rc = sqlite3BtreeBeginTrans(pMain, 2);
  111027. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111028. /* Do not attempt to change the page size for a WAL database */
  111029. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  111030. ==PAGER_JOURNALMODE_WAL ){
  111031. db->nextPagesize = 0;
  111032. }
  111033. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  111034. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  111035. || NEVER(db->mallocFailed)
  111036. ){
  111037. rc = SQLITE_NOMEM_BKPT;
  111038. goto end_of_vacuum;
  111039. }
  111040. #ifndef SQLITE_OMIT_AUTOVACUUM
  111041. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  111042. sqlite3BtreeGetAutoVacuum(pMain));
  111043. #endif
  111044. /* Query the schema of the main database. Create a mirror schema
  111045. ** in the temporary database.
  111046. */
  111047. rc = execExecSql(db, pzErrMsg,
  111048. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  111049. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  111050. " AND coalesce(rootpage,1)>0"
  111051. );
  111052. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111053. rc = execExecSql(db, pzErrMsg,
  111054. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  111055. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  111056. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111057. rc = execExecSql(db, pzErrMsg,
  111058. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  111059. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  111060. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111061. /* Loop through the tables in the main database. For each, do
  111062. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  111063. ** the contents to the temporary database.
  111064. */
  111065. assert( (db->flags & SQLITE_Vacuum)==0 );
  111066. db->flags |= SQLITE_Vacuum;
  111067. rc = execExecSql(db, pzErrMsg,
  111068. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  111069. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  111070. "FROM main.sqlite_master "
  111071. "WHERE type = 'table' AND name!='sqlite_sequence' "
  111072. " AND coalesce(rootpage,1)>0"
  111073. );
  111074. assert( (db->flags & SQLITE_Vacuum)!=0 );
  111075. db->flags &= ~SQLITE_Vacuum;
  111076. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111077. /* Copy over the sequence table
  111078. */
  111079. rc = execExecSql(db, pzErrMsg,
  111080. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  111081. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  111082. );
  111083. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111084. rc = execExecSql(db, pzErrMsg,
  111085. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  111086. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  111087. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  111088. );
  111089. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111090. /* Copy the triggers, views, and virtual tables from the main database
  111091. ** over to the temporary database. None of these objects has any
  111092. ** associated storage, so all we have to do is copy their entries
  111093. ** from the SQLITE_MASTER table.
  111094. */
  111095. rc = execSql(db, pzErrMsg,
  111096. "INSERT INTO vacuum_db.sqlite_master "
  111097. " SELECT type, name, tbl_name, rootpage, sql"
  111098. " FROM main.sqlite_master"
  111099. " WHERE type='view' OR type='trigger'"
  111100. " OR (type='table' AND rootpage=0)"
  111101. );
  111102. if( rc ) goto end_of_vacuum;
  111103. /* At this point, there is a write transaction open on both the
  111104. ** vacuum database and the main database. Assuming no error occurs,
  111105. ** both transactions are closed by this block - the main database
  111106. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  111107. ** call to sqlite3BtreeCommit().
  111108. */
  111109. {
  111110. u32 meta;
  111111. int i;
  111112. /* This array determines which meta meta values are preserved in the
  111113. ** vacuum. Even entries are the meta value number and odd entries
  111114. ** are an increment to apply to the meta value after the vacuum.
  111115. ** The increment is used to increase the schema cookie so that other
  111116. ** connections to the same database will know to reread the schema.
  111117. */
  111118. static const unsigned char aCopy[] = {
  111119. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  111120. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  111121. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  111122. BTREE_USER_VERSION, 0, /* Preserve the user version */
  111123. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  111124. };
  111125. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  111126. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  111127. /* Copy Btree meta values */
  111128. for(i=0; i<ArraySize(aCopy); i+=2){
  111129. /* GetMeta() and UpdateMeta() cannot fail in this context because
  111130. ** we already have page 1 loaded into cache and marked dirty. */
  111131. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  111132. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  111133. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  111134. }
  111135. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  111136. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111137. rc = sqlite3BtreeCommit(pTemp);
  111138. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  111139. #ifndef SQLITE_OMIT_AUTOVACUUM
  111140. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  111141. #endif
  111142. }
  111143. assert( rc==SQLITE_OK );
  111144. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  111145. end_of_vacuum:
  111146. /* Restore the original value of db->flags */
  111147. db->flags = saved_flags;
  111148. db->nChange = saved_nChange;
  111149. db->nTotalChange = saved_nTotalChange;
  111150. db->xTrace = saved_xTrace;
  111151. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  111152. /* Currently there is an SQL level transaction open on the vacuum
  111153. ** database. No locks are held on any other files (since the main file
  111154. ** was committed at the btree level). So it safe to end the transaction
  111155. ** by manually setting the autoCommit flag to true and detaching the
  111156. ** vacuum database. The vacuum_db journal file is deleted when the pager
  111157. ** is closed by the DETACH.
  111158. */
  111159. db->autoCommit = 1;
  111160. if( pDb ){
  111161. sqlite3BtreeClose(pDb->pBt);
  111162. pDb->pBt = 0;
  111163. pDb->pSchema = 0;
  111164. }
  111165. /* This both clears the schemas and reduces the size of the db->aDb[]
  111166. ** array. */
  111167. sqlite3ResetAllSchemasOfConnection(db);
  111168. return rc;
  111169. }
  111170. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  111171. /************** End of vacuum.c **********************************************/
  111172. /************** Begin file vtab.c ********************************************/
  111173. /*
  111174. ** 2006 June 10
  111175. **
  111176. ** The author disclaims copyright to this source code. In place of
  111177. ** a legal notice, here is a blessing:
  111178. **
  111179. ** May you do good and not evil.
  111180. ** May you find forgiveness for yourself and forgive others.
  111181. ** May you share freely, never taking more than you give.
  111182. **
  111183. *************************************************************************
  111184. ** This file contains code used to help implement virtual tables.
  111185. */
  111186. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111187. /* #include "sqliteInt.h" */
  111188. /*
  111189. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  111190. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  111191. ** this struct allocated on the stack. It is used by the implementation of
  111192. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  111193. ** are invoked only from within xCreate and xConnect methods.
  111194. */
  111195. struct VtabCtx {
  111196. VTable *pVTable; /* The virtual table being constructed */
  111197. Table *pTab; /* The Table object to which the virtual table belongs */
  111198. VtabCtx *pPrior; /* Parent context (if any) */
  111199. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  111200. };
  111201. /*
  111202. ** The actual function that does the work of creating a new module.
  111203. ** This function implements the sqlite3_create_module() and
  111204. ** sqlite3_create_module_v2() interfaces.
  111205. */
  111206. static int createModule(
  111207. sqlite3 *db, /* Database in which module is registered */
  111208. const char *zName, /* Name assigned to this module */
  111209. const sqlite3_module *pModule, /* The definition of the module */
  111210. void *pAux, /* Context pointer for xCreate/xConnect */
  111211. void (*xDestroy)(void *) /* Module destructor function */
  111212. ){
  111213. int rc = SQLITE_OK;
  111214. int nName;
  111215. sqlite3_mutex_enter(db->mutex);
  111216. nName = sqlite3Strlen30(zName);
  111217. if( sqlite3HashFind(&db->aModule, zName) ){
  111218. rc = SQLITE_MISUSE_BKPT;
  111219. }else{
  111220. Module *pMod;
  111221. pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
  111222. if( pMod ){
  111223. Module *pDel;
  111224. char *zCopy = (char *)(&pMod[1]);
  111225. memcpy(zCopy, zName, nName+1);
  111226. pMod->zName = zCopy;
  111227. pMod->pModule = pModule;
  111228. pMod->pAux = pAux;
  111229. pMod->xDestroy = xDestroy;
  111230. pMod->pEpoTab = 0;
  111231. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  111232. assert( pDel==0 || pDel==pMod );
  111233. if( pDel ){
  111234. sqlite3OomFault(db);
  111235. sqlite3DbFree(db, pDel);
  111236. }
  111237. }
  111238. }
  111239. rc = sqlite3ApiExit(db, rc);
  111240. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  111241. sqlite3_mutex_leave(db->mutex);
  111242. return rc;
  111243. }
  111244. /*
  111245. ** External API function used to create a new virtual-table module.
  111246. */
  111247. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  111248. sqlite3 *db, /* Database in which module is registered */
  111249. const char *zName, /* Name assigned to this module */
  111250. const sqlite3_module *pModule, /* The definition of the module */
  111251. void *pAux /* Context pointer for xCreate/xConnect */
  111252. ){
  111253. #ifdef SQLITE_ENABLE_API_ARMOR
  111254. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  111255. #endif
  111256. return createModule(db, zName, pModule, pAux, 0);
  111257. }
  111258. /*
  111259. ** External API function used to create a new virtual-table module.
  111260. */
  111261. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  111262. sqlite3 *db, /* Database in which module is registered */
  111263. const char *zName, /* Name assigned to this module */
  111264. const sqlite3_module *pModule, /* The definition of the module */
  111265. void *pAux, /* Context pointer for xCreate/xConnect */
  111266. void (*xDestroy)(void *) /* Module destructor function */
  111267. ){
  111268. #ifdef SQLITE_ENABLE_API_ARMOR
  111269. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  111270. #endif
  111271. return createModule(db, zName, pModule, pAux, xDestroy);
  111272. }
  111273. /*
  111274. ** Lock the virtual table so that it cannot be disconnected.
  111275. ** Locks nest. Every lock should have a corresponding unlock.
  111276. ** If an unlock is omitted, resources leaks will occur.
  111277. **
  111278. ** If a disconnect is attempted while a virtual table is locked,
  111279. ** the disconnect is deferred until all locks have been removed.
  111280. */
  111281. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  111282. pVTab->nRef++;
  111283. }
  111284. /*
  111285. ** pTab is a pointer to a Table structure representing a virtual-table.
  111286. ** Return a pointer to the VTable object used by connection db to access
  111287. ** this virtual-table, if one has been created, or NULL otherwise.
  111288. */
  111289. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  111290. VTable *pVtab;
  111291. assert( IsVirtual(pTab) );
  111292. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  111293. return pVtab;
  111294. }
  111295. /*
  111296. ** Decrement the ref-count on a virtual table object. When the ref-count
  111297. ** reaches zero, call the xDisconnect() method to delete the object.
  111298. */
  111299. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  111300. sqlite3 *db = pVTab->db;
  111301. assert( db );
  111302. assert( pVTab->nRef>0 );
  111303. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  111304. pVTab->nRef--;
  111305. if( pVTab->nRef==0 ){
  111306. sqlite3_vtab *p = pVTab->pVtab;
  111307. if( p ){
  111308. p->pModule->xDisconnect(p);
  111309. }
  111310. sqlite3DbFree(db, pVTab);
  111311. }
  111312. }
  111313. /*
  111314. ** Table p is a virtual table. This function moves all elements in the
  111315. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  111316. ** database connections to be disconnected at the next opportunity.
  111317. ** Except, if argument db is not NULL, then the entry associated with
  111318. ** connection db is left in the p->pVTable list.
  111319. */
  111320. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  111321. VTable *pRet = 0;
  111322. VTable *pVTable = p->pVTable;
  111323. p->pVTable = 0;
  111324. /* Assert that the mutex (if any) associated with the BtShared database
  111325. ** that contains table p is held by the caller. See header comments
  111326. ** above function sqlite3VtabUnlockList() for an explanation of why
  111327. ** this makes it safe to access the sqlite3.pDisconnect list of any
  111328. ** database connection that may have an entry in the p->pVTable list.
  111329. */
  111330. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  111331. while( pVTable ){
  111332. sqlite3 *db2 = pVTable->db;
  111333. VTable *pNext = pVTable->pNext;
  111334. assert( db2 );
  111335. if( db2==db ){
  111336. pRet = pVTable;
  111337. p->pVTable = pRet;
  111338. pRet->pNext = 0;
  111339. }else{
  111340. pVTable->pNext = db2->pDisconnect;
  111341. db2->pDisconnect = pVTable;
  111342. }
  111343. pVTable = pNext;
  111344. }
  111345. assert( !db || pRet );
  111346. return pRet;
  111347. }
  111348. /*
  111349. ** Table *p is a virtual table. This function removes the VTable object
  111350. ** for table *p associated with database connection db from the linked
  111351. ** list in p->pVTab. It also decrements the VTable ref count. This is
  111352. ** used when closing database connection db to free all of its VTable
  111353. ** objects without disturbing the rest of the Schema object (which may
  111354. ** be being used by other shared-cache connections).
  111355. */
  111356. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  111357. VTable **ppVTab;
  111358. assert( IsVirtual(p) );
  111359. assert( sqlite3BtreeHoldsAllMutexes(db) );
  111360. assert( sqlite3_mutex_held(db->mutex) );
  111361. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  111362. if( (*ppVTab)->db==db ){
  111363. VTable *pVTab = *ppVTab;
  111364. *ppVTab = pVTab->pNext;
  111365. sqlite3VtabUnlock(pVTab);
  111366. break;
  111367. }
  111368. }
  111369. }
  111370. /*
  111371. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  111372. **
  111373. ** This function may only be called when the mutexes associated with all
  111374. ** shared b-tree databases opened using connection db are held by the
  111375. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  111376. ** sqlite3.pDisconnect list is accessed only as follows:
  111377. **
  111378. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  111379. ** associated with the database handle itself must be held.
  111380. **
  111381. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  111382. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  111383. ** associated with the database the virtual table is stored in is held
  111384. ** or, if the virtual table is stored in a non-sharable database, then
  111385. ** the database handle mutex is held.
  111386. **
  111387. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  111388. ** by multiple threads. It is thread-safe.
  111389. */
  111390. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  111391. VTable *p = db->pDisconnect;
  111392. db->pDisconnect = 0;
  111393. assert( sqlite3BtreeHoldsAllMutexes(db) );
  111394. assert( sqlite3_mutex_held(db->mutex) );
  111395. if( p ){
  111396. sqlite3ExpirePreparedStatements(db);
  111397. do {
  111398. VTable *pNext = p->pNext;
  111399. sqlite3VtabUnlock(p);
  111400. p = pNext;
  111401. }while( p );
  111402. }
  111403. }
  111404. /*
  111405. ** Clear any and all virtual-table information from the Table record.
  111406. ** This routine is called, for example, just before deleting the Table
  111407. ** record.
  111408. **
  111409. ** Since it is a virtual-table, the Table structure contains a pointer
  111410. ** to the head of a linked list of VTable structures. Each VTable
  111411. ** structure is associated with a single sqlite3* user of the schema.
  111412. ** The reference count of the VTable structure associated with database
  111413. ** connection db is decremented immediately (which may lead to the
  111414. ** structure being xDisconnected and free). Any other VTable structures
  111415. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  111416. ** database connection.
  111417. */
  111418. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  111419. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  111420. if( p->azModuleArg ){
  111421. int i;
  111422. for(i=0; i<p->nModuleArg; i++){
  111423. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  111424. }
  111425. sqlite3DbFree(db, p->azModuleArg);
  111426. }
  111427. }
  111428. /*
  111429. ** Add a new module argument to pTable->azModuleArg[].
  111430. ** The string is not copied - the pointer is stored. The
  111431. ** string will be freed automatically when the table is
  111432. ** deleted.
  111433. */
  111434. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  111435. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  111436. char **azModuleArg;
  111437. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  111438. if( azModuleArg==0 ){
  111439. sqlite3DbFree(db, zArg);
  111440. }else{
  111441. int i = pTable->nModuleArg++;
  111442. azModuleArg[i] = zArg;
  111443. azModuleArg[i+1] = 0;
  111444. pTable->azModuleArg = azModuleArg;
  111445. }
  111446. }
  111447. /*
  111448. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  111449. ** statement. The module name has been parsed, but the optional list
  111450. ** of parameters that follow the module name are still pending.
  111451. */
  111452. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  111453. Parse *pParse, /* Parsing context */
  111454. Token *pName1, /* Name of new table, or database name */
  111455. Token *pName2, /* Name of new table or NULL */
  111456. Token *pModuleName, /* Name of the module for the virtual table */
  111457. int ifNotExists /* No error if the table already exists */
  111458. ){
  111459. int iDb; /* The database the table is being created in */
  111460. Table *pTable; /* The new virtual table */
  111461. sqlite3 *db; /* Database connection */
  111462. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  111463. pTable = pParse->pNewTable;
  111464. if( pTable==0 ) return;
  111465. assert( 0==pTable->pIndex );
  111466. db = pParse->db;
  111467. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  111468. assert( iDb>=0 );
  111469. pTable->tabFlags |= TF_Virtual;
  111470. pTable->nModuleArg = 0;
  111471. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  111472. addModuleArgument(db, pTable, 0);
  111473. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  111474. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  111475. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  111476. );
  111477. pParse->sNameToken.n = (int)(
  111478. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  111479. );
  111480. #ifndef SQLITE_OMIT_AUTHORIZATION
  111481. /* Creating a virtual table invokes the authorization callback twice.
  111482. ** The first invocation, to obtain permission to INSERT a row into the
  111483. ** sqlite_master table, has already been made by sqlite3StartTable().
  111484. ** The second call, to obtain permission to create the table, is made now.
  111485. */
  111486. if( pTable->azModuleArg ){
  111487. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  111488. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  111489. }
  111490. #endif
  111491. }
  111492. /*
  111493. ** This routine takes the module argument that has been accumulating
  111494. ** in pParse->zArg[] and appends it to the list of arguments on the
  111495. ** virtual table currently under construction in pParse->pTable.
  111496. */
  111497. static void addArgumentToVtab(Parse *pParse){
  111498. if( pParse->sArg.z && pParse->pNewTable ){
  111499. const char *z = (const char*)pParse->sArg.z;
  111500. int n = pParse->sArg.n;
  111501. sqlite3 *db = pParse->db;
  111502. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  111503. }
  111504. }
  111505. /*
  111506. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  111507. ** has been completely parsed.
  111508. */
  111509. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  111510. Table *pTab = pParse->pNewTable; /* The table being constructed */
  111511. sqlite3 *db = pParse->db; /* The database connection */
  111512. if( pTab==0 ) return;
  111513. addArgumentToVtab(pParse);
  111514. pParse->sArg.z = 0;
  111515. if( pTab->nModuleArg<1 ) return;
  111516. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  111517. ** first time (in other words if the virtual table is actually being
  111518. ** created now instead of just being read out of sqlite_master) then
  111519. ** do additional initialization work and store the statement text
  111520. ** in the sqlite_master table.
  111521. */
  111522. if( !db->init.busy ){
  111523. char *zStmt;
  111524. char *zWhere;
  111525. int iDb;
  111526. int iReg;
  111527. Vdbe *v;
  111528. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  111529. if( pEnd ){
  111530. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  111531. }
  111532. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  111533. /* A slot for the record has already been allocated in the
  111534. ** SQLITE_MASTER table. We just need to update that slot with all
  111535. ** the information we've collected.
  111536. **
  111537. ** The VM register number pParse->regRowid holds the rowid of an
  111538. ** entry in the sqlite_master table tht was created for this vtab
  111539. ** by sqlite3StartTable().
  111540. */
  111541. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  111542. sqlite3NestedParse(pParse,
  111543. "UPDATE %Q.%s "
  111544. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  111545. "WHERE rowid=#%d",
  111546. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  111547. pTab->zName,
  111548. pTab->zName,
  111549. zStmt,
  111550. pParse->regRowid
  111551. );
  111552. sqlite3DbFree(db, zStmt);
  111553. v = sqlite3GetVdbe(pParse);
  111554. sqlite3ChangeCookie(pParse, iDb);
  111555. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  111556. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  111557. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  111558. iReg = ++pParse->nMem;
  111559. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  111560. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  111561. }
  111562. /* If we are rereading the sqlite_master table create the in-memory
  111563. ** record of the table. The xConnect() method is not called until
  111564. ** the first time the virtual table is used in an SQL statement. This
  111565. ** allows a schema that contains virtual tables to be loaded before
  111566. ** the required virtual table implementations are registered. */
  111567. else {
  111568. Table *pOld;
  111569. Schema *pSchema = pTab->pSchema;
  111570. const char *zName = pTab->zName;
  111571. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  111572. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  111573. if( pOld ){
  111574. sqlite3OomFault(db);
  111575. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  111576. return;
  111577. }
  111578. pParse->pNewTable = 0;
  111579. }
  111580. }
  111581. /*
  111582. ** The parser calls this routine when it sees the first token
  111583. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  111584. */
  111585. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  111586. addArgumentToVtab(pParse);
  111587. pParse->sArg.z = 0;
  111588. pParse->sArg.n = 0;
  111589. }
  111590. /*
  111591. ** The parser calls this routine for each token after the first token
  111592. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  111593. */
  111594. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  111595. Token *pArg = &pParse->sArg;
  111596. if( pArg->z==0 ){
  111597. pArg->z = p->z;
  111598. pArg->n = p->n;
  111599. }else{
  111600. assert(pArg->z <= p->z);
  111601. pArg->n = (int)(&p->z[p->n] - pArg->z);
  111602. }
  111603. }
  111604. /*
  111605. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  111606. ** pointer to the function to invoke is passed as the fourth parameter
  111607. ** to this procedure.
  111608. */
  111609. static int vtabCallConstructor(
  111610. sqlite3 *db,
  111611. Table *pTab,
  111612. Module *pMod,
  111613. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  111614. char **pzErr
  111615. ){
  111616. VtabCtx sCtx;
  111617. VTable *pVTable;
  111618. int rc;
  111619. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  111620. int nArg = pTab->nModuleArg;
  111621. char *zErr = 0;
  111622. char *zModuleName;
  111623. int iDb;
  111624. VtabCtx *pCtx;
  111625. /* Check that the virtual-table is not already being initialized */
  111626. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  111627. if( pCtx->pTab==pTab ){
  111628. *pzErr = sqlite3MPrintf(db,
  111629. "vtable constructor called recursively: %s", pTab->zName
  111630. );
  111631. return SQLITE_LOCKED;
  111632. }
  111633. }
  111634. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  111635. if( !zModuleName ){
  111636. return SQLITE_NOMEM_BKPT;
  111637. }
  111638. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  111639. if( !pVTable ){
  111640. sqlite3DbFree(db, zModuleName);
  111641. return SQLITE_NOMEM_BKPT;
  111642. }
  111643. pVTable->db = db;
  111644. pVTable->pMod = pMod;
  111645. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  111646. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  111647. /* Invoke the virtual table constructor */
  111648. assert( &db->pVtabCtx );
  111649. assert( xConstruct );
  111650. sCtx.pTab = pTab;
  111651. sCtx.pVTable = pVTable;
  111652. sCtx.pPrior = db->pVtabCtx;
  111653. sCtx.bDeclared = 0;
  111654. db->pVtabCtx = &sCtx;
  111655. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  111656. db->pVtabCtx = sCtx.pPrior;
  111657. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  111658. assert( sCtx.pTab==pTab );
  111659. if( SQLITE_OK!=rc ){
  111660. if( zErr==0 ){
  111661. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  111662. }else {
  111663. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  111664. sqlite3_free(zErr);
  111665. }
  111666. sqlite3DbFree(db, pVTable);
  111667. }else if( ALWAYS(pVTable->pVtab) ){
  111668. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  111669. ** the sqlite3_vtab object if successful. */
  111670. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  111671. pVTable->pVtab->pModule = pMod->pModule;
  111672. pVTable->nRef = 1;
  111673. if( sCtx.bDeclared==0 ){
  111674. const char *zFormat = "vtable constructor did not declare schema: %s";
  111675. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  111676. sqlite3VtabUnlock(pVTable);
  111677. rc = SQLITE_ERROR;
  111678. }else{
  111679. int iCol;
  111680. u8 oooHidden = 0;
  111681. /* If everything went according to plan, link the new VTable structure
  111682. ** into the linked list headed by pTab->pVTable. Then loop through the
  111683. ** columns of the table to see if any of them contain the token "hidden".
  111684. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  111685. ** the type string. */
  111686. pVTable->pNext = pTab->pVTable;
  111687. pTab->pVTable = pVTable;
  111688. for(iCol=0; iCol<pTab->nCol; iCol++){
  111689. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  111690. int nType;
  111691. int i = 0;
  111692. nType = sqlite3Strlen30(zType);
  111693. for(i=0; i<nType; i++){
  111694. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  111695. && (i==0 || zType[i-1]==' ')
  111696. && (zType[i+6]=='\0' || zType[i+6]==' ')
  111697. ){
  111698. break;
  111699. }
  111700. }
  111701. if( i<nType ){
  111702. int j;
  111703. int nDel = 6 + (zType[i+6] ? 1 : 0);
  111704. for(j=i; (j+nDel)<=nType; j++){
  111705. zType[j] = zType[j+nDel];
  111706. }
  111707. if( zType[i]=='\0' && i>0 ){
  111708. assert(zType[i-1]==' ');
  111709. zType[i-1] = '\0';
  111710. }
  111711. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  111712. oooHidden = TF_OOOHidden;
  111713. }else{
  111714. pTab->tabFlags |= oooHidden;
  111715. }
  111716. }
  111717. }
  111718. }
  111719. sqlite3DbFree(db, zModuleName);
  111720. return rc;
  111721. }
  111722. /*
  111723. ** This function is invoked by the parser to call the xConnect() method
  111724. ** of the virtual table pTab. If an error occurs, an error code is returned
  111725. ** and an error left in pParse.
  111726. **
  111727. ** This call is a no-op if table pTab is not a virtual table.
  111728. */
  111729. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  111730. sqlite3 *db = pParse->db;
  111731. const char *zMod;
  111732. Module *pMod;
  111733. int rc;
  111734. assert( pTab );
  111735. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  111736. return SQLITE_OK;
  111737. }
  111738. /* Locate the required virtual table module */
  111739. zMod = pTab->azModuleArg[0];
  111740. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  111741. if( !pMod ){
  111742. const char *zModule = pTab->azModuleArg[0];
  111743. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  111744. rc = SQLITE_ERROR;
  111745. }else{
  111746. char *zErr = 0;
  111747. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  111748. if( rc!=SQLITE_OK ){
  111749. sqlite3ErrorMsg(pParse, "%s", zErr);
  111750. }
  111751. sqlite3DbFree(db, zErr);
  111752. }
  111753. return rc;
  111754. }
  111755. /*
  111756. ** Grow the db->aVTrans[] array so that there is room for at least one
  111757. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  111758. */
  111759. static int growVTrans(sqlite3 *db){
  111760. const int ARRAY_INCR = 5;
  111761. /* Grow the sqlite3.aVTrans array if required */
  111762. if( (db->nVTrans%ARRAY_INCR)==0 ){
  111763. VTable **aVTrans;
  111764. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  111765. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  111766. if( !aVTrans ){
  111767. return SQLITE_NOMEM_BKPT;
  111768. }
  111769. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  111770. db->aVTrans = aVTrans;
  111771. }
  111772. return SQLITE_OK;
  111773. }
  111774. /*
  111775. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  111776. ** have already been reserved using growVTrans().
  111777. */
  111778. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  111779. /* Add pVtab to the end of sqlite3.aVTrans */
  111780. db->aVTrans[db->nVTrans++] = pVTab;
  111781. sqlite3VtabLock(pVTab);
  111782. }
  111783. /*
  111784. ** This function is invoked by the vdbe to call the xCreate method
  111785. ** of the virtual table named zTab in database iDb.
  111786. **
  111787. ** If an error occurs, *pzErr is set to point an an English language
  111788. ** description of the error and an SQLITE_XXX error code is returned.
  111789. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  111790. */
  111791. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  111792. int rc = SQLITE_OK;
  111793. Table *pTab;
  111794. Module *pMod;
  111795. const char *zMod;
  111796. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  111797. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  111798. /* Locate the required virtual table module */
  111799. zMod = pTab->azModuleArg[0];
  111800. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  111801. /* If the module has been registered and includes a Create method,
  111802. ** invoke it now. If the module has not been registered, return an
  111803. ** error. Otherwise, do nothing.
  111804. */
  111805. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  111806. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  111807. rc = SQLITE_ERROR;
  111808. }else{
  111809. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  111810. }
  111811. /* Justification of ALWAYS(): The xConstructor method is required to
  111812. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  111813. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  111814. rc = growVTrans(db);
  111815. if( rc==SQLITE_OK ){
  111816. addToVTrans(db, sqlite3GetVTable(db, pTab));
  111817. }
  111818. }
  111819. return rc;
  111820. }
  111821. /*
  111822. ** This function is used to set the schema of a virtual table. It is only
  111823. ** valid to call this function from within the xCreate() or xConnect() of a
  111824. ** virtual table module.
  111825. */
  111826. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  111827. VtabCtx *pCtx;
  111828. Parse *pParse;
  111829. int rc = SQLITE_OK;
  111830. Table *pTab;
  111831. char *zErr = 0;
  111832. #ifdef SQLITE_ENABLE_API_ARMOR
  111833. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  111834. return SQLITE_MISUSE_BKPT;
  111835. }
  111836. #endif
  111837. sqlite3_mutex_enter(db->mutex);
  111838. pCtx = db->pVtabCtx;
  111839. if( !pCtx || pCtx->bDeclared ){
  111840. sqlite3Error(db, SQLITE_MISUSE);
  111841. sqlite3_mutex_leave(db->mutex);
  111842. return SQLITE_MISUSE_BKPT;
  111843. }
  111844. pTab = pCtx->pTab;
  111845. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  111846. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  111847. if( pParse==0 ){
  111848. rc = SQLITE_NOMEM_BKPT;
  111849. }else{
  111850. pParse->declareVtab = 1;
  111851. pParse->db = db;
  111852. pParse->nQueryLoop = 1;
  111853. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  111854. && pParse->pNewTable
  111855. && !db->mallocFailed
  111856. && !pParse->pNewTable->pSelect
  111857. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  111858. ){
  111859. if( !pTab->aCol ){
  111860. pTab->aCol = pParse->pNewTable->aCol;
  111861. pTab->nCol = pParse->pNewTable->nCol;
  111862. pParse->pNewTable->nCol = 0;
  111863. pParse->pNewTable->aCol = 0;
  111864. }
  111865. pCtx->bDeclared = 1;
  111866. }else{
  111867. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  111868. sqlite3DbFree(db, zErr);
  111869. rc = SQLITE_ERROR;
  111870. }
  111871. pParse->declareVtab = 0;
  111872. if( pParse->pVdbe ){
  111873. sqlite3VdbeFinalize(pParse->pVdbe);
  111874. }
  111875. sqlite3DeleteTable(db, pParse->pNewTable);
  111876. sqlite3ParserReset(pParse);
  111877. sqlite3StackFree(db, pParse);
  111878. }
  111879. assert( (rc&0xff)==rc );
  111880. rc = sqlite3ApiExit(db, rc);
  111881. sqlite3_mutex_leave(db->mutex);
  111882. return rc;
  111883. }
  111884. /*
  111885. ** This function is invoked by the vdbe to call the xDestroy method
  111886. ** of the virtual table named zTab in database iDb. This occurs
  111887. ** when a DROP TABLE is mentioned.
  111888. **
  111889. ** This call is a no-op if zTab is not a virtual table.
  111890. */
  111891. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  111892. int rc = SQLITE_OK;
  111893. Table *pTab;
  111894. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  111895. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  111896. VTable *p;
  111897. int (*xDestroy)(sqlite3_vtab *);
  111898. for(p=pTab->pVTable; p; p=p->pNext){
  111899. assert( p->pVtab );
  111900. if( p->pVtab->nRef>0 ){
  111901. return SQLITE_LOCKED;
  111902. }
  111903. }
  111904. p = vtabDisconnectAll(db, pTab);
  111905. xDestroy = p->pMod->pModule->xDestroy;
  111906. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  111907. rc = xDestroy(p->pVtab);
  111908. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  111909. if( rc==SQLITE_OK ){
  111910. assert( pTab->pVTable==p && p->pNext==0 );
  111911. p->pVtab = 0;
  111912. pTab->pVTable = 0;
  111913. sqlite3VtabUnlock(p);
  111914. }
  111915. }
  111916. return rc;
  111917. }
  111918. /*
  111919. ** This function invokes either the xRollback or xCommit method
  111920. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  111921. ** called is identified by the second argument, "offset", which is
  111922. ** the offset of the method to call in the sqlite3_module structure.
  111923. **
  111924. ** The array is cleared after invoking the callbacks.
  111925. */
  111926. static void callFinaliser(sqlite3 *db, int offset){
  111927. int i;
  111928. if( db->aVTrans ){
  111929. VTable **aVTrans = db->aVTrans;
  111930. db->aVTrans = 0;
  111931. for(i=0; i<db->nVTrans; i++){
  111932. VTable *pVTab = aVTrans[i];
  111933. sqlite3_vtab *p = pVTab->pVtab;
  111934. if( p ){
  111935. int (*x)(sqlite3_vtab *);
  111936. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  111937. if( x ) x(p);
  111938. }
  111939. pVTab->iSavepoint = 0;
  111940. sqlite3VtabUnlock(pVTab);
  111941. }
  111942. sqlite3DbFree(db, aVTrans);
  111943. db->nVTrans = 0;
  111944. }
  111945. }
  111946. /*
  111947. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  111948. ** array. Return the error code for the first error that occurs, or
  111949. ** SQLITE_OK if all xSync operations are successful.
  111950. **
  111951. ** If an error message is available, leave it in p->zErrMsg.
  111952. */
  111953. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  111954. int i;
  111955. int rc = SQLITE_OK;
  111956. VTable **aVTrans = db->aVTrans;
  111957. db->aVTrans = 0;
  111958. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  111959. int (*x)(sqlite3_vtab *);
  111960. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  111961. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  111962. rc = x(pVtab);
  111963. sqlite3VtabImportErrmsg(p, pVtab);
  111964. }
  111965. }
  111966. db->aVTrans = aVTrans;
  111967. return rc;
  111968. }
  111969. /*
  111970. ** Invoke the xRollback method of all virtual tables in the
  111971. ** sqlite3.aVTrans array. Then clear the array itself.
  111972. */
  111973. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  111974. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  111975. return SQLITE_OK;
  111976. }
  111977. /*
  111978. ** Invoke the xCommit method of all virtual tables in the
  111979. ** sqlite3.aVTrans array. Then clear the array itself.
  111980. */
  111981. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  111982. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  111983. return SQLITE_OK;
  111984. }
  111985. /*
  111986. ** If the virtual table pVtab supports the transaction interface
  111987. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  111988. ** not currently open, invoke the xBegin method now.
  111989. **
  111990. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  111991. ** in the sqlite3.aVTrans array.
  111992. */
  111993. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  111994. int rc = SQLITE_OK;
  111995. const sqlite3_module *pModule;
  111996. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  111997. ** than zero, then this function is being called from within a
  111998. ** virtual module xSync() callback. It is illegal to write to
  111999. ** virtual module tables in this case, so return SQLITE_LOCKED.
  112000. */
  112001. if( sqlite3VtabInSync(db) ){
  112002. return SQLITE_LOCKED;
  112003. }
  112004. if( !pVTab ){
  112005. return SQLITE_OK;
  112006. }
  112007. pModule = pVTab->pVtab->pModule;
  112008. if( pModule->xBegin ){
  112009. int i;
  112010. /* If pVtab is already in the aVTrans array, return early */
  112011. for(i=0; i<db->nVTrans; i++){
  112012. if( db->aVTrans[i]==pVTab ){
  112013. return SQLITE_OK;
  112014. }
  112015. }
  112016. /* Invoke the xBegin method. If successful, add the vtab to the
  112017. ** sqlite3.aVTrans[] array. */
  112018. rc = growVTrans(db);
  112019. if( rc==SQLITE_OK ){
  112020. rc = pModule->xBegin(pVTab->pVtab);
  112021. if( rc==SQLITE_OK ){
  112022. int iSvpt = db->nStatement + db->nSavepoint;
  112023. addToVTrans(db, pVTab);
  112024. if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
  112025. }
  112026. }
  112027. }
  112028. return rc;
  112029. }
  112030. /*
  112031. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  112032. ** virtual tables that currently have an open transaction. Pass iSavepoint
  112033. ** as the second argument to the virtual table method invoked.
  112034. **
  112035. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  112036. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  112037. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  112038. ** an open transaction is invoked.
  112039. **
  112040. ** If any virtual table method returns an error code other than SQLITE_OK,
  112041. ** processing is abandoned and the error returned to the caller of this
  112042. ** function immediately. If all calls to virtual table methods are successful,
  112043. ** SQLITE_OK is returned.
  112044. */
  112045. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  112046. int rc = SQLITE_OK;
  112047. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  112048. assert( iSavepoint>=-1 );
  112049. if( db->aVTrans ){
  112050. int i;
  112051. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  112052. VTable *pVTab = db->aVTrans[i];
  112053. const sqlite3_module *pMod = pVTab->pMod->pModule;
  112054. if( pVTab->pVtab && pMod->iVersion>=2 ){
  112055. int (*xMethod)(sqlite3_vtab *, int);
  112056. switch( op ){
  112057. case SAVEPOINT_BEGIN:
  112058. xMethod = pMod->xSavepoint;
  112059. pVTab->iSavepoint = iSavepoint+1;
  112060. break;
  112061. case SAVEPOINT_ROLLBACK:
  112062. xMethod = pMod->xRollbackTo;
  112063. break;
  112064. default:
  112065. xMethod = pMod->xRelease;
  112066. break;
  112067. }
  112068. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  112069. rc = xMethod(pVTab->pVtab, iSavepoint);
  112070. }
  112071. }
  112072. }
  112073. }
  112074. return rc;
  112075. }
  112076. /*
  112077. ** The first parameter (pDef) is a function implementation. The
  112078. ** second parameter (pExpr) is the first argument to this function.
  112079. ** If pExpr is a column in a virtual table, then let the virtual
  112080. ** table implementation have an opportunity to overload the function.
  112081. **
  112082. ** This routine is used to allow virtual table implementations to
  112083. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  112084. **
  112085. ** Return either the pDef argument (indicating no change) or a
  112086. ** new FuncDef structure that is marked as ephemeral using the
  112087. ** SQLITE_FUNC_EPHEM flag.
  112088. */
  112089. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  112090. sqlite3 *db, /* Database connection for reporting malloc problems */
  112091. FuncDef *pDef, /* Function to possibly overload */
  112092. int nArg, /* Number of arguments to the function */
  112093. Expr *pExpr /* First argument to the function */
  112094. ){
  112095. Table *pTab;
  112096. sqlite3_vtab *pVtab;
  112097. sqlite3_module *pMod;
  112098. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  112099. void *pArg = 0;
  112100. FuncDef *pNew;
  112101. int rc = 0;
  112102. char *zLowerName;
  112103. unsigned char *z;
  112104. /* Check to see the left operand is a column in a virtual table */
  112105. if( NEVER(pExpr==0) ) return pDef;
  112106. if( pExpr->op!=TK_COLUMN ) return pDef;
  112107. pTab = pExpr->pTab;
  112108. if( NEVER(pTab==0) ) return pDef;
  112109. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  112110. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  112111. assert( pVtab!=0 );
  112112. assert( pVtab->pModule!=0 );
  112113. pMod = (sqlite3_module *)pVtab->pModule;
  112114. if( pMod->xFindFunction==0 ) return pDef;
  112115. /* Call the xFindFunction method on the virtual table implementation
  112116. ** to see if the implementation wants to overload this function
  112117. */
  112118. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  112119. if( zLowerName ){
  112120. for(z=(unsigned char*)zLowerName; *z; z++){
  112121. *z = sqlite3UpperToLower[*z];
  112122. }
  112123. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
  112124. sqlite3DbFree(db, zLowerName);
  112125. }
  112126. if( rc==0 ){
  112127. return pDef;
  112128. }
  112129. /* Create a new ephemeral function definition for the overloaded
  112130. ** function */
  112131. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  112132. + sqlite3Strlen30(pDef->zName) + 1);
  112133. if( pNew==0 ){
  112134. return pDef;
  112135. }
  112136. *pNew = *pDef;
  112137. pNew->zName = (const char*)&pNew[1];
  112138. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  112139. pNew->xSFunc = xSFunc;
  112140. pNew->pUserData = pArg;
  112141. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  112142. return pNew;
  112143. }
  112144. /*
  112145. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  112146. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  112147. ** array if it is missing. If pTab is already in the array, this routine
  112148. ** is a no-op.
  112149. */
  112150. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  112151. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  112152. int i, n;
  112153. Table **apVtabLock;
  112154. assert( IsVirtual(pTab) );
  112155. for(i=0; i<pToplevel->nVtabLock; i++){
  112156. if( pTab==pToplevel->apVtabLock[i] ) return;
  112157. }
  112158. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  112159. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  112160. if( apVtabLock ){
  112161. pToplevel->apVtabLock = apVtabLock;
  112162. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  112163. }else{
  112164. sqlite3OomFault(pToplevel->db);
  112165. }
  112166. }
  112167. /*
  112168. ** Check to see if virtual tale module pMod can be have an eponymous
  112169. ** virtual table instance. If it can, create one if one does not already
  112170. ** exist. Return non-zero if the eponymous virtual table instance exists
  112171. ** when this routine returns, and return zero if it does not exist.
  112172. **
  112173. ** An eponymous virtual table instance is one that is named after its
  112174. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  112175. ** statement in order to come into existance. Eponymous virtual table
  112176. ** instances always exist. They cannot be DROP-ed.
  112177. **
  112178. ** Any virtual table module for which xConnect and xCreate are the same
  112179. ** method can have an eponymous virtual table instance.
  112180. */
  112181. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  112182. const sqlite3_module *pModule = pMod->pModule;
  112183. Table *pTab;
  112184. char *zErr = 0;
  112185. int nName;
  112186. int rc;
  112187. sqlite3 *db = pParse->db;
  112188. if( pMod->pEpoTab ) return 1;
  112189. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  112190. nName = sqlite3Strlen30(pMod->zName) + 1;
  112191. pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
  112192. if( pTab==0 ) return 0;
  112193. pMod->pEpoTab = pTab;
  112194. pTab->zName = (char*)&pTab[1];
  112195. memcpy(pTab->zName, pMod->zName, nName);
  112196. pTab->nRef = 1;
  112197. pTab->pSchema = db->aDb[0].pSchema;
  112198. pTab->tabFlags |= TF_Virtual;
  112199. pTab->nModuleArg = 0;
  112200. pTab->iPKey = -1;
  112201. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  112202. addModuleArgument(db, pTab, 0);
  112203. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  112204. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  112205. if( rc ){
  112206. sqlite3ErrorMsg(pParse, "%s", zErr);
  112207. sqlite3DbFree(db, zErr);
  112208. sqlite3VtabEponymousTableClear(db, pMod);
  112209. return 0;
  112210. }
  112211. return 1;
  112212. }
  112213. /*
  112214. ** Erase the eponymous virtual table instance associated with
  112215. ** virtual table module pMod, if it exists.
  112216. */
  112217. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  112218. Table *pTab = pMod->pEpoTab;
  112219. if( pTab!=0 ){
  112220. sqlite3DeleteColumnNames(db, pTab);
  112221. sqlite3VtabClear(db, pTab);
  112222. sqlite3DbFree(db, pTab);
  112223. pMod->pEpoTab = 0;
  112224. }
  112225. }
  112226. /*
  112227. ** Return the ON CONFLICT resolution mode in effect for the virtual
  112228. ** table update operation currently in progress.
  112229. **
  112230. ** The results of this routine are undefined unless it is called from
  112231. ** within an xUpdate method.
  112232. */
  112233. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
  112234. static const unsigned char aMap[] = {
  112235. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  112236. };
  112237. #ifdef SQLITE_ENABLE_API_ARMOR
  112238. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  112239. #endif
  112240. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  112241. assert( OE_Ignore==4 && OE_Replace==5 );
  112242. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  112243. return (int)aMap[db->vtabOnConflict-1];
  112244. }
  112245. /*
  112246. ** Call from within the xCreate() or xConnect() methods to provide
  112247. ** the SQLite core with additional information about the behavior
  112248. ** of the virtual table being implemented.
  112249. */
  112250. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
  112251. va_list ap;
  112252. int rc = SQLITE_OK;
  112253. #ifdef SQLITE_ENABLE_API_ARMOR
  112254. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  112255. #endif
  112256. sqlite3_mutex_enter(db->mutex);
  112257. va_start(ap, op);
  112258. switch( op ){
  112259. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  112260. VtabCtx *p = db->pVtabCtx;
  112261. if( !p ){
  112262. rc = SQLITE_MISUSE_BKPT;
  112263. }else{
  112264. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  112265. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  112266. }
  112267. break;
  112268. }
  112269. default:
  112270. rc = SQLITE_MISUSE_BKPT;
  112271. break;
  112272. }
  112273. va_end(ap);
  112274. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  112275. sqlite3_mutex_leave(db->mutex);
  112276. return rc;
  112277. }
  112278. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  112279. /************** End of vtab.c ************************************************/
  112280. /************** Begin file wherecode.c ***************************************/
  112281. /*
  112282. ** 2015-06-06
  112283. **
  112284. ** The author disclaims copyright to this source code. In place of
  112285. ** a legal notice, here is a blessing:
  112286. **
  112287. ** May you do good and not evil.
  112288. ** May you find forgiveness for yourself and forgive others.
  112289. ** May you share freely, never taking more than you give.
  112290. **
  112291. *************************************************************************
  112292. ** This module contains C code that generates VDBE code used to process
  112293. ** the WHERE clause of SQL statements.
  112294. **
  112295. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  112296. ** size of where.c and make it easier to edit. This file contains the routines
  112297. ** that actually generate the bulk of the WHERE loop code. The original where.c
  112298. ** file retains the code that does query planning and analysis.
  112299. */
  112300. /* #include "sqliteInt.h" */
  112301. /************** Include whereInt.h in the middle of wherecode.c **************/
  112302. /************** Begin file whereInt.h ****************************************/
  112303. /*
  112304. ** 2013-11-12
  112305. **
  112306. ** The author disclaims copyright to this source code. In place of
  112307. ** a legal notice, here is a blessing:
  112308. **
  112309. ** May you do good and not evil.
  112310. ** May you find forgiveness for yourself and forgive others.
  112311. ** May you share freely, never taking more than you give.
  112312. **
  112313. *************************************************************************
  112314. **
  112315. ** This file contains structure and macro definitions for the query
  112316. ** planner logic in "where.c". These definitions are broken out into
  112317. ** a separate source file for easier editing.
  112318. */
  112319. /*
  112320. ** Trace output macros
  112321. */
  112322. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  112323. /***/ int sqlite3WhereTrace;
  112324. #endif
  112325. #if defined(SQLITE_DEBUG) \
  112326. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  112327. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  112328. # define WHERETRACE_ENABLED 1
  112329. #else
  112330. # define WHERETRACE(K,X)
  112331. #endif
  112332. /* Forward references
  112333. */
  112334. typedef struct WhereClause WhereClause;
  112335. typedef struct WhereMaskSet WhereMaskSet;
  112336. typedef struct WhereOrInfo WhereOrInfo;
  112337. typedef struct WhereAndInfo WhereAndInfo;
  112338. typedef struct WhereLevel WhereLevel;
  112339. typedef struct WhereLoop WhereLoop;
  112340. typedef struct WherePath WherePath;
  112341. typedef struct WhereTerm WhereTerm;
  112342. typedef struct WhereLoopBuilder WhereLoopBuilder;
  112343. typedef struct WhereScan WhereScan;
  112344. typedef struct WhereOrCost WhereOrCost;
  112345. typedef struct WhereOrSet WhereOrSet;
  112346. /*
  112347. ** This object contains information needed to implement a single nested
  112348. ** loop in WHERE clause.
  112349. **
  112350. ** Contrast this object with WhereLoop. This object describes the
  112351. ** implementation of the loop. WhereLoop describes the algorithm.
  112352. ** This object contains a pointer to the WhereLoop algorithm as one of
  112353. ** its elements.
  112354. **
  112355. ** The WhereInfo object contains a single instance of this object for
  112356. ** each term in the FROM clause (which is to say, for each of the
  112357. ** nested loops as implemented). The order of WhereLevel objects determines
  112358. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  112359. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  112360. */
  112361. struct WhereLevel {
  112362. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  112363. int iTabCur; /* The VDBE cursor used to access the table */
  112364. int iIdxCur; /* The VDBE cursor used to access pIdx */
  112365. int addrBrk; /* Jump here to break out of the loop */
  112366. int addrNxt; /* Jump here to start the next IN combination */
  112367. int addrSkip; /* Jump here for next iteration of skip-scan */
  112368. int addrCont; /* Jump here to continue with the next loop cycle */
  112369. int addrFirst; /* First instruction of interior of the loop */
  112370. int addrBody; /* Beginning of the body of this loop */
  112371. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  112372. int iLikeRepCntr; /* LIKE range processing counter register */
  112373. int addrLikeRep; /* LIKE range processing address */
  112374. #endif
  112375. u8 iFrom; /* Which entry in the FROM clause */
  112376. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  112377. int p1, p2; /* Operands of the opcode used to ends the loop */
  112378. union { /* Information that depends on pWLoop->wsFlags */
  112379. struct {
  112380. int nIn; /* Number of entries in aInLoop[] */
  112381. struct InLoop {
  112382. int iCur; /* The VDBE cursor used by this IN operator */
  112383. int addrInTop; /* Top of the IN loop */
  112384. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  112385. } *aInLoop; /* Information about each nested IN operator */
  112386. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  112387. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  112388. } u;
  112389. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  112390. Bitmask notReady; /* FROM entries not usable at this level */
  112391. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  112392. int addrVisit; /* Address at which row is visited */
  112393. #endif
  112394. };
  112395. /*
  112396. ** Each instance of this object represents an algorithm for evaluating one
  112397. ** term of a join. Every term of the FROM clause will have at least
  112398. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  112399. ** prevent a query solution - which is an error) and many terms of the
  112400. ** FROM clause will have multiple WhereLoop objects, each describing a
  112401. ** potential way of implementing that FROM-clause term, together with
  112402. ** dependencies and cost estimates for using the chosen algorithm.
  112403. **
  112404. ** Query planning consists of building up a collection of these WhereLoop
  112405. ** objects, then computing a particular sequence of WhereLoop objects, with
  112406. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  112407. ** and that minimize the overall cost.
  112408. */
  112409. struct WhereLoop {
  112410. Bitmask prereq; /* Bitmask of other loops that must run first */
  112411. Bitmask maskSelf; /* Bitmask identifying table iTab */
  112412. #ifdef SQLITE_DEBUG
  112413. char cId; /* Symbolic ID of this loop for debugging use */
  112414. #endif
  112415. u8 iTab; /* Position in FROM clause of table for this loop */
  112416. u8 iSortIdx; /* Sorting index number. 0==None */
  112417. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  112418. LogEst rRun; /* Cost of running each loop */
  112419. LogEst nOut; /* Estimated number of output rows */
  112420. union {
  112421. struct { /* Information for internal btree tables */
  112422. u16 nEq; /* Number of equality constraints */
  112423. Index *pIndex; /* Index used, or NULL */
  112424. } btree;
  112425. struct { /* Information for virtual tables */
  112426. int idxNum; /* Index number */
  112427. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  112428. i8 isOrdered; /* True if satisfies ORDER BY */
  112429. u16 omitMask; /* Terms that may be omitted */
  112430. char *idxStr; /* Index identifier string */
  112431. } vtab;
  112432. } u;
  112433. u32 wsFlags; /* WHERE_* flags describing the plan */
  112434. u16 nLTerm; /* Number of entries in aLTerm[] */
  112435. u16 nSkip; /* Number of NULL aLTerm[] entries */
  112436. /**** whereLoopXfer() copies fields above ***********************/
  112437. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  112438. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  112439. WhereTerm **aLTerm; /* WhereTerms used */
  112440. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  112441. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  112442. };
  112443. /* This object holds the prerequisites and the cost of running a
  112444. ** subquery on one operand of an OR operator in the WHERE clause.
  112445. ** See WhereOrSet for additional information
  112446. */
  112447. struct WhereOrCost {
  112448. Bitmask prereq; /* Prerequisites */
  112449. LogEst rRun; /* Cost of running this subquery */
  112450. LogEst nOut; /* Number of outputs for this subquery */
  112451. };
  112452. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  112453. ** correspond to the subquery(s) of OR-clause processing. Only the
  112454. ** best N_OR_COST elements are retained.
  112455. */
  112456. #define N_OR_COST 3
  112457. struct WhereOrSet {
  112458. u16 n; /* Number of valid a[] entries */
  112459. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  112460. };
  112461. /*
  112462. ** Each instance of this object holds a sequence of WhereLoop objects
  112463. ** that implement some or all of a query plan.
  112464. **
  112465. ** Think of each WhereLoop object as a node in a graph with arcs
  112466. ** showing dependencies and costs for travelling between nodes. (That is
  112467. ** not a completely accurate description because WhereLoop costs are a
  112468. ** vector, not a scalar, and because dependencies are many-to-one, not
  112469. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  112470. ** Then a WherePath object is a path through the graph that visits some
  112471. ** or all of the WhereLoop objects once.
  112472. **
  112473. ** The "solver" works by creating the N best WherePath objects of length
  112474. ** 1. Then using those as a basis to compute the N best WherePath objects
  112475. ** of length 2. And so forth until the length of WherePaths equals the
  112476. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  112477. ** at the end is the chosen query plan.
  112478. */
  112479. struct WherePath {
  112480. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  112481. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  112482. LogEst nRow; /* Estimated number of rows generated by this path */
  112483. LogEst rCost; /* Total cost of this path */
  112484. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  112485. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  112486. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  112487. };
  112488. /*
  112489. ** The query generator uses an array of instances of this structure to
  112490. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  112491. ** clause subexpression is separated from the others by AND operators,
  112492. ** usually, or sometimes subexpressions separated by OR.
  112493. **
  112494. ** All WhereTerms are collected into a single WhereClause structure.
  112495. ** The following identity holds:
  112496. **
  112497. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  112498. **
  112499. ** When a term is of the form:
  112500. **
  112501. ** X <op> <expr>
  112502. **
  112503. ** where X is a column name and <op> is one of certain operators,
  112504. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  112505. ** cursor number and column number for X. WhereTerm.eOperator records
  112506. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  112507. ** use of a bitmask encoding for the operator allows us to search
  112508. ** quickly for terms that match any of several different operators.
  112509. **
  112510. ** A WhereTerm might also be two or more subterms connected by OR:
  112511. **
  112512. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  112513. **
  112514. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  112515. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  112516. ** is collected about the OR clause.
  112517. **
  112518. ** If a term in the WHERE clause does not match either of the two previous
  112519. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  112520. ** to the original subexpression content and wtFlags is set up appropriately
  112521. ** but no other fields in the WhereTerm object are meaningful.
  112522. **
  112523. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  112524. ** but they do so indirectly. A single WhereMaskSet structure translates
  112525. ** cursor number into bits and the translated bit is stored in the prereq
  112526. ** fields. The translation is used in order to maximize the number of
  112527. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  112528. ** spread out over the non-negative integers. For example, the cursor
  112529. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  112530. ** translates these sparse cursor numbers into consecutive integers
  112531. ** beginning with 0 in order to make the best possible use of the available
  112532. ** bits in the Bitmask. So, in the example above, the cursor numbers
  112533. ** would be mapped into integers 0 through 7.
  112534. **
  112535. ** The number of terms in a join is limited by the number of bits
  112536. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  112537. ** is only able to process joins with 64 or fewer tables.
  112538. */
  112539. struct WhereTerm {
  112540. Expr *pExpr; /* Pointer to the subexpression that is this term */
  112541. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  112542. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  112543. union {
  112544. int leftColumn; /* Column number of X in "X <op> <expr>" */
  112545. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  112546. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  112547. } u;
  112548. LogEst truthProb; /* Probability of truth for this expression */
  112549. u16 eOperator; /* A WO_xx value describing <op> */
  112550. u16 wtFlags; /* TERM_xxx bit flags. See below */
  112551. u8 nChild; /* Number of children that must disable us */
  112552. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  112553. WhereClause *pWC; /* The clause this term is part of */
  112554. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  112555. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  112556. };
  112557. /*
  112558. ** Allowed values of WhereTerm.wtFlags
  112559. */
  112560. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  112561. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  112562. #define TERM_CODED 0x04 /* This term is already coded */
  112563. #define TERM_COPIED 0x08 /* Has a child */
  112564. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  112565. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  112566. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  112567. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  112568. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  112569. #else
  112570. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  112571. #endif
  112572. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  112573. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  112574. #define TERM_LIKE 0x400 /* The original LIKE operator */
  112575. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  112576. /*
  112577. ** An instance of the WhereScan object is used as an iterator for locating
  112578. ** terms in the WHERE clause that are useful to the query planner.
  112579. */
  112580. struct WhereScan {
  112581. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  112582. WhereClause *pWC; /* WhereClause currently being scanned */
  112583. const char *zCollName; /* Required collating sequence, if not NULL */
  112584. Expr *pIdxExpr; /* Search for this index expression */
  112585. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  112586. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  112587. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  112588. u32 opMask; /* Acceptable operators */
  112589. int k; /* Resume scanning at this->pWC->a[this->k] */
  112590. int aiCur[11]; /* Cursors in the equivalence class */
  112591. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  112592. };
  112593. /*
  112594. ** An instance of the following structure holds all information about a
  112595. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  112596. **
  112597. ** Explanation of pOuter: For a WHERE clause of the form
  112598. **
  112599. ** a AND ((b AND c) OR (d AND e)) AND f
  112600. **
  112601. ** There are separate WhereClause objects for the whole clause and for
  112602. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  112603. ** subclauses points to the WhereClause object for the whole clause.
  112604. */
  112605. struct WhereClause {
  112606. WhereInfo *pWInfo; /* WHERE clause processing context */
  112607. WhereClause *pOuter; /* Outer conjunction */
  112608. u8 op; /* Split operator. TK_AND or TK_OR */
  112609. int nTerm; /* Number of terms */
  112610. int nSlot; /* Number of entries in a[] */
  112611. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  112612. #if defined(SQLITE_SMALL_STACK)
  112613. WhereTerm aStatic[1]; /* Initial static space for a[] */
  112614. #else
  112615. WhereTerm aStatic[8]; /* Initial static space for a[] */
  112616. #endif
  112617. };
  112618. /*
  112619. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  112620. ** a dynamically allocated instance of the following structure.
  112621. */
  112622. struct WhereOrInfo {
  112623. WhereClause wc; /* Decomposition into subterms */
  112624. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  112625. };
  112626. /*
  112627. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  112628. ** a dynamically allocated instance of the following structure.
  112629. */
  112630. struct WhereAndInfo {
  112631. WhereClause wc; /* The subexpression broken out */
  112632. };
  112633. /*
  112634. ** An instance of the following structure keeps track of a mapping
  112635. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  112636. **
  112637. ** The VDBE cursor numbers are small integers contained in
  112638. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  112639. ** clause, the cursor numbers might not begin with 0 and they might
  112640. ** contain gaps in the numbering sequence. But we want to make maximum
  112641. ** use of the bits in our bitmasks. This structure provides a mapping
  112642. ** from the sparse cursor numbers into consecutive integers beginning
  112643. ** with 0.
  112644. **
  112645. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  112646. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  112647. **
  112648. ** For example, if the WHERE clause expression used these VDBE
  112649. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  112650. ** would map those cursor numbers into bits 0 through 5.
  112651. **
  112652. ** Note that the mapping is not necessarily ordered. In the example
  112653. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  112654. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  112655. ** does not really matter. What is important is that sparse cursor
  112656. ** numbers all get mapped into bit numbers that begin with 0 and contain
  112657. ** no gaps.
  112658. */
  112659. struct WhereMaskSet {
  112660. int n; /* Number of assigned cursor values */
  112661. int ix[BMS]; /* Cursor assigned to each bit */
  112662. };
  112663. /*
  112664. ** Initialize a WhereMaskSet object
  112665. */
  112666. #define initMaskSet(P) (P)->n=0
  112667. /*
  112668. ** This object is a convenience wrapper holding all information needed
  112669. ** to construct WhereLoop objects for a particular query.
  112670. */
  112671. struct WhereLoopBuilder {
  112672. WhereInfo *pWInfo; /* Information about this WHERE */
  112673. WhereClause *pWC; /* WHERE clause terms */
  112674. ExprList *pOrderBy; /* ORDER BY clause */
  112675. WhereLoop *pNew; /* Template WhereLoop */
  112676. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  112677. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  112678. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  112679. int nRecValid; /* Number of valid fields currently in pRec */
  112680. #endif
  112681. };
  112682. /*
  112683. ** The WHERE clause processing routine has two halves. The
  112684. ** first part does the start of the WHERE loop and the second
  112685. ** half does the tail of the WHERE loop. An instance of
  112686. ** this structure is returned by the first half and passed
  112687. ** into the second half to give some continuity.
  112688. **
  112689. ** An instance of this object holds the complete state of the query
  112690. ** planner.
  112691. */
  112692. struct WhereInfo {
  112693. Parse *pParse; /* Parsing and code generating context */
  112694. SrcList *pTabList; /* List of tables in the join */
  112695. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  112696. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  112697. WhereLoop *pLoops; /* List of all WhereLoop objects */
  112698. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  112699. LogEst nRowOut; /* Estimated number of output rows */
  112700. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  112701. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  112702. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  112703. u8 sorted; /* True if really sorted (not just grouped) */
  112704. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  112705. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  112706. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  112707. u8 nLevel; /* Number of nested loop */
  112708. int iTop; /* The very beginning of the WHERE loop */
  112709. int iContinue; /* Jump here to continue with next record */
  112710. int iBreak; /* Jump here to break out of the loop */
  112711. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  112712. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  112713. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  112714. WhereClause sWC; /* Decomposition of the WHERE clause */
  112715. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  112716. };
  112717. /*
  112718. ** Private interfaces - callable only by other where.c routines.
  112719. **
  112720. ** where.c:
  112721. */
  112722. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  112723. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  112724. WhereClause *pWC, /* The WHERE clause to be searched */
  112725. int iCur, /* Cursor number of LHS */
  112726. int iColumn, /* Column number of LHS */
  112727. Bitmask notReady, /* RHS must not overlap with this mask */
  112728. u32 op, /* Mask of WO_xx values describing operator */
  112729. Index *pIdx /* Must be compatible with this index, if not NULL */
  112730. );
  112731. /* wherecode.c: */
  112732. #ifndef SQLITE_OMIT_EXPLAIN
  112733. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  112734. Parse *pParse, /* Parse context */
  112735. SrcList *pTabList, /* Table list this loop refers to */
  112736. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  112737. int iLevel, /* Value for "level" column of output */
  112738. int iFrom, /* Value for "from" column of output */
  112739. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  112740. );
  112741. #else
  112742. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  112743. #endif /* SQLITE_OMIT_EXPLAIN */
  112744. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  112745. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  112746. Vdbe *v, /* Vdbe to add scanstatus entry to */
  112747. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  112748. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  112749. int addrExplain /* Address of OP_Explain (or 0) */
  112750. );
  112751. #else
  112752. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  112753. #endif
  112754. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  112755. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  112756. int iLevel, /* Which level of pWInfo->a[] should be coded */
  112757. Bitmask notReady /* Which tables are currently available */
  112758. );
  112759. /* whereexpr.c: */
  112760. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  112761. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  112762. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  112763. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  112764. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  112765. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  112766. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  112767. /*
  112768. ** Bitmasks for the operators on WhereTerm objects. These are all
  112769. ** operators that are of interest to the query planner. An
  112770. ** OR-ed combination of these values can be used when searching for
  112771. ** particular WhereTerms within a WhereClause.
  112772. */
  112773. #define WO_IN 0x0001
  112774. #define WO_EQ 0x0002
  112775. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  112776. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  112777. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  112778. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  112779. #define WO_MATCH 0x0040
  112780. #define WO_IS 0x0080
  112781. #define WO_ISNULL 0x0100
  112782. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  112783. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  112784. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  112785. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  112786. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  112787. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  112788. /*
  112789. ** These are definitions of bits in the WhereLoop.wsFlags field.
  112790. ** The particular combination of bits in each WhereLoop help to
  112791. ** determine the algorithm that WhereLoop represents.
  112792. */
  112793. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  112794. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  112795. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  112796. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  112797. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  112798. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  112799. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  112800. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  112801. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  112802. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  112803. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  112804. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  112805. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  112806. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  112807. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  112808. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  112809. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  112810. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  112811. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  112812. /************** End of whereInt.h ********************************************/
  112813. /************** Continuing where we left off in wherecode.c ******************/
  112814. #ifndef SQLITE_OMIT_EXPLAIN
  112815. /*
  112816. ** This routine is a helper for explainIndexRange() below
  112817. **
  112818. ** pStr holds the text of an expression that we are building up one term
  112819. ** at a time. This routine adds a new term to the end of the expression.
  112820. ** Terms are separated by AND so add the "AND" text for second and subsequent
  112821. ** terms only.
  112822. */
  112823. static void explainAppendTerm(
  112824. StrAccum *pStr, /* The text expression being built */
  112825. int iTerm, /* Index of this term. First is zero */
  112826. const char *zColumn, /* Name of the column */
  112827. const char *zOp /* Name of the operator */
  112828. ){
  112829. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  112830. sqlite3StrAccumAppendAll(pStr, zColumn);
  112831. sqlite3StrAccumAppend(pStr, zOp, 1);
  112832. sqlite3StrAccumAppend(pStr, "?", 1);
  112833. }
  112834. /*
  112835. ** Return the name of the i-th column of the pIdx index.
  112836. */
  112837. static const char *explainIndexColumnName(Index *pIdx, int i){
  112838. i = pIdx->aiColumn[i];
  112839. if( i==XN_EXPR ) return "<expr>";
  112840. if( i==XN_ROWID ) return "rowid";
  112841. return pIdx->pTable->aCol[i].zName;
  112842. }
  112843. /*
  112844. ** Argument pLevel describes a strategy for scanning table pTab. This
  112845. ** function appends text to pStr that describes the subset of table
  112846. ** rows scanned by the strategy in the form of an SQL expression.
  112847. **
  112848. ** For example, if the query:
  112849. **
  112850. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  112851. **
  112852. ** is run and there is an index on (a, b), then this function returns a
  112853. ** string similar to:
  112854. **
  112855. ** "a=? AND b>?"
  112856. */
  112857. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  112858. Index *pIndex = pLoop->u.btree.pIndex;
  112859. u16 nEq = pLoop->u.btree.nEq;
  112860. u16 nSkip = pLoop->nSkip;
  112861. int i, j;
  112862. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  112863. sqlite3StrAccumAppend(pStr, " (", 2);
  112864. for(i=0; i<nEq; i++){
  112865. const char *z = explainIndexColumnName(pIndex, i);
  112866. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  112867. sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  112868. }
  112869. j = i;
  112870. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  112871. const char *z = explainIndexColumnName(pIndex, i);
  112872. explainAppendTerm(pStr, i++, z, ">");
  112873. }
  112874. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  112875. const char *z = explainIndexColumnName(pIndex, j);
  112876. explainAppendTerm(pStr, i, z, "<");
  112877. }
  112878. sqlite3StrAccumAppend(pStr, ")", 1);
  112879. }
  112880. /*
  112881. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  112882. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  112883. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  112884. ** is added to the output to describe the table scan strategy in pLevel.
  112885. **
  112886. ** If an OP_Explain opcode is added to the VM, its address is returned.
  112887. ** Otherwise, if no OP_Explain is coded, zero is returned.
  112888. */
  112889. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  112890. Parse *pParse, /* Parse context */
  112891. SrcList *pTabList, /* Table list this loop refers to */
  112892. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  112893. int iLevel, /* Value for "level" column of output */
  112894. int iFrom, /* Value for "from" column of output */
  112895. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  112896. ){
  112897. int ret = 0;
  112898. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  112899. if( pParse->explain==2 )
  112900. #endif
  112901. {
  112902. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  112903. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  112904. sqlite3 *db = pParse->db; /* Database handle */
  112905. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  112906. int isSearch; /* True for a SEARCH. False for SCAN. */
  112907. WhereLoop *pLoop; /* The controlling WhereLoop object */
  112908. u32 flags; /* Flags that describe this loop */
  112909. char *zMsg; /* Text to add to EQP output */
  112910. StrAccum str; /* EQP output string */
  112911. char zBuf[100]; /* Initial space for EQP output string */
  112912. pLoop = pLevel->pWLoop;
  112913. flags = pLoop->wsFlags;
  112914. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
  112915. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  112916. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  112917. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  112918. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  112919. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  112920. if( pItem->pSelect ){
  112921. sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
  112922. }else{
  112923. sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
  112924. }
  112925. if( pItem->zAlias ){
  112926. sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
  112927. }
  112928. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  112929. const char *zFmt = 0;
  112930. Index *pIdx;
  112931. assert( pLoop->u.btree.pIndex!=0 );
  112932. pIdx = pLoop->u.btree.pIndex;
  112933. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  112934. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  112935. if( isSearch ){
  112936. zFmt = "PRIMARY KEY";
  112937. }
  112938. }else if( flags & WHERE_PARTIALIDX ){
  112939. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  112940. }else if( flags & WHERE_AUTO_INDEX ){
  112941. zFmt = "AUTOMATIC COVERING INDEX";
  112942. }else if( flags & WHERE_IDX_ONLY ){
  112943. zFmt = "COVERING INDEX %s";
  112944. }else{
  112945. zFmt = "INDEX %s";
  112946. }
  112947. if( zFmt ){
  112948. sqlite3StrAccumAppend(&str, " USING ", 7);
  112949. sqlite3XPrintf(&str, zFmt, pIdx->zName);
  112950. explainIndexRange(&str, pLoop);
  112951. }
  112952. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  112953. const char *zRangeOp;
  112954. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  112955. zRangeOp = "=";
  112956. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  112957. zRangeOp = ">? AND rowid<";
  112958. }else if( flags&WHERE_BTM_LIMIT ){
  112959. zRangeOp = ">";
  112960. }else{
  112961. assert( flags&WHERE_TOP_LIMIT);
  112962. zRangeOp = "<";
  112963. }
  112964. sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  112965. }
  112966. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112967. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  112968. sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
  112969. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  112970. }
  112971. #endif
  112972. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  112973. if( pLoop->nOut>=10 ){
  112974. sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  112975. }else{
  112976. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  112977. }
  112978. #endif
  112979. zMsg = sqlite3StrAccumFinish(&str);
  112980. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  112981. }
  112982. return ret;
  112983. }
  112984. #endif /* SQLITE_OMIT_EXPLAIN */
  112985. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  112986. /*
  112987. ** Configure the VM passed as the first argument with an
  112988. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  112989. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  112990. ** clause that the scan reads data from.
  112991. **
  112992. ** If argument addrExplain is not 0, it must be the address of an
  112993. ** OP_Explain instruction that describes the same loop.
  112994. */
  112995. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  112996. Vdbe *v, /* Vdbe to add scanstatus entry to */
  112997. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  112998. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  112999. int addrExplain /* Address of OP_Explain (or 0) */
  113000. ){
  113001. const char *zObj = 0;
  113002. WhereLoop *pLoop = pLvl->pWLoop;
  113003. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  113004. zObj = pLoop->u.btree.pIndex->zName;
  113005. }else{
  113006. zObj = pSrclist->a[pLvl->iFrom].zName;
  113007. }
  113008. sqlite3VdbeScanStatus(
  113009. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  113010. );
  113011. }
  113012. #endif
  113013. /*
  113014. ** Disable a term in the WHERE clause. Except, do not disable the term
  113015. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  113016. ** or USING clause of that join.
  113017. **
  113018. ** Consider the term t2.z='ok' in the following queries:
  113019. **
  113020. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  113021. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  113022. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  113023. **
  113024. ** The t2.z='ok' is disabled in the in (2) because it originates
  113025. ** in the ON clause. The term is disabled in (3) because it is not part
  113026. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  113027. **
  113028. ** Disabling a term causes that term to not be tested in the inner loop
  113029. ** of the join. Disabling is an optimization. When terms are satisfied
  113030. ** by indices, we disable them to prevent redundant tests in the inner
  113031. ** loop. We would get the correct results if nothing were ever disabled,
  113032. ** but joins might run a little slower. The trick is to disable as much
  113033. ** as we can without disabling too much. If we disabled in (1), we'd get
  113034. ** the wrong answer. See ticket #813.
  113035. **
  113036. ** If all the children of a term are disabled, then that term is also
  113037. ** automatically disabled. In this way, terms get disabled if derived
  113038. ** virtual terms are tested first. For example:
  113039. **
  113040. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  113041. ** \___________/ \______/ \_____/
  113042. ** parent child1 child2
  113043. **
  113044. ** Only the parent term was in the original WHERE clause. The child1
  113045. ** and child2 terms were added by the LIKE optimization. If both of
  113046. ** the virtual child terms are valid, then testing of the parent can be
  113047. ** skipped.
  113048. **
  113049. ** Usually the parent term is marked as TERM_CODED. But if the parent
  113050. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  113051. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  113052. ** a conditional such that is only evaluated on the second pass of a
  113053. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  113054. */
  113055. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  113056. int nLoop = 0;
  113057. while( pTerm
  113058. && (pTerm->wtFlags & TERM_CODED)==0
  113059. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  113060. && (pLevel->notReady & pTerm->prereqAll)==0
  113061. ){
  113062. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  113063. pTerm->wtFlags |= TERM_LIKECOND;
  113064. }else{
  113065. pTerm->wtFlags |= TERM_CODED;
  113066. }
  113067. if( pTerm->iParent<0 ) break;
  113068. pTerm = &pTerm->pWC->a[pTerm->iParent];
  113069. pTerm->nChild--;
  113070. if( pTerm->nChild!=0 ) break;
  113071. nLoop++;
  113072. }
  113073. }
  113074. /*
  113075. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  113076. ** to the n registers starting at base.
  113077. **
  113078. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  113079. ** beginning and end of zAff are ignored. If all entries in zAff are
  113080. ** SQLITE_AFF_BLOB, then no code gets generated.
  113081. **
  113082. ** This routine makes its own copy of zAff so that the caller is free
  113083. ** to modify zAff after this routine returns.
  113084. */
  113085. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  113086. Vdbe *v = pParse->pVdbe;
  113087. if( zAff==0 ){
  113088. assert( pParse->db->mallocFailed );
  113089. return;
  113090. }
  113091. assert( v!=0 );
  113092. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  113093. ** and end of the affinity string.
  113094. */
  113095. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  113096. n--;
  113097. base++;
  113098. zAff++;
  113099. }
  113100. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  113101. n--;
  113102. }
  113103. /* Code the OP_Affinity opcode if there is anything left to do. */
  113104. if( n>0 ){
  113105. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  113106. sqlite3ExprCacheAffinityChange(pParse, base, n);
  113107. }
  113108. }
  113109. /*
  113110. ** Generate code for a single equality term of the WHERE clause. An equality
  113111. ** term can be either X=expr or X IN (...). pTerm is the term to be
  113112. ** coded.
  113113. **
  113114. ** The current value for the constraint is left in register iReg.
  113115. **
  113116. ** For a constraint of the form X=expr, the expression is evaluated and its
  113117. ** result is left on the stack. For constraints of the form X IN (...)
  113118. ** this routine sets up a loop that will iterate over all values of X.
  113119. */
  113120. static int codeEqualityTerm(
  113121. Parse *pParse, /* The parsing context */
  113122. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  113123. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  113124. int iEq, /* Index of the equality term within this level */
  113125. int bRev, /* True for reverse-order IN operations */
  113126. int iTarget /* Attempt to leave results in this register */
  113127. ){
  113128. Expr *pX = pTerm->pExpr;
  113129. Vdbe *v = pParse->pVdbe;
  113130. int iReg; /* Register holding results */
  113131. assert( iTarget>0 );
  113132. if( pX->op==TK_EQ || pX->op==TK_IS ){
  113133. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  113134. }else if( pX->op==TK_ISNULL ){
  113135. iReg = iTarget;
  113136. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  113137. #ifndef SQLITE_OMIT_SUBQUERY
  113138. }else{
  113139. int eType;
  113140. int iTab;
  113141. struct InLoop *pIn;
  113142. WhereLoop *pLoop = pLevel->pWLoop;
  113143. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  113144. && pLoop->u.btree.pIndex!=0
  113145. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  113146. ){
  113147. testcase( iEq==0 );
  113148. testcase( bRev );
  113149. bRev = !bRev;
  113150. }
  113151. assert( pX->op==TK_IN );
  113152. iReg = iTarget;
  113153. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  113154. if( eType==IN_INDEX_INDEX_DESC ){
  113155. testcase( bRev );
  113156. bRev = !bRev;
  113157. }
  113158. iTab = pX->iTable;
  113159. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  113160. VdbeCoverageIf(v, bRev);
  113161. VdbeCoverageIf(v, !bRev);
  113162. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  113163. pLoop->wsFlags |= WHERE_IN_ABLE;
  113164. if( pLevel->u.in.nIn==0 ){
  113165. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  113166. }
  113167. pLevel->u.in.nIn++;
  113168. pLevel->u.in.aInLoop =
  113169. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  113170. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  113171. pIn = pLevel->u.in.aInLoop;
  113172. if( pIn ){
  113173. pIn += pLevel->u.in.nIn - 1;
  113174. pIn->iCur = iTab;
  113175. if( eType==IN_INDEX_ROWID ){
  113176. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  113177. }else{
  113178. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  113179. }
  113180. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  113181. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  113182. }else{
  113183. pLevel->u.in.nIn = 0;
  113184. }
  113185. #endif
  113186. }
  113187. disableTerm(pLevel, pTerm);
  113188. return iReg;
  113189. }
  113190. /*
  113191. ** Generate code that will evaluate all == and IN constraints for an
  113192. ** index scan.
  113193. **
  113194. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  113195. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  113196. ** The index has as many as three equality constraints, but in this
  113197. ** example, the third "c" value is an inequality. So only two
  113198. ** constraints are coded. This routine will generate code to evaluate
  113199. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  113200. ** in consecutive registers and the index of the first register is returned.
  113201. **
  113202. ** In the example above nEq==2. But this subroutine works for any value
  113203. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  113204. ** The only thing it does is allocate the pLevel->iMem memory cell and
  113205. ** compute the affinity string.
  113206. **
  113207. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  113208. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  113209. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  113210. ** occurs after the nEq quality constraints.
  113211. **
  113212. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  113213. ** the index of the first memory cell in that range. The code that
  113214. ** calls this routine will use that memory range to store keys for
  113215. ** start and termination conditions of the loop.
  113216. ** key value of the loop. If one or more IN operators appear, then
  113217. ** this routine allocates an additional nEq memory cells for internal
  113218. ** use.
  113219. **
  113220. ** Before returning, *pzAff is set to point to a buffer containing a
  113221. ** copy of the column affinity string of the index allocated using
  113222. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  113223. ** with equality constraints that use BLOB or NONE affinity are set to
  113224. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  113225. **
  113226. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  113227. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  113228. **
  113229. ** In the example above, the index on t1(a) has TEXT affinity. But since
  113230. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  113231. ** no conversion should be attempted before using a t2.b value as part of
  113232. ** a key to search the index. Hence the first byte in the returned affinity
  113233. ** string in this example would be set to SQLITE_AFF_BLOB.
  113234. */
  113235. static int codeAllEqualityTerms(
  113236. Parse *pParse, /* Parsing context */
  113237. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  113238. int bRev, /* Reverse the order of IN operators */
  113239. int nExtraReg, /* Number of extra registers to allocate */
  113240. char **pzAff /* OUT: Set to point to affinity string */
  113241. ){
  113242. u16 nEq; /* The number of == or IN constraints to code */
  113243. u16 nSkip; /* Number of left-most columns to skip */
  113244. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  113245. Index *pIdx; /* The index being used for this loop */
  113246. WhereTerm *pTerm; /* A single constraint term */
  113247. WhereLoop *pLoop; /* The WhereLoop object */
  113248. int j; /* Loop counter */
  113249. int regBase; /* Base register */
  113250. int nReg; /* Number of registers to allocate */
  113251. char *zAff; /* Affinity string to return */
  113252. /* This module is only called on query plans that use an index. */
  113253. pLoop = pLevel->pWLoop;
  113254. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  113255. nEq = pLoop->u.btree.nEq;
  113256. nSkip = pLoop->nSkip;
  113257. pIdx = pLoop->u.btree.pIndex;
  113258. assert( pIdx!=0 );
  113259. /* Figure out how many memory cells we will need then allocate them.
  113260. */
  113261. regBase = pParse->nMem + 1;
  113262. nReg = pLoop->u.btree.nEq + nExtraReg;
  113263. pParse->nMem += nReg;
  113264. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  113265. assert( zAff!=0 || pParse->db->mallocFailed );
  113266. if( nSkip ){
  113267. int iIdxCur = pLevel->iIdxCur;
  113268. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  113269. VdbeCoverageIf(v, bRev==0);
  113270. VdbeCoverageIf(v, bRev!=0);
  113271. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  113272. j = sqlite3VdbeAddOp0(v, OP_Goto);
  113273. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  113274. iIdxCur, 0, regBase, nSkip);
  113275. VdbeCoverageIf(v, bRev==0);
  113276. VdbeCoverageIf(v, bRev!=0);
  113277. sqlite3VdbeJumpHere(v, j);
  113278. for(j=0; j<nSkip; j++){
  113279. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  113280. testcase( pIdx->aiColumn[j]==XN_EXPR );
  113281. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  113282. }
  113283. }
  113284. /* Evaluate the equality constraints
  113285. */
  113286. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  113287. for(j=nSkip; j<nEq; j++){
  113288. int r1;
  113289. pTerm = pLoop->aLTerm[j];
  113290. assert( pTerm!=0 );
  113291. /* The following testcase is true for indices with redundant columns.
  113292. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  113293. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  113294. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  113295. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  113296. if( r1!=regBase+j ){
  113297. if( nReg==1 ){
  113298. sqlite3ReleaseTempReg(pParse, regBase);
  113299. regBase = r1;
  113300. }else{
  113301. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  113302. }
  113303. }
  113304. testcase( pTerm->eOperator & WO_ISNULL );
  113305. testcase( pTerm->eOperator & WO_IN );
  113306. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  113307. Expr *pRight = pTerm->pExpr->pRight;
  113308. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  113309. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  113310. VdbeCoverage(v);
  113311. }
  113312. if( zAff ){
  113313. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  113314. zAff[j] = SQLITE_AFF_BLOB;
  113315. }
  113316. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  113317. zAff[j] = SQLITE_AFF_BLOB;
  113318. }
  113319. }
  113320. }
  113321. }
  113322. *pzAff = zAff;
  113323. return regBase;
  113324. }
  113325. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  113326. /*
  113327. ** If the most recently coded instruction is a constant range contraint
  113328. ** that originated from the LIKE optimization, then change the P3 to be
  113329. ** pLoop->iLikeRepCntr and set P5.
  113330. **
  113331. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  113332. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  113333. ** scan loop run twice, once for strings and a second time for BLOBs.
  113334. ** The OP_String opcodes on the second pass convert the upper and lower
  113335. ** bound string contants to blobs. This routine makes the necessary changes
  113336. ** to the OP_String opcodes for that to happen.
  113337. **
  113338. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  113339. ** only the one pass through the string space is required, so this routine
  113340. ** becomes a no-op.
  113341. */
  113342. static void whereLikeOptimizationStringFixup(
  113343. Vdbe *v, /* prepared statement under construction */
  113344. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  113345. WhereTerm *pTerm /* The upper or lower bound just coded */
  113346. ){
  113347. if( pTerm->wtFlags & TERM_LIKEOPT ){
  113348. VdbeOp *pOp;
  113349. assert( pLevel->iLikeRepCntr>0 );
  113350. pOp = sqlite3VdbeGetOp(v, -1);
  113351. assert( pOp!=0 );
  113352. assert( pOp->opcode==OP_String8
  113353. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  113354. pOp->p3 = pLevel->iLikeRepCntr;
  113355. pOp->p5 = 1;
  113356. }
  113357. }
  113358. #else
  113359. # define whereLikeOptimizationStringFixup(A,B,C)
  113360. #endif
  113361. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  113362. /*
  113363. ** Information is passed from codeCursorHint() down to individual nodes of
  113364. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  113365. ** structure.
  113366. */
  113367. struct CCurHint {
  113368. int iTabCur; /* Cursor for the main table */
  113369. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  113370. Index *pIdx; /* The index used to access the table */
  113371. };
  113372. /*
  113373. ** This function is called for every node of an expression that is a candidate
  113374. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  113375. ** the table CCurHint.iTabCur, verify that the same column can be
  113376. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  113377. */
  113378. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  113379. struct CCurHint *pHint = pWalker->u.pCCurHint;
  113380. assert( pHint->pIdx!=0 );
  113381. if( pExpr->op==TK_COLUMN
  113382. && pExpr->iTable==pHint->iTabCur
  113383. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  113384. ){
  113385. pWalker->eCode = 1;
  113386. }
  113387. return WRC_Continue;
  113388. }
  113389. /*
  113390. ** This function is called on every node of an expression tree used as an
  113391. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  113392. ** that accesses any table other than the one identified by
  113393. ** CCurHint.iTabCur, then do the following:
  113394. **
  113395. ** 1) allocate a register and code an OP_Column instruction to read
  113396. ** the specified column into the new register, and
  113397. **
  113398. ** 2) transform the expression node to a TK_REGISTER node that reads
  113399. ** from the newly populated register.
  113400. **
  113401. ** Also, if the node is a TK_COLUMN that does access the table idenified
  113402. ** by pCCurHint.iTabCur, and an index is being used (which we will
  113403. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  113404. ** an access of the index rather than the original table.
  113405. */
  113406. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  113407. int rc = WRC_Continue;
  113408. struct CCurHint *pHint = pWalker->u.pCCurHint;
  113409. if( pExpr->op==TK_COLUMN ){
  113410. if( pExpr->iTable!=pHint->iTabCur ){
  113411. Vdbe *v = pWalker->pParse->pVdbe;
  113412. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  113413. sqlite3ExprCodeGetColumnOfTable(
  113414. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  113415. );
  113416. pExpr->op = TK_REGISTER;
  113417. pExpr->iTable = reg;
  113418. }else if( pHint->pIdx!=0 ){
  113419. pExpr->iTable = pHint->iIdxCur;
  113420. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  113421. assert( pExpr->iColumn>=0 );
  113422. }
  113423. }else if( pExpr->op==TK_AGG_FUNCTION ){
  113424. /* An aggregate function in the WHERE clause of a query means this must
  113425. ** be a correlated sub-query, and expression pExpr is an aggregate from
  113426. ** the parent context. Do not walk the function arguments in this case.
  113427. **
  113428. ** todo: It should be possible to replace this node with a TK_REGISTER
  113429. ** expression, as the result of the expression must be stored in a
  113430. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  113431. rc = WRC_Prune;
  113432. }
  113433. return rc;
  113434. }
  113435. /*
  113436. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  113437. */
  113438. static void codeCursorHint(
  113439. WhereInfo *pWInfo, /* The where clause */
  113440. WhereLevel *pLevel, /* Which loop to provide hints for */
  113441. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  113442. ){
  113443. Parse *pParse = pWInfo->pParse;
  113444. sqlite3 *db = pParse->db;
  113445. Vdbe *v = pParse->pVdbe;
  113446. Expr *pExpr = 0;
  113447. WhereLoop *pLoop = pLevel->pWLoop;
  113448. int iCur;
  113449. WhereClause *pWC;
  113450. WhereTerm *pTerm;
  113451. int i, j;
  113452. struct CCurHint sHint;
  113453. Walker sWalker;
  113454. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  113455. iCur = pLevel->iTabCur;
  113456. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  113457. sHint.iTabCur = iCur;
  113458. sHint.iIdxCur = pLevel->iIdxCur;
  113459. sHint.pIdx = pLoop->u.btree.pIndex;
  113460. memset(&sWalker, 0, sizeof(sWalker));
  113461. sWalker.pParse = pParse;
  113462. sWalker.u.pCCurHint = &sHint;
  113463. pWC = &pWInfo->sWC;
  113464. for(i=0; i<pWC->nTerm; i++){
  113465. pTerm = &pWC->a[i];
  113466. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  113467. if( pTerm->prereqAll & pLevel->notReady ) continue;
  113468. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  113469. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  113470. ** the cursor. These terms are not needed as hints for a pure range
  113471. ** scan (that has no == terms) so omit them. */
  113472. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  113473. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  113474. if( j<pLoop->nLTerm ) continue;
  113475. }
  113476. /* No subqueries or non-deterministic functions allowed */
  113477. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  113478. /* For an index scan, make sure referenced columns are actually in
  113479. ** the index. */
  113480. if( sHint.pIdx!=0 ){
  113481. sWalker.eCode = 0;
  113482. sWalker.xExprCallback = codeCursorHintCheckExpr;
  113483. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  113484. if( sWalker.eCode ) continue;
  113485. }
  113486. /* If we survive all prior tests, that means this term is worth hinting */
  113487. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  113488. }
  113489. if( pExpr!=0 ){
  113490. sWalker.xExprCallback = codeCursorHintFixExpr;
  113491. sqlite3WalkExpr(&sWalker, pExpr);
  113492. sqlite3VdbeAddOp4(v, OP_CursorHint,
  113493. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  113494. (const char*)pExpr, P4_EXPR);
  113495. }
  113496. }
  113497. #else
  113498. # define codeCursorHint(A,B,C) /* No-op */
  113499. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  113500. /*
  113501. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  113502. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  113503. ** function generates code to do a deferred seek of cursor iCur to the
  113504. ** rowid stored in register iRowid.
  113505. **
  113506. ** Normally, this is just:
  113507. **
  113508. ** OP_Seek $iCur $iRowid
  113509. **
  113510. ** However, if the scan currently being coded is a branch of an OR-loop and
  113511. ** the statement currently being coded is a SELECT, then P3 of the OP_Seek
  113512. ** is set to iIdxCur and P4 is set to point to an array of integers
  113513. ** containing one entry for each column of the table cursor iCur is open
  113514. ** on. For each table column, if the column is the i'th column of the
  113515. ** index, then the corresponding array entry is set to (i+1). If the column
  113516. ** does not appear in the index at all, the array entry is set to 0.
  113517. */
  113518. static void codeDeferredSeek(
  113519. WhereInfo *pWInfo, /* Where clause context */
  113520. Index *pIdx, /* Index scan is using */
  113521. int iCur, /* Cursor for IPK b-tree */
  113522. int iIdxCur /* Index cursor */
  113523. ){
  113524. Parse *pParse = pWInfo->pParse; /* Parse context */
  113525. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  113526. assert( iIdxCur>0 );
  113527. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  113528. sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
  113529. if( (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)
  113530. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  113531. ){
  113532. int i;
  113533. Table *pTab = pIdx->pTable;
  113534. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  113535. if( ai ){
  113536. ai[0] = pTab->nCol;
  113537. for(i=0; i<pIdx->nColumn-1; i++){
  113538. assert( pIdx->aiColumn[i]<pTab->nCol );
  113539. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  113540. }
  113541. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  113542. }
  113543. }
  113544. }
  113545. /*
  113546. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  113547. ** implementation described by pWInfo.
  113548. */
  113549. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  113550. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  113551. int iLevel, /* Which level of pWInfo->a[] should be coded */
  113552. Bitmask notReady /* Which tables are currently available */
  113553. ){
  113554. int j, k; /* Loop counters */
  113555. int iCur; /* The VDBE cursor for the table */
  113556. int addrNxt; /* Where to jump to continue with the next IN case */
  113557. int omitTable; /* True if we use the index only */
  113558. int bRev; /* True if we need to scan in reverse order */
  113559. WhereLevel *pLevel; /* The where level to be coded */
  113560. WhereLoop *pLoop; /* The WhereLoop object being coded */
  113561. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  113562. WhereTerm *pTerm; /* A WHERE clause term */
  113563. Parse *pParse; /* Parsing context */
  113564. sqlite3 *db; /* Database connection */
  113565. Vdbe *v; /* The prepared stmt under constructions */
  113566. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  113567. int addrBrk; /* Jump here to break out of the loop */
  113568. int addrCont; /* Jump here to continue with next cycle */
  113569. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  113570. int iReleaseReg = 0; /* Temp register to free before returning */
  113571. pParse = pWInfo->pParse;
  113572. v = pParse->pVdbe;
  113573. pWC = &pWInfo->sWC;
  113574. db = pParse->db;
  113575. pLevel = &pWInfo->a[iLevel];
  113576. pLoop = pLevel->pWLoop;
  113577. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  113578. iCur = pTabItem->iCursor;
  113579. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  113580. bRev = (pWInfo->revMask>>iLevel)&1;
  113581. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  113582. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  113583. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  113584. /* Create labels for the "break" and "continue" instructions
  113585. ** for the current loop. Jump to addrBrk to break out of a loop.
  113586. ** Jump to cont to go immediately to the next iteration of the
  113587. ** loop.
  113588. **
  113589. ** When there is an IN operator, we also have a "addrNxt" label that
  113590. ** means to continue with the next IN value combination. When
  113591. ** there are no IN operators in the constraints, the "addrNxt" label
  113592. ** is the same as "addrBrk".
  113593. */
  113594. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  113595. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  113596. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  113597. ** initialize a memory cell that records if this table matches any
  113598. ** row of the left table of the join.
  113599. */
  113600. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  113601. pLevel->iLeftJoin = ++pParse->nMem;
  113602. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  113603. VdbeComment((v, "init LEFT JOIN no-match flag"));
  113604. }
  113605. /* Special case of a FROM clause subquery implemented as a co-routine */
  113606. if( pTabItem->fg.viaCoroutine ){
  113607. int regYield = pTabItem->regReturn;
  113608. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  113609. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  113610. VdbeCoverage(v);
  113611. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  113612. pLevel->op = OP_Goto;
  113613. }else
  113614. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113615. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  113616. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  113617. ** to access the data.
  113618. */
  113619. int iReg; /* P3 Value for OP_VFilter */
  113620. int addrNotFound;
  113621. int nConstraint = pLoop->nLTerm;
  113622. int iIn; /* Counter for IN constraints */
  113623. sqlite3ExprCachePush(pParse);
  113624. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  113625. addrNotFound = pLevel->addrBrk;
  113626. for(j=0; j<nConstraint; j++){
  113627. int iTarget = iReg+j+2;
  113628. pTerm = pLoop->aLTerm[j];
  113629. if( NEVER(pTerm==0) ) continue;
  113630. if( pTerm->eOperator & WO_IN ){
  113631. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  113632. addrNotFound = pLevel->addrNxt;
  113633. }else{
  113634. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  113635. }
  113636. }
  113637. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  113638. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  113639. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  113640. pLoop->u.vtab.idxStr,
  113641. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  113642. VdbeCoverage(v);
  113643. pLoop->u.vtab.needFree = 0;
  113644. pLevel->p1 = iCur;
  113645. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  113646. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  113647. iIn = pLevel->u.in.nIn;
  113648. for(j=nConstraint-1; j>=0; j--){
  113649. pTerm = pLoop->aLTerm[j];
  113650. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  113651. disableTerm(pLevel, pTerm);
  113652. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  113653. Expr *pCompare; /* The comparison operator */
  113654. Expr *pRight; /* RHS of the comparison */
  113655. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  113656. /* Reload the constraint value into reg[iReg+j+2]. The same value
  113657. ** was loaded into the same register prior to the OP_VFilter, but
  113658. ** the xFilter implementation might have changed the datatype or
  113659. ** encoding of the value in the register, so it *must* be reloaded. */
  113660. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  113661. if( !db->mallocFailed ){
  113662. assert( iIn>0 );
  113663. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  113664. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  113665. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  113666. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  113667. testcase( pOp->opcode==OP_Rowid );
  113668. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  113669. }
  113670. /* Generate code that will continue to the next row if
  113671. ** the IN constraint is not satisfied */
  113672. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
  113673. assert( pCompare!=0 || db->mallocFailed );
  113674. if( pCompare ){
  113675. pCompare->pLeft = pTerm->pExpr->pLeft;
  113676. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  113677. if( pRight ){
  113678. pRight->iTable = iReg+j+2;
  113679. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  113680. }
  113681. pCompare->pLeft = 0;
  113682. sqlite3ExprDelete(db, pCompare);
  113683. }
  113684. }
  113685. }
  113686. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  113687. sqlite3ExprCachePop(pParse);
  113688. }else
  113689. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  113690. if( (pLoop->wsFlags & WHERE_IPK)!=0
  113691. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  113692. ){
  113693. /* Case 2: We can directly reference a single row using an
  113694. ** equality comparison against the ROWID field. Or
  113695. ** we reference multiple rows using a "rowid IN (...)"
  113696. ** construct.
  113697. */
  113698. assert( pLoop->u.btree.nEq==1 );
  113699. pTerm = pLoop->aLTerm[0];
  113700. assert( pTerm!=0 );
  113701. assert( pTerm->pExpr!=0 );
  113702. assert( omitTable==0 );
  113703. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  113704. iReleaseReg = ++pParse->nMem;
  113705. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  113706. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  113707. addrNxt = pLevel->addrNxt;
  113708. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  113709. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  113710. VdbeCoverage(v);
  113711. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  113712. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  113713. VdbeComment((v, "pk"));
  113714. pLevel->op = OP_Noop;
  113715. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  113716. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  113717. ){
  113718. /* Case 3: We have an inequality comparison against the ROWID field.
  113719. */
  113720. int testOp = OP_Noop;
  113721. int start;
  113722. int memEndValue = 0;
  113723. WhereTerm *pStart, *pEnd;
  113724. assert( omitTable==0 );
  113725. j = 0;
  113726. pStart = pEnd = 0;
  113727. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  113728. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  113729. assert( pStart!=0 || pEnd!=0 );
  113730. if( bRev ){
  113731. pTerm = pStart;
  113732. pStart = pEnd;
  113733. pEnd = pTerm;
  113734. }
  113735. codeCursorHint(pWInfo, pLevel, pEnd);
  113736. if( pStart ){
  113737. Expr *pX; /* The expression that defines the start bound */
  113738. int r1, rTemp; /* Registers for holding the start boundary */
  113739. /* The following constant maps TK_xx codes into corresponding
  113740. ** seek opcodes. It depends on a particular ordering of TK_xx
  113741. */
  113742. const u8 aMoveOp[] = {
  113743. /* TK_GT */ OP_SeekGT,
  113744. /* TK_LE */ OP_SeekLE,
  113745. /* TK_LT */ OP_SeekLT,
  113746. /* TK_GE */ OP_SeekGE
  113747. };
  113748. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  113749. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  113750. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  113751. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  113752. testcase( pStart->wtFlags & TERM_VIRTUAL );
  113753. pX = pStart->pExpr;
  113754. assert( pX!=0 );
  113755. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  113756. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  113757. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  113758. VdbeComment((v, "pk"));
  113759. VdbeCoverageIf(v, pX->op==TK_GT);
  113760. VdbeCoverageIf(v, pX->op==TK_LE);
  113761. VdbeCoverageIf(v, pX->op==TK_LT);
  113762. VdbeCoverageIf(v, pX->op==TK_GE);
  113763. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  113764. sqlite3ReleaseTempReg(pParse, rTemp);
  113765. disableTerm(pLevel, pStart);
  113766. }else{
  113767. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  113768. VdbeCoverageIf(v, bRev==0);
  113769. VdbeCoverageIf(v, bRev!=0);
  113770. }
  113771. if( pEnd ){
  113772. Expr *pX;
  113773. pX = pEnd->pExpr;
  113774. assert( pX!=0 );
  113775. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  113776. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  113777. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  113778. memEndValue = ++pParse->nMem;
  113779. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  113780. if( pX->op==TK_LT || pX->op==TK_GT ){
  113781. testOp = bRev ? OP_Le : OP_Ge;
  113782. }else{
  113783. testOp = bRev ? OP_Lt : OP_Gt;
  113784. }
  113785. disableTerm(pLevel, pEnd);
  113786. }
  113787. start = sqlite3VdbeCurrentAddr(v);
  113788. pLevel->op = bRev ? OP_Prev : OP_Next;
  113789. pLevel->p1 = iCur;
  113790. pLevel->p2 = start;
  113791. assert( pLevel->p5==0 );
  113792. if( testOp!=OP_Noop ){
  113793. iRowidReg = ++pParse->nMem;
  113794. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  113795. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  113796. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  113797. VdbeCoverageIf(v, testOp==OP_Le);
  113798. VdbeCoverageIf(v, testOp==OP_Lt);
  113799. VdbeCoverageIf(v, testOp==OP_Ge);
  113800. VdbeCoverageIf(v, testOp==OP_Gt);
  113801. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  113802. }
  113803. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  113804. /* Case 4: A scan using an index.
  113805. **
  113806. ** The WHERE clause may contain zero or more equality
  113807. ** terms ("==" or "IN" operators) that refer to the N
  113808. ** left-most columns of the index. It may also contain
  113809. ** inequality constraints (>, <, >= or <=) on the indexed
  113810. ** column that immediately follows the N equalities. Only
  113811. ** the right-most column can be an inequality - the rest must
  113812. ** use the "==" and "IN" operators. For example, if the
  113813. ** index is on (x,y,z), then the following clauses are all
  113814. ** optimized:
  113815. **
  113816. ** x=5
  113817. ** x=5 AND y=10
  113818. ** x=5 AND y<10
  113819. ** x=5 AND y>5 AND y<10
  113820. ** x=5 AND y=5 AND z<=10
  113821. **
  113822. ** The z<10 term of the following cannot be used, only
  113823. ** the x=5 term:
  113824. **
  113825. ** x=5 AND z<10
  113826. **
  113827. ** N may be zero if there are inequality constraints.
  113828. ** If there are no inequality constraints, then N is at
  113829. ** least one.
  113830. **
  113831. ** This case is also used when there are no WHERE clause
  113832. ** constraints but an index is selected anyway, in order
  113833. ** to force the output order to conform to an ORDER BY.
  113834. */
  113835. static const u8 aStartOp[] = {
  113836. 0,
  113837. 0,
  113838. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  113839. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  113840. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  113841. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  113842. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  113843. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  113844. };
  113845. static const u8 aEndOp[] = {
  113846. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  113847. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  113848. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  113849. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  113850. };
  113851. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  113852. int regBase; /* Base register holding constraint values */
  113853. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  113854. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  113855. int startEq; /* True if range start uses ==, >= or <= */
  113856. int endEq; /* True if range end uses ==, >= or <= */
  113857. int start_constraints; /* Start of range is constrained */
  113858. int nConstraint; /* Number of constraint terms */
  113859. Index *pIdx; /* The index we will be using */
  113860. int iIdxCur; /* The VDBE cursor for the index */
  113861. int nExtraReg = 0; /* Number of extra registers needed */
  113862. int op; /* Instruction opcode */
  113863. char *zStartAff; /* Affinity for start of range constraint */
  113864. char cEndAff = 0; /* Affinity for end of range constraint */
  113865. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  113866. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  113867. pIdx = pLoop->u.btree.pIndex;
  113868. iIdxCur = pLevel->iIdxCur;
  113869. assert( nEq>=pLoop->nSkip );
  113870. /* If this loop satisfies a sort order (pOrderBy) request that
  113871. ** was passed to this function to implement a "SELECT min(x) ..."
  113872. ** query, then the caller will only allow the loop to run for
  113873. ** a single iteration. This means that the first row returned
  113874. ** should not have a NULL value stored in 'x'. If column 'x' is
  113875. ** the first one after the nEq equality constraints in the index,
  113876. ** this requires some special handling.
  113877. */
  113878. assert( pWInfo->pOrderBy==0
  113879. || pWInfo->pOrderBy->nExpr==1
  113880. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  113881. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  113882. && pWInfo->nOBSat>0
  113883. && (pIdx->nKeyCol>nEq)
  113884. ){
  113885. assert( pLoop->nSkip==0 );
  113886. bSeekPastNull = 1;
  113887. nExtraReg = 1;
  113888. }
  113889. /* Find any inequality constraint terms for the start and end
  113890. ** of the range.
  113891. */
  113892. j = nEq;
  113893. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  113894. pRangeStart = pLoop->aLTerm[j++];
  113895. nExtraReg = 1;
  113896. /* Like optimization range constraints always occur in pairs */
  113897. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  113898. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  113899. }
  113900. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  113901. pRangeEnd = pLoop->aLTerm[j++];
  113902. nExtraReg = 1;
  113903. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  113904. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  113905. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  113906. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  113907. pLevel->iLikeRepCntr = ++pParse->nMem;
  113908. testcase( bRev );
  113909. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  113910. sqlite3VdbeAddOp2(v, OP_Integer,
  113911. bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
  113912. pLevel->iLikeRepCntr);
  113913. VdbeComment((v, "LIKE loop counter"));
  113914. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  113915. }
  113916. #endif
  113917. if( pRangeStart==0
  113918. && (j = pIdx->aiColumn[nEq])>=0
  113919. && pIdx->pTable->aCol[j].notNull==0
  113920. ){
  113921. bSeekPastNull = 1;
  113922. }
  113923. }
  113924. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  113925. /* If we are doing a reverse order scan on an ascending index, or
  113926. ** a forward order scan on a descending index, interchange the
  113927. ** start and end terms (pRangeStart and pRangeEnd).
  113928. */
  113929. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  113930. || (bRev && pIdx->nKeyCol==nEq)
  113931. ){
  113932. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  113933. SWAP(u8, bSeekPastNull, bStopAtNull);
  113934. }
  113935. /* Generate code to evaluate all constraint terms using == or IN
  113936. ** and store the values of those terms in an array of registers
  113937. ** starting at regBase.
  113938. */
  113939. codeCursorHint(pWInfo, pLevel, pRangeEnd);
  113940. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  113941. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  113942. if( zStartAff ) cEndAff = zStartAff[nEq];
  113943. addrNxt = pLevel->addrNxt;
  113944. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  113945. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  113946. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  113947. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  113948. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  113949. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  113950. start_constraints = pRangeStart || nEq>0;
  113951. /* Seek the index cursor to the start of the range. */
  113952. nConstraint = nEq;
  113953. if( pRangeStart ){
  113954. Expr *pRight = pRangeStart->pExpr->pRight;
  113955. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  113956. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  113957. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  113958. && sqlite3ExprCanBeNull(pRight)
  113959. ){
  113960. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  113961. VdbeCoverage(v);
  113962. }
  113963. if( zStartAff ){
  113964. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
  113965. /* Since the comparison is to be performed with no conversions
  113966. ** applied to the operands, set the affinity to apply to pRight to
  113967. ** SQLITE_AFF_BLOB. */
  113968. zStartAff[nEq] = SQLITE_AFF_BLOB;
  113969. }
  113970. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  113971. zStartAff[nEq] = SQLITE_AFF_BLOB;
  113972. }
  113973. }
  113974. nConstraint++;
  113975. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  113976. }else if( bSeekPastNull ){
  113977. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  113978. nConstraint++;
  113979. startEq = 0;
  113980. start_constraints = 1;
  113981. }
  113982. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  113983. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  113984. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  113985. ** above has already left the cursor sitting on the correct row,
  113986. ** so no further seeking is needed */
  113987. }else{
  113988. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  113989. assert( op!=0 );
  113990. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  113991. VdbeCoverage(v);
  113992. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  113993. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  113994. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  113995. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  113996. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  113997. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  113998. }
  113999. /* Load the value for the inequality constraint at the end of the
  114000. ** range (if any).
  114001. */
  114002. nConstraint = nEq;
  114003. if( pRangeEnd ){
  114004. Expr *pRight = pRangeEnd->pExpr->pRight;
  114005. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  114006. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  114007. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  114008. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  114009. && sqlite3ExprCanBeNull(pRight)
  114010. ){
  114011. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  114012. VdbeCoverage(v);
  114013. }
  114014. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
  114015. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  114016. ){
  114017. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  114018. }
  114019. nConstraint++;
  114020. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  114021. }else if( bStopAtNull ){
  114022. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  114023. endEq = 0;
  114024. nConstraint++;
  114025. }
  114026. sqlite3DbFree(db, zStartAff);
  114027. /* Top of the loop body */
  114028. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  114029. /* Check if the index cursor is past the end of the range. */
  114030. if( nConstraint ){
  114031. op = aEndOp[bRev*2 + endEq];
  114032. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  114033. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  114034. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  114035. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  114036. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  114037. }
  114038. /* Seek the table cursor, if required */
  114039. disableTerm(pLevel, pRangeStart);
  114040. disableTerm(pLevel, pRangeEnd);
  114041. if( omitTable ){
  114042. /* pIdx is a covering index. No need to access the main table. */
  114043. }else if( HasRowid(pIdx->pTable) ){
  114044. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  114045. iRowidReg = ++pParse->nMem;
  114046. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  114047. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  114048. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  114049. VdbeCoverage(v);
  114050. }else{
  114051. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  114052. }
  114053. }else if( iCur!=iIdxCur ){
  114054. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  114055. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  114056. for(j=0; j<pPk->nKeyCol; j++){
  114057. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  114058. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  114059. }
  114060. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  114061. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  114062. }
  114063. /* Record the instruction used to terminate the loop. Disable
  114064. ** WHERE clause terms made redundant by the index range scan.
  114065. */
  114066. if( pLoop->wsFlags & WHERE_ONEROW ){
  114067. pLevel->op = OP_Noop;
  114068. }else if( bRev ){
  114069. pLevel->op = OP_Prev;
  114070. }else{
  114071. pLevel->op = OP_Next;
  114072. }
  114073. pLevel->p1 = iIdxCur;
  114074. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  114075. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  114076. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  114077. }else{
  114078. assert( pLevel->p5==0 );
  114079. }
  114080. }else
  114081. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  114082. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  114083. /* Case 5: Two or more separately indexed terms connected by OR
  114084. **
  114085. ** Example:
  114086. **
  114087. ** CREATE TABLE t1(a,b,c,d);
  114088. ** CREATE INDEX i1 ON t1(a);
  114089. ** CREATE INDEX i2 ON t1(b);
  114090. ** CREATE INDEX i3 ON t1(c);
  114091. **
  114092. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  114093. **
  114094. ** In the example, there are three indexed terms connected by OR.
  114095. ** The top of the loop looks like this:
  114096. **
  114097. ** Null 1 # Zero the rowset in reg 1
  114098. **
  114099. ** Then, for each indexed term, the following. The arguments to
  114100. ** RowSetTest are such that the rowid of the current row is inserted
  114101. ** into the RowSet. If it is already present, control skips the
  114102. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  114103. **
  114104. ** sqlite3WhereBegin(<term>)
  114105. ** RowSetTest # Insert rowid into rowset
  114106. ** Gosub 2 A
  114107. ** sqlite3WhereEnd()
  114108. **
  114109. ** Following the above, code to terminate the loop. Label A, the target
  114110. ** of the Gosub above, jumps to the instruction right after the Goto.
  114111. **
  114112. ** Null 1 # Zero the rowset in reg 1
  114113. ** Goto B # The loop is finished.
  114114. **
  114115. ** A: <loop body> # Return data, whatever.
  114116. **
  114117. ** Return 2 # Jump back to the Gosub
  114118. **
  114119. ** B: <after the loop>
  114120. **
  114121. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  114122. ** use an ephemeral index instead of a RowSet to record the primary
  114123. ** keys of the rows we have already seen.
  114124. **
  114125. */
  114126. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  114127. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  114128. Index *pCov = 0; /* Potential covering index (or NULL) */
  114129. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  114130. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  114131. int regRowset = 0; /* Register for RowSet object */
  114132. int regRowid = 0; /* Register holding rowid */
  114133. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  114134. int iRetInit; /* Address of regReturn init */
  114135. int untestedTerms = 0; /* Some terms not completely tested */
  114136. int ii; /* Loop counter */
  114137. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  114138. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  114139. Table *pTab = pTabItem->pTab;
  114140. pTerm = pLoop->aLTerm[0];
  114141. assert( pTerm!=0 );
  114142. assert( pTerm->eOperator & WO_OR );
  114143. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  114144. pOrWc = &pTerm->u.pOrInfo->wc;
  114145. pLevel->op = OP_Return;
  114146. pLevel->p1 = regReturn;
  114147. /* Set up a new SrcList in pOrTab containing the table being scanned
  114148. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  114149. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  114150. */
  114151. if( pWInfo->nLevel>1 ){
  114152. int nNotReady; /* The number of notReady tables */
  114153. struct SrcList_item *origSrc; /* Original list of tables */
  114154. nNotReady = pWInfo->nLevel - iLevel - 1;
  114155. pOrTab = sqlite3StackAllocRaw(db,
  114156. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  114157. if( pOrTab==0 ) return notReady;
  114158. pOrTab->nAlloc = (u8)(nNotReady + 1);
  114159. pOrTab->nSrc = pOrTab->nAlloc;
  114160. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  114161. origSrc = pWInfo->pTabList->a;
  114162. for(k=1; k<=nNotReady; k++){
  114163. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  114164. }
  114165. }else{
  114166. pOrTab = pWInfo->pTabList;
  114167. }
  114168. /* Initialize the rowset register to contain NULL. An SQL NULL is
  114169. ** equivalent to an empty rowset. Or, create an ephemeral index
  114170. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  114171. **
  114172. ** Also initialize regReturn to contain the address of the instruction
  114173. ** immediately following the OP_Return at the bottom of the loop. This
  114174. ** is required in a few obscure LEFT JOIN cases where control jumps
  114175. ** over the top of the loop into the body of it. In this case the
  114176. ** correct response for the end-of-loop code (the OP_Return) is to
  114177. ** fall through to the next instruction, just as an OP_Next does if
  114178. ** called on an uninitialized cursor.
  114179. */
  114180. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  114181. if( HasRowid(pTab) ){
  114182. regRowset = ++pParse->nMem;
  114183. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  114184. }else{
  114185. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  114186. regRowset = pParse->nTab++;
  114187. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  114188. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  114189. }
  114190. regRowid = ++pParse->nMem;
  114191. }
  114192. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  114193. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  114194. ** Then for every term xN, evaluate as the subexpression: xN AND z
  114195. ** That way, terms in y that are factored into the disjunction will
  114196. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  114197. **
  114198. ** Actually, each subexpression is converted to "xN AND w" where w is
  114199. ** the "interesting" terms of z - terms that did not originate in the
  114200. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  114201. ** indices.
  114202. **
  114203. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  114204. ** is not contained in the ON clause of a LEFT JOIN.
  114205. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  114206. */
  114207. if( pWC->nTerm>1 ){
  114208. int iTerm;
  114209. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  114210. Expr *pExpr = pWC->a[iTerm].pExpr;
  114211. if( &pWC->a[iTerm] == pTerm ) continue;
  114212. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  114213. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  114214. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  114215. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  114216. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  114217. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  114218. pExpr = sqlite3ExprDup(db, pExpr, 0);
  114219. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  114220. }
  114221. if( pAndExpr ){
  114222. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
  114223. }
  114224. }
  114225. /* Run a separate WHERE clause for each term of the OR clause. After
  114226. ** eliminating duplicates from other WHERE clauses, the action for each
  114227. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  114228. */
  114229. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  114230. | WHERE_FORCE_TABLE
  114231. | WHERE_ONETABLE_ONLY
  114232. | WHERE_NO_AUTOINDEX;
  114233. for(ii=0; ii<pOrWc->nTerm; ii++){
  114234. WhereTerm *pOrTerm = &pOrWc->a[ii];
  114235. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  114236. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  114237. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  114238. int jmp1 = 0; /* Address of jump operation */
  114239. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  114240. pAndExpr->pLeft = pOrExpr;
  114241. pOrExpr = pAndExpr;
  114242. }
  114243. /* Loop through table entries that match term pOrTerm. */
  114244. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  114245. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  114246. wctrlFlags, iCovCur);
  114247. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  114248. if( pSubWInfo ){
  114249. WhereLoop *pSubLoop;
  114250. int addrExplain = sqlite3WhereExplainOneScan(
  114251. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  114252. );
  114253. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  114254. /* This is the sub-WHERE clause body. First skip over
  114255. ** duplicate rows from prior sub-WHERE clauses, and record the
  114256. ** rowid (or PRIMARY KEY) for the current row so that the same
  114257. ** row will be skipped in subsequent sub-WHERE clauses.
  114258. */
  114259. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  114260. int r;
  114261. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  114262. if( HasRowid(pTab) ){
  114263. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  114264. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  114265. r,iSet);
  114266. VdbeCoverage(v);
  114267. }else{
  114268. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  114269. int nPk = pPk->nKeyCol;
  114270. int iPk;
  114271. /* Read the PK into an array of temp registers. */
  114272. r = sqlite3GetTempRange(pParse, nPk);
  114273. for(iPk=0; iPk<nPk; iPk++){
  114274. int iCol = pPk->aiColumn[iPk];
  114275. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  114276. }
  114277. /* Check if the temp table already contains this key. If so,
  114278. ** the row has already been included in the result set and
  114279. ** can be ignored (by jumping past the Gosub below). Otherwise,
  114280. ** insert the key into the temp table and proceed with processing
  114281. ** the row.
  114282. **
  114283. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  114284. ** is zero, assume that the key cannot already be present in
  114285. ** the temp table. And if iSet is -1, assume that there is no
  114286. ** need to insert the key into the temp table, as it will never
  114287. ** be tested for. */
  114288. if( iSet ){
  114289. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  114290. VdbeCoverage(v);
  114291. }
  114292. if( iSet>=0 ){
  114293. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  114294. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  114295. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  114296. }
  114297. /* Release the array of temp registers */
  114298. sqlite3ReleaseTempRange(pParse, r, nPk);
  114299. }
  114300. }
  114301. /* Invoke the main loop body as a subroutine */
  114302. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  114303. /* Jump here (skipping the main loop body subroutine) if the
  114304. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  114305. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  114306. /* The pSubWInfo->untestedTerms flag means that this OR term
  114307. ** contained one or more AND term from a notReady table. The
  114308. ** terms from the notReady table could not be tested and will
  114309. ** need to be tested later.
  114310. */
  114311. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  114312. /* If all of the OR-connected terms are optimized using the same
  114313. ** index, and the index is opened using the same cursor number
  114314. ** by each call to sqlite3WhereBegin() made by this loop, it may
  114315. ** be possible to use that index as a covering index.
  114316. **
  114317. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  114318. ** uses an index, and this is either the first OR-connected term
  114319. ** processed or the index is the same as that used by all previous
  114320. ** terms, set pCov to the candidate covering index. Otherwise, set
  114321. ** pCov to NULL to indicate that no candidate covering index will
  114322. ** be available.
  114323. */
  114324. pSubLoop = pSubWInfo->a[0].pWLoop;
  114325. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  114326. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  114327. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  114328. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  114329. ){
  114330. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  114331. pCov = pSubLoop->u.btree.pIndex;
  114332. wctrlFlags |= WHERE_REOPEN_IDX;
  114333. }else{
  114334. pCov = 0;
  114335. }
  114336. /* Finish the loop through table entries that match term pOrTerm. */
  114337. sqlite3WhereEnd(pSubWInfo);
  114338. }
  114339. }
  114340. }
  114341. pLevel->u.pCovidx = pCov;
  114342. if( pCov ) pLevel->iIdxCur = iCovCur;
  114343. if( pAndExpr ){
  114344. pAndExpr->pLeft = 0;
  114345. sqlite3ExprDelete(db, pAndExpr);
  114346. }
  114347. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  114348. sqlite3VdbeGoto(v, pLevel->addrBrk);
  114349. sqlite3VdbeResolveLabel(v, iLoopBody);
  114350. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  114351. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  114352. }else
  114353. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  114354. {
  114355. /* Case 6: There is no usable index. We must do a complete
  114356. ** scan of the entire table.
  114357. */
  114358. static const u8 aStep[] = { OP_Next, OP_Prev };
  114359. static const u8 aStart[] = { OP_Rewind, OP_Last };
  114360. assert( bRev==0 || bRev==1 );
  114361. if( pTabItem->fg.isRecursive ){
  114362. /* Tables marked isRecursive have only a single row that is stored in
  114363. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  114364. pLevel->op = OP_Noop;
  114365. }else{
  114366. codeCursorHint(pWInfo, pLevel, 0);
  114367. pLevel->op = aStep[bRev];
  114368. pLevel->p1 = iCur;
  114369. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  114370. VdbeCoverageIf(v, bRev==0);
  114371. VdbeCoverageIf(v, bRev!=0);
  114372. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  114373. }
  114374. }
  114375. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  114376. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  114377. #endif
  114378. /* Insert code to test every subexpression that can be completely
  114379. ** computed using the current set of tables.
  114380. */
  114381. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  114382. Expr *pE;
  114383. int skipLikeAddr = 0;
  114384. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  114385. testcase( pTerm->wtFlags & TERM_CODED );
  114386. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  114387. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  114388. testcase( pWInfo->untestedTerms==0
  114389. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  114390. pWInfo->untestedTerms = 1;
  114391. continue;
  114392. }
  114393. pE = pTerm->pExpr;
  114394. assert( pE!=0 );
  114395. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  114396. continue;
  114397. }
  114398. if( pTerm->wtFlags & TERM_LIKECOND ){
  114399. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  114400. continue;
  114401. #else
  114402. assert( pLevel->iLikeRepCntr>0 );
  114403. skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
  114404. VdbeCoverage(v);
  114405. #endif
  114406. }
  114407. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  114408. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  114409. pTerm->wtFlags |= TERM_CODED;
  114410. }
  114411. /* Insert code to test for implied constraints based on transitivity
  114412. ** of the "==" operator.
  114413. **
  114414. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  114415. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  114416. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  114417. ** the implied "t1.a=123" constraint.
  114418. */
  114419. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  114420. Expr *pE, *pEAlt;
  114421. WhereTerm *pAlt;
  114422. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  114423. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  114424. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  114425. if( pTerm->leftCursor!=iCur ) continue;
  114426. if( pLevel->iLeftJoin ) continue;
  114427. pE = pTerm->pExpr;
  114428. assert( !ExprHasProperty(pE, EP_FromJoin) );
  114429. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  114430. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  114431. WO_EQ|WO_IN|WO_IS, 0);
  114432. if( pAlt==0 ) continue;
  114433. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  114434. testcase( pAlt->eOperator & WO_EQ );
  114435. testcase( pAlt->eOperator & WO_IS );
  114436. testcase( pAlt->eOperator & WO_IN );
  114437. VdbeModuleComment((v, "begin transitive constraint"));
  114438. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  114439. if( pEAlt ){
  114440. *pEAlt = *pAlt->pExpr;
  114441. pEAlt->pLeft = pE->pLeft;
  114442. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  114443. sqlite3StackFree(db, pEAlt);
  114444. }
  114445. }
  114446. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  114447. ** at least one row of the right table has matched the left table.
  114448. */
  114449. if( pLevel->iLeftJoin ){
  114450. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  114451. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  114452. VdbeComment((v, "record LEFT JOIN hit"));
  114453. sqlite3ExprCacheClear(pParse);
  114454. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  114455. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  114456. testcase( pTerm->wtFlags & TERM_CODED );
  114457. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  114458. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  114459. assert( pWInfo->untestedTerms );
  114460. continue;
  114461. }
  114462. assert( pTerm->pExpr );
  114463. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  114464. pTerm->wtFlags |= TERM_CODED;
  114465. }
  114466. }
  114467. return pLevel->notReady;
  114468. }
  114469. /************** End of wherecode.c *******************************************/
  114470. /************** Begin file whereexpr.c ***************************************/
  114471. /*
  114472. ** 2015-06-08
  114473. **
  114474. ** The author disclaims copyright to this source code. In place of
  114475. ** a legal notice, here is a blessing:
  114476. **
  114477. ** May you do good and not evil.
  114478. ** May you find forgiveness for yourself and forgive others.
  114479. ** May you share freely, never taking more than you give.
  114480. **
  114481. *************************************************************************
  114482. ** This module contains C code that generates VDBE code used to process
  114483. ** the WHERE clause of SQL statements.
  114484. **
  114485. ** This file was originally part of where.c but was split out to improve
  114486. ** readability and editabiliity. This file contains utility routines for
  114487. ** analyzing Expr objects in the WHERE clause.
  114488. */
  114489. /* #include "sqliteInt.h" */
  114490. /* #include "whereInt.h" */
  114491. /* Forward declarations */
  114492. static void exprAnalyze(SrcList*, WhereClause*, int);
  114493. /*
  114494. ** Deallocate all memory associated with a WhereOrInfo object.
  114495. */
  114496. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  114497. sqlite3WhereClauseClear(&p->wc);
  114498. sqlite3DbFree(db, p);
  114499. }
  114500. /*
  114501. ** Deallocate all memory associated with a WhereAndInfo object.
  114502. */
  114503. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  114504. sqlite3WhereClauseClear(&p->wc);
  114505. sqlite3DbFree(db, p);
  114506. }
  114507. /*
  114508. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  114509. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  114510. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  114511. ** 0 is returned if the new WhereTerm could not be added due to a memory
  114512. ** allocation error. The memory allocation failure will be recorded in
  114513. ** the db->mallocFailed flag so that higher-level functions can detect it.
  114514. **
  114515. ** This routine will increase the size of the pWC->a[] array as necessary.
  114516. **
  114517. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  114518. ** for freeing the expression p is assumed by the WhereClause object pWC.
  114519. ** This is true even if this routine fails to allocate a new WhereTerm.
  114520. **
  114521. ** WARNING: This routine might reallocate the space used to store
  114522. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  114523. ** calling this routine. Such pointers may be reinitialized by referencing
  114524. ** the pWC->a[] array.
  114525. */
  114526. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  114527. WhereTerm *pTerm;
  114528. int idx;
  114529. testcase( wtFlags & TERM_VIRTUAL );
  114530. if( pWC->nTerm>=pWC->nSlot ){
  114531. WhereTerm *pOld = pWC->a;
  114532. sqlite3 *db = pWC->pWInfo->pParse->db;
  114533. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  114534. if( pWC->a==0 ){
  114535. if( wtFlags & TERM_DYNAMIC ){
  114536. sqlite3ExprDelete(db, p);
  114537. }
  114538. pWC->a = pOld;
  114539. return 0;
  114540. }
  114541. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  114542. if( pOld!=pWC->aStatic ){
  114543. sqlite3DbFree(db, pOld);
  114544. }
  114545. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  114546. memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
  114547. }
  114548. pTerm = &pWC->a[idx = pWC->nTerm++];
  114549. if( p && ExprHasProperty(p, EP_Unlikely) ){
  114550. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  114551. }else{
  114552. pTerm->truthProb = 1;
  114553. }
  114554. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  114555. pTerm->wtFlags = wtFlags;
  114556. pTerm->pWC = pWC;
  114557. pTerm->iParent = -1;
  114558. return idx;
  114559. }
  114560. /*
  114561. ** Return TRUE if the given operator is one of the operators that is
  114562. ** allowed for an indexable WHERE clause term. The allowed operators are
  114563. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  114564. */
  114565. static int allowedOp(int op){
  114566. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  114567. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  114568. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  114569. assert( TK_GE==TK_EQ+4 );
  114570. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  114571. }
  114572. /*
  114573. ** Commute a comparison operator. Expressions of the form "X op Y"
  114574. ** are converted into "Y op X".
  114575. **
  114576. ** If left/right precedence rules come into play when determining the
  114577. ** collating sequence, then COLLATE operators are adjusted to ensure
  114578. ** that the collating sequence does not change. For example:
  114579. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  114580. ** the left hand side of a comparison overrides any collation sequence
  114581. ** attached to the right. For the same reason the EP_Collate flag
  114582. ** is not commuted.
  114583. */
  114584. static void exprCommute(Parse *pParse, Expr *pExpr){
  114585. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  114586. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  114587. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  114588. if( expRight==expLeft ){
  114589. /* Either X and Y both have COLLATE operator or neither do */
  114590. if( expRight ){
  114591. /* Both X and Y have COLLATE operators. Make sure X is always
  114592. ** used by clearing the EP_Collate flag from Y. */
  114593. pExpr->pRight->flags &= ~EP_Collate;
  114594. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  114595. /* Neither X nor Y have COLLATE operators, but X has a non-default
  114596. ** collating sequence. So add the EP_Collate marker on X to cause
  114597. ** it to be searched first. */
  114598. pExpr->pLeft->flags |= EP_Collate;
  114599. }
  114600. }
  114601. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  114602. if( pExpr->op>=TK_GT ){
  114603. assert( TK_LT==TK_GT+2 );
  114604. assert( TK_GE==TK_LE+2 );
  114605. assert( TK_GT>TK_EQ );
  114606. assert( TK_GT<TK_LE );
  114607. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  114608. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  114609. }
  114610. }
  114611. /*
  114612. ** Translate from TK_xx operator to WO_xx bitmask.
  114613. */
  114614. static u16 operatorMask(int op){
  114615. u16 c;
  114616. assert( allowedOp(op) );
  114617. if( op==TK_IN ){
  114618. c = WO_IN;
  114619. }else if( op==TK_ISNULL ){
  114620. c = WO_ISNULL;
  114621. }else if( op==TK_IS ){
  114622. c = WO_IS;
  114623. }else{
  114624. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  114625. c = (u16)(WO_EQ<<(op-TK_EQ));
  114626. }
  114627. assert( op!=TK_ISNULL || c==WO_ISNULL );
  114628. assert( op!=TK_IN || c==WO_IN );
  114629. assert( op!=TK_EQ || c==WO_EQ );
  114630. assert( op!=TK_LT || c==WO_LT );
  114631. assert( op!=TK_LE || c==WO_LE );
  114632. assert( op!=TK_GT || c==WO_GT );
  114633. assert( op!=TK_GE || c==WO_GE );
  114634. assert( op!=TK_IS || c==WO_IS );
  114635. return c;
  114636. }
  114637. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  114638. /*
  114639. ** Check to see if the given expression is a LIKE or GLOB operator that
  114640. ** can be optimized using inequality constraints. Return TRUE if it is
  114641. ** so and false if not.
  114642. **
  114643. ** In order for the operator to be optimizible, the RHS must be a string
  114644. ** literal that does not begin with a wildcard. The LHS must be a column
  114645. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  114646. ** that virtual tables cannot participate in the LIKE optimization.) The
  114647. ** collating sequence for the column on the LHS must be appropriate for
  114648. ** the operator.
  114649. */
  114650. static int isLikeOrGlob(
  114651. Parse *pParse, /* Parsing and code generating context */
  114652. Expr *pExpr, /* Test this expression */
  114653. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  114654. int *pisComplete, /* True if the only wildcard is % in the last character */
  114655. int *pnoCase /* True if uppercase is equivalent to lowercase */
  114656. ){
  114657. const char *z = 0; /* String on RHS of LIKE operator */
  114658. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  114659. ExprList *pList; /* List of operands to the LIKE operator */
  114660. int c; /* One character in z[] */
  114661. int cnt; /* Number of non-wildcard prefix characters */
  114662. char wc[3]; /* Wildcard characters */
  114663. sqlite3 *db = pParse->db; /* Database connection */
  114664. sqlite3_value *pVal = 0;
  114665. int op; /* Opcode of pRight */
  114666. int rc; /* Result code to return */
  114667. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  114668. return 0;
  114669. }
  114670. #ifdef SQLITE_EBCDIC
  114671. if( *pnoCase ) return 0;
  114672. #endif
  114673. pList = pExpr->x.pList;
  114674. pLeft = pList->a[1].pExpr;
  114675. if( pLeft->op!=TK_COLUMN
  114676. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  114677. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  114678. ){
  114679. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  114680. ** be the name of an indexed column with TEXT affinity. */
  114681. return 0;
  114682. }
  114683. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  114684. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  114685. op = pRight->op;
  114686. if( op==TK_VARIABLE ){
  114687. Vdbe *pReprepare = pParse->pReprepare;
  114688. int iCol = pRight->iColumn;
  114689. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  114690. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  114691. z = (char *)sqlite3_value_text(pVal);
  114692. }
  114693. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  114694. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  114695. }else if( op==TK_STRING ){
  114696. z = pRight->u.zToken;
  114697. }
  114698. if( z ){
  114699. cnt = 0;
  114700. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  114701. cnt++;
  114702. }
  114703. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  114704. Expr *pPrefix;
  114705. *pisComplete = c==wc[0] && z[cnt+1]==0;
  114706. pPrefix = sqlite3Expr(db, TK_STRING, z);
  114707. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  114708. *ppPrefix = pPrefix;
  114709. if( op==TK_VARIABLE ){
  114710. Vdbe *v = pParse->pVdbe;
  114711. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  114712. if( *pisComplete && pRight->u.zToken[1] ){
  114713. /* If the rhs of the LIKE expression is a variable, and the current
  114714. ** value of the variable means there is no need to invoke the LIKE
  114715. ** function, then no OP_Variable will be added to the program.
  114716. ** This causes problems for the sqlite3_bind_parameter_name()
  114717. ** API. To work around them, add a dummy OP_Variable here.
  114718. */
  114719. int r1 = sqlite3GetTempReg(pParse);
  114720. sqlite3ExprCodeTarget(pParse, pRight, r1);
  114721. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  114722. sqlite3ReleaseTempReg(pParse, r1);
  114723. }
  114724. }
  114725. }else{
  114726. z = 0;
  114727. }
  114728. }
  114729. rc = (z!=0);
  114730. sqlite3ValueFree(pVal);
  114731. return rc;
  114732. }
  114733. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  114734. #ifndef SQLITE_OMIT_VIRTUALTABLE
  114735. /*
  114736. ** Check to see if the given expression is of the form
  114737. **
  114738. ** column OP expr
  114739. **
  114740. ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
  114741. ** column of a virtual table.
  114742. **
  114743. ** If it is then return TRUE. If not, return FALSE.
  114744. */
  114745. static int isMatchOfColumn(
  114746. Expr *pExpr, /* Test this expression */
  114747. unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
  114748. ){
  114749. struct Op2 {
  114750. const char *zOp;
  114751. unsigned char eOp2;
  114752. } aOp[] = {
  114753. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  114754. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  114755. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  114756. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  114757. };
  114758. ExprList *pList;
  114759. Expr *pCol; /* Column reference */
  114760. int i;
  114761. if( pExpr->op!=TK_FUNCTION ){
  114762. return 0;
  114763. }
  114764. pList = pExpr->x.pList;
  114765. if( pList==0 || pList->nExpr!=2 ){
  114766. return 0;
  114767. }
  114768. pCol = pList->a[1].pExpr;
  114769. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  114770. return 0;
  114771. }
  114772. for(i=0; i<ArraySize(aOp); i++){
  114773. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  114774. *peOp2 = aOp[i].eOp2;
  114775. return 1;
  114776. }
  114777. }
  114778. return 0;
  114779. }
  114780. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  114781. /*
  114782. ** If the pBase expression originated in the ON or USING clause of
  114783. ** a join, then transfer the appropriate markings over to derived.
  114784. */
  114785. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  114786. if( pDerived ){
  114787. pDerived->flags |= pBase->flags & EP_FromJoin;
  114788. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  114789. }
  114790. }
  114791. /*
  114792. ** Mark term iChild as being a child of term iParent
  114793. */
  114794. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  114795. pWC->a[iChild].iParent = iParent;
  114796. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  114797. pWC->a[iParent].nChild++;
  114798. }
  114799. /*
  114800. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  114801. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  114802. ** the number of available subterms, return NULL.
  114803. */
  114804. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  114805. if( pTerm->eOperator!=WO_AND ){
  114806. return N==0 ? pTerm : 0;
  114807. }
  114808. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  114809. return &pTerm->u.pAndInfo->wc.a[N];
  114810. }
  114811. return 0;
  114812. }
  114813. /*
  114814. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  114815. ** two subterms are in disjunction - they are OR-ed together.
  114816. **
  114817. ** If these two terms are both of the form: "A op B" with the same
  114818. ** A and B values but different operators and if the operators are
  114819. ** compatible (if one is = and the other is <, for example) then
  114820. ** add a new virtual AND term to pWC that is the combination of the
  114821. ** two.
  114822. **
  114823. ** Some examples:
  114824. **
  114825. ** x<y OR x=y --> x<=y
  114826. ** x=y OR x=y --> x=y
  114827. ** x<=y OR x<y --> x<=y
  114828. **
  114829. ** The following is NOT generated:
  114830. **
  114831. ** x<y OR x>y --> x!=y
  114832. */
  114833. static void whereCombineDisjuncts(
  114834. SrcList *pSrc, /* the FROM clause */
  114835. WhereClause *pWC, /* The complete WHERE clause */
  114836. WhereTerm *pOne, /* First disjunct */
  114837. WhereTerm *pTwo /* Second disjunct */
  114838. ){
  114839. u16 eOp = pOne->eOperator | pTwo->eOperator;
  114840. sqlite3 *db; /* Database connection (for malloc) */
  114841. Expr *pNew; /* New virtual expression */
  114842. int op; /* Operator for the combined expression */
  114843. int idxNew; /* Index in pWC of the next virtual term */
  114844. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  114845. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  114846. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  114847. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  114848. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  114849. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  114850. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  114851. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  114852. /* If we reach this point, it means the two subterms can be combined */
  114853. if( (eOp & (eOp-1))!=0 ){
  114854. if( eOp & (WO_LT|WO_LE) ){
  114855. eOp = WO_LE;
  114856. }else{
  114857. assert( eOp & (WO_GT|WO_GE) );
  114858. eOp = WO_GE;
  114859. }
  114860. }
  114861. db = pWC->pWInfo->pParse->db;
  114862. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  114863. if( pNew==0 ) return;
  114864. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  114865. pNew->op = op;
  114866. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  114867. exprAnalyze(pSrc, pWC, idxNew);
  114868. }
  114869. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  114870. /*
  114871. ** Analyze a term that consists of two or more OR-connected
  114872. ** subterms. So in:
  114873. **
  114874. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  114875. ** ^^^^^^^^^^^^^^^^^^^^
  114876. **
  114877. ** This routine analyzes terms such as the middle term in the above example.
  114878. ** A WhereOrTerm object is computed and attached to the term under
  114879. ** analysis, regardless of the outcome of the analysis. Hence:
  114880. **
  114881. ** WhereTerm.wtFlags |= TERM_ORINFO
  114882. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  114883. **
  114884. ** The term being analyzed must have two or more of OR-connected subterms.
  114885. ** A single subterm might be a set of AND-connected sub-subterms.
  114886. ** Examples of terms under analysis:
  114887. **
  114888. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  114889. ** (B) x=expr1 OR expr2=x OR x=expr3
  114890. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  114891. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  114892. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  114893. ** (F) x>A OR (x=A AND y>=B)
  114894. **
  114895. ** CASE 1:
  114896. **
  114897. ** If all subterms are of the form T.C=expr for some single column of C and
  114898. ** a single table T (as shown in example B above) then create a new virtual
  114899. ** term that is an equivalent IN expression. In other words, if the term
  114900. ** being analyzed is:
  114901. **
  114902. ** x = expr1 OR expr2 = x OR x = expr3
  114903. **
  114904. ** then create a new virtual term like this:
  114905. **
  114906. ** x IN (expr1,expr2,expr3)
  114907. **
  114908. ** CASE 2:
  114909. **
  114910. ** If there are exactly two disjuncts and one side has x>A and the other side
  114911. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  114912. ** WHERE clause of the form "x>=A". Example:
  114913. **
  114914. ** x>A OR (x=A AND y>B) adds: x>=A
  114915. **
  114916. ** The added conjunct can sometimes be helpful in query planning.
  114917. **
  114918. ** CASE 3:
  114919. **
  114920. ** If all subterms are indexable by a single table T, then set
  114921. **
  114922. ** WhereTerm.eOperator = WO_OR
  114923. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  114924. **
  114925. ** A subterm is "indexable" if it is of the form
  114926. ** "T.C <op> <expr>" where C is any column of table T and
  114927. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  114928. ** A subterm is also indexable if it is an AND of two or more
  114929. ** subsubterms at least one of which is indexable. Indexable AND
  114930. ** subterms have their eOperator set to WO_AND and they have
  114931. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  114932. **
  114933. ** From another point of view, "indexable" means that the subterm could
  114934. ** potentially be used with an index if an appropriate index exists.
  114935. ** This analysis does not consider whether or not the index exists; that
  114936. ** is decided elsewhere. This analysis only looks at whether subterms
  114937. ** appropriate for indexing exist.
  114938. **
  114939. ** All examples A through E above satisfy case 3. But if a term
  114940. ** also satisfies case 1 (such as B) we know that the optimizer will
  114941. ** always prefer case 1, so in that case we pretend that case 3 is not
  114942. ** satisfied.
  114943. **
  114944. ** It might be the case that multiple tables are indexable. For example,
  114945. ** (E) above is indexable on tables P, Q, and R.
  114946. **
  114947. ** Terms that satisfy case 3 are candidates for lookup by using
  114948. ** separate indices to find rowids for each subterm and composing
  114949. ** the union of all rowids using a RowSet object. This is similar
  114950. ** to "bitmap indices" in other database engines.
  114951. **
  114952. ** OTHERWISE:
  114953. **
  114954. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  114955. ** zero. This term is not useful for search.
  114956. */
  114957. static void exprAnalyzeOrTerm(
  114958. SrcList *pSrc, /* the FROM clause */
  114959. WhereClause *pWC, /* the complete WHERE clause */
  114960. int idxTerm /* Index of the OR-term to be analyzed */
  114961. ){
  114962. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  114963. Parse *pParse = pWInfo->pParse; /* Parser context */
  114964. sqlite3 *db = pParse->db; /* Database connection */
  114965. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  114966. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  114967. int i; /* Loop counters */
  114968. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  114969. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  114970. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  114971. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  114972. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  114973. /*
  114974. ** Break the OR clause into its separate subterms. The subterms are
  114975. ** stored in a WhereClause structure containing within the WhereOrInfo
  114976. ** object that is attached to the original OR clause term.
  114977. */
  114978. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  114979. assert( pExpr->op==TK_OR );
  114980. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  114981. if( pOrInfo==0 ) return;
  114982. pTerm->wtFlags |= TERM_ORINFO;
  114983. pOrWc = &pOrInfo->wc;
  114984. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  114985. sqlite3WhereClauseInit(pOrWc, pWInfo);
  114986. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  114987. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  114988. if( db->mallocFailed ) return;
  114989. assert( pOrWc->nTerm>=2 );
  114990. /*
  114991. ** Compute the set of tables that might satisfy cases 1 or 3.
  114992. */
  114993. indexable = ~(Bitmask)0;
  114994. chngToIN = ~(Bitmask)0;
  114995. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  114996. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  114997. WhereAndInfo *pAndInfo;
  114998. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  114999. chngToIN = 0;
  115000. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  115001. if( pAndInfo ){
  115002. WhereClause *pAndWC;
  115003. WhereTerm *pAndTerm;
  115004. int j;
  115005. Bitmask b = 0;
  115006. pOrTerm->u.pAndInfo = pAndInfo;
  115007. pOrTerm->wtFlags |= TERM_ANDINFO;
  115008. pOrTerm->eOperator = WO_AND;
  115009. pAndWC = &pAndInfo->wc;
  115010. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  115011. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  115012. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  115013. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  115014. pAndWC->pOuter = pWC;
  115015. if( !db->mallocFailed ){
  115016. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  115017. assert( pAndTerm->pExpr );
  115018. if( allowedOp(pAndTerm->pExpr->op) ){
  115019. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  115020. }
  115021. }
  115022. }
  115023. indexable &= b;
  115024. }
  115025. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  115026. /* Skip this term for now. We revisit it when we process the
  115027. ** corresponding TERM_VIRTUAL term */
  115028. }else{
  115029. Bitmask b;
  115030. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  115031. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  115032. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  115033. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  115034. }
  115035. indexable &= b;
  115036. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  115037. chngToIN = 0;
  115038. }else{
  115039. chngToIN &= b;
  115040. }
  115041. }
  115042. }
  115043. /*
  115044. ** Record the set of tables that satisfy case 3. The set might be
  115045. ** empty.
  115046. */
  115047. pOrInfo->indexable = indexable;
  115048. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  115049. /* For a two-way OR, attempt to implementation case 2.
  115050. */
  115051. if( indexable && pOrWc->nTerm==2 ){
  115052. int iOne = 0;
  115053. WhereTerm *pOne;
  115054. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  115055. int iTwo = 0;
  115056. WhereTerm *pTwo;
  115057. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  115058. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  115059. }
  115060. }
  115061. }
  115062. /*
  115063. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  115064. ** we have to do some additional checking to see if case 1 really
  115065. ** is satisfied.
  115066. **
  115067. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  115068. ** that there is no possibility of transforming the OR clause into an
  115069. ** IN operator because one or more terms in the OR clause contain
  115070. ** something other than == on a column in the single table. The 1-bit
  115071. ** case means that every term of the OR clause is of the form
  115072. ** "table.column=expr" for some single table. The one bit that is set
  115073. ** will correspond to the common table. We still need to check to make
  115074. ** sure the same column is used on all terms. The 2-bit case is when
  115075. ** the all terms are of the form "table1.column=table2.column". It
  115076. ** might be possible to form an IN operator with either table1.column
  115077. ** or table2.column as the LHS if either is common to every term of
  115078. ** the OR clause.
  115079. **
  115080. ** Note that terms of the form "table.column1=table.column2" (the
  115081. ** same table on both sizes of the ==) cannot be optimized.
  115082. */
  115083. if( chngToIN ){
  115084. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  115085. int iColumn = -1; /* Column index on lhs of IN operator */
  115086. int iCursor = -1; /* Table cursor common to all terms */
  115087. int j = 0; /* Loop counter */
  115088. /* Search for a table and column that appears on one side or the
  115089. ** other of the == operator in every subterm. That table and column
  115090. ** will be recorded in iCursor and iColumn. There might not be any
  115091. ** such table and column. Set okToChngToIN if an appropriate table
  115092. ** and column is found but leave okToChngToIN false if not found.
  115093. */
  115094. for(j=0; j<2 && !okToChngToIN; j++){
  115095. pOrTerm = pOrWc->a;
  115096. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  115097. assert( pOrTerm->eOperator & WO_EQ );
  115098. pOrTerm->wtFlags &= ~TERM_OR_OK;
  115099. if( pOrTerm->leftCursor==iCursor ){
  115100. /* This is the 2-bit case and we are on the second iteration and
  115101. ** current term is from the first iteration. So skip this term. */
  115102. assert( j==1 );
  115103. continue;
  115104. }
  115105. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  115106. pOrTerm->leftCursor))==0 ){
  115107. /* This term must be of the form t1.a==t2.b where t2 is in the
  115108. ** chngToIN set but t1 is not. This term will be either preceded
  115109. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  115110. ** and use its inversion. */
  115111. testcase( pOrTerm->wtFlags & TERM_COPIED );
  115112. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  115113. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  115114. continue;
  115115. }
  115116. iColumn = pOrTerm->u.leftColumn;
  115117. iCursor = pOrTerm->leftCursor;
  115118. break;
  115119. }
  115120. if( i<0 ){
  115121. /* No candidate table+column was found. This can only occur
  115122. ** on the second iteration */
  115123. assert( j==1 );
  115124. assert( IsPowerOfTwo(chngToIN) );
  115125. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  115126. break;
  115127. }
  115128. testcase( j==1 );
  115129. /* We have found a candidate table and column. Check to see if that
  115130. ** table and column is common to every term in the OR clause */
  115131. okToChngToIN = 1;
  115132. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  115133. assert( pOrTerm->eOperator & WO_EQ );
  115134. if( pOrTerm->leftCursor!=iCursor ){
  115135. pOrTerm->wtFlags &= ~TERM_OR_OK;
  115136. }else if( pOrTerm->u.leftColumn!=iColumn ){
  115137. okToChngToIN = 0;
  115138. }else{
  115139. int affLeft, affRight;
  115140. /* If the right-hand side is also a column, then the affinities
  115141. ** of both right and left sides must be such that no type
  115142. ** conversions are required on the right. (Ticket #2249)
  115143. */
  115144. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  115145. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  115146. if( affRight!=0 && affRight!=affLeft ){
  115147. okToChngToIN = 0;
  115148. }else{
  115149. pOrTerm->wtFlags |= TERM_OR_OK;
  115150. }
  115151. }
  115152. }
  115153. }
  115154. /* At this point, okToChngToIN is true if original pTerm satisfies
  115155. ** case 1. In that case, construct a new virtual term that is
  115156. ** pTerm converted into an IN operator.
  115157. */
  115158. if( okToChngToIN ){
  115159. Expr *pDup; /* A transient duplicate expression */
  115160. ExprList *pList = 0; /* The RHS of the IN operator */
  115161. Expr *pLeft = 0; /* The LHS of the IN operator */
  115162. Expr *pNew; /* The complete IN operator */
  115163. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  115164. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  115165. assert( pOrTerm->eOperator & WO_EQ );
  115166. assert( pOrTerm->leftCursor==iCursor );
  115167. assert( pOrTerm->u.leftColumn==iColumn );
  115168. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  115169. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  115170. pLeft = pOrTerm->pExpr->pLeft;
  115171. }
  115172. assert( pLeft!=0 );
  115173. pDup = sqlite3ExprDup(db, pLeft, 0);
  115174. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  115175. if( pNew ){
  115176. int idxNew;
  115177. transferJoinMarkings(pNew, pExpr);
  115178. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  115179. pNew->x.pList = pList;
  115180. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  115181. testcase( idxNew==0 );
  115182. exprAnalyze(pSrc, pWC, idxNew);
  115183. pTerm = &pWC->a[idxTerm];
  115184. markTermAsChild(pWC, idxNew, idxTerm);
  115185. }else{
  115186. sqlite3ExprListDelete(db, pList);
  115187. }
  115188. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  115189. }
  115190. }
  115191. }
  115192. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  115193. /*
  115194. ** We already know that pExpr is a binary operator where both operands are
  115195. ** column references. This routine checks to see if pExpr is an equivalence
  115196. ** relation:
  115197. ** 1. The SQLITE_Transitive optimization must be enabled
  115198. ** 2. Must be either an == or an IS operator
  115199. ** 3. Not originating in the ON clause of an OUTER JOIN
  115200. ** 4. The affinities of A and B must be compatible
  115201. ** 5a. Both operands use the same collating sequence OR
  115202. ** 5b. The overall collating sequence is BINARY
  115203. ** If this routine returns TRUE, that means that the RHS can be substituted
  115204. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  115205. ** This is an optimization. No harm comes from returning 0. But if 1 is
  115206. ** returned when it should not be, then incorrect answers might result.
  115207. */
  115208. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  115209. char aff1, aff2;
  115210. CollSeq *pColl;
  115211. const char *zColl1, *zColl2;
  115212. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  115213. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  115214. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  115215. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  115216. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  115217. if( aff1!=aff2
  115218. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  115219. ){
  115220. return 0;
  115221. }
  115222. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  115223. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  115224. pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  115225. /* Since pLeft and pRight are both a column references, their collating
  115226. ** sequence should always be defined. */
  115227. zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
  115228. pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  115229. zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
  115230. return sqlite3StrICmp(zColl1, zColl2)==0;
  115231. }
  115232. /*
  115233. ** Recursively walk the expressions of a SELECT statement and generate
  115234. ** a bitmask indicating which tables are used in that expression
  115235. ** tree.
  115236. */
  115237. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  115238. Bitmask mask = 0;
  115239. while( pS ){
  115240. SrcList *pSrc = pS->pSrc;
  115241. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  115242. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  115243. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  115244. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  115245. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  115246. if( ALWAYS(pSrc!=0) ){
  115247. int i;
  115248. for(i=0; i<pSrc->nSrc; i++){
  115249. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  115250. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  115251. }
  115252. }
  115253. pS = pS->pPrior;
  115254. }
  115255. return mask;
  115256. }
  115257. /*
  115258. ** Expression pExpr is one operand of a comparison operator that might
  115259. ** be useful for indexing. This routine checks to see if pExpr appears
  115260. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  115261. ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
  115262. ** number of the table that is indexed and *piColumn to the column number
  115263. ** of the column that is indexed, or -2 if an expression is being indexed.
  115264. **
  115265. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  115266. ** true even if that particular column is not indexed, because the column
  115267. ** might be added to an automatic index later.
  115268. */
  115269. static int exprMightBeIndexed(
  115270. SrcList *pFrom, /* The FROM clause */
  115271. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  115272. Expr *pExpr, /* An operand of a comparison operator */
  115273. int *piCur, /* Write the referenced table cursor number here */
  115274. int *piColumn /* Write the referenced table column number here */
  115275. ){
  115276. Index *pIdx;
  115277. int i;
  115278. int iCur;
  115279. if( pExpr->op==TK_COLUMN ){
  115280. *piCur = pExpr->iTable;
  115281. *piColumn = pExpr->iColumn;
  115282. return 1;
  115283. }
  115284. if( mPrereq==0 ) return 0; /* No table references */
  115285. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  115286. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  115287. iCur = pFrom->a[i].iCursor;
  115288. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  115289. if( pIdx->aColExpr==0 ) continue;
  115290. for(i=0; i<pIdx->nKeyCol; i++){
  115291. if( pIdx->aiColumn[i]!=(-2) ) continue;
  115292. if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  115293. *piCur = iCur;
  115294. *piColumn = -2;
  115295. return 1;
  115296. }
  115297. }
  115298. }
  115299. return 0;
  115300. }
  115301. /*
  115302. ** The input to this routine is an WhereTerm structure with only the
  115303. ** "pExpr" field filled in. The job of this routine is to analyze the
  115304. ** subexpression and populate all the other fields of the WhereTerm
  115305. ** structure.
  115306. **
  115307. ** If the expression is of the form "<expr> <op> X" it gets commuted
  115308. ** to the standard form of "X <op> <expr>".
  115309. **
  115310. ** If the expression is of the form "X <op> Y" where both X and Y are
  115311. ** columns, then the original expression is unchanged and a new virtual
  115312. ** term of the form "Y <op> X" is added to the WHERE clause and
  115313. ** analyzed separately. The original term is marked with TERM_COPIED
  115314. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  115315. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  115316. ** is a commuted copy of a prior term.) The original term has nChild=1
  115317. ** and the copy has idxParent set to the index of the original term.
  115318. */
  115319. static void exprAnalyze(
  115320. SrcList *pSrc, /* the FROM clause */
  115321. WhereClause *pWC, /* the WHERE clause */
  115322. int idxTerm /* Index of the term to be analyzed */
  115323. ){
  115324. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  115325. WhereTerm *pTerm; /* The term to be analyzed */
  115326. WhereMaskSet *pMaskSet; /* Set of table index masks */
  115327. Expr *pExpr; /* The expression to be analyzed */
  115328. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  115329. Bitmask prereqAll; /* Prerequesites of pExpr */
  115330. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  115331. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  115332. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  115333. int noCase = 0; /* uppercase equivalent to lowercase */
  115334. int op; /* Top-level operator. pExpr->op */
  115335. Parse *pParse = pWInfo->pParse; /* Parsing context */
  115336. sqlite3 *db = pParse->db; /* Database connection */
  115337. unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
  115338. if( db->mallocFailed ){
  115339. return;
  115340. }
  115341. pTerm = &pWC->a[idxTerm];
  115342. pMaskSet = &pWInfo->sMaskSet;
  115343. pExpr = pTerm->pExpr;
  115344. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  115345. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  115346. op = pExpr->op;
  115347. if( op==TK_IN ){
  115348. assert( pExpr->pRight==0 );
  115349. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  115350. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  115351. }else{
  115352. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  115353. }
  115354. }else if( op==TK_ISNULL ){
  115355. pTerm->prereqRight = 0;
  115356. }else{
  115357. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  115358. }
  115359. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  115360. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  115361. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  115362. prereqAll |= x;
  115363. extraRight = x-1; /* ON clause terms may not be used with an index
  115364. ** on left table of a LEFT JOIN. Ticket #3015 */
  115365. }
  115366. pTerm->prereqAll = prereqAll;
  115367. pTerm->leftCursor = -1;
  115368. pTerm->iParent = -1;
  115369. pTerm->eOperator = 0;
  115370. if( allowedOp(op) ){
  115371. int iCur, iColumn;
  115372. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  115373. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  115374. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  115375. if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
  115376. pTerm->leftCursor = iCur;
  115377. pTerm->u.leftColumn = iColumn;
  115378. pTerm->eOperator = operatorMask(op) & opMask;
  115379. }
  115380. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  115381. if( pRight
  115382. && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
  115383. ){
  115384. WhereTerm *pNew;
  115385. Expr *pDup;
  115386. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  115387. if( pTerm->leftCursor>=0 ){
  115388. int idxNew;
  115389. pDup = sqlite3ExprDup(db, pExpr, 0);
  115390. if( db->mallocFailed ){
  115391. sqlite3ExprDelete(db, pDup);
  115392. return;
  115393. }
  115394. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  115395. if( idxNew==0 ) return;
  115396. pNew = &pWC->a[idxNew];
  115397. markTermAsChild(pWC, idxNew, idxTerm);
  115398. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  115399. pTerm = &pWC->a[idxTerm];
  115400. pTerm->wtFlags |= TERM_COPIED;
  115401. if( termIsEquivalence(pParse, pDup) ){
  115402. pTerm->eOperator |= WO_EQUIV;
  115403. eExtraOp = WO_EQUIV;
  115404. }
  115405. }else{
  115406. pDup = pExpr;
  115407. pNew = pTerm;
  115408. }
  115409. exprCommute(pParse, pDup);
  115410. pNew->leftCursor = iCur;
  115411. pNew->u.leftColumn = iColumn;
  115412. testcase( (prereqLeft | extraRight) != prereqLeft );
  115413. pNew->prereqRight = prereqLeft | extraRight;
  115414. pNew->prereqAll = prereqAll;
  115415. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  115416. }
  115417. }
  115418. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  115419. /* If a term is the BETWEEN operator, create two new virtual terms
  115420. ** that define the range that the BETWEEN implements. For example:
  115421. **
  115422. ** a BETWEEN b AND c
  115423. **
  115424. ** is converted into:
  115425. **
  115426. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  115427. **
  115428. ** The two new terms are added onto the end of the WhereClause object.
  115429. ** The new terms are "dynamic" and are children of the original BETWEEN
  115430. ** term. That means that if the BETWEEN term is coded, the children are
  115431. ** skipped. Or, if the children are satisfied by an index, the original
  115432. ** BETWEEN term is skipped.
  115433. */
  115434. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  115435. ExprList *pList = pExpr->x.pList;
  115436. int i;
  115437. static const u8 ops[] = {TK_GE, TK_LE};
  115438. assert( pList!=0 );
  115439. assert( pList->nExpr==2 );
  115440. for(i=0; i<2; i++){
  115441. Expr *pNewExpr;
  115442. int idxNew;
  115443. pNewExpr = sqlite3PExpr(pParse, ops[i],
  115444. sqlite3ExprDup(db, pExpr->pLeft, 0),
  115445. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  115446. transferJoinMarkings(pNewExpr, pExpr);
  115447. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  115448. testcase( idxNew==0 );
  115449. exprAnalyze(pSrc, pWC, idxNew);
  115450. pTerm = &pWC->a[idxTerm];
  115451. markTermAsChild(pWC, idxNew, idxTerm);
  115452. }
  115453. }
  115454. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  115455. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  115456. /* Analyze a term that is composed of two or more subterms connected by
  115457. ** an OR operator.
  115458. */
  115459. else if( pExpr->op==TK_OR ){
  115460. assert( pWC->op==TK_AND );
  115461. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  115462. pTerm = &pWC->a[idxTerm];
  115463. }
  115464. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  115465. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  115466. /* Add constraints to reduce the search space on a LIKE or GLOB
  115467. ** operator.
  115468. **
  115469. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  115470. **
  115471. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  115472. **
  115473. ** The last character of the prefix "abc" is incremented to form the
  115474. ** termination condition "abd". If case is not significant (the default
  115475. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  115476. ** bound is made all lowercase so that the bounds also work when comparing
  115477. ** BLOBs.
  115478. */
  115479. if( pWC->op==TK_AND
  115480. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  115481. ){
  115482. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  115483. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  115484. Expr *pNewExpr1;
  115485. Expr *pNewExpr2;
  115486. int idxNew1;
  115487. int idxNew2;
  115488. const char *zCollSeqName; /* Name of collating sequence */
  115489. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  115490. pLeft = pExpr->x.pList->a[1].pExpr;
  115491. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  115492. /* Convert the lower bound to upper-case and the upper bound to
  115493. ** lower-case (upper-case is less than lower-case in ASCII) so that
  115494. ** the range constraints also work for BLOBs
  115495. */
  115496. if( noCase && !pParse->db->mallocFailed ){
  115497. int i;
  115498. char c;
  115499. pTerm->wtFlags |= TERM_LIKE;
  115500. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  115501. pStr1->u.zToken[i] = sqlite3Toupper(c);
  115502. pStr2->u.zToken[i] = sqlite3Tolower(c);
  115503. }
  115504. }
  115505. if( !db->mallocFailed ){
  115506. u8 c, *pC; /* Last character before the first wildcard */
  115507. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  115508. c = *pC;
  115509. if( noCase ){
  115510. /* The point is to increment the last character before the first
  115511. ** wildcard. But if we increment '@', that will push it into the
  115512. ** alphabetic range where case conversions will mess up the
  115513. ** inequality. To avoid this, make sure to also run the full
  115514. ** LIKE on all candidate expressions by clearing the isComplete flag
  115515. */
  115516. if( c=='A'-1 ) isComplete = 0;
  115517. c = sqlite3UpperToLower[c];
  115518. }
  115519. *pC = c + 1;
  115520. }
  115521. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  115522. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  115523. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  115524. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  115525. pStr1, 0);
  115526. transferJoinMarkings(pNewExpr1, pExpr);
  115527. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  115528. testcase( idxNew1==0 );
  115529. exprAnalyze(pSrc, pWC, idxNew1);
  115530. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  115531. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  115532. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  115533. pStr2, 0);
  115534. transferJoinMarkings(pNewExpr2, pExpr);
  115535. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  115536. testcase( idxNew2==0 );
  115537. exprAnalyze(pSrc, pWC, idxNew2);
  115538. pTerm = &pWC->a[idxTerm];
  115539. if( isComplete ){
  115540. markTermAsChild(pWC, idxNew1, idxTerm);
  115541. markTermAsChild(pWC, idxNew2, idxTerm);
  115542. }
  115543. }
  115544. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  115545. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115546. /* Add a WO_MATCH auxiliary term to the constraint set if the
  115547. ** current expression is of the form: column MATCH expr.
  115548. ** This information is used by the xBestIndex methods of
  115549. ** virtual tables. The native query optimizer does not attempt
  115550. ** to do anything with MATCH functions.
  115551. */
  115552. if( isMatchOfColumn(pExpr, &eOp2) ){
  115553. int idxNew;
  115554. Expr *pRight, *pLeft;
  115555. WhereTerm *pNewTerm;
  115556. Bitmask prereqColumn, prereqExpr;
  115557. pRight = pExpr->x.pList->a[0].pExpr;
  115558. pLeft = pExpr->x.pList->a[1].pExpr;
  115559. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  115560. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  115561. if( (prereqExpr & prereqColumn)==0 ){
  115562. Expr *pNewExpr;
  115563. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  115564. 0, sqlite3ExprDup(db, pRight, 0), 0);
  115565. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  115566. testcase( idxNew==0 );
  115567. pNewTerm = &pWC->a[idxNew];
  115568. pNewTerm->prereqRight = prereqExpr;
  115569. pNewTerm->leftCursor = pLeft->iTable;
  115570. pNewTerm->u.leftColumn = pLeft->iColumn;
  115571. pNewTerm->eOperator = WO_MATCH;
  115572. pNewTerm->eMatchOp = eOp2;
  115573. markTermAsChild(pWC, idxNew, idxTerm);
  115574. pTerm = &pWC->a[idxTerm];
  115575. pTerm->wtFlags |= TERM_COPIED;
  115576. pNewTerm->prereqAll = pTerm->prereqAll;
  115577. }
  115578. }
  115579. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  115580. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115581. /* When sqlite_stat3 histogram data is available an operator of the
  115582. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  115583. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  115584. ** virtual term of that form.
  115585. **
  115586. ** Note that the virtual term must be tagged with TERM_VNULL.
  115587. */
  115588. if( pExpr->op==TK_NOTNULL
  115589. && pExpr->pLeft->op==TK_COLUMN
  115590. && pExpr->pLeft->iColumn>=0
  115591. && OptimizationEnabled(db, SQLITE_Stat34)
  115592. ){
  115593. Expr *pNewExpr;
  115594. Expr *pLeft = pExpr->pLeft;
  115595. int idxNew;
  115596. WhereTerm *pNewTerm;
  115597. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  115598. sqlite3ExprDup(db, pLeft, 0),
  115599. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  115600. idxNew = whereClauseInsert(pWC, pNewExpr,
  115601. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  115602. if( idxNew ){
  115603. pNewTerm = &pWC->a[idxNew];
  115604. pNewTerm->prereqRight = 0;
  115605. pNewTerm->leftCursor = pLeft->iTable;
  115606. pNewTerm->u.leftColumn = pLeft->iColumn;
  115607. pNewTerm->eOperator = WO_GT;
  115608. markTermAsChild(pWC, idxNew, idxTerm);
  115609. pTerm = &pWC->a[idxTerm];
  115610. pTerm->wtFlags |= TERM_COPIED;
  115611. pNewTerm->prereqAll = pTerm->prereqAll;
  115612. }
  115613. }
  115614. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  115615. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  115616. ** an index for tables to the left of the join.
  115617. */
  115618. pTerm->prereqRight |= extraRight;
  115619. }
  115620. /***************************************************************************
  115621. ** Routines with file scope above. Interface to the rest of the where.c
  115622. ** subsystem follows.
  115623. ***************************************************************************/
  115624. /*
  115625. ** This routine identifies subexpressions in the WHERE clause where
  115626. ** each subexpression is separated by the AND operator or some other
  115627. ** operator specified in the op parameter. The WhereClause structure
  115628. ** is filled with pointers to subexpressions. For example:
  115629. **
  115630. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  115631. ** \________/ \_______________/ \________________/
  115632. ** slot[0] slot[1] slot[2]
  115633. **
  115634. ** The original WHERE clause in pExpr is unaltered. All this routine
  115635. ** does is make slot[] entries point to substructure within pExpr.
  115636. **
  115637. ** In the previous sentence and in the diagram, "slot[]" refers to
  115638. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  115639. ** all terms of the WHERE clause.
  115640. */
  115641. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  115642. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  115643. pWC->op = op;
  115644. if( pE2==0 ) return;
  115645. if( pE2->op!=op ){
  115646. whereClauseInsert(pWC, pExpr, 0);
  115647. }else{
  115648. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  115649. sqlite3WhereSplit(pWC, pE2->pRight, op);
  115650. }
  115651. }
  115652. /*
  115653. ** Initialize a preallocated WhereClause structure.
  115654. */
  115655. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  115656. WhereClause *pWC, /* The WhereClause to be initialized */
  115657. WhereInfo *pWInfo /* The WHERE processing context */
  115658. ){
  115659. pWC->pWInfo = pWInfo;
  115660. pWC->pOuter = 0;
  115661. pWC->nTerm = 0;
  115662. pWC->nSlot = ArraySize(pWC->aStatic);
  115663. pWC->a = pWC->aStatic;
  115664. }
  115665. /*
  115666. ** Deallocate a WhereClause structure. The WhereClause structure
  115667. ** itself is not freed. This routine is the inverse of
  115668. ** sqlite3WhereClauseInit().
  115669. */
  115670. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  115671. int i;
  115672. WhereTerm *a;
  115673. sqlite3 *db = pWC->pWInfo->pParse->db;
  115674. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  115675. if( a->wtFlags & TERM_DYNAMIC ){
  115676. sqlite3ExprDelete(db, a->pExpr);
  115677. }
  115678. if( a->wtFlags & TERM_ORINFO ){
  115679. whereOrInfoDelete(db, a->u.pOrInfo);
  115680. }else if( a->wtFlags & TERM_ANDINFO ){
  115681. whereAndInfoDelete(db, a->u.pAndInfo);
  115682. }
  115683. }
  115684. if( pWC->a!=pWC->aStatic ){
  115685. sqlite3DbFree(db, pWC->a);
  115686. }
  115687. }
  115688. /*
  115689. ** These routines walk (recursively) an expression tree and generate
  115690. ** a bitmask indicating which tables are used in that expression
  115691. ** tree.
  115692. */
  115693. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  115694. Bitmask mask = 0;
  115695. if( p==0 ) return 0;
  115696. if( p->op==TK_COLUMN ){
  115697. mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
  115698. return mask;
  115699. }
  115700. mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
  115701. mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  115702. if( ExprHasProperty(p, EP_xIsSelect) ){
  115703. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  115704. }else{
  115705. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  115706. }
  115707. return mask;
  115708. }
  115709. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  115710. int i;
  115711. Bitmask mask = 0;
  115712. if( pList ){
  115713. for(i=0; i<pList->nExpr; i++){
  115714. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  115715. }
  115716. }
  115717. return mask;
  115718. }
  115719. /*
  115720. ** Call exprAnalyze on all terms in a WHERE clause.
  115721. **
  115722. ** Note that exprAnalyze() might add new virtual terms onto the
  115723. ** end of the WHERE clause. We do not want to analyze these new
  115724. ** virtual terms, so start analyzing at the end and work forward
  115725. ** so that the added virtual terms are never processed.
  115726. */
  115727. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  115728. SrcList *pTabList, /* the FROM clause */
  115729. WhereClause *pWC /* the WHERE clause to be analyzed */
  115730. ){
  115731. int i;
  115732. for(i=pWC->nTerm-1; i>=0; i--){
  115733. exprAnalyze(pTabList, pWC, i);
  115734. }
  115735. }
  115736. /*
  115737. ** For table-valued-functions, transform the function arguments into
  115738. ** new WHERE clause terms.
  115739. **
  115740. ** Each function argument translates into an equality constraint against
  115741. ** a HIDDEN column in the table.
  115742. */
  115743. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  115744. Parse *pParse, /* Parsing context */
  115745. struct SrcList_item *pItem, /* The FROM clause term to process */
  115746. WhereClause *pWC /* Xfer function arguments to here */
  115747. ){
  115748. Table *pTab;
  115749. int j, k;
  115750. ExprList *pArgs;
  115751. Expr *pColRef;
  115752. Expr *pTerm;
  115753. if( pItem->fg.isTabFunc==0 ) return;
  115754. pTab = pItem->pTab;
  115755. assert( pTab!=0 );
  115756. pArgs = pItem->u1.pFuncArg;
  115757. if( pArgs==0 ) return;
  115758. for(j=k=0; j<pArgs->nExpr; j++){
  115759. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  115760. if( k>=pTab->nCol ){
  115761. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  115762. pTab->zName, j);
  115763. return;
  115764. }
  115765. pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  115766. if( pColRef==0 ) return;
  115767. pColRef->iTable = pItem->iCursor;
  115768. pColRef->iColumn = k++;
  115769. pColRef->pTab = pTab;
  115770. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  115771. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  115772. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  115773. }
  115774. }
  115775. /************** End of whereexpr.c *******************************************/
  115776. /************** Begin file where.c *******************************************/
  115777. /*
  115778. ** 2001 September 15
  115779. **
  115780. ** The author disclaims copyright to this source code. In place of
  115781. ** a legal notice, here is a blessing:
  115782. **
  115783. ** May you do good and not evil.
  115784. ** May you find forgiveness for yourself and forgive others.
  115785. ** May you share freely, never taking more than you give.
  115786. **
  115787. *************************************************************************
  115788. ** This module contains C code that generates VDBE code used to process
  115789. ** the WHERE clause of SQL statements. This module is responsible for
  115790. ** generating the code that loops through a table looking for applicable
  115791. ** rows. Indices are selected and used to speed the search when doing
  115792. ** so is applicable. Because this module is responsible for selecting
  115793. ** indices, you might also think of this module as the "query optimizer".
  115794. */
  115795. /* #include "sqliteInt.h" */
  115796. /* #include "whereInt.h" */
  115797. /* Forward declaration of methods */
  115798. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  115799. /* Test variable that can be set to enable WHERE tracing */
  115800. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  115801. /***/ int sqlite3WhereTrace = 0;
  115802. #endif
  115803. /*
  115804. ** Return the estimated number of output rows from a WHERE clause
  115805. */
  115806. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  115807. return pWInfo->nRowOut;
  115808. }
  115809. /*
  115810. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  115811. ** WHERE clause returns outputs for DISTINCT processing.
  115812. */
  115813. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  115814. return pWInfo->eDistinct;
  115815. }
  115816. /*
  115817. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  115818. ** Return FALSE if the output needs to be sorted.
  115819. */
  115820. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  115821. return pWInfo->nOBSat;
  115822. }
  115823. /*
  115824. ** Return the VDBE address or label to jump to in order to continue
  115825. ** immediately with the next row of a WHERE clause.
  115826. */
  115827. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  115828. assert( pWInfo->iContinue!=0 );
  115829. return pWInfo->iContinue;
  115830. }
  115831. /*
  115832. ** Return the VDBE address or label to jump to in order to break
  115833. ** out of a WHERE loop.
  115834. */
  115835. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  115836. return pWInfo->iBreak;
  115837. }
  115838. /*
  115839. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  115840. ** operate directly on the rowis returned by a WHERE clause. Return
  115841. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  115842. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  115843. ** optimization can be used on multiple
  115844. **
  115845. ** If the ONEPASS optimization is used (if this routine returns true)
  115846. ** then also write the indices of open cursors used by ONEPASS
  115847. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  115848. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  115849. ** Either value may be -1, indicating that cursor is not used.
  115850. ** Any cursors returned will have been opened for writing.
  115851. **
  115852. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  115853. ** unable to use the ONEPASS optimization.
  115854. */
  115855. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  115856. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  115857. #ifdef WHERETRACE_ENABLED
  115858. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  115859. sqlite3DebugPrintf("%s cursors: %d %d\n",
  115860. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  115861. aiCur[0], aiCur[1]);
  115862. }
  115863. #endif
  115864. return pWInfo->eOnePass;
  115865. }
  115866. /*
  115867. ** Move the content of pSrc into pDest
  115868. */
  115869. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  115870. pDest->n = pSrc->n;
  115871. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  115872. }
  115873. /*
  115874. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  115875. **
  115876. ** The new entry might overwrite an existing entry, or it might be
  115877. ** appended, or it might be discarded. Do whatever is the right thing
  115878. ** so that pSet keeps the N_OR_COST best entries seen so far.
  115879. */
  115880. static int whereOrInsert(
  115881. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  115882. Bitmask prereq, /* Prerequisites of the new entry */
  115883. LogEst rRun, /* Run-cost of the new entry */
  115884. LogEst nOut /* Number of outputs for the new entry */
  115885. ){
  115886. u16 i;
  115887. WhereOrCost *p;
  115888. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  115889. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  115890. goto whereOrInsert_done;
  115891. }
  115892. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  115893. return 0;
  115894. }
  115895. }
  115896. if( pSet->n<N_OR_COST ){
  115897. p = &pSet->a[pSet->n++];
  115898. p->nOut = nOut;
  115899. }else{
  115900. p = pSet->a;
  115901. for(i=1; i<pSet->n; i++){
  115902. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  115903. }
  115904. if( p->rRun<=rRun ) return 0;
  115905. }
  115906. whereOrInsert_done:
  115907. p->prereq = prereq;
  115908. p->rRun = rRun;
  115909. if( p->nOut>nOut ) p->nOut = nOut;
  115910. return 1;
  115911. }
  115912. /*
  115913. ** Return the bitmask for the given cursor number. Return 0 if
  115914. ** iCursor is not in the set.
  115915. */
  115916. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  115917. int i;
  115918. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  115919. for(i=0; i<pMaskSet->n; i++){
  115920. if( pMaskSet->ix[i]==iCursor ){
  115921. return MASKBIT(i);
  115922. }
  115923. }
  115924. return 0;
  115925. }
  115926. /*
  115927. ** Create a new mask for cursor iCursor.
  115928. **
  115929. ** There is one cursor per table in the FROM clause. The number of
  115930. ** tables in the FROM clause is limited by a test early in the
  115931. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  115932. ** array will never overflow.
  115933. */
  115934. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  115935. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  115936. pMaskSet->ix[pMaskSet->n++] = iCursor;
  115937. }
  115938. /*
  115939. ** Advance to the next WhereTerm that matches according to the criteria
  115940. ** established when the pScan object was initialized by whereScanInit().
  115941. ** Return NULL if there are no more matching WhereTerms.
  115942. */
  115943. static WhereTerm *whereScanNext(WhereScan *pScan){
  115944. int iCur; /* The cursor on the LHS of the term */
  115945. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  115946. Expr *pX; /* An expression being tested */
  115947. WhereClause *pWC; /* Shorthand for pScan->pWC */
  115948. WhereTerm *pTerm; /* The term being tested */
  115949. int k = pScan->k; /* Where to start scanning */
  115950. while( pScan->iEquiv<=pScan->nEquiv ){
  115951. iCur = pScan->aiCur[pScan->iEquiv-1];
  115952. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  115953. if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
  115954. while( (pWC = pScan->pWC)!=0 ){
  115955. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  115956. if( pTerm->leftCursor==iCur
  115957. && pTerm->u.leftColumn==iColumn
  115958. && (iColumn!=XN_EXPR
  115959. || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
  115960. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  115961. ){
  115962. if( (pTerm->eOperator & WO_EQUIV)!=0
  115963. && pScan->nEquiv<ArraySize(pScan->aiCur)
  115964. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  115965. ){
  115966. int j;
  115967. for(j=0; j<pScan->nEquiv; j++){
  115968. if( pScan->aiCur[j]==pX->iTable
  115969. && pScan->aiColumn[j]==pX->iColumn ){
  115970. break;
  115971. }
  115972. }
  115973. if( j==pScan->nEquiv ){
  115974. pScan->aiCur[j] = pX->iTable;
  115975. pScan->aiColumn[j] = pX->iColumn;
  115976. pScan->nEquiv++;
  115977. }
  115978. }
  115979. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  115980. /* Verify the affinity and collating sequence match */
  115981. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  115982. CollSeq *pColl;
  115983. Parse *pParse = pWC->pWInfo->pParse;
  115984. pX = pTerm->pExpr;
  115985. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  115986. continue;
  115987. }
  115988. assert(pX->pLeft);
  115989. pColl = sqlite3BinaryCompareCollSeq(pParse,
  115990. pX->pLeft, pX->pRight);
  115991. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  115992. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  115993. continue;
  115994. }
  115995. }
  115996. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  115997. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  115998. && pX->iTable==pScan->aiCur[0]
  115999. && pX->iColumn==pScan->aiColumn[0]
  116000. ){
  116001. testcase( pTerm->eOperator & WO_IS );
  116002. continue;
  116003. }
  116004. pScan->k = k+1;
  116005. return pTerm;
  116006. }
  116007. }
  116008. }
  116009. pScan->pWC = pScan->pWC->pOuter;
  116010. k = 0;
  116011. }
  116012. pScan->pWC = pScan->pOrigWC;
  116013. k = 0;
  116014. pScan->iEquiv++;
  116015. }
  116016. return 0;
  116017. }
  116018. /*
  116019. ** Initialize a WHERE clause scanner object. Return a pointer to the
  116020. ** first match. Return NULL if there are no matches.
  116021. **
  116022. ** The scanner will be searching the WHERE clause pWC. It will look
  116023. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  116024. ** iCur. The <op> must be one of the operators described by opMask.
  116025. **
  116026. ** If the search is for X and the WHERE clause contains terms of the
  116027. ** form X=Y then this routine might also return terms of the form
  116028. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  116029. ** but is enough to handle most commonly occurring SQL statements.
  116030. **
  116031. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  116032. ** index pIdx.
  116033. */
  116034. static WhereTerm *whereScanInit(
  116035. WhereScan *pScan, /* The WhereScan object being initialized */
  116036. WhereClause *pWC, /* The WHERE clause to be scanned */
  116037. int iCur, /* Cursor to scan for */
  116038. int iColumn, /* Column to scan for */
  116039. u32 opMask, /* Operator(s) to scan for */
  116040. Index *pIdx /* Must be compatible with this index */
  116041. ){
  116042. int j = 0;
  116043. /* memset(pScan, 0, sizeof(*pScan)); */
  116044. pScan->pOrigWC = pWC;
  116045. pScan->pWC = pWC;
  116046. pScan->pIdxExpr = 0;
  116047. if( pIdx ){
  116048. j = iColumn;
  116049. iColumn = pIdx->aiColumn[j];
  116050. if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  116051. if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
  116052. }
  116053. if( pIdx && iColumn>=0 ){
  116054. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  116055. pScan->zCollName = pIdx->azColl[j];
  116056. }else{
  116057. pScan->idxaff = 0;
  116058. pScan->zCollName = 0;
  116059. }
  116060. pScan->opMask = opMask;
  116061. pScan->k = 0;
  116062. pScan->aiCur[0] = iCur;
  116063. pScan->aiColumn[0] = iColumn;
  116064. pScan->nEquiv = 1;
  116065. pScan->iEquiv = 1;
  116066. return whereScanNext(pScan);
  116067. }
  116068. /*
  116069. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  116070. ** where X is a reference to the iColumn of table iCur and <op> is one of
  116071. ** the WO_xx operator codes specified by the op parameter.
  116072. ** Return a pointer to the term. Return 0 if not found.
  116073. **
  116074. ** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
  116075. ** rather than the iColumn-th column of table iCur.
  116076. **
  116077. ** The term returned might by Y=<expr> if there is another constraint in
  116078. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  116079. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  116080. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  116081. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  116082. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  116083. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  116084. **
  116085. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  116086. ** then try for the one with no dependencies on <expr> - in other words where
  116087. ** <expr> is a constant expression of some kind. Only return entries of
  116088. ** the form "X <op> Y" where Y is a column in another table if no terms of
  116089. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  116090. ** exist, try to return a term that does not use WO_EQUIV.
  116091. */
  116092. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  116093. WhereClause *pWC, /* The WHERE clause to be searched */
  116094. int iCur, /* Cursor number of LHS */
  116095. int iColumn, /* Column number of LHS */
  116096. Bitmask notReady, /* RHS must not overlap with this mask */
  116097. u32 op, /* Mask of WO_xx values describing operator */
  116098. Index *pIdx /* Must be compatible with this index, if not NULL */
  116099. ){
  116100. WhereTerm *pResult = 0;
  116101. WhereTerm *p;
  116102. WhereScan scan;
  116103. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  116104. op &= WO_EQ|WO_IS;
  116105. while( p ){
  116106. if( (p->prereqRight & notReady)==0 ){
  116107. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  116108. testcase( p->eOperator & WO_IS );
  116109. return p;
  116110. }
  116111. if( pResult==0 ) pResult = p;
  116112. }
  116113. p = whereScanNext(&scan);
  116114. }
  116115. return pResult;
  116116. }
  116117. /*
  116118. ** This function searches pList for an entry that matches the iCol-th column
  116119. ** of index pIdx.
  116120. **
  116121. ** If such an expression is found, its index in pList->a[] is returned. If
  116122. ** no expression is found, -1 is returned.
  116123. */
  116124. static int findIndexCol(
  116125. Parse *pParse, /* Parse context */
  116126. ExprList *pList, /* Expression list to search */
  116127. int iBase, /* Cursor for table associated with pIdx */
  116128. Index *pIdx, /* Index to match column of */
  116129. int iCol /* Column of index to match */
  116130. ){
  116131. int i;
  116132. const char *zColl = pIdx->azColl[iCol];
  116133. for(i=0; i<pList->nExpr; i++){
  116134. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  116135. if( p->op==TK_COLUMN
  116136. && p->iColumn==pIdx->aiColumn[iCol]
  116137. && p->iTable==iBase
  116138. ){
  116139. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  116140. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  116141. return i;
  116142. }
  116143. }
  116144. }
  116145. return -1;
  116146. }
  116147. /*
  116148. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  116149. */
  116150. static int indexColumnNotNull(Index *pIdx, int iCol){
  116151. int j;
  116152. assert( pIdx!=0 );
  116153. assert( iCol>=0 && iCol<pIdx->nColumn );
  116154. j = pIdx->aiColumn[iCol];
  116155. if( j>=0 ){
  116156. return pIdx->pTable->aCol[j].notNull;
  116157. }else if( j==(-1) ){
  116158. return 1;
  116159. }else{
  116160. assert( j==(-2) );
  116161. return 0; /* Assume an indexed expression can always yield a NULL */
  116162. }
  116163. }
  116164. /*
  116165. ** Return true if the DISTINCT expression-list passed as the third argument
  116166. ** is redundant.
  116167. **
  116168. ** A DISTINCT list is redundant if any subset of the columns in the
  116169. ** DISTINCT list are collectively unique and individually non-null.
  116170. */
  116171. static int isDistinctRedundant(
  116172. Parse *pParse, /* Parsing context */
  116173. SrcList *pTabList, /* The FROM clause */
  116174. WhereClause *pWC, /* The WHERE clause */
  116175. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  116176. ){
  116177. Table *pTab;
  116178. Index *pIdx;
  116179. int i;
  116180. int iBase;
  116181. /* If there is more than one table or sub-select in the FROM clause of
  116182. ** this query, then it will not be possible to show that the DISTINCT
  116183. ** clause is redundant. */
  116184. if( pTabList->nSrc!=1 ) return 0;
  116185. iBase = pTabList->a[0].iCursor;
  116186. pTab = pTabList->a[0].pTab;
  116187. /* If any of the expressions is an IPK column on table iBase, then return
  116188. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  116189. ** current SELECT is a correlated sub-query.
  116190. */
  116191. for(i=0; i<pDistinct->nExpr; i++){
  116192. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  116193. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  116194. }
  116195. /* Loop through all indices on the table, checking each to see if it makes
  116196. ** the DISTINCT qualifier redundant. It does so if:
  116197. **
  116198. ** 1. The index is itself UNIQUE, and
  116199. **
  116200. ** 2. All of the columns in the index are either part of the pDistinct
  116201. ** list, or else the WHERE clause contains a term of the form "col=X",
  116202. ** where X is a constant value. The collation sequences of the
  116203. ** comparison and select-list expressions must match those of the index.
  116204. **
  116205. ** 3. All of those index columns for which the WHERE clause does not
  116206. ** contain a "col=X" term are subject to a NOT NULL constraint.
  116207. */
  116208. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  116209. if( !IsUniqueIndex(pIdx) ) continue;
  116210. for(i=0; i<pIdx->nKeyCol; i++){
  116211. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  116212. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  116213. if( indexColumnNotNull(pIdx, i)==0 ) break;
  116214. }
  116215. }
  116216. if( i==pIdx->nKeyCol ){
  116217. /* This index implies that the DISTINCT qualifier is redundant. */
  116218. return 1;
  116219. }
  116220. }
  116221. return 0;
  116222. }
  116223. /*
  116224. ** Estimate the logarithm of the input value to base 2.
  116225. */
  116226. static LogEst estLog(LogEst N){
  116227. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  116228. }
  116229. /*
  116230. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  116231. **
  116232. ** This routine runs over generated VDBE code and translates OP_Column
  116233. ** opcodes into OP_Copy when the table is being accessed via co-routine
  116234. ** instead of via table lookup.
  116235. **
  116236. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  116237. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  116238. ** then each OP_Rowid is transformed into an instruction to increment the
  116239. ** value stored in its output register.
  116240. */
  116241. static void translateColumnToCopy(
  116242. Vdbe *v, /* The VDBE containing code to translate */
  116243. int iStart, /* Translate from this opcode to the end */
  116244. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  116245. int iRegister, /* The first column is in this register */
  116246. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  116247. ){
  116248. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  116249. int iEnd = sqlite3VdbeCurrentAddr(v);
  116250. for(; iStart<iEnd; iStart++, pOp++){
  116251. if( pOp->p1!=iTabCur ) continue;
  116252. if( pOp->opcode==OP_Column ){
  116253. pOp->opcode = OP_Copy;
  116254. pOp->p1 = pOp->p2 + iRegister;
  116255. pOp->p2 = pOp->p3;
  116256. pOp->p3 = 0;
  116257. }else if( pOp->opcode==OP_Rowid ){
  116258. if( bIncrRowid ){
  116259. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  116260. pOp->opcode = OP_AddImm;
  116261. pOp->p1 = pOp->p2;
  116262. pOp->p2 = 1;
  116263. }else{
  116264. pOp->opcode = OP_Null;
  116265. pOp->p1 = 0;
  116266. pOp->p3 = 0;
  116267. }
  116268. }
  116269. }
  116270. }
  116271. /*
  116272. ** Two routines for printing the content of an sqlite3_index_info
  116273. ** structure. Used for testing and debugging only. If neither
  116274. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  116275. ** are no-ops.
  116276. */
  116277. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  116278. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  116279. int i;
  116280. if( !sqlite3WhereTrace ) return;
  116281. for(i=0; i<p->nConstraint; i++){
  116282. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  116283. i,
  116284. p->aConstraint[i].iColumn,
  116285. p->aConstraint[i].iTermOffset,
  116286. p->aConstraint[i].op,
  116287. p->aConstraint[i].usable);
  116288. }
  116289. for(i=0; i<p->nOrderBy; i++){
  116290. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  116291. i,
  116292. p->aOrderBy[i].iColumn,
  116293. p->aOrderBy[i].desc);
  116294. }
  116295. }
  116296. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  116297. int i;
  116298. if( !sqlite3WhereTrace ) return;
  116299. for(i=0; i<p->nConstraint; i++){
  116300. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  116301. i,
  116302. p->aConstraintUsage[i].argvIndex,
  116303. p->aConstraintUsage[i].omit);
  116304. }
  116305. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  116306. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  116307. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  116308. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  116309. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  116310. }
  116311. #else
  116312. #define TRACE_IDX_INPUTS(A)
  116313. #define TRACE_IDX_OUTPUTS(A)
  116314. #endif
  116315. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  116316. /*
  116317. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  116318. ** could be used with an index to access pSrc, assuming an appropriate
  116319. ** index existed.
  116320. */
  116321. static int termCanDriveIndex(
  116322. WhereTerm *pTerm, /* WHERE clause term to check */
  116323. struct SrcList_item *pSrc, /* Table we are trying to access */
  116324. Bitmask notReady /* Tables in outer loops of the join */
  116325. ){
  116326. char aff;
  116327. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  116328. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  116329. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  116330. if( pTerm->u.leftColumn<0 ) return 0;
  116331. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  116332. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  116333. testcase( pTerm->pExpr->op==TK_IS );
  116334. return 1;
  116335. }
  116336. #endif
  116337. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  116338. /*
  116339. ** Generate code to construct the Index object for an automatic index
  116340. ** and to set up the WhereLevel object pLevel so that the code generator
  116341. ** makes use of the automatic index.
  116342. */
  116343. static void constructAutomaticIndex(
  116344. Parse *pParse, /* The parsing context */
  116345. WhereClause *pWC, /* The WHERE clause */
  116346. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  116347. Bitmask notReady, /* Mask of cursors that are not available */
  116348. WhereLevel *pLevel /* Write new index here */
  116349. ){
  116350. int nKeyCol; /* Number of columns in the constructed index */
  116351. WhereTerm *pTerm; /* A single term of the WHERE clause */
  116352. WhereTerm *pWCEnd; /* End of pWC->a[] */
  116353. Index *pIdx; /* Object describing the transient index */
  116354. Vdbe *v; /* Prepared statement under construction */
  116355. int addrInit; /* Address of the initialization bypass jump */
  116356. Table *pTable; /* The table being indexed */
  116357. int addrTop; /* Top of the index fill loop */
  116358. int regRecord; /* Register holding an index record */
  116359. int n; /* Column counter */
  116360. int i; /* Loop counter */
  116361. int mxBitCol; /* Maximum column in pSrc->colUsed */
  116362. CollSeq *pColl; /* Collating sequence to on a column */
  116363. WhereLoop *pLoop; /* The Loop object */
  116364. char *zNotUsed; /* Extra space on the end of pIdx */
  116365. Bitmask idxCols; /* Bitmap of columns used for indexing */
  116366. Bitmask extraCols; /* Bitmap of additional columns */
  116367. u8 sentWarning = 0; /* True if a warnning has been issued */
  116368. Expr *pPartial = 0; /* Partial Index Expression */
  116369. int iContinue = 0; /* Jump here to skip excluded rows */
  116370. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  116371. int addrCounter = 0; /* Address where integer counter is initialized */
  116372. int regBase; /* Array of registers where record is assembled */
  116373. /* Generate code to skip over the creation and initialization of the
  116374. ** transient index on 2nd and subsequent iterations of the loop. */
  116375. v = pParse->pVdbe;
  116376. assert( v!=0 );
  116377. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  116378. /* Count the number of columns that will be added to the index
  116379. ** and used to match WHERE clause constraints */
  116380. nKeyCol = 0;
  116381. pTable = pSrc->pTab;
  116382. pWCEnd = &pWC->a[pWC->nTerm];
  116383. pLoop = pLevel->pWLoop;
  116384. idxCols = 0;
  116385. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  116386. Expr *pExpr = pTerm->pExpr;
  116387. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  116388. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  116389. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  116390. if( pLoop->prereq==0
  116391. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  116392. && !ExprHasProperty(pExpr, EP_FromJoin)
  116393. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  116394. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  116395. sqlite3ExprDup(pParse->db, pExpr, 0));
  116396. }
  116397. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  116398. int iCol = pTerm->u.leftColumn;
  116399. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  116400. testcase( iCol==BMS );
  116401. testcase( iCol==BMS-1 );
  116402. if( !sentWarning ){
  116403. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  116404. "automatic index on %s(%s)", pTable->zName,
  116405. pTable->aCol[iCol].zName);
  116406. sentWarning = 1;
  116407. }
  116408. if( (idxCols & cMask)==0 ){
  116409. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  116410. goto end_auto_index_create;
  116411. }
  116412. pLoop->aLTerm[nKeyCol++] = pTerm;
  116413. idxCols |= cMask;
  116414. }
  116415. }
  116416. }
  116417. assert( nKeyCol>0 );
  116418. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  116419. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  116420. | WHERE_AUTO_INDEX;
  116421. /* Count the number of additional columns needed to create a
  116422. ** covering index. A "covering index" is an index that contains all
  116423. ** columns that are needed by the query. With a covering index, the
  116424. ** original table never needs to be accessed. Automatic indices must
  116425. ** be a covering index because the index will not be updated if the
  116426. ** original table changes and the index and table cannot both be used
  116427. ** if they go out of sync.
  116428. */
  116429. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  116430. mxBitCol = MIN(BMS-1,pTable->nCol);
  116431. testcase( pTable->nCol==BMS-1 );
  116432. testcase( pTable->nCol==BMS-2 );
  116433. for(i=0; i<mxBitCol; i++){
  116434. if( extraCols & MASKBIT(i) ) nKeyCol++;
  116435. }
  116436. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  116437. nKeyCol += pTable->nCol - BMS + 1;
  116438. }
  116439. /* Construct the Index object to describe this index */
  116440. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  116441. if( pIdx==0 ) goto end_auto_index_create;
  116442. pLoop->u.btree.pIndex = pIdx;
  116443. pIdx->zName = "auto-index";
  116444. pIdx->pTable = pTable;
  116445. n = 0;
  116446. idxCols = 0;
  116447. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  116448. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  116449. int iCol = pTerm->u.leftColumn;
  116450. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  116451. testcase( iCol==BMS-1 );
  116452. testcase( iCol==BMS );
  116453. if( (idxCols & cMask)==0 ){
  116454. Expr *pX = pTerm->pExpr;
  116455. idxCols |= cMask;
  116456. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  116457. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  116458. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  116459. n++;
  116460. }
  116461. }
  116462. }
  116463. assert( (u32)n==pLoop->u.btree.nEq );
  116464. /* Add additional columns needed to make the automatic index into
  116465. ** a covering index */
  116466. for(i=0; i<mxBitCol; i++){
  116467. if( extraCols & MASKBIT(i) ){
  116468. pIdx->aiColumn[n] = i;
  116469. pIdx->azColl[n] = sqlite3StrBINARY;
  116470. n++;
  116471. }
  116472. }
  116473. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  116474. for(i=BMS-1; i<pTable->nCol; i++){
  116475. pIdx->aiColumn[n] = i;
  116476. pIdx->azColl[n] = sqlite3StrBINARY;
  116477. n++;
  116478. }
  116479. }
  116480. assert( n==nKeyCol );
  116481. pIdx->aiColumn[n] = XN_ROWID;
  116482. pIdx->azColl[n] = sqlite3StrBINARY;
  116483. /* Create the automatic index */
  116484. assert( pLevel->iIdxCur>=0 );
  116485. pLevel->iIdxCur = pParse->nTab++;
  116486. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  116487. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  116488. VdbeComment((v, "for %s", pTable->zName));
  116489. /* Fill the automatic index with content */
  116490. sqlite3ExprCachePush(pParse);
  116491. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  116492. if( pTabItem->fg.viaCoroutine ){
  116493. int regYield = pTabItem->regReturn;
  116494. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  116495. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  116496. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  116497. VdbeCoverage(v);
  116498. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  116499. }else{
  116500. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  116501. }
  116502. if( pPartial ){
  116503. iContinue = sqlite3VdbeMakeLabel(v);
  116504. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  116505. pLoop->wsFlags |= WHERE_PARTIALIDX;
  116506. }
  116507. regRecord = sqlite3GetTempReg(pParse);
  116508. regBase = sqlite3GenerateIndexKey(
  116509. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  116510. );
  116511. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  116512. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  116513. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  116514. if( pTabItem->fg.viaCoroutine ){
  116515. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  116516. translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
  116517. sqlite3VdbeGoto(v, addrTop);
  116518. pTabItem->fg.viaCoroutine = 0;
  116519. }else{
  116520. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  116521. }
  116522. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  116523. sqlite3VdbeJumpHere(v, addrTop);
  116524. sqlite3ReleaseTempReg(pParse, regRecord);
  116525. sqlite3ExprCachePop(pParse);
  116526. /* Jump here when skipping the initialization */
  116527. sqlite3VdbeJumpHere(v, addrInit);
  116528. end_auto_index_create:
  116529. sqlite3ExprDelete(pParse->db, pPartial);
  116530. }
  116531. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  116532. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116533. /*
  116534. ** Allocate and populate an sqlite3_index_info structure. It is the
  116535. ** responsibility of the caller to eventually release the structure
  116536. ** by passing the pointer returned by this function to sqlite3_free().
  116537. */
  116538. static sqlite3_index_info *allocateIndexInfo(
  116539. Parse *pParse,
  116540. WhereClause *pWC,
  116541. Bitmask mUnusable, /* Ignore terms with these prereqs */
  116542. struct SrcList_item *pSrc,
  116543. ExprList *pOrderBy
  116544. ){
  116545. int i, j;
  116546. int nTerm;
  116547. struct sqlite3_index_constraint *pIdxCons;
  116548. struct sqlite3_index_orderby *pIdxOrderBy;
  116549. struct sqlite3_index_constraint_usage *pUsage;
  116550. WhereTerm *pTerm;
  116551. int nOrderBy;
  116552. sqlite3_index_info *pIdxInfo;
  116553. /* Count the number of possible WHERE clause constraints referring
  116554. ** to this virtual table */
  116555. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  116556. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  116557. if( pTerm->prereqRight & mUnusable ) continue;
  116558. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  116559. testcase( pTerm->eOperator & WO_IN );
  116560. testcase( pTerm->eOperator & WO_ISNULL );
  116561. testcase( pTerm->eOperator & WO_IS );
  116562. testcase( pTerm->eOperator & WO_ALL );
  116563. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  116564. if( pTerm->wtFlags & TERM_VNULL ) continue;
  116565. assert( pTerm->u.leftColumn>=(-1) );
  116566. nTerm++;
  116567. }
  116568. /* If the ORDER BY clause contains only columns in the current
  116569. ** virtual table then allocate space for the aOrderBy part of
  116570. ** the sqlite3_index_info structure.
  116571. */
  116572. nOrderBy = 0;
  116573. if( pOrderBy ){
  116574. int n = pOrderBy->nExpr;
  116575. for(i=0; i<n; i++){
  116576. Expr *pExpr = pOrderBy->a[i].pExpr;
  116577. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  116578. }
  116579. if( i==n){
  116580. nOrderBy = n;
  116581. }
  116582. }
  116583. /* Allocate the sqlite3_index_info structure
  116584. */
  116585. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  116586. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  116587. + sizeof(*pIdxOrderBy)*nOrderBy );
  116588. if( pIdxInfo==0 ){
  116589. sqlite3ErrorMsg(pParse, "out of memory");
  116590. return 0;
  116591. }
  116592. /* Initialize the structure. The sqlite3_index_info structure contains
  116593. ** many fields that are declared "const" to prevent xBestIndex from
  116594. ** changing them. We have to do some funky casting in order to
  116595. ** initialize those fields.
  116596. */
  116597. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  116598. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  116599. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  116600. *(int*)&pIdxInfo->nConstraint = nTerm;
  116601. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  116602. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  116603. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  116604. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  116605. pUsage;
  116606. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  116607. u8 op;
  116608. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  116609. if( pTerm->prereqRight & mUnusable ) continue;
  116610. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  116611. testcase( pTerm->eOperator & WO_IN );
  116612. testcase( pTerm->eOperator & WO_IS );
  116613. testcase( pTerm->eOperator & WO_ISNULL );
  116614. testcase( pTerm->eOperator & WO_ALL );
  116615. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  116616. if( pTerm->wtFlags & TERM_VNULL ) continue;
  116617. assert( pTerm->u.leftColumn>=(-1) );
  116618. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  116619. pIdxCons[j].iTermOffset = i;
  116620. op = (u8)pTerm->eOperator & WO_ALL;
  116621. if( op==WO_IN ) op = WO_EQ;
  116622. if( op==WO_MATCH ){
  116623. op = pTerm->eMatchOp;
  116624. }
  116625. pIdxCons[j].op = op;
  116626. /* The direct assignment in the previous line is possible only because
  116627. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  116628. ** following asserts verify this fact. */
  116629. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  116630. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  116631. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  116632. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  116633. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  116634. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  116635. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  116636. j++;
  116637. }
  116638. for(i=0; i<nOrderBy; i++){
  116639. Expr *pExpr = pOrderBy->a[i].pExpr;
  116640. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  116641. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  116642. }
  116643. return pIdxInfo;
  116644. }
  116645. /*
  116646. ** The table object reference passed as the second argument to this function
  116647. ** must represent a virtual table. This function invokes the xBestIndex()
  116648. ** method of the virtual table with the sqlite3_index_info object that
  116649. ** comes in as the 3rd argument to this function.
  116650. **
  116651. ** If an error occurs, pParse is populated with an error message and a
  116652. ** non-zero value is returned. Otherwise, 0 is returned and the output
  116653. ** part of the sqlite3_index_info structure is left populated.
  116654. **
  116655. ** Whether or not an error is returned, it is the responsibility of the
  116656. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  116657. ** that this is required.
  116658. */
  116659. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  116660. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  116661. int rc;
  116662. TRACE_IDX_INPUTS(p);
  116663. rc = pVtab->pModule->xBestIndex(pVtab, p);
  116664. TRACE_IDX_OUTPUTS(p);
  116665. if( rc!=SQLITE_OK ){
  116666. if( rc==SQLITE_NOMEM ){
  116667. sqlite3OomFault(pParse->db);
  116668. }else if( !pVtab->zErrMsg ){
  116669. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  116670. }else{
  116671. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  116672. }
  116673. }
  116674. sqlite3_free(pVtab->zErrMsg);
  116675. pVtab->zErrMsg = 0;
  116676. #if 0
  116677. /* This error is now caught by the caller.
  116678. ** Search for "xBestIndex malfunction" below */
  116679. for(i=0; i<p->nConstraint; i++){
  116680. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  116681. sqlite3ErrorMsg(pParse,
  116682. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  116683. }
  116684. }
  116685. #endif
  116686. return pParse->nErr;
  116687. }
  116688. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  116689. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116690. /*
  116691. ** Estimate the location of a particular key among all keys in an
  116692. ** index. Store the results in aStat as follows:
  116693. **
  116694. ** aStat[0] Est. number of rows less than pRec
  116695. ** aStat[1] Est. number of rows equal to pRec
  116696. **
  116697. ** Return the index of the sample that is the smallest sample that
  116698. ** is greater than or equal to pRec. Note that this index is not an index
  116699. ** into the aSample[] array - it is an index into a virtual set of samples
  116700. ** based on the contents of aSample[] and the number of fields in record
  116701. ** pRec.
  116702. */
  116703. static int whereKeyStats(
  116704. Parse *pParse, /* Database connection */
  116705. Index *pIdx, /* Index to consider domain of */
  116706. UnpackedRecord *pRec, /* Vector of values to consider */
  116707. int roundUp, /* Round up if true. Round down if false */
  116708. tRowcnt *aStat /* OUT: stats written here */
  116709. ){
  116710. IndexSample *aSample = pIdx->aSample;
  116711. int iCol; /* Index of required stats in anEq[] etc. */
  116712. int i; /* Index of first sample >= pRec */
  116713. int iSample; /* Smallest sample larger than or equal to pRec */
  116714. int iMin = 0; /* Smallest sample not yet tested */
  116715. int iTest; /* Next sample to test */
  116716. int res; /* Result of comparison operation */
  116717. int nField; /* Number of fields in pRec */
  116718. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  116719. #ifndef SQLITE_DEBUG
  116720. UNUSED_PARAMETER( pParse );
  116721. #endif
  116722. assert( pRec!=0 );
  116723. assert( pIdx->nSample>0 );
  116724. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  116725. /* Do a binary search to find the first sample greater than or equal
  116726. ** to pRec. If pRec contains a single field, the set of samples to search
  116727. ** is simply the aSample[] array. If the samples in aSample[] contain more
  116728. ** than one fields, all fields following the first are ignored.
  116729. **
  116730. ** If pRec contains N fields, where N is more than one, then as well as the
  116731. ** samples in aSample[] (truncated to N fields), the search also has to
  116732. ** consider prefixes of those samples. For example, if the set of samples
  116733. ** in aSample is:
  116734. **
  116735. ** aSample[0] = (a, 5)
  116736. ** aSample[1] = (a, 10)
  116737. ** aSample[2] = (b, 5)
  116738. ** aSample[3] = (c, 100)
  116739. ** aSample[4] = (c, 105)
  116740. **
  116741. ** Then the search space should ideally be the samples above and the
  116742. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  116743. ** the code actually searches this set:
  116744. **
  116745. ** 0: (a)
  116746. ** 1: (a, 5)
  116747. ** 2: (a, 10)
  116748. ** 3: (a, 10)
  116749. ** 4: (b)
  116750. ** 5: (b, 5)
  116751. ** 6: (c)
  116752. ** 7: (c, 100)
  116753. ** 8: (c, 105)
  116754. ** 9: (c, 105)
  116755. **
  116756. ** For each sample in the aSample[] array, N samples are present in the
  116757. ** effective sample array. In the above, samples 0 and 1 are based on
  116758. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  116759. **
  116760. ** Often, sample i of each block of N effective samples has (i+1) fields.
  116761. ** Except, each sample may be extended to ensure that it is greater than or
  116762. ** equal to the previous sample in the array. For example, in the above,
  116763. ** sample 2 is the first sample of a block of N samples, so at first it
  116764. ** appears that it should be 1 field in size. However, that would make it
  116765. ** smaller than sample 1, so the binary search would not work. As a result,
  116766. ** it is extended to two fields. The duplicates that this creates do not
  116767. ** cause any problems.
  116768. */
  116769. nField = pRec->nField;
  116770. iCol = 0;
  116771. iSample = pIdx->nSample * nField;
  116772. do{
  116773. int iSamp; /* Index in aSample[] of test sample */
  116774. int n; /* Number of fields in test sample */
  116775. iTest = (iMin+iSample)/2;
  116776. iSamp = iTest / nField;
  116777. if( iSamp>0 ){
  116778. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  116779. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  116780. ** fields that is greater than the previous effective sample. */
  116781. for(n=(iTest % nField) + 1; n<nField; n++){
  116782. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  116783. }
  116784. }else{
  116785. n = iTest + 1;
  116786. }
  116787. pRec->nField = n;
  116788. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  116789. if( res<0 ){
  116790. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  116791. iMin = iTest+1;
  116792. }else if( res==0 && n<nField ){
  116793. iLower = aSample[iSamp].anLt[n-1];
  116794. iMin = iTest+1;
  116795. res = -1;
  116796. }else{
  116797. iSample = iTest;
  116798. iCol = n-1;
  116799. }
  116800. }while( res && iMin<iSample );
  116801. i = iSample / nField;
  116802. #ifdef SQLITE_DEBUG
  116803. /* The following assert statements check that the binary search code
  116804. ** above found the right answer. This block serves no purpose other
  116805. ** than to invoke the asserts. */
  116806. if( pParse->db->mallocFailed==0 ){
  116807. if( res==0 ){
  116808. /* If (res==0) is true, then pRec must be equal to sample i. */
  116809. assert( i<pIdx->nSample );
  116810. assert( iCol==nField-1 );
  116811. pRec->nField = nField;
  116812. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  116813. || pParse->db->mallocFailed
  116814. );
  116815. }else{
  116816. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  116817. ** all samples in the aSample[] array, pRec must be smaller than the
  116818. ** (iCol+1) field prefix of sample i. */
  116819. assert( i<=pIdx->nSample && i>=0 );
  116820. pRec->nField = iCol+1;
  116821. assert( i==pIdx->nSample
  116822. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  116823. || pParse->db->mallocFailed );
  116824. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  116825. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  116826. ** be greater than or equal to the (iCol) field prefix of sample i.
  116827. ** If (i>0), then pRec must also be greater than sample (i-1). */
  116828. if( iCol>0 ){
  116829. pRec->nField = iCol;
  116830. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  116831. || pParse->db->mallocFailed );
  116832. }
  116833. if( i>0 ){
  116834. pRec->nField = nField;
  116835. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  116836. || pParse->db->mallocFailed );
  116837. }
  116838. }
  116839. }
  116840. #endif /* ifdef SQLITE_DEBUG */
  116841. if( res==0 ){
  116842. /* Record pRec is equal to sample i */
  116843. assert( iCol==nField-1 );
  116844. aStat[0] = aSample[i].anLt[iCol];
  116845. aStat[1] = aSample[i].anEq[iCol];
  116846. }else{
  116847. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  116848. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  116849. ** is larger than all samples in the array. */
  116850. tRowcnt iUpper, iGap;
  116851. if( i>=pIdx->nSample ){
  116852. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  116853. }else{
  116854. iUpper = aSample[i].anLt[iCol];
  116855. }
  116856. if( iLower>=iUpper ){
  116857. iGap = 0;
  116858. }else{
  116859. iGap = iUpper - iLower;
  116860. }
  116861. if( roundUp ){
  116862. iGap = (iGap*2)/3;
  116863. }else{
  116864. iGap = iGap/3;
  116865. }
  116866. aStat[0] = iLower + iGap;
  116867. aStat[1] = pIdx->aAvgEq[iCol];
  116868. }
  116869. /* Restore the pRec->nField value before returning. */
  116870. pRec->nField = nField;
  116871. return i;
  116872. }
  116873. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  116874. /*
  116875. ** If it is not NULL, pTerm is a term that provides an upper or lower
  116876. ** bound on a range scan. Without considering pTerm, it is estimated
  116877. ** that the scan will visit nNew rows. This function returns the number
  116878. ** estimated to be visited after taking pTerm into account.
  116879. **
  116880. ** If the user explicitly specified a likelihood() value for this term,
  116881. ** then the return value is the likelihood multiplied by the number of
  116882. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  116883. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  116884. */
  116885. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  116886. LogEst nRet = nNew;
  116887. if( pTerm ){
  116888. if( pTerm->truthProb<=0 ){
  116889. nRet += pTerm->truthProb;
  116890. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  116891. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  116892. }
  116893. }
  116894. return nRet;
  116895. }
  116896. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116897. /*
  116898. ** Return the affinity for a single column of an index.
  116899. */
  116900. static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  116901. assert( iCol>=0 && iCol<pIdx->nColumn );
  116902. if( !pIdx->zColAff ){
  116903. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  116904. }
  116905. return pIdx->zColAff[iCol];
  116906. }
  116907. #endif
  116908. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116909. /*
  116910. ** This function is called to estimate the number of rows visited by a
  116911. ** range-scan on a skip-scan index. For example:
  116912. **
  116913. ** CREATE INDEX i1 ON t1(a, b, c);
  116914. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  116915. **
  116916. ** Value pLoop->nOut is currently set to the estimated number of rows
  116917. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  116918. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  116919. ** on the stat4 data for the index. this scan will be peformed multiple
  116920. ** times (once for each (a,b) combination that matches a=?) is dealt with
  116921. ** by the caller.
  116922. **
  116923. ** It does this by scanning through all stat4 samples, comparing values
  116924. ** extracted from pLower and pUpper with the corresponding column in each
  116925. ** sample. If L and U are the number of samples found to be less than or
  116926. ** equal to the values extracted from pLower and pUpper respectively, and
  116927. ** N is the total number of samples, the pLoop->nOut value is adjusted
  116928. ** as follows:
  116929. **
  116930. ** nOut = nOut * ( min(U - L, 1) / N )
  116931. **
  116932. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  116933. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  116934. ** U is set to N.
  116935. **
  116936. ** Normally, this function sets *pbDone to 1 before returning. However,
  116937. ** if no value can be extracted from either pLower or pUpper (and so the
  116938. ** estimate of the number of rows delivered remains unchanged), *pbDone
  116939. ** is left as is.
  116940. **
  116941. ** If an error occurs, an SQLite error code is returned. Otherwise,
  116942. ** SQLITE_OK.
  116943. */
  116944. static int whereRangeSkipScanEst(
  116945. Parse *pParse, /* Parsing & code generating context */
  116946. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  116947. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  116948. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  116949. int *pbDone /* Set to true if at least one expr. value extracted */
  116950. ){
  116951. Index *p = pLoop->u.btree.pIndex;
  116952. int nEq = pLoop->u.btree.nEq;
  116953. sqlite3 *db = pParse->db;
  116954. int nLower = -1;
  116955. int nUpper = p->nSample+1;
  116956. int rc = SQLITE_OK;
  116957. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  116958. CollSeq *pColl;
  116959. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  116960. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  116961. sqlite3_value *pVal = 0; /* Value extracted from record */
  116962. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  116963. if( pLower ){
  116964. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  116965. nLower = 0;
  116966. }
  116967. if( pUpper && rc==SQLITE_OK ){
  116968. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  116969. nUpper = p2 ? 0 : p->nSample;
  116970. }
  116971. if( p1 || p2 ){
  116972. int i;
  116973. int nDiff;
  116974. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  116975. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  116976. if( rc==SQLITE_OK && p1 ){
  116977. int res = sqlite3MemCompare(p1, pVal, pColl);
  116978. if( res>=0 ) nLower++;
  116979. }
  116980. if( rc==SQLITE_OK && p2 ){
  116981. int res = sqlite3MemCompare(p2, pVal, pColl);
  116982. if( res>=0 ) nUpper++;
  116983. }
  116984. }
  116985. nDiff = (nUpper - nLower);
  116986. if( nDiff<=0 ) nDiff = 1;
  116987. /* If there is both an upper and lower bound specified, and the
  116988. ** comparisons indicate that they are close together, use the fallback
  116989. ** method (assume that the scan visits 1/64 of the rows) for estimating
  116990. ** the number of rows visited. Otherwise, estimate the number of rows
  116991. ** using the method described in the header comment for this function. */
  116992. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  116993. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  116994. pLoop->nOut -= nAdjust;
  116995. *pbDone = 1;
  116996. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  116997. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  116998. }
  116999. }else{
  117000. assert( *pbDone==0 );
  117001. }
  117002. sqlite3ValueFree(p1);
  117003. sqlite3ValueFree(p2);
  117004. sqlite3ValueFree(pVal);
  117005. return rc;
  117006. }
  117007. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  117008. /*
  117009. ** This function is used to estimate the number of rows that will be visited
  117010. ** by scanning an index for a range of values. The range may have an upper
  117011. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  117012. ** and lower bounds are represented by pLower and pUpper respectively. For
  117013. ** example, assuming that index p is on t1(a):
  117014. **
  117015. ** ... FROM t1 WHERE a > ? AND a < ? ...
  117016. ** |_____| |_____|
  117017. ** | |
  117018. ** pLower pUpper
  117019. **
  117020. ** If either of the upper or lower bound is not present, then NULL is passed in
  117021. ** place of the corresponding WhereTerm.
  117022. **
  117023. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  117024. ** column subject to the range constraint. Or, equivalently, the number of
  117025. ** equality constraints optimized by the proposed index scan. For example,
  117026. ** assuming index p is on t1(a, b), and the SQL query is:
  117027. **
  117028. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  117029. **
  117030. ** then nEq is set to 1 (as the range restricted column, b, is the second
  117031. ** left-most column of the index). Or, if the query is:
  117032. **
  117033. ** ... FROM t1 WHERE a > ? AND a < ? ...
  117034. **
  117035. ** then nEq is set to 0.
  117036. **
  117037. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  117038. ** number of rows that the index scan is expected to visit without
  117039. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  117040. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  117041. ** to account for the range constraints pLower and pUpper.
  117042. **
  117043. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  117044. ** used, a single range inequality reduces the search space by a factor of 4.
  117045. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  117046. ** rows visited by a factor of 64.
  117047. */
  117048. static int whereRangeScanEst(
  117049. Parse *pParse, /* Parsing & code generating context */
  117050. WhereLoopBuilder *pBuilder,
  117051. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  117052. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  117053. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  117054. ){
  117055. int rc = SQLITE_OK;
  117056. int nOut = pLoop->nOut;
  117057. LogEst nNew;
  117058. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117059. Index *p = pLoop->u.btree.pIndex;
  117060. int nEq = pLoop->u.btree.nEq;
  117061. if( p->nSample>0 && nEq<p->nSampleCol ){
  117062. if( nEq==pBuilder->nRecValid ){
  117063. UnpackedRecord *pRec = pBuilder->pRec;
  117064. tRowcnt a[2];
  117065. u8 aff;
  117066. /* Variable iLower will be set to the estimate of the number of rows in
  117067. ** the index that are less than the lower bound of the range query. The
  117068. ** lower bound being the concatenation of $P and $L, where $P is the
  117069. ** key-prefix formed by the nEq values matched against the nEq left-most
  117070. ** columns of the index, and $L is the value in pLower.
  117071. **
  117072. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  117073. ** is not a simple variable or literal value), the lower bound of the
  117074. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  117075. ** if $L is available, whereKeyStats() is called for both ($P) and
  117076. ** ($P:$L) and the larger of the two returned values is used.
  117077. **
  117078. ** Similarly, iUpper is to be set to the estimate of the number of rows
  117079. ** less than the upper bound of the range query. Where the upper bound
  117080. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  117081. ** of iUpper are requested of whereKeyStats() and the smaller used.
  117082. **
  117083. ** The number of rows between the two bounds is then just iUpper-iLower.
  117084. */
  117085. tRowcnt iLower; /* Rows less than the lower bound */
  117086. tRowcnt iUpper; /* Rows less than the upper bound */
  117087. int iLwrIdx = -2; /* aSample[] for the lower bound */
  117088. int iUprIdx = -1; /* aSample[] for the upper bound */
  117089. if( pRec ){
  117090. testcase( pRec->nField!=pBuilder->nRecValid );
  117091. pRec->nField = pBuilder->nRecValid;
  117092. }
  117093. aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
  117094. assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
  117095. /* Determine iLower and iUpper using ($P) only. */
  117096. if( nEq==0 ){
  117097. iLower = 0;
  117098. iUpper = p->nRowEst0;
  117099. }else{
  117100. /* Note: this call could be optimized away - since the same values must
  117101. ** have been requested when testing key $P in whereEqualScanEst(). */
  117102. whereKeyStats(pParse, p, pRec, 0, a);
  117103. iLower = a[0];
  117104. iUpper = a[0] + a[1];
  117105. }
  117106. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  117107. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  117108. assert( p->aSortOrder!=0 );
  117109. if( p->aSortOrder[nEq] ){
  117110. /* The roles of pLower and pUpper are swapped for a DESC index */
  117111. SWAP(WhereTerm*, pLower, pUpper);
  117112. }
  117113. /* If possible, improve on the iLower estimate using ($P:$L). */
  117114. if( pLower ){
  117115. int bOk; /* True if value is extracted from pExpr */
  117116. Expr *pExpr = pLower->pExpr->pRight;
  117117. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  117118. if( rc==SQLITE_OK && bOk ){
  117119. tRowcnt iNew;
  117120. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  117121. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  117122. if( iNew>iLower ) iLower = iNew;
  117123. nOut--;
  117124. pLower = 0;
  117125. }
  117126. }
  117127. /* If possible, improve on the iUpper estimate using ($P:$U). */
  117128. if( pUpper ){
  117129. int bOk; /* True if value is extracted from pExpr */
  117130. Expr *pExpr = pUpper->pExpr->pRight;
  117131. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  117132. if( rc==SQLITE_OK && bOk ){
  117133. tRowcnt iNew;
  117134. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  117135. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  117136. if( iNew<iUpper ) iUpper = iNew;
  117137. nOut--;
  117138. pUpper = 0;
  117139. }
  117140. }
  117141. pBuilder->pRec = pRec;
  117142. if( rc==SQLITE_OK ){
  117143. if( iUpper>iLower ){
  117144. nNew = sqlite3LogEst(iUpper - iLower);
  117145. /* TUNING: If both iUpper and iLower are derived from the same
  117146. ** sample, then assume they are 4x more selective. This brings
  117147. ** the estimated selectivity more in line with what it would be
  117148. ** if estimated without the use of STAT3/4 tables. */
  117149. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  117150. }else{
  117151. nNew = 10; assert( 10==sqlite3LogEst(2) );
  117152. }
  117153. if( nNew<nOut ){
  117154. nOut = nNew;
  117155. }
  117156. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  117157. (u32)iLower, (u32)iUpper, nOut));
  117158. }
  117159. }else{
  117160. int bDone = 0;
  117161. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  117162. if( bDone ) return rc;
  117163. }
  117164. }
  117165. #else
  117166. UNUSED_PARAMETER(pParse);
  117167. UNUSED_PARAMETER(pBuilder);
  117168. assert( pLower || pUpper );
  117169. #endif
  117170. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  117171. nNew = whereRangeAdjust(pLower, nOut);
  117172. nNew = whereRangeAdjust(pUpper, nNew);
  117173. /* TUNING: If there is both an upper and lower limit and neither limit
  117174. ** has an application-defined likelihood(), assume the range is
  117175. ** reduced by an additional 75%. This means that, by default, an open-ended
  117176. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  117177. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  117178. ** match 1/64 of the index. */
  117179. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  117180. nNew -= 20;
  117181. }
  117182. nOut -= (pLower!=0) + (pUpper!=0);
  117183. if( nNew<10 ) nNew = 10;
  117184. if( nNew<nOut ) nOut = nNew;
  117185. #if defined(WHERETRACE_ENABLED)
  117186. if( pLoop->nOut>nOut ){
  117187. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  117188. pLoop->nOut, nOut));
  117189. }
  117190. #endif
  117191. pLoop->nOut = (LogEst)nOut;
  117192. return rc;
  117193. }
  117194. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117195. /*
  117196. ** Estimate the number of rows that will be returned based on
  117197. ** an equality constraint x=VALUE and where that VALUE occurs in
  117198. ** the histogram data. This only works when x is the left-most
  117199. ** column of an index and sqlite_stat3 histogram data is available
  117200. ** for that index. When pExpr==NULL that means the constraint is
  117201. ** "x IS NULL" instead of "x=VALUE".
  117202. **
  117203. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  117204. ** If unable to make an estimate, leave *pnRow unchanged and return
  117205. ** non-zero.
  117206. **
  117207. ** This routine can fail if it is unable to load a collating sequence
  117208. ** required for string comparison, or if unable to allocate memory
  117209. ** for a UTF conversion required for comparison. The error is stored
  117210. ** in the pParse structure.
  117211. */
  117212. static int whereEqualScanEst(
  117213. Parse *pParse, /* Parsing & code generating context */
  117214. WhereLoopBuilder *pBuilder,
  117215. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  117216. tRowcnt *pnRow /* Write the revised row estimate here */
  117217. ){
  117218. Index *p = pBuilder->pNew->u.btree.pIndex;
  117219. int nEq = pBuilder->pNew->u.btree.nEq;
  117220. UnpackedRecord *pRec = pBuilder->pRec;
  117221. u8 aff; /* Column affinity */
  117222. int rc; /* Subfunction return code */
  117223. tRowcnt a[2]; /* Statistics */
  117224. int bOk;
  117225. assert( nEq>=1 );
  117226. assert( nEq<=p->nColumn );
  117227. assert( p->aSample!=0 );
  117228. assert( p->nSample>0 );
  117229. assert( pBuilder->nRecValid<nEq );
  117230. /* If values are not available for all fields of the index to the left
  117231. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  117232. if( pBuilder->nRecValid<(nEq-1) ){
  117233. return SQLITE_NOTFOUND;
  117234. }
  117235. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  117236. ** below would return the same value. */
  117237. if( nEq>=p->nColumn ){
  117238. *pnRow = 1;
  117239. return SQLITE_OK;
  117240. }
  117241. aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
  117242. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  117243. pBuilder->pRec = pRec;
  117244. if( rc!=SQLITE_OK ) return rc;
  117245. if( bOk==0 ) return SQLITE_NOTFOUND;
  117246. pBuilder->nRecValid = nEq;
  117247. whereKeyStats(pParse, p, pRec, 0, a);
  117248. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  117249. p->zName, nEq-1, (int)a[1]));
  117250. *pnRow = a[1];
  117251. return rc;
  117252. }
  117253. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  117254. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117255. /*
  117256. ** Estimate the number of rows that will be returned based on
  117257. ** an IN constraint where the right-hand side of the IN operator
  117258. ** is a list of values. Example:
  117259. **
  117260. ** WHERE x IN (1,2,3,4)
  117261. **
  117262. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  117263. ** If unable to make an estimate, leave *pnRow unchanged and return
  117264. ** non-zero.
  117265. **
  117266. ** This routine can fail if it is unable to load a collating sequence
  117267. ** required for string comparison, or if unable to allocate memory
  117268. ** for a UTF conversion required for comparison. The error is stored
  117269. ** in the pParse structure.
  117270. */
  117271. static int whereInScanEst(
  117272. Parse *pParse, /* Parsing & code generating context */
  117273. WhereLoopBuilder *pBuilder,
  117274. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  117275. tRowcnt *pnRow /* Write the revised row estimate here */
  117276. ){
  117277. Index *p = pBuilder->pNew->u.btree.pIndex;
  117278. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  117279. int nRecValid = pBuilder->nRecValid;
  117280. int rc = SQLITE_OK; /* Subfunction return code */
  117281. tRowcnt nEst; /* Number of rows for a single term */
  117282. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  117283. int i; /* Loop counter */
  117284. assert( p->aSample!=0 );
  117285. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  117286. nEst = nRow0;
  117287. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  117288. nRowEst += nEst;
  117289. pBuilder->nRecValid = nRecValid;
  117290. }
  117291. if( rc==SQLITE_OK ){
  117292. if( nRowEst > nRow0 ) nRowEst = nRow0;
  117293. *pnRow = nRowEst;
  117294. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  117295. }
  117296. assert( pBuilder->nRecValid==nRecValid );
  117297. return rc;
  117298. }
  117299. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  117300. #ifdef WHERETRACE_ENABLED
  117301. /*
  117302. ** Print the content of a WhereTerm object
  117303. */
  117304. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  117305. if( pTerm==0 ){
  117306. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  117307. }else{
  117308. char zType[4];
  117309. memcpy(zType, "...", 4);
  117310. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  117311. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  117312. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  117313. sqlite3DebugPrintf(
  117314. "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
  117315. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  117316. pTerm->eOperator, pTerm->wtFlags);
  117317. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  117318. }
  117319. }
  117320. #endif
  117321. #ifdef WHERETRACE_ENABLED
  117322. /*
  117323. ** Print a WhereLoop object for debugging purposes
  117324. */
  117325. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  117326. WhereInfo *pWInfo = pWC->pWInfo;
  117327. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  117328. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  117329. Table *pTab = pItem->pTab;
  117330. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  117331. p->iTab, nb, p->maskSelf, nb, p->prereq);
  117332. sqlite3DebugPrintf(" %12s",
  117333. pItem->zAlias ? pItem->zAlias : pTab->zName);
  117334. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  117335. const char *zName;
  117336. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  117337. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  117338. int i = sqlite3Strlen30(zName) - 1;
  117339. while( zName[i]!='_' ) i--;
  117340. zName += i;
  117341. }
  117342. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  117343. }else{
  117344. sqlite3DebugPrintf("%20s","");
  117345. }
  117346. }else{
  117347. char *z;
  117348. if( p->u.vtab.idxStr ){
  117349. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  117350. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  117351. }else{
  117352. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  117353. }
  117354. sqlite3DebugPrintf(" %-19s", z);
  117355. sqlite3_free(z);
  117356. }
  117357. if( p->wsFlags & WHERE_SKIPSCAN ){
  117358. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  117359. }else{
  117360. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  117361. }
  117362. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  117363. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  117364. int i;
  117365. for(i=0; i<p->nLTerm; i++){
  117366. whereTermPrint(p->aLTerm[i], i);
  117367. }
  117368. }
  117369. }
  117370. #endif
  117371. /*
  117372. ** Convert bulk memory into a valid WhereLoop that can be passed
  117373. ** to whereLoopClear harmlessly.
  117374. */
  117375. static void whereLoopInit(WhereLoop *p){
  117376. p->aLTerm = p->aLTermSpace;
  117377. p->nLTerm = 0;
  117378. p->nLSlot = ArraySize(p->aLTermSpace);
  117379. p->wsFlags = 0;
  117380. }
  117381. /*
  117382. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  117383. */
  117384. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  117385. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  117386. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  117387. sqlite3_free(p->u.vtab.idxStr);
  117388. p->u.vtab.needFree = 0;
  117389. p->u.vtab.idxStr = 0;
  117390. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  117391. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  117392. sqlite3DbFree(db, p->u.btree.pIndex);
  117393. p->u.btree.pIndex = 0;
  117394. }
  117395. }
  117396. }
  117397. /*
  117398. ** Deallocate internal memory used by a WhereLoop object
  117399. */
  117400. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  117401. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  117402. whereLoopClearUnion(db, p);
  117403. whereLoopInit(p);
  117404. }
  117405. /*
  117406. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  117407. */
  117408. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  117409. WhereTerm **paNew;
  117410. if( p->nLSlot>=n ) return SQLITE_OK;
  117411. n = (n+7)&~7;
  117412. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  117413. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  117414. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  117415. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  117416. p->aLTerm = paNew;
  117417. p->nLSlot = n;
  117418. return SQLITE_OK;
  117419. }
  117420. /*
  117421. ** Transfer content from the second pLoop into the first.
  117422. */
  117423. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  117424. whereLoopClearUnion(db, pTo);
  117425. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  117426. memset(&pTo->u, 0, sizeof(pTo->u));
  117427. return SQLITE_NOMEM_BKPT;
  117428. }
  117429. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  117430. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  117431. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  117432. pFrom->u.vtab.needFree = 0;
  117433. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  117434. pFrom->u.btree.pIndex = 0;
  117435. }
  117436. return SQLITE_OK;
  117437. }
  117438. /*
  117439. ** Delete a WhereLoop object
  117440. */
  117441. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  117442. whereLoopClear(db, p);
  117443. sqlite3DbFree(db, p);
  117444. }
  117445. /*
  117446. ** Free a WhereInfo structure
  117447. */
  117448. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  117449. if( ALWAYS(pWInfo) ){
  117450. int i;
  117451. for(i=0; i<pWInfo->nLevel; i++){
  117452. WhereLevel *pLevel = &pWInfo->a[i];
  117453. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  117454. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  117455. }
  117456. }
  117457. sqlite3WhereClauseClear(&pWInfo->sWC);
  117458. while( pWInfo->pLoops ){
  117459. WhereLoop *p = pWInfo->pLoops;
  117460. pWInfo->pLoops = p->pNextLoop;
  117461. whereLoopDelete(db, p);
  117462. }
  117463. sqlite3DbFree(db, pWInfo);
  117464. }
  117465. }
  117466. /*
  117467. ** Return TRUE if all of the following are true:
  117468. **
  117469. ** (1) X has the same or lower cost that Y
  117470. ** (2) X is a proper subset of Y
  117471. ** (3) X skips at least as many columns as Y
  117472. **
  117473. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  117474. ** than Y and that every WHERE clause term used by X is also used
  117475. ** by Y.
  117476. **
  117477. ** If X is a proper subset of Y then Y is a better choice and ought
  117478. ** to have a lower cost. This routine returns TRUE when that cost
  117479. ** relationship is inverted and needs to be adjusted. The third rule
  117480. ** was added because if X uses skip-scan less than Y it still might
  117481. ** deserve a lower cost even if it is a proper subset of Y.
  117482. */
  117483. static int whereLoopCheaperProperSubset(
  117484. const WhereLoop *pX, /* First WhereLoop to compare */
  117485. const WhereLoop *pY /* Compare against this WhereLoop */
  117486. ){
  117487. int i, j;
  117488. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  117489. return 0; /* X is not a subset of Y */
  117490. }
  117491. if( pY->nSkip > pX->nSkip ) return 0;
  117492. if( pX->rRun >= pY->rRun ){
  117493. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  117494. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  117495. }
  117496. for(i=pX->nLTerm-1; i>=0; i--){
  117497. if( pX->aLTerm[i]==0 ) continue;
  117498. for(j=pY->nLTerm-1; j>=0; j--){
  117499. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  117500. }
  117501. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  117502. }
  117503. return 1; /* All conditions meet */
  117504. }
  117505. /*
  117506. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  117507. ** that:
  117508. **
  117509. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  117510. ** subset of pTemplate
  117511. **
  117512. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  117513. ** is a proper subset.
  117514. **
  117515. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  117516. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  117517. ** also used by Y.
  117518. */
  117519. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  117520. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  117521. for(; p; p=p->pNextLoop){
  117522. if( p->iTab!=pTemplate->iTab ) continue;
  117523. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  117524. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  117525. /* Adjust pTemplate cost downward so that it is cheaper than its
  117526. ** subset p. */
  117527. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  117528. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  117529. pTemplate->rRun = p->rRun;
  117530. pTemplate->nOut = p->nOut - 1;
  117531. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  117532. /* Adjust pTemplate cost upward so that it is costlier than p since
  117533. ** pTemplate is a proper subset of p */
  117534. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  117535. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  117536. pTemplate->rRun = p->rRun;
  117537. pTemplate->nOut = p->nOut + 1;
  117538. }
  117539. }
  117540. }
  117541. /*
  117542. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  117543. ** supplanted by pTemplate.
  117544. **
  117545. ** Return NULL if the WhereLoop list contains an entry that can supplant
  117546. ** pTemplate, in other words if pTemplate does not belong on the list.
  117547. **
  117548. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  117549. ** link that points to pX.
  117550. **
  117551. ** If pTemplate cannot supplant any existing element of the list but needs
  117552. ** to be added to the list, then return a pointer to the tail of the list.
  117553. */
  117554. static WhereLoop **whereLoopFindLesser(
  117555. WhereLoop **ppPrev,
  117556. const WhereLoop *pTemplate
  117557. ){
  117558. WhereLoop *p;
  117559. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  117560. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  117561. /* If either the iTab or iSortIdx values for two WhereLoop are different
  117562. ** then those WhereLoops need to be considered separately. Neither is
  117563. ** a candidate to replace the other. */
  117564. continue;
  117565. }
  117566. /* In the current implementation, the rSetup value is either zero
  117567. ** or the cost of building an automatic index (NlogN) and the NlogN
  117568. ** is the same for compatible WhereLoops. */
  117569. assert( p->rSetup==0 || pTemplate->rSetup==0
  117570. || p->rSetup==pTemplate->rSetup );
  117571. /* whereLoopAddBtree() always generates and inserts the automatic index
  117572. ** case first. Hence compatible candidate WhereLoops never have a larger
  117573. ** rSetup. Call this SETUP-INVARIANT */
  117574. assert( p->rSetup>=pTemplate->rSetup );
  117575. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  117576. ** UNIQUE constraint) with one or more == constraints is better
  117577. ** than an automatic index. Unless it is a skip-scan. */
  117578. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  117579. && (pTemplate->nSkip)==0
  117580. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  117581. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  117582. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  117583. ){
  117584. break;
  117585. }
  117586. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  117587. ** discarded. WhereLoop p is better if:
  117588. ** (1) p has no more dependencies than pTemplate, and
  117589. ** (2) p has an equal or lower cost than pTemplate
  117590. */
  117591. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  117592. && p->rSetup<=pTemplate->rSetup /* (2a) */
  117593. && p->rRun<=pTemplate->rRun /* (2b) */
  117594. && p->nOut<=pTemplate->nOut /* (2c) */
  117595. ){
  117596. return 0; /* Discard pTemplate */
  117597. }
  117598. /* If pTemplate is always better than p, then cause p to be overwritten
  117599. ** with pTemplate. pTemplate is better than p if:
  117600. ** (1) pTemplate has no more dependences than p, and
  117601. ** (2) pTemplate has an equal or lower cost than p.
  117602. */
  117603. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  117604. && p->rRun>=pTemplate->rRun /* (2a) */
  117605. && p->nOut>=pTemplate->nOut /* (2b) */
  117606. ){
  117607. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  117608. break; /* Cause p to be overwritten by pTemplate */
  117609. }
  117610. }
  117611. return ppPrev;
  117612. }
  117613. /*
  117614. ** Insert or replace a WhereLoop entry using the template supplied.
  117615. **
  117616. ** An existing WhereLoop entry might be overwritten if the new template
  117617. ** is better and has fewer dependencies. Or the template will be ignored
  117618. ** and no insert will occur if an existing WhereLoop is faster and has
  117619. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  117620. ** added based on the template.
  117621. **
  117622. ** If pBuilder->pOrSet is not NULL then we care about only the
  117623. ** prerequisites and rRun and nOut costs of the N best loops. That
  117624. ** information is gathered in the pBuilder->pOrSet object. This special
  117625. ** processing mode is used only for OR clause processing.
  117626. **
  117627. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  117628. ** still might overwrite similar loops with the new template if the
  117629. ** new template is better. Loops may be overwritten if the following
  117630. ** conditions are met:
  117631. **
  117632. ** (1) They have the same iTab.
  117633. ** (2) They have the same iSortIdx.
  117634. ** (3) The template has same or fewer dependencies than the current loop
  117635. ** (4) The template has the same or lower cost than the current loop
  117636. */
  117637. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  117638. WhereLoop **ppPrev, *p;
  117639. WhereInfo *pWInfo = pBuilder->pWInfo;
  117640. sqlite3 *db = pWInfo->pParse->db;
  117641. int rc;
  117642. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  117643. ** and prereqs.
  117644. */
  117645. if( pBuilder->pOrSet!=0 ){
  117646. if( pTemplate->nLTerm ){
  117647. #if WHERETRACE_ENABLED
  117648. u16 n = pBuilder->pOrSet->n;
  117649. int x =
  117650. #endif
  117651. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  117652. pTemplate->nOut);
  117653. #if WHERETRACE_ENABLED /* 0x8 */
  117654. if( sqlite3WhereTrace & 0x8 ){
  117655. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  117656. whereLoopPrint(pTemplate, pBuilder->pWC);
  117657. }
  117658. #endif
  117659. }
  117660. return SQLITE_OK;
  117661. }
  117662. /* Look for an existing WhereLoop to replace with pTemplate
  117663. */
  117664. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  117665. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  117666. if( ppPrev==0 ){
  117667. /* There already exists a WhereLoop on the list that is better
  117668. ** than pTemplate, so just ignore pTemplate */
  117669. #if WHERETRACE_ENABLED /* 0x8 */
  117670. if( sqlite3WhereTrace & 0x8 ){
  117671. sqlite3DebugPrintf(" skip: ");
  117672. whereLoopPrint(pTemplate, pBuilder->pWC);
  117673. }
  117674. #endif
  117675. return SQLITE_OK;
  117676. }else{
  117677. p = *ppPrev;
  117678. }
  117679. /* If we reach this point it means that either p[] should be overwritten
  117680. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  117681. ** WhereLoop and insert it.
  117682. */
  117683. #if WHERETRACE_ENABLED /* 0x8 */
  117684. if( sqlite3WhereTrace & 0x8 ){
  117685. if( p!=0 ){
  117686. sqlite3DebugPrintf("replace: ");
  117687. whereLoopPrint(p, pBuilder->pWC);
  117688. }
  117689. sqlite3DebugPrintf(" add: ");
  117690. whereLoopPrint(pTemplate, pBuilder->pWC);
  117691. }
  117692. #endif
  117693. if( p==0 ){
  117694. /* Allocate a new WhereLoop to add to the end of the list */
  117695. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  117696. if( p==0 ) return SQLITE_NOMEM_BKPT;
  117697. whereLoopInit(p);
  117698. p->pNextLoop = 0;
  117699. }else{
  117700. /* We will be overwriting WhereLoop p[]. But before we do, first
  117701. ** go through the rest of the list and delete any other entries besides
  117702. ** p[] that are also supplated by pTemplate */
  117703. WhereLoop **ppTail = &p->pNextLoop;
  117704. WhereLoop *pToDel;
  117705. while( *ppTail ){
  117706. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  117707. if( ppTail==0 ) break;
  117708. pToDel = *ppTail;
  117709. if( pToDel==0 ) break;
  117710. *ppTail = pToDel->pNextLoop;
  117711. #if WHERETRACE_ENABLED /* 0x8 */
  117712. if( sqlite3WhereTrace & 0x8 ){
  117713. sqlite3DebugPrintf(" delete: ");
  117714. whereLoopPrint(pToDel, pBuilder->pWC);
  117715. }
  117716. #endif
  117717. whereLoopDelete(db, pToDel);
  117718. }
  117719. }
  117720. rc = whereLoopXfer(db, p, pTemplate);
  117721. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  117722. Index *pIndex = p->u.btree.pIndex;
  117723. if( pIndex && pIndex->tnum==0 ){
  117724. p->u.btree.pIndex = 0;
  117725. }
  117726. }
  117727. return rc;
  117728. }
  117729. /*
  117730. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  117731. ** WHERE clause that reference the loop but which are not used by an
  117732. ** index.
  117733. *
  117734. ** For every WHERE clause term that is not used by the index
  117735. ** and which has a truth probability assigned by one of the likelihood(),
  117736. ** likely(), or unlikely() SQL functions, reduce the estimated number
  117737. ** of output rows by the probability specified.
  117738. **
  117739. ** TUNING: For every WHERE clause term that is not used by the index
  117740. ** and which does not have an assigned truth probability, heuristics
  117741. ** described below are used to try to estimate the truth probability.
  117742. ** TODO --> Perhaps this is something that could be improved by better
  117743. ** table statistics.
  117744. **
  117745. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  117746. ** value corresponds to -1 in LogEst notation, so this means decrement
  117747. ** the WhereLoop.nOut field for every such WHERE clause term.
  117748. **
  117749. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  117750. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  117751. ** final output row estimate is no greater than 1/4 of the total number
  117752. ** of rows in the table. In other words, assume that x==EXPR will filter
  117753. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  117754. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  117755. ** on the "x" column and so in that case only cap the output row estimate
  117756. ** at 1/2 instead of 1/4.
  117757. */
  117758. static void whereLoopOutputAdjust(
  117759. WhereClause *pWC, /* The WHERE clause */
  117760. WhereLoop *pLoop, /* The loop to adjust downward */
  117761. LogEst nRow /* Number of rows in the entire table */
  117762. ){
  117763. WhereTerm *pTerm, *pX;
  117764. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  117765. int i, j, k;
  117766. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  117767. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  117768. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  117769. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  117770. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  117771. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  117772. for(j=pLoop->nLTerm-1; j>=0; j--){
  117773. pX = pLoop->aLTerm[j];
  117774. if( pX==0 ) continue;
  117775. if( pX==pTerm ) break;
  117776. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  117777. }
  117778. if( j<0 ){
  117779. if( pTerm->truthProb<=0 ){
  117780. /* If a truth probability is specified using the likelihood() hints,
  117781. ** then use the probability provided by the application. */
  117782. pLoop->nOut += pTerm->truthProb;
  117783. }else{
  117784. /* In the absence of explicit truth probabilities, use heuristics to
  117785. ** guess a reasonable truth probability. */
  117786. pLoop->nOut--;
  117787. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  117788. Expr *pRight = pTerm->pExpr->pRight;
  117789. testcase( pTerm->pExpr->op==TK_IS );
  117790. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  117791. k = 10;
  117792. }else{
  117793. k = 20;
  117794. }
  117795. if( iReduce<k ) iReduce = k;
  117796. }
  117797. }
  117798. }
  117799. }
  117800. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  117801. }
  117802. /*
  117803. ** Adjust the cost C by the costMult facter T. This only occurs if
  117804. ** compiled with -DSQLITE_ENABLE_COSTMULT
  117805. */
  117806. #ifdef SQLITE_ENABLE_COSTMULT
  117807. # define ApplyCostMultiplier(C,T) C += T
  117808. #else
  117809. # define ApplyCostMultiplier(C,T)
  117810. #endif
  117811. /*
  117812. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  117813. ** index pIndex. Try to match one more.
  117814. **
  117815. ** When this function is called, pBuilder->pNew->nOut contains the
  117816. ** number of rows expected to be visited by filtering using the nEq
  117817. ** terms only. If it is modified, this value is restored before this
  117818. ** function returns.
  117819. **
  117820. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  117821. ** INTEGER PRIMARY KEY.
  117822. */
  117823. static int whereLoopAddBtreeIndex(
  117824. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  117825. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  117826. Index *pProbe, /* An index on pSrc */
  117827. LogEst nInMul /* log(Number of iterations due to IN) */
  117828. ){
  117829. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  117830. Parse *pParse = pWInfo->pParse; /* Parsing context */
  117831. sqlite3 *db = pParse->db; /* Database connection malloc context */
  117832. WhereLoop *pNew; /* Template WhereLoop under construction */
  117833. WhereTerm *pTerm; /* A WhereTerm under consideration */
  117834. int opMask; /* Valid operators for constraints */
  117835. WhereScan scan; /* Iterator for WHERE terms */
  117836. Bitmask saved_prereq; /* Original value of pNew->prereq */
  117837. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  117838. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  117839. u16 saved_nSkip; /* Original value of pNew->nSkip */
  117840. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  117841. LogEst saved_nOut; /* Original value of pNew->nOut */
  117842. int rc = SQLITE_OK; /* Return code */
  117843. LogEst rSize; /* Number of rows in the table */
  117844. LogEst rLogSize; /* Logarithm of table size */
  117845. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  117846. pNew = pBuilder->pNew;
  117847. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  117848. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  117849. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  117850. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  117851. opMask = WO_LT|WO_LE;
  117852. }else{
  117853. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  117854. }
  117855. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  117856. assert( pNew->u.btree.nEq<pProbe->nColumn );
  117857. saved_nEq = pNew->u.btree.nEq;
  117858. saved_nSkip = pNew->nSkip;
  117859. saved_nLTerm = pNew->nLTerm;
  117860. saved_wsFlags = pNew->wsFlags;
  117861. saved_prereq = pNew->prereq;
  117862. saved_nOut = pNew->nOut;
  117863. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  117864. opMask, pProbe);
  117865. pNew->rSetup = 0;
  117866. rSize = pProbe->aiRowLogEst[0];
  117867. rLogSize = estLog(rSize);
  117868. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  117869. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  117870. LogEst rCostIdx;
  117871. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  117872. int nIn = 0;
  117873. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117874. int nRecValid = pBuilder->nRecValid;
  117875. #endif
  117876. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  117877. && indexColumnNotNull(pProbe, saved_nEq)
  117878. ){
  117879. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  117880. }
  117881. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  117882. /* Do not allow the upper bound of a LIKE optimization range constraint
  117883. ** to mix with a lower range bound from some other source */
  117884. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  117885. /* Do not allow IS constraints from the WHERE clause to be used by the
  117886. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  117887. ** allowed */
  117888. if( (pSrc->fg.jointype & JT_LEFT)!=0
  117889. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  117890. && (eOp & (WO_IS|WO_ISNULL))!=0
  117891. ){
  117892. testcase( eOp & WO_IS );
  117893. testcase( eOp & WO_ISNULL );
  117894. continue;
  117895. }
  117896. pNew->wsFlags = saved_wsFlags;
  117897. pNew->u.btree.nEq = saved_nEq;
  117898. pNew->nLTerm = saved_nLTerm;
  117899. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  117900. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  117901. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  117902. assert( nInMul==0
  117903. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  117904. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  117905. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  117906. );
  117907. if( eOp & WO_IN ){
  117908. Expr *pExpr = pTerm->pExpr;
  117909. pNew->wsFlags |= WHERE_COLUMN_IN;
  117910. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  117911. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  117912. nIn = 46; assert( 46==sqlite3LogEst(25) );
  117913. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  117914. /* "x IN (value, value, ...)" */
  117915. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  117916. }
  117917. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  117918. ** changes "x IN (?)" into "x=?". */
  117919. }else if( eOp & (WO_EQ|WO_IS) ){
  117920. int iCol = pProbe->aiColumn[saved_nEq];
  117921. pNew->wsFlags |= WHERE_COLUMN_EQ;
  117922. assert( saved_nEq==pNew->u.btree.nEq );
  117923. if( iCol==XN_ROWID
  117924. || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  117925. ){
  117926. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  117927. pNew->wsFlags |= WHERE_UNQ_WANTED;
  117928. }else{
  117929. pNew->wsFlags |= WHERE_ONEROW;
  117930. }
  117931. }
  117932. }else if( eOp & WO_ISNULL ){
  117933. pNew->wsFlags |= WHERE_COLUMN_NULL;
  117934. }else if( eOp & (WO_GT|WO_GE) ){
  117935. testcase( eOp & WO_GT );
  117936. testcase( eOp & WO_GE );
  117937. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  117938. pBtm = pTerm;
  117939. pTop = 0;
  117940. if( pTerm->wtFlags & TERM_LIKEOPT ){
  117941. /* Range contraints that come from the LIKE optimization are
  117942. ** always used in pairs. */
  117943. pTop = &pTerm[1];
  117944. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  117945. assert( pTop->wtFlags & TERM_LIKEOPT );
  117946. assert( pTop->eOperator==WO_LT );
  117947. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  117948. pNew->aLTerm[pNew->nLTerm++] = pTop;
  117949. pNew->wsFlags |= WHERE_TOP_LIMIT;
  117950. }
  117951. }else{
  117952. assert( eOp & (WO_LT|WO_LE) );
  117953. testcase( eOp & WO_LT );
  117954. testcase( eOp & WO_LE );
  117955. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  117956. pTop = pTerm;
  117957. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  117958. pNew->aLTerm[pNew->nLTerm-2] : 0;
  117959. }
  117960. /* At this point pNew->nOut is set to the number of rows expected to
  117961. ** be visited by the index scan before considering term pTerm, or the
  117962. ** values of nIn and nInMul. In other words, assuming that all
  117963. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  117964. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  117965. assert( pNew->nOut==saved_nOut );
  117966. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  117967. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  117968. ** data, using some other estimate. */
  117969. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  117970. }else{
  117971. int nEq = ++pNew->u.btree.nEq;
  117972. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  117973. assert( pNew->nOut==saved_nOut );
  117974. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  117975. assert( (eOp & WO_IN) || nIn==0 );
  117976. testcase( eOp & WO_IN );
  117977. pNew->nOut += pTerm->truthProb;
  117978. pNew->nOut -= nIn;
  117979. }else{
  117980. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117981. tRowcnt nOut = 0;
  117982. if( nInMul==0
  117983. && pProbe->nSample
  117984. && pNew->u.btree.nEq<=pProbe->nSampleCol
  117985. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  117986. ){
  117987. Expr *pExpr = pTerm->pExpr;
  117988. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  117989. testcase( eOp & WO_EQ );
  117990. testcase( eOp & WO_IS );
  117991. testcase( eOp & WO_ISNULL );
  117992. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  117993. }else{
  117994. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  117995. }
  117996. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  117997. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  117998. if( nOut ){
  117999. pNew->nOut = sqlite3LogEst(nOut);
  118000. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  118001. pNew->nOut -= nIn;
  118002. }
  118003. }
  118004. if( nOut==0 )
  118005. #endif
  118006. {
  118007. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  118008. if( eOp & WO_ISNULL ){
  118009. /* TUNING: If there is no likelihood() value, assume that a
  118010. ** "col IS NULL" expression matches twice as many rows
  118011. ** as (col=?). */
  118012. pNew->nOut += 10;
  118013. }
  118014. }
  118015. }
  118016. }
  118017. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  118018. ** it to pNew->rRun, which is currently set to the cost of the index
  118019. ** seek only. Then, if this is a non-covering index, add the cost of
  118020. ** visiting the rows in the main table. */
  118021. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  118022. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  118023. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  118024. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  118025. }
  118026. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  118027. nOutUnadjusted = pNew->nOut;
  118028. pNew->rRun += nInMul + nIn;
  118029. pNew->nOut += nInMul + nIn;
  118030. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  118031. rc = whereLoopInsert(pBuilder, pNew);
  118032. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  118033. pNew->nOut = saved_nOut;
  118034. }else{
  118035. pNew->nOut = nOutUnadjusted;
  118036. }
  118037. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  118038. && pNew->u.btree.nEq<pProbe->nColumn
  118039. ){
  118040. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  118041. }
  118042. pNew->nOut = saved_nOut;
  118043. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  118044. pBuilder->nRecValid = nRecValid;
  118045. #endif
  118046. }
  118047. pNew->prereq = saved_prereq;
  118048. pNew->u.btree.nEq = saved_nEq;
  118049. pNew->nSkip = saved_nSkip;
  118050. pNew->wsFlags = saved_wsFlags;
  118051. pNew->nOut = saved_nOut;
  118052. pNew->nLTerm = saved_nLTerm;
  118053. /* Consider using a skip-scan if there are no WHERE clause constraints
  118054. ** available for the left-most terms of the index, and if the average
  118055. ** number of repeats in the left-most terms is at least 18.
  118056. **
  118057. ** The magic number 18 is selected on the basis that scanning 17 rows
  118058. ** is almost always quicker than an index seek (even though if the index
  118059. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  118060. ** the code). And, even if it is not, it should not be too much slower.
  118061. ** On the other hand, the extra seeks could end up being significantly
  118062. ** more expensive. */
  118063. assert( 42==sqlite3LogEst(18) );
  118064. if( saved_nEq==saved_nSkip
  118065. && saved_nEq+1<pProbe->nKeyCol
  118066. && pProbe->noSkipScan==0
  118067. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  118068. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  118069. ){
  118070. LogEst nIter;
  118071. pNew->u.btree.nEq++;
  118072. pNew->nSkip++;
  118073. pNew->aLTerm[pNew->nLTerm++] = 0;
  118074. pNew->wsFlags |= WHERE_SKIPSCAN;
  118075. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  118076. pNew->nOut -= nIter;
  118077. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  118078. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  118079. nIter += 5;
  118080. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  118081. pNew->nOut = saved_nOut;
  118082. pNew->u.btree.nEq = saved_nEq;
  118083. pNew->nSkip = saved_nSkip;
  118084. pNew->wsFlags = saved_wsFlags;
  118085. }
  118086. return rc;
  118087. }
  118088. /*
  118089. ** Return True if it is possible that pIndex might be useful in
  118090. ** implementing the ORDER BY clause in pBuilder.
  118091. **
  118092. ** Return False if pBuilder does not contain an ORDER BY clause or
  118093. ** if there is no way for pIndex to be useful in implementing that
  118094. ** ORDER BY clause.
  118095. */
  118096. static int indexMightHelpWithOrderBy(
  118097. WhereLoopBuilder *pBuilder,
  118098. Index *pIndex,
  118099. int iCursor
  118100. ){
  118101. ExprList *pOB;
  118102. ExprList *aColExpr;
  118103. int ii, jj;
  118104. if( pIndex->bUnordered ) return 0;
  118105. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  118106. for(ii=0; ii<pOB->nExpr; ii++){
  118107. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  118108. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  118109. if( pExpr->iColumn<0 ) return 1;
  118110. for(jj=0; jj<pIndex->nKeyCol; jj++){
  118111. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  118112. }
  118113. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  118114. for(jj=0; jj<pIndex->nKeyCol; jj++){
  118115. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  118116. if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  118117. return 1;
  118118. }
  118119. }
  118120. }
  118121. }
  118122. return 0;
  118123. }
  118124. /*
  118125. ** Return a bitmask where 1s indicate that the corresponding column of
  118126. ** the table is used by an index. Only the first 63 columns are considered.
  118127. */
  118128. static Bitmask columnsInIndex(Index *pIdx){
  118129. Bitmask m = 0;
  118130. int j;
  118131. for(j=pIdx->nColumn-1; j>=0; j--){
  118132. int x = pIdx->aiColumn[j];
  118133. if( x>=0 ){
  118134. testcase( x==BMS-1 );
  118135. testcase( x==BMS-2 );
  118136. if( x<BMS-1 ) m |= MASKBIT(x);
  118137. }
  118138. }
  118139. return m;
  118140. }
  118141. /* Check to see if a partial index with pPartIndexWhere can be used
  118142. ** in the current query. Return true if it can be and false if not.
  118143. */
  118144. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  118145. int i;
  118146. WhereTerm *pTerm;
  118147. while( pWhere->op==TK_AND ){
  118148. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  118149. pWhere = pWhere->pRight;
  118150. }
  118151. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  118152. Expr *pExpr = pTerm->pExpr;
  118153. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  118154. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  118155. ){
  118156. return 1;
  118157. }
  118158. }
  118159. return 0;
  118160. }
  118161. /*
  118162. ** Add all WhereLoop objects for a single table of the join where the table
  118163. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  118164. ** a b-tree table, not a virtual table.
  118165. **
  118166. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  118167. ** are calculated as follows:
  118168. **
  118169. ** For a full scan, assuming the table (or index) contains nRow rows:
  118170. **
  118171. ** cost = nRow * 3.0 // full-table scan
  118172. ** cost = nRow * K // scan of covering index
  118173. ** cost = nRow * (K+3.0) // scan of non-covering index
  118174. **
  118175. ** where K is a value between 1.1 and 3.0 set based on the relative
  118176. ** estimated average size of the index and table records.
  118177. **
  118178. ** For an index scan, where nVisit is the number of index rows visited
  118179. ** by the scan, and nSeek is the number of seek operations required on
  118180. ** the index b-tree:
  118181. **
  118182. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  118183. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  118184. **
  118185. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  118186. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  118187. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  118188. **
  118189. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  118190. ** of uncertainty. For this reason, scoring is designed to pick plans that
  118191. ** "do the least harm" if the estimates are inaccurate. For example, a
  118192. ** log(nRow) factor is omitted from a non-covering index scan in order to
  118193. ** bias the scoring in favor of using an index, since the worst-case
  118194. ** performance of using an index is far better than the worst-case performance
  118195. ** of a full table scan.
  118196. */
  118197. static int whereLoopAddBtree(
  118198. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  118199. Bitmask mPrereq /* Extra prerequesites for using this table */
  118200. ){
  118201. WhereInfo *pWInfo; /* WHERE analysis context */
  118202. Index *pProbe; /* An index we are evaluating */
  118203. Index sPk; /* A fake index object for the primary key */
  118204. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  118205. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  118206. SrcList *pTabList; /* The FROM clause */
  118207. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  118208. WhereLoop *pNew; /* Template WhereLoop object */
  118209. int rc = SQLITE_OK; /* Return code */
  118210. int iSortIdx = 1; /* Index number */
  118211. int b; /* A boolean value */
  118212. LogEst rSize; /* number of rows in the table */
  118213. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  118214. WhereClause *pWC; /* The parsed WHERE clause */
  118215. Table *pTab; /* Table being queried */
  118216. pNew = pBuilder->pNew;
  118217. pWInfo = pBuilder->pWInfo;
  118218. pTabList = pWInfo->pTabList;
  118219. pSrc = pTabList->a + pNew->iTab;
  118220. pTab = pSrc->pTab;
  118221. pWC = pBuilder->pWC;
  118222. assert( !IsVirtual(pSrc->pTab) );
  118223. if( pSrc->pIBIndex ){
  118224. /* An INDEXED BY clause specifies a particular index to use */
  118225. pProbe = pSrc->pIBIndex;
  118226. }else if( !HasRowid(pTab) ){
  118227. pProbe = pTab->pIndex;
  118228. }else{
  118229. /* There is no INDEXED BY clause. Create a fake Index object in local
  118230. ** variable sPk to represent the rowid primary key index. Make this
  118231. ** fake index the first in a chain of Index objects with all of the real
  118232. ** indices to follow */
  118233. Index *pFirst; /* First of real indices on the table */
  118234. memset(&sPk, 0, sizeof(Index));
  118235. sPk.nKeyCol = 1;
  118236. sPk.nColumn = 1;
  118237. sPk.aiColumn = &aiColumnPk;
  118238. sPk.aiRowLogEst = aiRowEstPk;
  118239. sPk.onError = OE_Replace;
  118240. sPk.pTable = pTab;
  118241. sPk.szIdxRow = pTab->szTabRow;
  118242. aiRowEstPk[0] = pTab->nRowLogEst;
  118243. aiRowEstPk[1] = 0;
  118244. pFirst = pSrc->pTab->pIndex;
  118245. if( pSrc->fg.notIndexed==0 ){
  118246. /* The real indices of the table are only considered if the
  118247. ** NOT INDEXED qualifier is omitted from the FROM clause */
  118248. sPk.pNext = pFirst;
  118249. }
  118250. pProbe = &sPk;
  118251. }
  118252. rSize = pTab->nRowLogEst;
  118253. rLogSize = estLog(rSize);
  118254. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  118255. /* Automatic indexes */
  118256. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  118257. && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
  118258. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  118259. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  118260. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  118261. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  118262. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  118263. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  118264. ){
  118265. /* Generate auto-index WhereLoops */
  118266. WhereTerm *pTerm;
  118267. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  118268. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  118269. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  118270. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  118271. pNew->u.btree.nEq = 1;
  118272. pNew->nSkip = 0;
  118273. pNew->u.btree.pIndex = 0;
  118274. pNew->nLTerm = 1;
  118275. pNew->aLTerm[0] = pTerm;
  118276. /* TUNING: One-time cost for computing the automatic index is
  118277. ** estimated to be X*N*log2(N) where N is the number of rows in
  118278. ** the table being indexed and where X is 7 (LogEst=28) for normal
  118279. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  118280. ** of X is smaller for views and subqueries so that the query planner
  118281. ** will be more aggressive about generating automatic indexes for
  118282. ** those objects, since there is no opportunity to add schema
  118283. ** indexes on subqueries and views. */
  118284. pNew->rSetup = rLogSize + rSize + 4;
  118285. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  118286. pNew->rSetup += 24;
  118287. }
  118288. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  118289. /* TUNING: Each index lookup yields 20 rows in the table. This
  118290. ** is more than the usual guess of 10 rows, since we have no way
  118291. ** of knowing how selective the index will ultimately be. It would
  118292. ** not be unreasonable to make this value much larger. */
  118293. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  118294. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  118295. pNew->wsFlags = WHERE_AUTO_INDEX;
  118296. pNew->prereq = mPrereq | pTerm->prereqRight;
  118297. rc = whereLoopInsert(pBuilder, pNew);
  118298. }
  118299. }
  118300. }
  118301. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  118302. /* Loop over all indices
  118303. */
  118304. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  118305. if( pProbe->pPartIdxWhere!=0
  118306. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  118307. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  118308. continue; /* Partial index inappropriate for this query */
  118309. }
  118310. rSize = pProbe->aiRowLogEst[0];
  118311. pNew->u.btree.nEq = 0;
  118312. pNew->nSkip = 0;
  118313. pNew->nLTerm = 0;
  118314. pNew->iSortIdx = 0;
  118315. pNew->rSetup = 0;
  118316. pNew->prereq = mPrereq;
  118317. pNew->nOut = rSize;
  118318. pNew->u.btree.pIndex = pProbe;
  118319. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  118320. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  118321. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  118322. if( pProbe->tnum<=0 ){
  118323. /* Integer primary key index */
  118324. pNew->wsFlags = WHERE_IPK;
  118325. /* Full table scan */
  118326. pNew->iSortIdx = b ? iSortIdx : 0;
  118327. /* TUNING: Cost of full table scan is (N*3.0). */
  118328. pNew->rRun = rSize + 16;
  118329. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  118330. whereLoopOutputAdjust(pWC, pNew, rSize);
  118331. rc = whereLoopInsert(pBuilder, pNew);
  118332. pNew->nOut = rSize;
  118333. if( rc ) break;
  118334. }else{
  118335. Bitmask m;
  118336. if( pProbe->isCovering ){
  118337. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  118338. m = 0;
  118339. }else{
  118340. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  118341. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  118342. }
  118343. /* Full scan via index */
  118344. if( b
  118345. || !HasRowid(pTab)
  118346. || ( m==0
  118347. && pProbe->bUnordered==0
  118348. && (pProbe->szIdxRow<pTab->szTabRow)
  118349. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  118350. && sqlite3GlobalConfig.bUseCis
  118351. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  118352. )
  118353. ){
  118354. pNew->iSortIdx = b ? iSortIdx : 0;
  118355. /* The cost of visiting the index rows is N*K, where K is
  118356. ** between 1.1 and 3.0, depending on the relative sizes of the
  118357. ** index and table rows. If this is a non-covering index scan,
  118358. ** also add the cost of visiting table rows (N*3.0). */
  118359. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  118360. if( m!=0 ){
  118361. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  118362. }
  118363. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  118364. whereLoopOutputAdjust(pWC, pNew, rSize);
  118365. rc = whereLoopInsert(pBuilder, pNew);
  118366. pNew->nOut = rSize;
  118367. if( rc ) break;
  118368. }
  118369. }
  118370. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  118371. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  118372. sqlite3Stat4ProbeFree(pBuilder->pRec);
  118373. pBuilder->nRecValid = 0;
  118374. pBuilder->pRec = 0;
  118375. #endif
  118376. /* If there was an INDEXED BY clause, then only that one index is
  118377. ** considered. */
  118378. if( pSrc->pIBIndex ) break;
  118379. }
  118380. return rc;
  118381. }
  118382. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118383. /*
  118384. ** Argument pIdxInfo is already populated with all constraints that may
  118385. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  118386. ** function marks a subset of those constraints usable, invokes the
  118387. ** xBestIndex method and adds the returned plan to pBuilder.
  118388. **
  118389. ** A constraint is marked usable if:
  118390. **
  118391. ** * Argument mUsable indicates that its prerequisites are available, and
  118392. **
  118393. ** * It is not one of the operators specified in the mExclude mask passed
  118394. ** as the fourth argument (which in practice is either WO_IN or 0).
  118395. **
  118396. ** Argument mPrereq is a mask of tables that must be scanned before the
  118397. ** virtual table in question. These are added to the plans prerequisites
  118398. ** before it is added to pBuilder.
  118399. **
  118400. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  118401. ** uses one or more WO_IN terms, or false otherwise.
  118402. */
  118403. static int whereLoopAddVirtualOne(
  118404. WhereLoopBuilder *pBuilder,
  118405. Bitmask mPrereq, /* Mask of tables that must be used. */
  118406. Bitmask mUsable, /* Mask of usable tables */
  118407. u16 mExclude, /* Exclude terms using these operators */
  118408. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  118409. int *pbIn /* OUT: True if plan uses an IN(...) op */
  118410. ){
  118411. WhereClause *pWC = pBuilder->pWC;
  118412. struct sqlite3_index_constraint *pIdxCons;
  118413. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  118414. int i;
  118415. int mxTerm;
  118416. int rc = SQLITE_OK;
  118417. WhereLoop *pNew = pBuilder->pNew;
  118418. Parse *pParse = pBuilder->pWInfo->pParse;
  118419. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  118420. int nConstraint = pIdxInfo->nConstraint;
  118421. assert( (mUsable & mPrereq)==mPrereq );
  118422. *pbIn = 0;
  118423. pNew->prereq = mPrereq;
  118424. /* Set the usable flag on the subset of constraints identified by
  118425. ** arguments mUsable and mExclude. */
  118426. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  118427. for(i=0; i<nConstraint; i++, pIdxCons++){
  118428. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  118429. pIdxCons->usable = 0;
  118430. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  118431. && (pTerm->eOperator & mExclude)==0
  118432. ){
  118433. pIdxCons->usable = 1;
  118434. }
  118435. }
  118436. /* Initialize the output fields of the sqlite3_index_info structure */
  118437. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  118438. assert( pIdxInfo->needToFreeIdxStr==0 );
  118439. pIdxInfo->idxStr = 0;
  118440. pIdxInfo->idxNum = 0;
  118441. pIdxInfo->orderByConsumed = 0;
  118442. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  118443. pIdxInfo->estimatedRows = 25;
  118444. pIdxInfo->idxFlags = 0;
  118445. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  118446. /* Invoke the virtual table xBestIndex() method */
  118447. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  118448. if( rc ) return rc;
  118449. mxTerm = -1;
  118450. assert( pNew->nLSlot>=nConstraint );
  118451. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  118452. pNew->u.vtab.omitMask = 0;
  118453. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  118454. for(i=0; i<nConstraint; i++, pIdxCons++){
  118455. int iTerm;
  118456. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  118457. WhereTerm *pTerm;
  118458. int j = pIdxCons->iTermOffset;
  118459. if( iTerm>=nConstraint
  118460. || j<0
  118461. || j>=pWC->nTerm
  118462. || pNew->aLTerm[iTerm]!=0
  118463. || pIdxCons->usable==0
  118464. ){
  118465. rc = SQLITE_ERROR;
  118466. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  118467. return rc;
  118468. }
  118469. testcase( iTerm==nConstraint-1 );
  118470. testcase( j==0 );
  118471. testcase( j==pWC->nTerm-1 );
  118472. pTerm = &pWC->a[j];
  118473. pNew->prereq |= pTerm->prereqRight;
  118474. assert( iTerm<pNew->nLSlot );
  118475. pNew->aLTerm[iTerm] = pTerm;
  118476. if( iTerm>mxTerm ) mxTerm = iTerm;
  118477. testcase( iTerm==15 );
  118478. testcase( iTerm==16 );
  118479. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  118480. if( (pTerm->eOperator & WO_IN)!=0 ){
  118481. /* A virtual table that is constrained by an IN clause may not
  118482. ** consume the ORDER BY clause because (1) the order of IN terms
  118483. ** is not necessarily related to the order of output terms and
  118484. ** (2) Multiple outputs from a single IN value will not merge
  118485. ** together. */
  118486. pIdxInfo->orderByConsumed = 0;
  118487. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  118488. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  118489. }
  118490. }
  118491. }
  118492. pNew->nLTerm = mxTerm+1;
  118493. assert( pNew->nLTerm<=pNew->nLSlot );
  118494. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  118495. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  118496. pIdxInfo->needToFreeIdxStr = 0;
  118497. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  118498. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  118499. pIdxInfo->nOrderBy : 0);
  118500. pNew->rSetup = 0;
  118501. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  118502. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  118503. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  118504. ** that the scan will visit at most one row. Clear it otherwise. */
  118505. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  118506. pNew->wsFlags |= WHERE_ONEROW;
  118507. }else{
  118508. pNew->wsFlags &= ~WHERE_ONEROW;
  118509. }
  118510. rc = whereLoopInsert(pBuilder, pNew);
  118511. if( pNew->u.vtab.needFree ){
  118512. sqlite3_free(pNew->u.vtab.idxStr);
  118513. pNew->u.vtab.needFree = 0;
  118514. }
  118515. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  118516. *pbIn, (sqlite3_uint64)mPrereq,
  118517. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  118518. return rc;
  118519. }
  118520. /*
  118521. ** Add all WhereLoop objects for a table of the join identified by
  118522. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  118523. **
  118524. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  118525. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  118526. ** entries that occur before the virtual table in the FROM clause and are
  118527. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  118528. ** mUnusable mask contains all FROM clause entries that occur after the
  118529. ** virtual table and are separated from it by at least one LEFT or
  118530. ** CROSS JOIN.
  118531. **
  118532. ** For example, if the query were:
  118533. **
  118534. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  118535. **
  118536. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  118537. **
  118538. ** All the tables in mPrereq must be scanned before the current virtual
  118539. ** table. So any terms for which all prerequisites are satisfied by
  118540. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  118541. ** Conversely, all tables in mUnusable must be scanned after the current
  118542. ** virtual table, so any terms for which the prerequisites overlap with
  118543. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  118544. */
  118545. static int whereLoopAddVirtual(
  118546. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  118547. Bitmask mPrereq, /* Tables that must be scanned before this one */
  118548. Bitmask mUnusable /* Tables that must be scanned after this one */
  118549. ){
  118550. int rc = SQLITE_OK; /* Return code */
  118551. WhereInfo *pWInfo; /* WHERE analysis context */
  118552. Parse *pParse; /* The parsing context */
  118553. WhereClause *pWC; /* The WHERE clause */
  118554. struct SrcList_item *pSrc; /* The FROM clause term to search */
  118555. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  118556. int nConstraint; /* Number of constraints in p */
  118557. int bIn; /* True if plan uses IN(...) operator */
  118558. WhereLoop *pNew;
  118559. Bitmask mBest; /* Tables used by best possible plan */
  118560. assert( (mPrereq & mUnusable)==0 );
  118561. pWInfo = pBuilder->pWInfo;
  118562. pParse = pWInfo->pParse;
  118563. pWC = pBuilder->pWC;
  118564. pNew = pBuilder->pNew;
  118565. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  118566. assert( IsVirtual(pSrc->pTab) );
  118567. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy);
  118568. if( p==0 ) return SQLITE_NOMEM_BKPT;
  118569. pNew->rSetup = 0;
  118570. pNew->wsFlags = WHERE_VIRTUALTABLE;
  118571. pNew->nLTerm = 0;
  118572. pNew->u.vtab.needFree = 0;
  118573. nConstraint = p->nConstraint;
  118574. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  118575. sqlite3DbFree(pParse->db, p);
  118576. return SQLITE_NOMEM_BKPT;
  118577. }
  118578. /* First call xBestIndex() with all constraints usable. */
  118579. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  118580. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, &bIn);
  118581. /* If the call to xBestIndex() with all terms enabled produced a plan
  118582. ** that does not require any source tables (IOW: a plan with mBest==0),
  118583. ** then there is no point in making any further calls to xBestIndex()
  118584. ** since they will all return the same result (if the xBestIndex()
  118585. ** implementation is sane). */
  118586. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  118587. int seenZero = 0; /* True if a plan with no prereqs seen */
  118588. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  118589. Bitmask mPrev = 0;
  118590. Bitmask mBestNoIn = 0;
  118591. /* If the plan produced by the earlier call uses an IN(...) term, call
  118592. ** xBestIndex again, this time with IN(...) terms disabled. */
  118593. if( bIn ){
  118594. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  118595. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, WO_IN, p, &bIn);
  118596. assert( bIn==0 );
  118597. mBestNoIn = pNew->prereq & ~mPrereq;
  118598. if( mBestNoIn==0 ){
  118599. seenZero = 1;
  118600. seenZeroNoIN = 1;
  118601. }
  118602. }
  118603. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  118604. ** in the set of terms that apply to the current virtual table. */
  118605. while( rc==SQLITE_OK ){
  118606. int i;
  118607. Bitmask mNext = ALLBITS;
  118608. assert( mNext>0 );
  118609. for(i=0; i<nConstraint; i++){
  118610. Bitmask mThis = (
  118611. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  118612. );
  118613. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  118614. }
  118615. mPrev = mNext;
  118616. if( mNext==ALLBITS ) break;
  118617. if( mNext==mBest || mNext==mBestNoIn ) continue;
  118618. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  118619. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  118620. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mNext|mPrereq, 0, p, &bIn);
  118621. if( pNew->prereq==mPrereq ){
  118622. seenZero = 1;
  118623. if( bIn==0 ) seenZeroNoIN = 1;
  118624. }
  118625. }
  118626. /* If the calls to xBestIndex() in the above loop did not find a plan
  118627. ** that requires no source tables at all (i.e. one guaranteed to be
  118628. ** usable), make a call here with all source tables disabled */
  118629. if( rc==SQLITE_OK && seenZero==0 ){
  118630. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  118631. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, 0, p, &bIn);
  118632. if( bIn==0 ) seenZeroNoIN = 1;
  118633. }
  118634. /* If the calls to xBestIndex() have so far failed to find a plan
  118635. ** that requires no source tables at all and does not use an IN(...)
  118636. ** operator, make a final call to obtain one here. */
  118637. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  118638. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  118639. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, WO_IN, p, &bIn);
  118640. }
  118641. }
  118642. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  118643. sqlite3DbFree(pParse->db, p);
  118644. return rc;
  118645. }
  118646. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  118647. /*
  118648. ** Add WhereLoop entries to handle OR terms. This works for either
  118649. ** btrees or virtual tables.
  118650. */
  118651. static int whereLoopAddOr(
  118652. WhereLoopBuilder *pBuilder,
  118653. Bitmask mPrereq,
  118654. Bitmask mUnusable
  118655. ){
  118656. WhereInfo *pWInfo = pBuilder->pWInfo;
  118657. WhereClause *pWC;
  118658. WhereLoop *pNew;
  118659. WhereTerm *pTerm, *pWCEnd;
  118660. int rc = SQLITE_OK;
  118661. int iCur;
  118662. WhereClause tempWC;
  118663. WhereLoopBuilder sSubBuild;
  118664. WhereOrSet sSum, sCur;
  118665. struct SrcList_item *pItem;
  118666. pWC = pBuilder->pWC;
  118667. pWCEnd = pWC->a + pWC->nTerm;
  118668. pNew = pBuilder->pNew;
  118669. memset(&sSum, 0, sizeof(sSum));
  118670. pItem = pWInfo->pTabList->a + pNew->iTab;
  118671. iCur = pItem->iCursor;
  118672. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  118673. if( (pTerm->eOperator & WO_OR)!=0
  118674. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  118675. ){
  118676. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  118677. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  118678. WhereTerm *pOrTerm;
  118679. int once = 1;
  118680. int i, j;
  118681. sSubBuild = *pBuilder;
  118682. sSubBuild.pOrderBy = 0;
  118683. sSubBuild.pOrSet = &sCur;
  118684. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  118685. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  118686. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  118687. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  118688. }else if( pOrTerm->leftCursor==iCur ){
  118689. tempWC.pWInfo = pWC->pWInfo;
  118690. tempWC.pOuter = pWC;
  118691. tempWC.op = TK_AND;
  118692. tempWC.nTerm = 1;
  118693. tempWC.a = pOrTerm;
  118694. sSubBuild.pWC = &tempWC;
  118695. }else{
  118696. continue;
  118697. }
  118698. sCur.n = 0;
  118699. #ifdef WHERETRACE_ENABLED
  118700. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  118701. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  118702. if( sqlite3WhereTrace & 0x400 ){
  118703. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  118704. whereTermPrint(&sSubBuild.pWC->a[i], i);
  118705. }
  118706. }
  118707. #endif
  118708. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118709. if( IsVirtual(pItem->pTab) ){
  118710. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  118711. }else
  118712. #endif
  118713. {
  118714. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  118715. }
  118716. if( rc==SQLITE_OK ){
  118717. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  118718. }
  118719. assert( rc==SQLITE_OK || sCur.n==0 );
  118720. if( sCur.n==0 ){
  118721. sSum.n = 0;
  118722. break;
  118723. }else if( once ){
  118724. whereOrMove(&sSum, &sCur);
  118725. once = 0;
  118726. }else{
  118727. WhereOrSet sPrev;
  118728. whereOrMove(&sPrev, &sSum);
  118729. sSum.n = 0;
  118730. for(i=0; i<sPrev.n; i++){
  118731. for(j=0; j<sCur.n; j++){
  118732. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  118733. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  118734. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  118735. }
  118736. }
  118737. }
  118738. }
  118739. pNew->nLTerm = 1;
  118740. pNew->aLTerm[0] = pTerm;
  118741. pNew->wsFlags = WHERE_MULTI_OR;
  118742. pNew->rSetup = 0;
  118743. pNew->iSortIdx = 0;
  118744. memset(&pNew->u, 0, sizeof(pNew->u));
  118745. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  118746. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  118747. ** of all sub-scans required by the OR-scan. However, due to rounding
  118748. ** errors, it may be that the cost of the OR-scan is equal to its
  118749. ** most expensive sub-scan. Add the smallest possible penalty
  118750. ** (equivalent to multiplying the cost by 1.07) to ensure that
  118751. ** this does not happen. Otherwise, for WHERE clauses such as the
  118752. ** following where there is an index on "y":
  118753. **
  118754. ** WHERE likelihood(x=?, 0.99) OR y=?
  118755. **
  118756. ** the planner may elect to "OR" together a full-table scan and an
  118757. ** index lookup. And other similarly odd results. */
  118758. pNew->rRun = sSum.a[i].rRun + 1;
  118759. pNew->nOut = sSum.a[i].nOut;
  118760. pNew->prereq = sSum.a[i].prereq;
  118761. rc = whereLoopInsert(pBuilder, pNew);
  118762. }
  118763. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  118764. }
  118765. }
  118766. return rc;
  118767. }
  118768. /*
  118769. ** Add all WhereLoop objects for all tables
  118770. */
  118771. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  118772. WhereInfo *pWInfo = pBuilder->pWInfo;
  118773. Bitmask mPrereq = 0;
  118774. Bitmask mPrior = 0;
  118775. int iTab;
  118776. SrcList *pTabList = pWInfo->pTabList;
  118777. struct SrcList_item *pItem;
  118778. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  118779. sqlite3 *db = pWInfo->pParse->db;
  118780. int rc = SQLITE_OK;
  118781. WhereLoop *pNew;
  118782. u8 priorJointype = 0;
  118783. /* Loop over the tables in the join, from left to right */
  118784. pNew = pBuilder->pNew;
  118785. whereLoopInit(pNew);
  118786. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  118787. Bitmask mUnusable = 0;
  118788. pNew->iTab = iTab;
  118789. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  118790. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  118791. /* This condition is true when pItem is the FROM clause term on the
  118792. ** right-hand-side of a LEFT or CROSS JOIN. */
  118793. mPrereq = mPrior;
  118794. }
  118795. priorJointype = pItem->fg.jointype;
  118796. if( IsVirtual(pItem->pTab) ){
  118797. struct SrcList_item *p;
  118798. for(p=&pItem[1]; p<pEnd; p++){
  118799. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  118800. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  118801. }
  118802. }
  118803. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  118804. }else{
  118805. rc = whereLoopAddBtree(pBuilder, mPrereq);
  118806. }
  118807. if( rc==SQLITE_OK ){
  118808. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  118809. }
  118810. mPrior |= pNew->maskSelf;
  118811. if( rc || db->mallocFailed ) break;
  118812. }
  118813. whereLoopClear(db, pNew);
  118814. return rc;
  118815. }
  118816. /*
  118817. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  118818. ** parameters) to see if it outputs rows in the requested ORDER BY
  118819. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  118820. **
  118821. ** N>0: N terms of the ORDER BY clause are satisfied
  118822. ** N==0: No terms of the ORDER BY clause are satisfied
  118823. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  118824. **
  118825. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  118826. ** strict. With GROUP BY and DISTINCT the only requirement is that
  118827. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  118828. ** and DISTINCT do not require rows to appear in any particular order as long
  118829. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  118830. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  118831. ** pOrderBy terms must be matched in strict left-to-right order.
  118832. */
  118833. static i8 wherePathSatisfiesOrderBy(
  118834. WhereInfo *pWInfo, /* The WHERE clause */
  118835. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  118836. WherePath *pPath, /* The WherePath to check */
  118837. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  118838. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  118839. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  118840. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  118841. ){
  118842. u8 revSet; /* True if rev is known */
  118843. u8 rev; /* Composite sort order */
  118844. u8 revIdx; /* Index sort order */
  118845. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  118846. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  118847. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  118848. u16 nKeyCol; /* Number of key columns in pIndex */
  118849. u16 nColumn; /* Total number of ordered columns in the index */
  118850. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  118851. int iLoop; /* Index of WhereLoop in pPath being processed */
  118852. int i, j; /* Loop counters */
  118853. int iCur; /* Cursor number for current WhereLoop */
  118854. int iColumn; /* A column number within table iCur */
  118855. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  118856. WhereTerm *pTerm; /* A single term of the WHERE clause */
  118857. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  118858. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  118859. Index *pIndex; /* The index associated with pLoop */
  118860. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  118861. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  118862. Bitmask obDone; /* Mask of all ORDER BY terms */
  118863. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  118864. Bitmask ready; /* Mask of inner loops */
  118865. /*
  118866. ** We say the WhereLoop is "one-row" if it generates no more than one
  118867. ** row of output. A WhereLoop is one-row if all of the following are true:
  118868. ** (a) All index columns match with WHERE_COLUMN_EQ.
  118869. ** (b) The index is unique
  118870. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  118871. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  118872. **
  118873. ** We say the WhereLoop is "order-distinct" if the set of columns from
  118874. ** that WhereLoop that are in the ORDER BY clause are different for every
  118875. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  118876. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  118877. ** is not order-distinct. To be order-distinct is not quite the same as being
  118878. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  118879. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  118880. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  118881. **
  118882. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  118883. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  118884. ** automatically order-distinct.
  118885. */
  118886. assert( pOrderBy!=0 );
  118887. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  118888. nOrderBy = pOrderBy->nExpr;
  118889. testcase( nOrderBy==BMS-1 );
  118890. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  118891. isOrderDistinct = 1;
  118892. obDone = MASKBIT(nOrderBy)-1;
  118893. orderDistinctMask = 0;
  118894. ready = 0;
  118895. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  118896. if( iLoop>0 ) ready |= pLoop->maskSelf;
  118897. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  118898. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  118899. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  118900. break;
  118901. }
  118902. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  118903. /* Mark off any ORDER BY term X that is a column in the table of
  118904. ** the current loop for which there is term in the WHERE
  118905. ** clause of the form X IS NULL or X=? that reference only outer
  118906. ** loops.
  118907. */
  118908. for(i=0; i<nOrderBy; i++){
  118909. if( MASKBIT(i) & obSat ) continue;
  118910. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  118911. if( pOBExpr->op!=TK_COLUMN ) continue;
  118912. if( pOBExpr->iTable!=iCur ) continue;
  118913. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  118914. ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
  118915. if( pTerm==0 ) continue;
  118916. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  118917. const char *z1, *z2;
  118918. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  118919. if( !pColl ) pColl = db->pDfltColl;
  118920. z1 = pColl->zName;
  118921. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  118922. if( !pColl ) pColl = db->pDfltColl;
  118923. z2 = pColl->zName;
  118924. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  118925. testcase( pTerm->pExpr->op==TK_IS );
  118926. }
  118927. obSat |= MASKBIT(i);
  118928. }
  118929. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  118930. if( pLoop->wsFlags & WHERE_IPK ){
  118931. pIndex = 0;
  118932. nKeyCol = 0;
  118933. nColumn = 1;
  118934. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  118935. return 0;
  118936. }else{
  118937. nKeyCol = pIndex->nKeyCol;
  118938. nColumn = pIndex->nColumn;
  118939. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  118940. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  118941. || !HasRowid(pIndex->pTable));
  118942. isOrderDistinct = IsUniqueIndex(pIndex);
  118943. }
  118944. /* Loop through all columns of the index and deal with the ones
  118945. ** that are not constrained by == or IN.
  118946. */
  118947. rev = revSet = 0;
  118948. distinctColumns = 0;
  118949. for(j=0; j<nColumn; j++){
  118950. u8 bOnce; /* True to run the ORDER BY search loop */
  118951. /* Skip over == and IS NULL terms */
  118952. if( j<pLoop->u.btree.nEq
  118953. && pLoop->nSkip==0
  118954. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
  118955. ){
  118956. if( i & WO_ISNULL ){
  118957. testcase( isOrderDistinct );
  118958. isOrderDistinct = 0;
  118959. }
  118960. continue;
  118961. }
  118962. /* Get the column number in the table (iColumn) and sort order
  118963. ** (revIdx) for the j-th column of the index.
  118964. */
  118965. if( pIndex ){
  118966. iColumn = pIndex->aiColumn[j];
  118967. revIdx = pIndex->aSortOrder[j];
  118968. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  118969. }else{
  118970. iColumn = XN_ROWID;
  118971. revIdx = 0;
  118972. }
  118973. /* An unconstrained column that might be NULL means that this
  118974. ** WhereLoop is not well-ordered
  118975. */
  118976. if( isOrderDistinct
  118977. && iColumn>=0
  118978. && j>=pLoop->u.btree.nEq
  118979. && pIndex->pTable->aCol[iColumn].notNull==0
  118980. ){
  118981. isOrderDistinct = 0;
  118982. }
  118983. /* Find the ORDER BY term that corresponds to the j-th column
  118984. ** of the index and mark that ORDER BY term off
  118985. */
  118986. bOnce = 1;
  118987. isMatch = 0;
  118988. for(i=0; bOnce && i<nOrderBy; i++){
  118989. if( MASKBIT(i) & obSat ) continue;
  118990. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  118991. testcase( wctrlFlags & WHERE_GROUPBY );
  118992. testcase( wctrlFlags & WHERE_DISTINCTBY );
  118993. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  118994. if( iColumn>=(-1) ){
  118995. if( pOBExpr->op!=TK_COLUMN ) continue;
  118996. if( pOBExpr->iTable!=iCur ) continue;
  118997. if( pOBExpr->iColumn!=iColumn ) continue;
  118998. }else{
  118999. if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
  119000. continue;
  119001. }
  119002. }
  119003. if( iColumn>=0 ){
  119004. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  119005. if( !pColl ) pColl = db->pDfltColl;
  119006. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  119007. }
  119008. isMatch = 1;
  119009. break;
  119010. }
  119011. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  119012. /* Make sure the sort order is compatible in an ORDER BY clause.
  119013. ** Sort order is irrelevant for a GROUP BY clause. */
  119014. if( revSet ){
  119015. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  119016. }else{
  119017. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  119018. if( rev ) *pRevMask |= MASKBIT(iLoop);
  119019. revSet = 1;
  119020. }
  119021. }
  119022. if( isMatch ){
  119023. if( iColumn<0 ){
  119024. testcase( distinctColumns==0 );
  119025. distinctColumns = 1;
  119026. }
  119027. obSat |= MASKBIT(i);
  119028. }else{
  119029. /* No match found */
  119030. if( j==0 || j<nKeyCol ){
  119031. testcase( isOrderDistinct!=0 );
  119032. isOrderDistinct = 0;
  119033. }
  119034. break;
  119035. }
  119036. } /* end Loop over all index columns */
  119037. if( distinctColumns ){
  119038. testcase( isOrderDistinct==0 );
  119039. isOrderDistinct = 1;
  119040. }
  119041. } /* end-if not one-row */
  119042. /* Mark off any other ORDER BY terms that reference pLoop */
  119043. if( isOrderDistinct ){
  119044. orderDistinctMask |= pLoop->maskSelf;
  119045. for(i=0; i<nOrderBy; i++){
  119046. Expr *p;
  119047. Bitmask mTerm;
  119048. if( MASKBIT(i) & obSat ) continue;
  119049. p = pOrderBy->a[i].pExpr;
  119050. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  119051. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  119052. if( (mTerm&~orderDistinctMask)==0 ){
  119053. obSat |= MASKBIT(i);
  119054. }
  119055. }
  119056. }
  119057. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  119058. if( obSat==obDone ) return (i8)nOrderBy;
  119059. if( !isOrderDistinct ){
  119060. for(i=nOrderBy-1; i>0; i--){
  119061. Bitmask m = MASKBIT(i) - 1;
  119062. if( (obSat&m)==m ) return i;
  119063. }
  119064. return 0;
  119065. }
  119066. return -1;
  119067. }
  119068. /*
  119069. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  119070. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  119071. ** BY clause - and so any order that groups rows as required satisfies the
  119072. ** request.
  119073. **
  119074. ** Normally, in this case it is not possible for the caller to determine
  119075. ** whether or not the rows are really being delivered in sorted order, or
  119076. ** just in some other order that provides the required grouping. However,
  119077. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  119078. ** this function may be called on the returned WhereInfo object. It returns
  119079. ** true if the rows really will be sorted in the specified order, or false
  119080. ** otherwise.
  119081. **
  119082. ** For example, assuming:
  119083. **
  119084. ** CREATE INDEX i1 ON t1(x, Y);
  119085. **
  119086. ** then
  119087. **
  119088. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  119089. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  119090. */
  119091. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  119092. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  119093. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  119094. return pWInfo->sorted;
  119095. }
  119096. #ifdef WHERETRACE_ENABLED
  119097. /* For debugging use only: */
  119098. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  119099. static char zName[65];
  119100. int i;
  119101. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  119102. if( pLast ) zName[i++] = pLast->cId;
  119103. zName[i] = 0;
  119104. return zName;
  119105. }
  119106. #endif
  119107. /*
  119108. ** Return the cost of sorting nRow rows, assuming that the keys have
  119109. ** nOrderby columns and that the first nSorted columns are already in
  119110. ** order.
  119111. */
  119112. static LogEst whereSortingCost(
  119113. WhereInfo *pWInfo,
  119114. LogEst nRow,
  119115. int nOrderBy,
  119116. int nSorted
  119117. ){
  119118. /* TUNING: Estimated cost of a full external sort, where N is
  119119. ** the number of rows to sort is:
  119120. **
  119121. ** cost = (3.0 * N * log(N)).
  119122. **
  119123. ** Or, if the order-by clause has X terms but only the last Y
  119124. ** terms are out of order, then block-sorting will reduce the
  119125. ** sorting cost to:
  119126. **
  119127. ** cost = (3.0 * N * log(N)) * (Y/X)
  119128. **
  119129. ** The (Y/X) term is implemented using stack variable rScale
  119130. ** below. */
  119131. LogEst rScale, rSortCost;
  119132. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  119133. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  119134. rSortCost = nRow + rScale + 16;
  119135. /* Multiple by log(M) where M is the number of output rows.
  119136. ** Use the LIMIT for M if it is smaller */
  119137. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  119138. nRow = pWInfo->iLimit;
  119139. }
  119140. rSortCost += estLog(nRow);
  119141. return rSortCost;
  119142. }
  119143. /*
  119144. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  119145. ** attempts to find the lowest cost path that visits each WhereLoop
  119146. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  119147. **
  119148. ** Assume that the total number of output rows that will need to be sorted
  119149. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  119150. ** costs if nRowEst==0.
  119151. **
  119152. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  119153. ** error occurs.
  119154. */
  119155. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  119156. int mxChoice; /* Maximum number of simultaneous paths tracked */
  119157. int nLoop; /* Number of terms in the join */
  119158. Parse *pParse; /* Parsing context */
  119159. sqlite3 *db; /* The database connection */
  119160. int iLoop; /* Loop counter over the terms of the join */
  119161. int ii, jj; /* Loop counters */
  119162. int mxI = 0; /* Index of next entry to replace */
  119163. int nOrderBy; /* Number of ORDER BY clause terms */
  119164. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  119165. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  119166. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  119167. WherePath *aFrom; /* All nFrom paths at the previous level */
  119168. WherePath *aTo; /* The nTo best paths at the current level */
  119169. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  119170. WherePath *pTo; /* An element of aTo[] that we are working on */
  119171. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  119172. WhereLoop **pX; /* Used to divy up the pSpace memory */
  119173. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  119174. char *pSpace; /* Temporary memory used by this routine */
  119175. int nSpace; /* Bytes of space allocated at pSpace */
  119176. pParse = pWInfo->pParse;
  119177. db = pParse->db;
  119178. nLoop = pWInfo->nLevel;
  119179. /* TUNING: For simple queries, only the best path is tracked.
  119180. ** For 2-way joins, the 5 best paths are followed.
  119181. ** For joins of 3 or more tables, track the 10 best paths */
  119182. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  119183. assert( nLoop<=pWInfo->pTabList->nSrc );
  119184. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  119185. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  119186. ** case the purpose of this call is to estimate the number of rows returned
  119187. ** by the overall query. Once this estimate has been obtained, the caller
  119188. ** will invoke this function a second time, passing the estimate as the
  119189. ** nRowEst parameter. */
  119190. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  119191. nOrderBy = 0;
  119192. }else{
  119193. nOrderBy = pWInfo->pOrderBy->nExpr;
  119194. }
  119195. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  119196. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  119197. nSpace += sizeof(LogEst) * nOrderBy;
  119198. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  119199. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  119200. aTo = (WherePath*)pSpace;
  119201. aFrom = aTo+mxChoice;
  119202. memset(aFrom, 0, sizeof(aFrom[0]));
  119203. pX = (WhereLoop**)(aFrom+mxChoice);
  119204. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  119205. pFrom->aLoop = pX;
  119206. }
  119207. if( nOrderBy ){
  119208. /* If there is an ORDER BY clause and it is not being ignored, set up
  119209. ** space for the aSortCost[] array. Each element of the aSortCost array
  119210. ** is either zero - meaning it has not yet been initialized - or the
  119211. ** cost of sorting nRowEst rows of data where the first X terms of
  119212. ** the ORDER BY clause are already in order, where X is the array
  119213. ** index. */
  119214. aSortCost = (LogEst*)pX;
  119215. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  119216. }
  119217. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  119218. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  119219. /* Seed the search with a single WherePath containing zero WhereLoops.
  119220. **
  119221. ** TUNING: Do not let the number of iterations go above 28. If the cost
  119222. ** of computing an automatic index is not paid back within the first 28
  119223. ** rows, then do not use the automatic index. */
  119224. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  119225. nFrom = 1;
  119226. assert( aFrom[0].isOrdered==0 );
  119227. if( nOrderBy ){
  119228. /* If nLoop is zero, then there are no FROM terms in the query. Since
  119229. ** in this case the query may return a maximum of one row, the results
  119230. ** are already in the requested order. Set isOrdered to nOrderBy to
  119231. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  119232. ** -1, indicating that the result set may or may not be ordered,
  119233. ** depending on the loops added to the current plan. */
  119234. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  119235. }
  119236. /* Compute successively longer WherePaths using the previous generation
  119237. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  119238. ** best paths at each generation */
  119239. for(iLoop=0; iLoop<nLoop; iLoop++){
  119240. nTo = 0;
  119241. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  119242. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  119243. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  119244. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  119245. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  119246. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  119247. Bitmask maskNew; /* Mask of src visited by (..) */
  119248. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  119249. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  119250. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  119251. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
  119252. /* Do not use an automatic index if the this loop is expected
  119253. ** to run less than 2 times. */
  119254. assert( 10==sqlite3LogEst(2) );
  119255. continue;
  119256. }
  119257. /* At this point, pWLoop is a candidate to be the next loop.
  119258. ** Compute its cost */
  119259. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  119260. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  119261. nOut = pFrom->nRow + pWLoop->nOut;
  119262. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  119263. if( isOrdered<0 ){
  119264. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  119265. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  119266. iLoop, pWLoop, &revMask);
  119267. }else{
  119268. revMask = pFrom->revLoop;
  119269. }
  119270. if( isOrdered>=0 && isOrdered<nOrderBy ){
  119271. if( aSortCost[isOrdered]==0 ){
  119272. aSortCost[isOrdered] = whereSortingCost(
  119273. pWInfo, nRowEst, nOrderBy, isOrdered
  119274. );
  119275. }
  119276. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  119277. WHERETRACE(0x002,
  119278. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  119279. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  119280. rUnsorted, rCost));
  119281. }else{
  119282. rCost = rUnsorted;
  119283. }
  119284. /* Check to see if pWLoop should be added to the set of
  119285. ** mxChoice best-so-far paths.
  119286. **
  119287. ** First look for an existing path among best-so-far paths
  119288. ** that covers the same set of loops and has the same isOrdered
  119289. ** setting as the current path candidate.
  119290. **
  119291. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  119292. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  119293. ** of legal values for isOrdered, -1..64.
  119294. */
  119295. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  119296. if( pTo->maskLoop==maskNew
  119297. && ((pTo->isOrdered^isOrdered)&0x80)==0
  119298. ){
  119299. testcase( jj==nTo-1 );
  119300. break;
  119301. }
  119302. }
  119303. if( jj>=nTo ){
  119304. /* None of the existing best-so-far paths match the candidate. */
  119305. if( nTo>=mxChoice
  119306. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  119307. ){
  119308. /* The current candidate is no better than any of the mxChoice
  119309. ** paths currently in the best-so-far buffer. So discard
  119310. ** this candidate as not viable. */
  119311. #ifdef WHERETRACE_ENABLED /* 0x4 */
  119312. if( sqlite3WhereTrace&0x4 ){
  119313. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  119314. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  119315. isOrdered>=0 ? isOrdered+'0' : '?');
  119316. }
  119317. #endif
  119318. continue;
  119319. }
  119320. /* If we reach this points it means that the new candidate path
  119321. ** needs to be added to the set of best-so-far paths. */
  119322. if( nTo<mxChoice ){
  119323. /* Increase the size of the aTo set by one */
  119324. jj = nTo++;
  119325. }else{
  119326. /* New path replaces the prior worst to keep count below mxChoice */
  119327. jj = mxI;
  119328. }
  119329. pTo = &aTo[jj];
  119330. #ifdef WHERETRACE_ENABLED /* 0x4 */
  119331. if( sqlite3WhereTrace&0x4 ){
  119332. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  119333. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  119334. isOrdered>=0 ? isOrdered+'0' : '?');
  119335. }
  119336. #endif
  119337. }else{
  119338. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  119339. ** same set of loops and has the sam isOrdered setting as the
  119340. ** candidate path. Check to see if the candidate should replace
  119341. ** pTo or if the candidate should be skipped */
  119342. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  119343. #ifdef WHERETRACE_ENABLED /* 0x4 */
  119344. if( sqlite3WhereTrace&0x4 ){
  119345. sqlite3DebugPrintf(
  119346. "Skip %s cost=%-3d,%3d order=%c",
  119347. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  119348. isOrdered>=0 ? isOrdered+'0' : '?');
  119349. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  119350. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  119351. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  119352. }
  119353. #endif
  119354. /* Discard the candidate path from further consideration */
  119355. testcase( pTo->rCost==rCost );
  119356. continue;
  119357. }
  119358. testcase( pTo->rCost==rCost+1 );
  119359. /* Control reaches here if the candidate path is better than the
  119360. ** pTo path. Replace pTo with the candidate. */
  119361. #ifdef WHERETRACE_ENABLED /* 0x4 */
  119362. if( sqlite3WhereTrace&0x4 ){
  119363. sqlite3DebugPrintf(
  119364. "Update %s cost=%-3d,%3d order=%c",
  119365. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  119366. isOrdered>=0 ? isOrdered+'0' : '?');
  119367. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  119368. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  119369. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  119370. }
  119371. #endif
  119372. }
  119373. /* pWLoop is a winner. Add it to the set of best so far */
  119374. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  119375. pTo->revLoop = revMask;
  119376. pTo->nRow = nOut;
  119377. pTo->rCost = rCost;
  119378. pTo->rUnsorted = rUnsorted;
  119379. pTo->isOrdered = isOrdered;
  119380. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  119381. pTo->aLoop[iLoop] = pWLoop;
  119382. if( nTo>=mxChoice ){
  119383. mxI = 0;
  119384. mxCost = aTo[0].rCost;
  119385. mxUnsorted = aTo[0].nRow;
  119386. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  119387. if( pTo->rCost>mxCost
  119388. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  119389. ){
  119390. mxCost = pTo->rCost;
  119391. mxUnsorted = pTo->rUnsorted;
  119392. mxI = jj;
  119393. }
  119394. }
  119395. }
  119396. }
  119397. }
  119398. #ifdef WHERETRACE_ENABLED /* >=2 */
  119399. if( sqlite3WhereTrace & 0x02 ){
  119400. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  119401. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  119402. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  119403. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  119404. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  119405. if( pTo->isOrdered>0 ){
  119406. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  119407. }else{
  119408. sqlite3DebugPrintf("\n");
  119409. }
  119410. }
  119411. }
  119412. #endif
  119413. /* Swap the roles of aFrom and aTo for the next generation */
  119414. pFrom = aTo;
  119415. aTo = aFrom;
  119416. aFrom = pFrom;
  119417. nFrom = nTo;
  119418. }
  119419. if( nFrom==0 ){
  119420. sqlite3ErrorMsg(pParse, "no query solution");
  119421. sqlite3DbFree(db, pSpace);
  119422. return SQLITE_ERROR;
  119423. }
  119424. /* Find the lowest cost path. pFrom will be left pointing to that path */
  119425. pFrom = aFrom;
  119426. for(ii=1; ii<nFrom; ii++){
  119427. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  119428. }
  119429. assert( pWInfo->nLevel==nLoop );
  119430. /* Load the lowest cost path into pWInfo */
  119431. for(iLoop=0; iLoop<nLoop; iLoop++){
  119432. WhereLevel *pLevel = pWInfo->a + iLoop;
  119433. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  119434. pLevel->iFrom = pWLoop->iTab;
  119435. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  119436. }
  119437. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  119438. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  119439. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  119440. && nRowEst
  119441. ){
  119442. Bitmask notUsed;
  119443. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  119444. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  119445. if( rc==pWInfo->pResultSet->nExpr ){
  119446. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  119447. }
  119448. }
  119449. if( pWInfo->pOrderBy ){
  119450. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  119451. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  119452. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  119453. }
  119454. }else{
  119455. pWInfo->nOBSat = pFrom->isOrdered;
  119456. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  119457. pWInfo->revMask = pFrom->revLoop;
  119458. }
  119459. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  119460. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  119461. ){
  119462. Bitmask revMask = 0;
  119463. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  119464. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  119465. );
  119466. assert( pWInfo->sorted==0 );
  119467. if( nOrder==pWInfo->pOrderBy->nExpr ){
  119468. pWInfo->sorted = 1;
  119469. pWInfo->revMask = revMask;
  119470. }
  119471. }
  119472. }
  119473. pWInfo->nRowOut = pFrom->nRow;
  119474. /* Free temporary memory and return success */
  119475. sqlite3DbFree(db, pSpace);
  119476. return SQLITE_OK;
  119477. }
  119478. /*
  119479. ** Most queries use only a single table (they are not joins) and have
  119480. ** simple == constraints against indexed fields. This routine attempts
  119481. ** to plan those simple cases using much less ceremony than the
  119482. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  119483. ** times for the common case.
  119484. **
  119485. ** Return non-zero on success, if this query can be handled by this
  119486. ** no-frills query planner. Return zero if this query needs the
  119487. ** general-purpose query planner.
  119488. */
  119489. static int whereShortCut(WhereLoopBuilder *pBuilder){
  119490. WhereInfo *pWInfo;
  119491. struct SrcList_item *pItem;
  119492. WhereClause *pWC;
  119493. WhereTerm *pTerm;
  119494. WhereLoop *pLoop;
  119495. int iCur;
  119496. int j;
  119497. Table *pTab;
  119498. Index *pIdx;
  119499. pWInfo = pBuilder->pWInfo;
  119500. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  119501. assert( pWInfo->pTabList->nSrc>=1 );
  119502. pItem = pWInfo->pTabList->a;
  119503. pTab = pItem->pTab;
  119504. if( IsVirtual(pTab) ) return 0;
  119505. if( pItem->fg.isIndexedBy ) return 0;
  119506. iCur = pItem->iCursor;
  119507. pWC = &pWInfo->sWC;
  119508. pLoop = pBuilder->pNew;
  119509. pLoop->wsFlags = 0;
  119510. pLoop->nSkip = 0;
  119511. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  119512. if( pTerm ){
  119513. testcase( pTerm->eOperator & WO_IS );
  119514. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  119515. pLoop->aLTerm[0] = pTerm;
  119516. pLoop->nLTerm = 1;
  119517. pLoop->u.btree.nEq = 1;
  119518. /* TUNING: Cost of a rowid lookup is 10 */
  119519. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  119520. }else{
  119521. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119522. int opMask;
  119523. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  119524. if( !IsUniqueIndex(pIdx)
  119525. || pIdx->pPartIdxWhere!=0
  119526. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  119527. ) continue;
  119528. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  119529. for(j=0; j<pIdx->nKeyCol; j++){
  119530. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  119531. if( pTerm==0 ) break;
  119532. testcase( pTerm->eOperator & WO_IS );
  119533. pLoop->aLTerm[j] = pTerm;
  119534. }
  119535. if( j!=pIdx->nKeyCol ) continue;
  119536. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  119537. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  119538. pLoop->wsFlags |= WHERE_IDX_ONLY;
  119539. }
  119540. pLoop->nLTerm = j;
  119541. pLoop->u.btree.nEq = j;
  119542. pLoop->u.btree.pIndex = pIdx;
  119543. /* TUNING: Cost of a unique index lookup is 15 */
  119544. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  119545. break;
  119546. }
  119547. }
  119548. if( pLoop->wsFlags ){
  119549. pLoop->nOut = (LogEst)1;
  119550. pWInfo->a[0].pWLoop = pLoop;
  119551. pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  119552. pWInfo->a[0].iTabCur = iCur;
  119553. pWInfo->nRowOut = 1;
  119554. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  119555. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  119556. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  119557. }
  119558. #ifdef SQLITE_DEBUG
  119559. pLoop->cId = '0';
  119560. #endif
  119561. return 1;
  119562. }
  119563. return 0;
  119564. }
  119565. /*
  119566. ** Generate the beginning of the loop used for WHERE clause processing.
  119567. ** The return value is a pointer to an opaque structure that contains
  119568. ** information needed to terminate the loop. Later, the calling routine
  119569. ** should invoke sqlite3WhereEnd() with the return value of this function
  119570. ** in order to complete the WHERE clause processing.
  119571. **
  119572. ** If an error occurs, this routine returns NULL.
  119573. **
  119574. ** The basic idea is to do a nested loop, one loop for each table in
  119575. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  119576. ** same as a SELECT with only a single table in the FROM clause.) For
  119577. ** example, if the SQL is this:
  119578. **
  119579. ** SELECT * FROM t1, t2, t3 WHERE ...;
  119580. **
  119581. ** Then the code generated is conceptually like the following:
  119582. **
  119583. ** foreach row1 in t1 do \ Code generated
  119584. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  119585. ** foreach row3 in t3 do /
  119586. ** ...
  119587. ** end \ Code generated
  119588. ** end |-- by sqlite3WhereEnd()
  119589. ** end /
  119590. **
  119591. ** Note that the loops might not be nested in the order in which they
  119592. ** appear in the FROM clause if a different order is better able to make
  119593. ** use of indices. Note also that when the IN operator appears in
  119594. ** the WHERE clause, it might result in additional nested loops for
  119595. ** scanning through all values on the right-hand side of the IN.
  119596. **
  119597. ** There are Btree cursors associated with each table. t1 uses cursor
  119598. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  119599. ** And so forth. This routine generates code to open those VDBE cursors
  119600. ** and sqlite3WhereEnd() generates the code to close them.
  119601. **
  119602. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  119603. ** in pTabList pointing at their appropriate entries. The [...] code
  119604. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  119605. ** data from the various tables of the loop.
  119606. **
  119607. ** If the WHERE clause is empty, the foreach loops must each scan their
  119608. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  119609. ** the tables have indices and there are terms in the WHERE clause that
  119610. ** refer to those indices, a complete table scan can be avoided and the
  119611. ** code will run much faster. Most of the work of this routine is checking
  119612. ** to see if there are indices that can be used to speed up the loop.
  119613. **
  119614. ** Terms of the WHERE clause are also used to limit which rows actually
  119615. ** make it to the "..." in the middle of the loop. After each "foreach",
  119616. ** terms of the WHERE clause that use only terms in that loop and outer
  119617. ** loops are evaluated and if false a jump is made around all subsequent
  119618. ** inner loops (or around the "..." if the test occurs within the inner-
  119619. ** most loop)
  119620. **
  119621. ** OUTER JOINS
  119622. **
  119623. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  119624. **
  119625. ** foreach row1 in t1 do
  119626. ** flag = 0
  119627. ** foreach row2 in t2 do
  119628. ** start:
  119629. ** ...
  119630. ** flag = 1
  119631. ** end
  119632. ** if flag==0 then
  119633. ** move the row2 cursor to a null row
  119634. ** goto start
  119635. ** fi
  119636. ** end
  119637. **
  119638. ** ORDER BY CLAUSE PROCESSING
  119639. **
  119640. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  119641. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  119642. ** if there is one. If there is no ORDER BY clause or if this routine
  119643. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  119644. **
  119645. ** The iIdxCur parameter is the cursor number of an index. If
  119646. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  119647. ** to use for OR clause processing. The WHERE clause should use this
  119648. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  119649. ** the first cursor in an array of cursors for all indices. iIdxCur should
  119650. ** be used to compute the appropriate cursor depending on which index is
  119651. ** used.
  119652. */
  119653. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  119654. Parse *pParse, /* The parser context */
  119655. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  119656. Expr *pWhere, /* The WHERE clause */
  119657. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  119658. ExprList *pResultSet, /* Result set of the query */
  119659. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  119660. int iAuxArg /* If WHERE_ONETABLE_ONLY is set, index cursor number,
  119661. ** If WHERE_USE_LIMIT, then the limit amount */
  119662. ){
  119663. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  119664. int nTabList; /* Number of elements in pTabList */
  119665. WhereInfo *pWInfo; /* Will become the return value of this function */
  119666. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  119667. Bitmask notReady; /* Cursors that are not yet positioned */
  119668. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  119669. WhereMaskSet *pMaskSet; /* The expression mask set */
  119670. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  119671. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  119672. int ii; /* Loop counter */
  119673. sqlite3 *db; /* Database connection */
  119674. int rc; /* Return code */
  119675. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  119676. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  119677. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  119678. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  119679. ));
  119680. /* Only one of WHERE_ONETABLE_ONLY or WHERE_USE_LIMIT */
  119681. assert( (wctrlFlags & WHERE_ONETABLE_ONLY)==0
  119682. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  119683. /* Variable initialization */
  119684. db = pParse->db;
  119685. memset(&sWLB, 0, sizeof(sWLB));
  119686. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  119687. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  119688. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  119689. sWLB.pOrderBy = pOrderBy;
  119690. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  119691. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  119692. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  119693. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  119694. }
  119695. /* The number of tables in the FROM clause is limited by the number of
  119696. ** bits in a Bitmask
  119697. */
  119698. testcase( pTabList->nSrc==BMS );
  119699. if( pTabList->nSrc>BMS ){
  119700. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  119701. return 0;
  119702. }
  119703. /* This function normally generates a nested loop for all tables in
  119704. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  119705. ** only generate code for the first table in pTabList and assume that
  119706. ** any cursors associated with subsequent tables are uninitialized.
  119707. */
  119708. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  119709. /* Allocate and initialize the WhereInfo structure that will become the
  119710. ** return value. A single allocation is used to store the WhereInfo
  119711. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  119712. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  119713. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  119714. ** some architectures. Hence the ROUND8() below.
  119715. */
  119716. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  119717. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  119718. if( db->mallocFailed ){
  119719. sqlite3DbFree(db, pWInfo);
  119720. pWInfo = 0;
  119721. goto whereBeginError;
  119722. }
  119723. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  119724. pWInfo->nLevel = nTabList;
  119725. pWInfo->pParse = pParse;
  119726. pWInfo->pTabList = pTabList;
  119727. pWInfo->pOrderBy = pOrderBy;
  119728. pWInfo->pResultSet = pResultSet;
  119729. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  119730. pWInfo->wctrlFlags = wctrlFlags;
  119731. pWInfo->iLimit = iAuxArg;
  119732. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  119733. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  119734. pMaskSet = &pWInfo->sMaskSet;
  119735. sWLB.pWInfo = pWInfo;
  119736. sWLB.pWC = &pWInfo->sWC;
  119737. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  119738. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  119739. whereLoopInit(sWLB.pNew);
  119740. #ifdef SQLITE_DEBUG
  119741. sWLB.pNew->cId = '*';
  119742. #endif
  119743. /* Split the WHERE clause into separate subexpressions where each
  119744. ** subexpression is separated by an AND operator.
  119745. */
  119746. initMaskSet(pMaskSet);
  119747. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  119748. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  119749. /* Special case: a WHERE clause that is constant. Evaluate the
  119750. ** expression and either jump over all of the code or fall thru.
  119751. */
  119752. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  119753. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  119754. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  119755. SQLITE_JUMPIFNULL);
  119756. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  119757. }
  119758. }
  119759. /* Special case: No FROM clause
  119760. */
  119761. if( nTabList==0 ){
  119762. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  119763. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  119764. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  119765. }
  119766. }
  119767. /* Assign a bit from the bitmask to every term in the FROM clause.
  119768. **
  119769. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  119770. **
  119771. ** The rule of the previous sentence ensures thta if X is the bitmask for
  119772. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  119773. ** Knowing the bitmask for all tables to the left of a left join is
  119774. ** important. Ticket #3015.
  119775. **
  119776. ** Note that bitmasks are created for all pTabList->nSrc tables in
  119777. ** pTabList, not just the first nTabList tables. nTabList is normally
  119778. ** equal to pTabList->nSrc but might be shortened to 1 if the
  119779. ** WHERE_ONETABLE_ONLY flag is set.
  119780. */
  119781. for(ii=0; ii<pTabList->nSrc; ii++){
  119782. createMask(pMaskSet, pTabList->a[ii].iCursor);
  119783. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  119784. }
  119785. #ifdef SQLITE_DEBUG
  119786. for(ii=0; ii<pTabList->nSrc; ii++){
  119787. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  119788. assert( m==MASKBIT(ii) );
  119789. }
  119790. #endif
  119791. /* Analyze all of the subexpressions. */
  119792. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  119793. if( db->mallocFailed ) goto whereBeginError;
  119794. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  119795. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  119796. /* The DISTINCT marking is pointless. Ignore it. */
  119797. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  119798. }else if( pOrderBy==0 ){
  119799. /* Try to ORDER BY the result set to make distinct processing easier */
  119800. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  119801. pWInfo->pOrderBy = pResultSet;
  119802. }
  119803. }
  119804. /* Construct the WhereLoop objects */
  119805. #if defined(WHERETRACE_ENABLED)
  119806. if( sqlite3WhereTrace & 0xffff ){
  119807. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  119808. if( wctrlFlags & WHERE_USE_LIMIT ){
  119809. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  119810. }
  119811. sqlite3DebugPrintf(")\n");
  119812. }
  119813. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  119814. int i;
  119815. for(i=0; i<sWLB.pWC->nTerm; i++){
  119816. whereTermPrint(&sWLB.pWC->a[i], i);
  119817. }
  119818. }
  119819. #endif
  119820. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  119821. rc = whereLoopAddAll(&sWLB);
  119822. if( rc ) goto whereBeginError;
  119823. #ifdef WHERETRACE_ENABLED
  119824. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  119825. WhereLoop *p;
  119826. int i;
  119827. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  119828. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  119829. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  119830. p->cId = zLabel[i%sizeof(zLabel)];
  119831. whereLoopPrint(p, sWLB.pWC);
  119832. }
  119833. }
  119834. #endif
  119835. wherePathSolver(pWInfo, 0);
  119836. if( db->mallocFailed ) goto whereBeginError;
  119837. if( pWInfo->pOrderBy ){
  119838. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  119839. if( db->mallocFailed ) goto whereBeginError;
  119840. }
  119841. }
  119842. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  119843. pWInfo->revMask = ALLBITS;
  119844. }
  119845. if( pParse->nErr || NEVER(db->mallocFailed) ){
  119846. goto whereBeginError;
  119847. }
  119848. #ifdef WHERETRACE_ENABLED
  119849. if( sqlite3WhereTrace ){
  119850. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  119851. if( pWInfo->nOBSat>0 ){
  119852. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  119853. }
  119854. switch( pWInfo->eDistinct ){
  119855. case WHERE_DISTINCT_UNIQUE: {
  119856. sqlite3DebugPrintf(" DISTINCT=unique");
  119857. break;
  119858. }
  119859. case WHERE_DISTINCT_ORDERED: {
  119860. sqlite3DebugPrintf(" DISTINCT=ordered");
  119861. break;
  119862. }
  119863. case WHERE_DISTINCT_UNORDERED: {
  119864. sqlite3DebugPrintf(" DISTINCT=unordered");
  119865. break;
  119866. }
  119867. }
  119868. sqlite3DebugPrintf("\n");
  119869. for(ii=0; ii<pWInfo->nLevel; ii++){
  119870. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  119871. }
  119872. }
  119873. #endif
  119874. /* Attempt to omit tables from the join that do not effect the result */
  119875. if( pWInfo->nLevel>=2
  119876. && pResultSet!=0
  119877. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  119878. ){
  119879. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  119880. if( sWLB.pOrderBy ){
  119881. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  119882. }
  119883. while( pWInfo->nLevel>=2 ){
  119884. WhereTerm *pTerm, *pEnd;
  119885. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  119886. if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
  119887. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  119888. && (pLoop->wsFlags & WHERE_ONEROW)==0
  119889. ){
  119890. break;
  119891. }
  119892. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  119893. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  119894. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  119895. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  119896. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  119897. ){
  119898. break;
  119899. }
  119900. }
  119901. if( pTerm<pEnd ) break;
  119902. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  119903. pWInfo->nLevel--;
  119904. nTabList--;
  119905. }
  119906. }
  119907. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  119908. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  119909. /* If the caller is an UPDATE or DELETE statement that is requesting
  119910. ** to use a one-pass algorithm, determine if this is appropriate.
  119911. */
  119912. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  119913. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  119914. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  119915. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  119916. if( bOnerow
  119917. || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
  119918. && 0==(wsFlags & WHERE_VIRTUALTABLE))
  119919. ){
  119920. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  119921. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  119922. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  119923. bFordelete = OPFLAG_FORDELETE;
  119924. }
  119925. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  119926. }
  119927. }
  119928. }
  119929. /* Open all tables in the pTabList and any indices selected for
  119930. ** searching those tables.
  119931. */
  119932. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  119933. Table *pTab; /* Table to open */
  119934. int iDb; /* Index of database containing table/index */
  119935. struct SrcList_item *pTabItem;
  119936. pTabItem = &pTabList->a[pLevel->iFrom];
  119937. pTab = pTabItem->pTab;
  119938. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  119939. pLoop = pLevel->pWLoop;
  119940. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  119941. /* Do nothing */
  119942. }else
  119943. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119944. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  119945. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  119946. int iCur = pTabItem->iCursor;
  119947. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  119948. }else if( IsVirtual(pTab) ){
  119949. /* noop */
  119950. }else
  119951. #endif
  119952. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  119953. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  119954. int op = OP_OpenRead;
  119955. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  119956. op = OP_OpenWrite;
  119957. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  119958. };
  119959. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  119960. assert( pTabItem->iCursor==pLevel->iTabCur );
  119961. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  119962. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  119963. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  119964. Bitmask b = pTabItem->colUsed;
  119965. int n = 0;
  119966. for(; b; b=b>>1, n++){}
  119967. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  119968. assert( n<=pTab->nCol );
  119969. }
  119970. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  119971. if( pLoop->u.btree.pIndex!=0 ){
  119972. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  119973. }else
  119974. #endif
  119975. {
  119976. sqlite3VdbeChangeP5(v, bFordelete);
  119977. }
  119978. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  119979. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  119980. (const u8*)&pTabItem->colUsed, P4_INT64);
  119981. #endif
  119982. }else{
  119983. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  119984. }
  119985. if( pLoop->wsFlags & WHERE_INDEXED ){
  119986. Index *pIx = pLoop->u.btree.pIndex;
  119987. int iIndexCur;
  119988. int op = OP_OpenRead;
  119989. /* iAuxArg is always set if to a positive value if ONEPASS is possible */
  119990. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  119991. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  119992. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  119993. ){
  119994. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  119995. ** WITHOUT ROWID table. No need for a separate index */
  119996. iIndexCur = pLevel->iTabCur;
  119997. op = 0;
  119998. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  119999. Index *pJ = pTabItem->pTab->pIndex;
  120000. iIndexCur = iAuxArg;
  120001. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  120002. while( ALWAYS(pJ) && pJ!=pIx ){
  120003. iIndexCur++;
  120004. pJ = pJ->pNext;
  120005. }
  120006. op = OP_OpenWrite;
  120007. pWInfo->aiCurOnePass[1] = iIndexCur;
  120008. }else if( iAuxArg && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  120009. iIndexCur = iAuxArg;
  120010. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  120011. }else{
  120012. iIndexCur = pParse->nTab++;
  120013. }
  120014. pLevel->iIdxCur = iIndexCur;
  120015. assert( pIx->pSchema==pTab->pSchema );
  120016. assert( iIndexCur>=0 );
  120017. if( op ){
  120018. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  120019. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  120020. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  120021. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  120022. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  120023. ){
  120024. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  120025. }
  120026. VdbeComment((v, "%s", pIx->zName));
  120027. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  120028. {
  120029. u64 colUsed = 0;
  120030. int ii, jj;
  120031. for(ii=0; ii<pIx->nColumn; ii++){
  120032. jj = pIx->aiColumn[ii];
  120033. if( jj<0 ) continue;
  120034. if( jj>63 ) jj = 63;
  120035. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  120036. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  120037. }
  120038. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  120039. (u8*)&colUsed, P4_INT64);
  120040. }
  120041. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  120042. }
  120043. }
  120044. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  120045. }
  120046. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  120047. if( db->mallocFailed ) goto whereBeginError;
  120048. /* Generate the code to do the search. Each iteration of the for
  120049. ** loop below generates code for a single nested loop of the VM
  120050. ** program.
  120051. */
  120052. notReady = ~(Bitmask)0;
  120053. for(ii=0; ii<nTabList; ii++){
  120054. int addrExplain;
  120055. int wsFlags;
  120056. pLevel = &pWInfo->a[ii];
  120057. wsFlags = pLevel->pWLoop->wsFlags;
  120058. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  120059. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  120060. constructAutomaticIndex(pParse, &pWInfo->sWC,
  120061. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  120062. if( db->mallocFailed ) goto whereBeginError;
  120063. }
  120064. #endif
  120065. addrExplain = sqlite3WhereExplainOneScan(
  120066. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  120067. );
  120068. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  120069. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  120070. pWInfo->iContinue = pLevel->addrCont;
  120071. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
  120072. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  120073. }
  120074. }
  120075. /* Done. */
  120076. VdbeModuleComment((v, "Begin WHERE-core"));
  120077. return pWInfo;
  120078. /* Jump here if malloc fails */
  120079. whereBeginError:
  120080. if( pWInfo ){
  120081. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  120082. whereInfoFree(db, pWInfo);
  120083. }
  120084. return 0;
  120085. }
  120086. /*
  120087. ** Generate the end of the WHERE loop. See comments on
  120088. ** sqlite3WhereBegin() for additional information.
  120089. */
  120090. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  120091. Parse *pParse = pWInfo->pParse;
  120092. Vdbe *v = pParse->pVdbe;
  120093. int i;
  120094. WhereLevel *pLevel;
  120095. WhereLoop *pLoop;
  120096. SrcList *pTabList = pWInfo->pTabList;
  120097. sqlite3 *db = pParse->db;
  120098. /* Generate loop termination code.
  120099. */
  120100. VdbeModuleComment((v, "End WHERE-core"));
  120101. sqlite3ExprCacheClear(pParse);
  120102. for(i=pWInfo->nLevel-1; i>=0; i--){
  120103. int addr;
  120104. pLevel = &pWInfo->a[i];
  120105. pLoop = pLevel->pWLoop;
  120106. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  120107. if( pLevel->op!=OP_Noop ){
  120108. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  120109. sqlite3VdbeChangeP5(v, pLevel->p5);
  120110. VdbeCoverage(v);
  120111. VdbeCoverageIf(v, pLevel->op==OP_Next);
  120112. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  120113. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  120114. }
  120115. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  120116. struct InLoop *pIn;
  120117. int j;
  120118. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  120119. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  120120. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  120121. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  120122. VdbeCoverage(v);
  120123. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  120124. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  120125. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  120126. }
  120127. }
  120128. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  120129. if( pLevel->addrSkip ){
  120130. sqlite3VdbeGoto(v, pLevel->addrSkip);
  120131. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  120132. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  120133. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  120134. }
  120135. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  120136. if( pLevel->addrLikeRep ){
  120137. int op;
  120138. if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
  120139. op = OP_DecrJumpZero;
  120140. }else{
  120141. op = OP_JumpZeroIncr;
  120142. }
  120143. sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
  120144. VdbeCoverage(v);
  120145. }
  120146. #endif
  120147. if( pLevel->iLeftJoin ){
  120148. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  120149. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  120150. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  120151. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  120152. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  120153. }
  120154. if( pLoop->wsFlags & WHERE_INDEXED ){
  120155. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  120156. }
  120157. if( pLevel->op==OP_Return ){
  120158. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  120159. }else{
  120160. sqlite3VdbeGoto(v, pLevel->addrFirst);
  120161. }
  120162. sqlite3VdbeJumpHere(v, addr);
  120163. }
  120164. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  120165. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  120166. }
  120167. /* The "break" point is here, just past the end of the outer loop.
  120168. ** Set it.
  120169. */
  120170. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  120171. assert( pWInfo->nLevel<=pTabList->nSrc );
  120172. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  120173. int k, last;
  120174. VdbeOp *pOp;
  120175. Index *pIdx = 0;
  120176. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  120177. Table *pTab = pTabItem->pTab;
  120178. assert( pTab!=0 );
  120179. pLoop = pLevel->pWLoop;
  120180. /* For a co-routine, change all OP_Column references to the table of
  120181. ** the co-routine into OP_Copy of result contained in a register.
  120182. ** OP_Rowid becomes OP_Null.
  120183. */
  120184. if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
  120185. translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
  120186. pTabItem->regResult, 0);
  120187. continue;
  120188. }
  120189. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  120190. ** Except, do not close cursors that will be reused by the OR optimization
  120191. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  120192. ** created for the ONEPASS optimization.
  120193. */
  120194. if( (pTab->tabFlags & TF_Ephemeral)==0
  120195. && pTab->pSelect==0
  120196. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  120197. ){
  120198. int ws = pLoop->wsFlags;
  120199. if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
  120200. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  120201. }
  120202. if( (ws & WHERE_INDEXED)!=0
  120203. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  120204. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  120205. ){
  120206. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  120207. }
  120208. }
  120209. /* If this scan uses an index, make VDBE code substitutions to read data
  120210. ** from the index instead of from the table where possible. In some cases
  120211. ** this optimization prevents the table from ever being read, which can
  120212. ** yield a significant performance boost.
  120213. **
  120214. ** Calls to the code generator in between sqlite3WhereBegin and
  120215. ** sqlite3WhereEnd will have created code that references the table
  120216. ** directly. This loop scans all that code looking for opcodes
  120217. ** that reference the table and converts them into opcodes that
  120218. ** reference the index.
  120219. */
  120220. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  120221. pIdx = pLoop->u.btree.pIndex;
  120222. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  120223. pIdx = pLevel->u.pCovidx;
  120224. }
  120225. if( pIdx
  120226. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  120227. && !db->mallocFailed
  120228. ){
  120229. last = sqlite3VdbeCurrentAddr(v);
  120230. k = pLevel->addrBody;
  120231. pOp = sqlite3VdbeGetOp(v, k);
  120232. for(; k<last; k++, pOp++){
  120233. if( pOp->p1!=pLevel->iTabCur ) continue;
  120234. if( pOp->opcode==OP_Column ){
  120235. int x = pOp->p2;
  120236. assert( pIdx->pTable==pTab );
  120237. if( !HasRowid(pTab) ){
  120238. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  120239. x = pPk->aiColumn[x];
  120240. assert( x>=0 );
  120241. }
  120242. x = sqlite3ColumnOfIndex(pIdx, x);
  120243. if( x>=0 ){
  120244. pOp->p2 = x;
  120245. pOp->p1 = pLevel->iIdxCur;
  120246. }
  120247. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  120248. }else if( pOp->opcode==OP_Rowid ){
  120249. pOp->p1 = pLevel->iIdxCur;
  120250. pOp->opcode = OP_IdxRowid;
  120251. }
  120252. }
  120253. }
  120254. }
  120255. /* Final cleanup
  120256. */
  120257. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  120258. whereInfoFree(db, pWInfo);
  120259. return;
  120260. }
  120261. /************** End of where.c ***********************************************/
  120262. /************** Begin file parse.c *******************************************/
  120263. /*
  120264. ** 2000-05-29
  120265. **
  120266. ** The author disclaims copyright to this source code. In place of
  120267. ** a legal notice, here is a blessing:
  120268. **
  120269. ** May you do good and not evil.
  120270. ** May you find forgiveness for yourself and forgive others.
  120271. ** May you share freely, never taking more than you give.
  120272. **
  120273. *************************************************************************
  120274. ** Driver template for the LEMON parser generator.
  120275. **
  120276. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  120277. ** this template to construct a parser. The "lemon" program inserts text
  120278. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  120279. ** interstitial "-" characters) contained in this template is changed into
  120280. ** the value of the %name directive from the grammar. Otherwise, the content
  120281. ** of this template is copied straight through into the generate parser
  120282. ** source file.
  120283. **
  120284. ** The following is the concatenation of all %include directives from the
  120285. ** input grammar file:
  120286. */
  120287. /* #include <stdio.h> */
  120288. /************ Begin %include sections from the grammar ************************/
  120289. /* #include "sqliteInt.h" */
  120290. /*
  120291. ** Disable all error recovery processing in the parser push-down
  120292. ** automaton.
  120293. */
  120294. #define YYNOERRORRECOVERY 1
  120295. /*
  120296. ** Make yytestcase() the same as testcase()
  120297. */
  120298. #define yytestcase(X) testcase(X)
  120299. /*
  120300. ** Indicate that sqlite3ParserFree() will never be called with a null
  120301. ** pointer.
  120302. */
  120303. #define YYPARSEFREENEVERNULL 1
  120304. /*
  120305. ** Alternative datatype for the argument to the malloc() routine passed
  120306. ** into sqlite3ParserAlloc(). The default is size_t.
  120307. */
  120308. #define YYMALLOCARGTYPE u64
  120309. /*
  120310. ** An instance of this structure holds information about the
  120311. ** LIMIT clause of a SELECT statement.
  120312. */
  120313. struct LimitVal {
  120314. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  120315. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  120316. };
  120317. /*
  120318. ** An instance of this structure is used to store the LIKE,
  120319. ** GLOB, NOT LIKE, and NOT GLOB operators.
  120320. */
  120321. struct LikeOp {
  120322. Token eOperator; /* "like" or "glob" or "regexp" */
  120323. int bNot; /* True if the NOT keyword is present */
  120324. };
  120325. /*
  120326. ** An instance of the following structure describes the event of a
  120327. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  120328. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  120329. **
  120330. ** UPDATE ON (a,b,c)
  120331. **
  120332. ** Then the "b" IdList records the list "a,b,c".
  120333. */
  120334. struct TrigEvent { int a; IdList * b; };
  120335. /*
  120336. ** An instance of this structure holds the ATTACH key and the key type.
  120337. */
  120338. struct AttachKey { int type; Token key; };
  120339. /*
  120340. ** Disable lookaside memory allocation for objects that might be
  120341. ** shared across database connections.
  120342. */
  120343. static void disableLookaside(Parse *pParse){
  120344. pParse->disableLookaside++;
  120345. pParse->db->lookaside.bDisable++;
  120346. }
  120347. /*
  120348. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  120349. ** all elements in the list. And make sure list length does not exceed
  120350. ** SQLITE_LIMIT_COMPOUND_SELECT.
  120351. */
  120352. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  120353. if( p->pPrior ){
  120354. Select *pNext = 0, *pLoop;
  120355. int mxSelect, cnt = 0;
  120356. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  120357. pLoop->pNext = pNext;
  120358. pLoop->selFlags |= SF_Compound;
  120359. }
  120360. if( (p->selFlags & SF_MultiValue)==0 &&
  120361. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  120362. cnt>mxSelect
  120363. ){
  120364. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  120365. }
  120366. }
  120367. }
  120368. /* This is a utility routine used to set the ExprSpan.zStart and
  120369. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  120370. ** range of text beginning with pStart and going to the end of pEnd.
  120371. */
  120372. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  120373. pOut->zStart = pStart->z;
  120374. pOut->zEnd = &pEnd->z[pEnd->n];
  120375. }
  120376. /* Construct a new Expr object from a single identifier. Use the
  120377. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  120378. ** that created the expression.
  120379. */
  120380. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
  120381. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, &t);
  120382. pOut->zStart = t.z;
  120383. pOut->zEnd = &t.z[t.n];
  120384. }
  120385. /* This routine constructs a binary expression node out of two ExprSpan
  120386. ** objects and uses the result to populate a new ExprSpan object.
  120387. */
  120388. static void spanBinaryExpr(
  120389. Parse *pParse, /* The parsing context. Errors accumulate here */
  120390. int op, /* The binary operation */
  120391. ExprSpan *pLeft, /* The left operand, and output */
  120392. ExprSpan *pRight /* The right operand */
  120393. ){
  120394. pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  120395. pLeft->zEnd = pRight->zEnd;
  120396. }
  120397. /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
  120398. ** outside of *ppExpr.
  120399. */
  120400. static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
  120401. if( doNot ){
  120402. pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
  120403. }
  120404. }
  120405. /* Construct an expression node for a unary postfix operator
  120406. */
  120407. static void spanUnaryPostfix(
  120408. Parse *pParse, /* Parsing context to record errors */
  120409. int op, /* The operator */
  120410. ExprSpan *pOperand, /* The operand, and output */
  120411. Token *pPostOp /* The operand token for setting the span */
  120412. ){
  120413. pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  120414. pOperand->zEnd = &pPostOp->z[pPostOp->n];
  120415. }
  120416. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  120417. ** unary TK_ISNULL or TK_NOTNULL expression. */
  120418. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  120419. sqlite3 *db = pParse->db;
  120420. if( pA && pY && pY->op==TK_NULL ){
  120421. pA->op = (u8)op;
  120422. sqlite3ExprDelete(db, pA->pRight);
  120423. pA->pRight = 0;
  120424. }
  120425. }
  120426. /* Construct an expression node for a unary prefix operator
  120427. */
  120428. static void spanUnaryPrefix(
  120429. ExprSpan *pOut, /* Write the new expression node here */
  120430. Parse *pParse, /* Parsing context to record errors */
  120431. int op, /* The operator */
  120432. ExprSpan *pOperand, /* The operand */
  120433. Token *pPreOp /* The operand token for setting the span */
  120434. ){
  120435. pOut->zStart = pPreOp->z;
  120436. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  120437. pOut->zEnd = pOperand->zEnd;
  120438. }
  120439. /* Add a single new term to an ExprList that is used to store a
  120440. ** list of identifiers. Report an error if the ID list contains
  120441. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  120442. ** error while parsing a legacy schema.
  120443. */
  120444. static ExprList *parserAddExprIdListTerm(
  120445. Parse *pParse,
  120446. ExprList *pPrior,
  120447. Token *pIdToken,
  120448. int hasCollate,
  120449. int sortOrder
  120450. ){
  120451. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  120452. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  120453. && pParse->db->init.busy==0
  120454. ){
  120455. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  120456. pIdToken->n, pIdToken->z);
  120457. }
  120458. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  120459. return p;
  120460. }
  120461. /**************** End of %include directives **********************************/
  120462. /* These constants specify the various numeric values for terminal symbols
  120463. ** in a format understandable to "makeheaders". This section is blank unless
  120464. ** "lemon" is run with the "-m" command-line option.
  120465. ***************** Begin makeheaders token definitions *************************/
  120466. /**************** End makeheaders token definitions ***************************/
  120467. /* The next sections is a series of control #defines.
  120468. ** various aspects of the generated parser.
  120469. ** YYCODETYPE is the data type used to store the integer codes
  120470. ** that represent terminal and non-terminal symbols.
  120471. ** "unsigned char" is used if there are fewer than
  120472. ** 256 symbols. Larger types otherwise.
  120473. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  120474. ** any terminal or nonterminal symbol.
  120475. ** YYFALLBACK If defined, this indicates that one or more tokens
  120476. ** (also known as: "terminal symbols") have fall-back
  120477. ** values which should be used if the original symbol
  120478. ** would not parse. This permits keywords to sometimes
  120479. ** be used as identifiers, for example.
  120480. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  120481. ** that indicate what to do in response to the next
  120482. ** token.
  120483. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  120484. ** symbols. Background: A "minor type" is a semantic
  120485. ** value associated with a terminal or non-terminal
  120486. ** symbols. For example, for an "ID" terminal symbol,
  120487. ** the minor type might be the name of the identifier.
  120488. ** Each non-terminal can have a different minor type.
  120489. ** Terminal symbols all have the same minor type, though.
  120490. ** This macros defines the minor type for terminal
  120491. ** symbols.
  120492. ** YYMINORTYPE is the data type used for all minor types.
  120493. ** This is typically a union of many types, one of
  120494. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  120495. ** for terminal symbols is called "yy0".
  120496. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  120497. ** zero the stack is dynamically sized using realloc()
  120498. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  120499. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  120500. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  120501. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  120502. ** YYERRORSYMBOL is the code number of the error symbol. If not
  120503. ** defined, then do no error processing.
  120504. ** YYNSTATE the combined number of states.
  120505. ** YYNRULE the number of rules in the grammar
  120506. ** YY_MAX_SHIFT Maximum value for shift actions
  120507. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  120508. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  120509. ** YY_MIN_REDUCE Maximum value for reduce actions
  120510. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  120511. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  120512. ** YY_NO_ACTION The yy_action[] code for no-op
  120513. */
  120514. #ifndef INTERFACE
  120515. # define INTERFACE 1
  120516. #endif
  120517. /************* Begin control #defines *****************************************/
  120518. #define YYCODETYPE unsigned char
  120519. #define YYNOCODE 251
  120520. #define YYACTIONTYPE unsigned short int
  120521. #define YYWILDCARD 70
  120522. #define sqlite3ParserTOKENTYPE Token
  120523. typedef union {
  120524. int yyinit;
  120525. sqlite3ParserTOKENTYPE yy0;
  120526. struct LimitVal yy64;
  120527. Expr* yy122;
  120528. Select* yy159;
  120529. IdList* yy180;
  120530. struct {int value; int mask;} yy207;
  120531. struct LikeOp yy318;
  120532. TriggerStep* yy327;
  120533. With* yy331;
  120534. ExprSpan yy342;
  120535. SrcList* yy347;
  120536. int yy392;
  120537. struct TrigEvent yy410;
  120538. ExprList* yy442;
  120539. } YYMINORTYPE;
  120540. #ifndef YYSTACKDEPTH
  120541. #define YYSTACKDEPTH 100
  120542. #endif
  120543. #define sqlite3ParserARG_SDECL Parse *pParse;
  120544. #define sqlite3ParserARG_PDECL ,Parse *pParse
  120545. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  120546. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  120547. #define YYFALLBACK 1
  120548. #define YYNSTATE 440
  120549. #define YYNRULE 326
  120550. #define YY_MAX_SHIFT 439
  120551. #define YY_MIN_SHIFTREDUCE 649
  120552. #define YY_MAX_SHIFTREDUCE 974
  120553. #define YY_MIN_REDUCE 975
  120554. #define YY_MAX_REDUCE 1300
  120555. #define YY_ERROR_ACTION 1301
  120556. #define YY_ACCEPT_ACTION 1302
  120557. #define YY_NO_ACTION 1303
  120558. /************* End control #defines *******************************************/
  120559. /* Define the yytestcase() macro to be a no-op if is not already defined
  120560. ** otherwise.
  120561. **
  120562. ** Applications can choose to define yytestcase() in the %include section
  120563. ** to a macro that can assist in verifying code coverage. For production
  120564. ** code the yytestcase() macro should be turned off. But it is useful
  120565. ** for testing.
  120566. */
  120567. #ifndef yytestcase
  120568. # define yytestcase(X)
  120569. #endif
  120570. /* Next are the tables used to determine what action to take based on the
  120571. ** current state and lookahead token. These tables are used to implement
  120572. ** functions that take a state number and lookahead value and return an
  120573. ** action integer.
  120574. **
  120575. ** Suppose the action integer is N. Then the action is determined as
  120576. ** follows
  120577. **
  120578. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  120579. ** token onto the stack and goto state N.
  120580. **
  120581. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  120582. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  120583. **
  120584. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  120585. ** and YY_MAX_REDUCE
  120586. ** N == YY_ERROR_ACTION A syntax error has occurred.
  120587. **
  120588. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  120589. **
  120590. ** N == YY_NO_ACTION No such action. Denotes unused
  120591. ** slots in the yy_action[] table.
  120592. **
  120593. ** The action table is constructed as a single large table named yy_action[].
  120594. ** Given state S and lookahead X, the action is computed as
  120595. **
  120596. ** yy_action[ yy_shift_ofst[S] + X ]
  120597. **
  120598. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  120599. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  120600. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  120601. ** and that yy_default[S] should be used instead.
  120602. **
  120603. ** The formula above is for computing the action when the lookahead is
  120604. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  120605. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  120606. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  120607. ** YY_SHIFT_USE_DFLT.
  120608. **
  120609. ** The following are the tables generated in this section:
  120610. **
  120611. ** yy_action[] A single table containing all actions.
  120612. ** yy_lookahead[] A table containing the lookahead for each entry in
  120613. ** yy_action. Used to detect hash collisions.
  120614. ** yy_shift_ofst[] For each state, the offset into yy_action for
  120615. ** shifting terminals.
  120616. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  120617. ** shifting non-terminals after a reduce.
  120618. ** yy_default[] Default action for each state.
  120619. **
  120620. *********** Begin parsing tables **********************************************/
  120621. #define YY_ACTTAB_COUNT (1499)
  120622. static const YYACTIONTYPE yy_action[] = {
  120623. /* 0 */ 315, 1302, 146, 921, 2, 194, 922, 342, 952, 91,
  120624. /* 10 */ 91, 91, 91, 84, 89, 89, 89, 89, 88, 88,
  120625. /* 20 */ 87, 87, 87, 86, 339, 87, 87, 87, 86, 339,
  120626. /* 30 */ 331, 819, 819, 91, 91, 91, 91, 339, 89, 89,
  120627. /* 40 */ 89, 89, 88, 88, 87, 87, 87, 86, 339, 319,
  120628. /* 50 */ 933, 933, 92, 93, 83, 831, 834, 823, 823, 90,
  120629. /* 60 */ 90, 91, 91, 91, 91, 123, 89, 89, 89, 89,
  120630. /* 70 */ 88, 88, 87, 87, 87, 86, 339, 315, 952, 89,
  120631. /* 80 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
  120632. /* 90 */ 365, 772, 360, 24, 933, 933, 947, 694, 933, 933,
  120633. /* 100 */ 773, 937, 933, 933, 434, 715, 328, 434, 819, 819,
  120634. /* 110 */ 203, 160, 278, 391, 273, 390, 190, 933, 933, 370,
  120635. /* 120 */ 934, 935, 367, 271, 953, 48, 679, 953, 48, 92,
  120636. /* 130 */ 93, 83, 831, 834, 823, 823, 90, 90, 91, 91,
  120637. /* 140 */ 91, 91, 123, 89, 89, 89, 89, 88, 88, 87,
  120638. /* 150 */ 87, 87, 86, 339, 315, 682, 337, 336, 218, 412,
  120639. /* 160 */ 398, 68, 412, 403, 934, 935, 743, 959, 934, 935,
  120640. /* 170 */ 810, 937, 934, 935, 957, 221, 958, 88, 88, 87,
  120641. /* 180 */ 87, 87, 86, 339, 291, 819, 819, 934, 935, 185,
  120642. /* 190 */ 94, 792, 388, 385, 384, 1240, 1240, 792, 804, 960,
  120643. /* 200 */ 960, 290, 798, 383, 123, 315, 92, 93, 83, 831,
  120644. /* 210 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 326,
  120645. /* 220 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
  120646. /* 230 */ 339, 681, 741, 803, 803, 803, 819, 819, 944, 56,
  120647. /* 240 */ 253, 353, 242, 85, 82, 168, 253, 358, 252, 110,
  120648. /* 250 */ 96, 233, 397, 698, 677, 683, 683, 92, 93, 83,
  120649. /* 260 */ 831, 834, 823, 823, 90, 90, 91, 91, 91, 91,
  120650. /* 270 */ 433, 89, 89, 89, 89, 88, 88, 87, 87, 87,
  120651. /* 280 */ 86, 339, 315, 434, 439, 651, 396, 57, 733, 733,
  120652. /* 290 */ 234, 291, 107, 287, 395, 86, 339, 810, 427, 728,
  120653. /* 300 */ 933, 933, 185, 953, 30, 388, 385, 384, 215, 949,
  120654. /* 310 */ 434, 933, 933, 819, 819, 697, 383, 162, 161, 407,
  120655. /* 320 */ 400, 85, 82, 168, 677, 804, 335, 113, 771, 798,
  120656. /* 330 */ 953, 48, 22, 351, 92, 93, 83, 831, 834, 823,
  120657. /* 340 */ 823, 90, 90, 91, 91, 91, 91, 870, 89, 89,
  120658. /* 350 */ 89, 89, 88, 88, 87, 87, 87, 86, 339, 315,
  120659. /* 360 */ 803, 803, 803, 268, 123, 412, 394, 1, 933, 933,
  120660. /* 370 */ 934, 935, 933, 933, 85, 82, 168, 232, 5, 343,
  120661. /* 380 */ 194, 934, 935, 952, 85, 82, 168, 54, 956, 434,
  120662. /* 390 */ 819, 819, 431, 938, 939, 792, 67, 759, 350, 144,
  120663. /* 400 */ 166, 770, 123, 896, 889, 955, 348, 288, 758, 953,
  120664. /* 410 */ 47, 92, 93, 83, 831, 834, 823, 823, 90, 90,
  120665. /* 420 */ 91, 91, 91, 91, 892, 89, 89, 89, 89, 88,
  120666. /* 430 */ 88, 87, 87, 87, 86, 339, 315, 113, 934, 935,
  120667. /* 440 */ 687, 893, 934, 935, 253, 358, 252, 85, 82, 168,
  120668. /* 450 */ 820, 820, 956, 952, 338, 938, 939, 894, 701, 721,
  120669. /* 460 */ 359, 289, 233, 397, 434, 349, 434, 819, 819, 955,
  120670. /* 470 */ 866, 722, 23, 389, 832, 835, 692, 357, 904, 667,
  120671. /* 480 */ 194, 702, 402, 952, 953, 48, 953, 48, 92, 93,
  120672. /* 490 */ 83, 831, 834, 823, 823, 90, 90, 91, 91, 91,
  120673. /* 500 */ 91, 824, 89, 89, 89, 89, 88, 88, 87, 87,
  120674. /* 510 */ 87, 86, 339, 315, 434, 113, 434, 680, 434, 332,
  120675. /* 520 */ 434, 408, 889, 356, 380, 940, 401, 720, 948, 864,
  120676. /* 530 */ 191, 165, 329, 689, 953, 9, 953, 9, 953, 9,
  120677. /* 540 */ 953, 9, 718, 948, 819, 819, 953, 8, 325, 111,
  120678. /* 550 */ 327, 153, 224, 952, 410, 113, 189, 337, 336, 913,
  120679. /* 560 */ 1295, 852, 75, 1295, 73, 92, 93, 83, 831, 834,
  120680. /* 570 */ 823, 823, 90, 90, 91, 91, 91, 91, 359, 89,
  120681. /* 580 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
  120682. /* 590 */ 315, 730, 148, 236, 797, 366, 789, 892, 1179, 434,
  120683. /* 600 */ 960, 960, 400, 148, 314, 212, 873, 911, 757, 404,
  120684. /* 610 */ 872, 300, 320, 434, 893, 311, 237, 271, 405, 953,
  120685. /* 620 */ 34, 819, 819, 225, 371, 945, 360, 913, 1296, 113,
  120686. /* 630 */ 894, 1296, 417, 953, 35, 1245, 922, 342, 259, 247,
  120687. /* 640 */ 290, 315, 92, 93, 83, 831, 834, 823, 823, 90,
  120688. /* 650 */ 90, 91, 91, 91, 91, 148, 89, 89, 89, 89,
  120689. /* 660 */ 88, 88, 87, 87, 87, 86, 339, 310, 434, 796,
  120690. /* 670 */ 434, 240, 819, 819, 266, 911, 876, 876, 373, 346,
  120691. /* 680 */ 167, 654, 655, 656, 259, 244, 19, 246, 953, 11,
  120692. /* 690 */ 953, 26, 222, 92, 93, 83, 831, 834, 823, 823,
  120693. /* 700 */ 90, 90, 91, 91, 91, 91, 757, 89, 89, 89,
  120694. /* 710 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 434,
  120695. /* 720 */ 261, 434, 264, 696, 434, 241, 434, 344, 971, 308,
  120696. /* 730 */ 757, 434, 796, 434, 324, 434, 393, 423, 434, 953,
  120697. /* 740 */ 36, 953, 37, 20, 953, 38, 953, 27, 434, 819,
  120698. /* 750 */ 819, 953, 28, 953, 39, 953, 40, 738, 953, 41,
  120699. /* 760 */ 71, 738, 737, 245, 307, 973, 737, 259, 953, 10,
  120700. /* 770 */ 92, 93, 83, 831, 834, 823, 823, 90, 90, 91,
  120701. /* 780 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
  120702. /* 790 */ 87, 87, 87, 86, 339, 315, 434, 372, 434, 259,
  120703. /* 800 */ 149, 434, 167, 953, 42, 188, 187, 186, 219, 434,
  120704. /* 810 */ 748, 434, 974, 434, 796, 434, 953, 98, 953, 43,
  120705. /* 820 */ 862, 953, 44, 434, 920, 2, 819, 819, 757, 953,
  120706. /* 830 */ 31, 953, 45, 953, 46, 953, 32, 74, 307, 912,
  120707. /* 840 */ 220, 259, 259, 953, 115, 909, 315, 92, 93, 83,
  120708. /* 850 */ 831, 834, 823, 823, 90, 90, 91, 91, 91, 91,
  120709. /* 860 */ 434, 89, 89, 89, 89, 88, 88, 87, 87, 87,
  120710. /* 870 */ 86, 339, 434, 248, 434, 215, 949, 819, 819, 333,
  120711. /* 880 */ 953, 116, 895, 860, 176, 259, 974, 400, 361, 259,
  120712. /* 890 */ 951, 887, 953, 117, 953, 52, 884, 315, 92, 93,
  120713. /* 900 */ 83, 831, 834, 823, 823, 90, 90, 91, 91, 91,
  120714. /* 910 */ 91, 434, 89, 89, 89, 89, 88, 88, 87, 87,
  120715. /* 920 */ 87, 86, 339, 434, 113, 434, 258, 883, 819, 819,
  120716. /* 930 */ 727, 953, 33, 363, 259, 673, 321, 189, 430, 321,
  120717. /* 940 */ 368, 365, 364, 953, 99, 953, 49, 365, 315, 92,
  120718. /* 950 */ 81, 83, 831, 834, 823, 823, 90, 90, 91, 91,
  120719. /* 960 */ 91, 91, 434, 89, 89, 89, 89, 88, 88, 87,
  120720. /* 970 */ 87, 87, 86, 339, 434, 723, 434, 214, 165, 819,
  120721. /* 980 */ 819, 772, 953, 100, 322, 124, 1269, 158, 65, 710,
  120722. /* 990 */ 773, 700, 699, 320, 953, 101, 953, 97, 255, 315,
  120723. /* 1000 */ 216, 93, 83, 831, 834, 823, 823, 90, 90, 91,
  120724. /* 1010 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
  120725. /* 1020 */ 87, 87, 87, 86, 339, 434, 251, 434, 707, 708,
  120726. /* 1030 */ 819, 819, 223, 953, 114, 908, 794, 254, 309, 193,
  120727. /* 1040 */ 67, 381, 869, 869, 199, 953, 112, 953, 105, 269,
  120728. /* 1050 */ 726, 260, 67, 83, 831, 834, 823, 823, 90, 90,
  120729. /* 1060 */ 91, 91, 91, 91, 263, 89, 89, 89, 89, 88,
  120730. /* 1070 */ 88, 87, 87, 87, 86, 339, 79, 429, 690, 3,
  120731. /* 1080 */ 1174, 228, 434, 113, 340, 340, 868, 868, 265, 79,
  120732. /* 1090 */ 429, 735, 3, 859, 70, 432, 434, 340, 340, 434,
  120733. /* 1100 */ 1259, 434, 953, 104, 434, 670, 416, 766, 432, 434,
  120734. /* 1110 */ 193, 434, 413, 434, 418, 806, 953, 102, 420, 953,
  120735. /* 1120 */ 103, 953, 48, 123, 953, 51, 810, 418, 424, 953,
  120736. /* 1130 */ 53, 953, 50, 953, 25, 267, 123, 711, 113, 810,
  120737. /* 1140 */ 428, 277, 695, 272, 764, 113, 76, 77, 690, 434,
  120738. /* 1150 */ 795, 113, 276, 78, 436, 435, 412, 414, 798, 76,
  120739. /* 1160 */ 77, 113, 855, 859, 376, 199, 78, 436, 435, 953,
  120740. /* 1170 */ 29, 798, 744, 113, 755, 79, 429, 675, 3, 415,
  120741. /* 1180 */ 109, 292, 293, 340, 340, 806, 802, 678, 672, 803,
  120742. /* 1190 */ 803, 803, 805, 18, 432, 661, 660, 662, 927, 209,
  120743. /* 1200 */ 150, 352, 803, 803, 803, 805, 18, 6, 306, 280,
  120744. /* 1210 */ 282, 284, 786, 418, 250, 386, 243, 886, 694, 362,
  120745. /* 1220 */ 286, 163, 275, 79, 429, 810, 3, 857, 856, 159,
  120746. /* 1230 */ 419, 340, 340, 298, 930, 968, 126, 196, 965, 903,
  120747. /* 1240 */ 901, 323, 432, 136, 55, 76, 77, 742, 147, 58,
  120748. /* 1250 */ 121, 129, 78, 436, 435, 65, 783, 798, 354, 131,
  120749. /* 1260 */ 355, 418, 379, 132, 133, 134, 175, 139, 151, 369,
  120750. /* 1270 */ 888, 180, 791, 810, 61, 851, 871, 69, 429, 375,
  120751. /* 1280 */ 3, 756, 210, 257, 181, 340, 340, 145, 803, 803,
  120752. /* 1290 */ 803, 805, 18, 76, 77, 377, 432, 262, 182, 183,
  120753. /* 1300 */ 78, 436, 435, 663, 312, 798, 392, 714, 713, 712,
  120754. /* 1310 */ 330, 705, 692, 313, 704, 418, 686, 406, 752, 685,
  120755. /* 1320 */ 274, 684, 942, 64, 279, 195, 281, 810, 753, 839,
  120756. /* 1330 */ 751, 283, 72, 750, 285, 422, 803, 803, 803, 805,
  120757. /* 1340 */ 18, 334, 426, 95, 411, 229, 409, 76, 77, 230,
  120758. /* 1350 */ 734, 66, 231, 294, 78, 436, 435, 204, 295, 798,
  120759. /* 1360 */ 217, 296, 297, 669, 21, 305, 304, 303, 206, 301,
  120760. /* 1370 */ 437, 928, 664, 205, 208, 207, 438, 658, 657, 652,
  120761. /* 1380 */ 118, 108, 119, 226, 650, 341, 157, 170, 169, 239,
  120762. /* 1390 */ 803, 803, 803, 805, 18, 125, 120, 235, 238, 317,
  120763. /* 1400 */ 318, 345, 106, 790, 867, 127, 865, 128, 130, 724,
  120764. /* 1410 */ 249, 172, 174, 882, 135, 137, 59, 138, 173, 60,
  120765. /* 1420 */ 885, 123, 171, 177, 178, 881, 7, 12, 179, 256,
  120766. /* 1430 */ 874, 140, 193, 962, 374, 141, 666, 152, 378, 276,
  120767. /* 1440 */ 184, 382, 142, 122, 62, 13, 387, 703, 270, 14,
  120768. /* 1450 */ 63, 227, 809, 808, 837, 732, 15, 841, 736, 4,
  120769. /* 1460 */ 765, 211, 399, 164, 213, 143, 760, 201, 70, 316,
  120770. /* 1470 */ 67, 838, 836, 891, 198, 192, 16, 197, 890, 917,
  120771. /* 1480 */ 154, 17, 202, 421, 918, 155, 200, 156, 425, 840,
  120772. /* 1490 */ 807, 1261, 676, 80, 302, 299, 347, 1260, 923,
  120773. };
  120774. static const YYCODETYPE yy_lookahead[] = {
  120775. /* 0 */ 19, 144, 145, 146, 147, 24, 1, 2, 27, 80,
  120776. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  120777. /* 20 */ 91, 92, 93, 94, 95, 91, 92, 93, 94, 95,
  120778. /* 30 */ 19, 50, 51, 80, 81, 82, 83, 95, 85, 86,
  120779. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 157,
  120780. /* 50 */ 27, 28, 71, 72, 73, 74, 75, 76, 77, 78,
  120781. /* 60 */ 79, 80, 81, 82, 83, 66, 85, 86, 87, 88,
  120782. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 85,
  120783. /* 80 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  120784. /* 90 */ 152, 33, 152, 22, 27, 28, 179, 180, 27, 28,
  120785. /* 100 */ 42, 27, 27, 28, 152, 188, 95, 152, 50, 51,
  120786. /* 110 */ 99, 100, 101, 102, 103, 104, 105, 27, 28, 227,
  120787. /* 120 */ 97, 98, 230, 112, 172, 173, 172, 172, 173, 71,
  120788. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  120789. /* 140 */ 82, 83, 66, 85, 86, 87, 88, 89, 90, 91,
  120790. /* 150 */ 92, 93, 94, 95, 19, 172, 89, 90, 218, 207,
  120791. /* 160 */ 208, 26, 207, 208, 97, 98, 91, 100, 97, 98,
  120792. /* 170 */ 69, 97, 97, 98, 107, 237, 109, 89, 90, 91,
  120793. /* 180 */ 92, 93, 94, 95, 152, 50, 51, 97, 98, 99,
  120794. /* 190 */ 55, 59, 102, 103, 104, 119, 120, 59, 97, 132,
  120795. /* 200 */ 133, 152, 101, 113, 66, 19, 71, 72, 73, 74,
  120796. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 187,
  120797. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  120798. /* 230 */ 95, 172, 210, 132, 133, 134, 50, 51, 185, 53,
  120799. /* 240 */ 108, 109, 110, 221, 222, 223, 108, 109, 110, 22,
  120800. /* 250 */ 22, 119, 120, 181, 27, 27, 28, 71, 72, 73,
  120801. /* 260 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  120802. /* 270 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  120803. /* 280 */ 94, 95, 19, 152, 148, 149, 115, 24, 117, 118,
  120804. /* 290 */ 154, 152, 156, 152, 163, 94, 95, 69, 249, 163,
  120805. /* 300 */ 27, 28, 99, 172, 173, 102, 103, 104, 194, 195,
  120806. /* 310 */ 152, 27, 28, 50, 51, 181, 113, 89, 90, 152,
  120807. /* 320 */ 206, 221, 222, 223, 97, 97, 187, 196, 175, 101,
  120808. /* 330 */ 172, 173, 196, 219, 71, 72, 73, 74, 75, 76,
  120809. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 11, 85, 86,
  120810. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  120811. /* 360 */ 132, 133, 134, 23, 66, 207, 208, 22, 27, 28,
  120812. /* 370 */ 97, 98, 27, 28, 221, 222, 223, 199, 22, 243,
  120813. /* 380 */ 24, 97, 98, 27, 221, 222, 223, 209, 152, 152,
  120814. /* 390 */ 50, 51, 168, 169, 170, 59, 26, 124, 100, 58,
  120815. /* 400 */ 152, 175, 66, 240, 163, 169, 170, 152, 124, 172,
  120816. /* 410 */ 173, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  120817. /* 420 */ 80, 81, 82, 83, 12, 85, 86, 87, 88, 89,
  120818. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 196, 97, 98,
  120819. /* 440 */ 23, 29, 97, 98, 108, 109, 110, 221, 222, 223,
  120820. /* 450 */ 50, 51, 152, 97, 168, 169, 170, 45, 37, 47,
  120821. /* 460 */ 219, 224, 119, 120, 152, 229, 152, 50, 51, 169,
  120822. /* 470 */ 170, 59, 231, 52, 74, 75, 106, 236, 152, 21,
  120823. /* 480 */ 24, 60, 163, 27, 172, 173, 172, 173, 71, 72,
  120824. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  120825. /* 500 */ 83, 101, 85, 86, 87, 88, 89, 90, 91, 92,
  120826. /* 510 */ 93, 94, 95, 19, 152, 196, 152, 23, 152, 207,
  120827. /* 520 */ 152, 207, 163, 65, 19, 171, 152, 190, 191, 229,
  120828. /* 530 */ 211, 212, 111, 179, 172, 173, 172, 173, 172, 173,
  120829. /* 540 */ 172, 173, 190, 191, 50, 51, 172, 173, 186, 22,
  120830. /* 550 */ 186, 24, 186, 97, 186, 196, 51, 89, 90, 22,
  120831. /* 560 */ 23, 103, 137, 26, 139, 71, 72, 73, 74, 75,
  120832. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 219, 85,
  120833. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  120834. /* 590 */ 19, 195, 152, 152, 23, 236, 163, 12, 140, 152,
  120835. /* 600 */ 132, 133, 206, 152, 164, 23, 31, 70, 26, 19,
  120836. /* 610 */ 35, 160, 107, 152, 29, 164, 152, 112, 28, 172,
  120837. /* 620 */ 173, 50, 51, 183, 49, 185, 152, 22, 23, 196,
  120838. /* 630 */ 45, 26, 47, 172, 173, 0, 1, 2, 152, 16,
  120839. /* 640 */ 152, 19, 71, 72, 73, 74, 75, 76, 77, 78,
  120840. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  120841. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 164, 152, 152,
  120842. /* 670 */ 152, 152, 50, 51, 16, 70, 108, 109, 110, 193,
  120843. /* 680 */ 98, 7, 8, 9, 152, 62, 22, 64, 172, 173,
  120844. /* 690 */ 172, 173, 218, 71, 72, 73, 74, 75, 76, 77,
  120845. /* 700 */ 78, 79, 80, 81, 82, 83, 124, 85, 86, 87,
  120846. /* 710 */ 88, 89, 90, 91, 92, 93, 94, 95, 19, 152,
  120847. /* 720 */ 62, 152, 64, 181, 152, 193, 152, 241, 246, 247,
  120848. /* 730 */ 26, 152, 152, 152, 217, 152, 91, 249, 152, 172,
  120849. /* 740 */ 173, 172, 173, 79, 172, 173, 172, 173, 152, 50,
  120850. /* 750 */ 51, 172, 173, 172, 173, 172, 173, 116, 172, 173,
  120851. /* 760 */ 138, 116, 121, 140, 22, 23, 121, 152, 172, 173,
  120852. /* 770 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  120853. /* 780 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  120854. /* 790 */ 91, 92, 93, 94, 95, 19, 152, 217, 152, 152,
  120855. /* 800 */ 24, 152, 98, 172, 173, 108, 109, 110, 193, 152,
  120856. /* 810 */ 213, 152, 70, 152, 152, 152, 172, 173, 172, 173,
  120857. /* 820 */ 152, 172, 173, 152, 146, 147, 50, 51, 124, 172,
  120858. /* 830 */ 173, 172, 173, 172, 173, 172, 173, 138, 22, 23,
  120859. /* 840 */ 193, 152, 152, 172, 173, 152, 19, 71, 72, 73,
  120860. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  120861. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  120862. /* 870 */ 94, 95, 152, 152, 152, 194, 195, 50, 51, 217,
  120863. /* 880 */ 172, 173, 193, 193, 26, 152, 70, 206, 152, 152,
  120864. /* 890 */ 26, 163, 172, 173, 172, 173, 152, 19, 71, 72,
  120865. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  120866. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  120867. /* 920 */ 93, 94, 95, 152, 196, 152, 193, 152, 50, 51,
  120868. /* 930 */ 193, 172, 173, 19, 152, 166, 167, 51, 166, 167,
  120869. /* 940 */ 152, 152, 28, 172, 173, 172, 173, 152, 19, 71,
  120870. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  120871. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  120872. /* 970 */ 92, 93, 94, 95, 152, 193, 152, 211, 212, 50,
  120873. /* 980 */ 51, 33, 172, 173, 244, 245, 23, 123, 130, 26,
  120874. /* 990 */ 42, 100, 101, 107, 172, 173, 172, 173, 152, 19,
  120875. /* 1000 */ 22, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  120876. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  120877. /* 1020 */ 91, 92, 93, 94, 95, 152, 237, 152, 7, 8,
  120878. /* 1030 */ 50, 51, 237, 172, 173, 23, 23, 23, 26, 26,
  120879. /* 1040 */ 26, 23, 132, 133, 26, 172, 173, 172, 173, 23,
  120880. /* 1050 */ 163, 152, 26, 73, 74, 75, 76, 77, 78, 79,
  120881. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  120882. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 27, 22,
  120883. /* 1080 */ 23, 210, 152, 196, 27, 28, 132, 133, 152, 19,
  120884. /* 1090 */ 20, 23, 22, 27, 26, 38, 152, 27, 28, 152,
  120885. /* 1100 */ 122, 152, 172, 173, 152, 163, 191, 23, 38, 152,
  120886. /* 1110 */ 26, 152, 163, 152, 57, 27, 172, 173, 163, 172,
  120887. /* 1120 */ 173, 172, 173, 66, 172, 173, 69, 57, 163, 172,
  120888. /* 1130 */ 173, 172, 173, 172, 173, 152, 66, 152, 196, 69,
  120889. /* 1140 */ 163, 101, 152, 152, 152, 196, 89, 90, 97, 152,
  120890. /* 1150 */ 152, 196, 112, 96, 97, 98, 207, 208, 101, 89,
  120891. /* 1160 */ 90, 196, 23, 97, 233, 26, 96, 97, 98, 172,
  120892. /* 1170 */ 173, 101, 152, 196, 152, 19, 20, 23, 22, 152,
  120893. /* 1180 */ 26, 152, 152, 27, 28, 97, 152, 152, 152, 132,
  120894. /* 1190 */ 133, 134, 135, 136, 38, 152, 152, 152, 152, 232,
  120895. /* 1200 */ 197, 214, 132, 133, 134, 135, 136, 198, 150, 210,
  120896. /* 1210 */ 210, 210, 201, 57, 238, 176, 214, 201, 180, 238,
  120897. /* 1220 */ 214, 184, 175, 19, 20, 69, 22, 175, 175, 198,
  120898. /* 1230 */ 226, 27, 28, 200, 155, 39, 242, 122, 41, 159,
  120899. /* 1240 */ 159, 159, 38, 22, 239, 89, 90, 91, 220, 239,
  120900. /* 1250 */ 71, 189, 96, 97, 98, 130, 201, 101, 18, 192,
  120901. /* 1260 */ 159, 57, 18, 192, 192, 192, 158, 189, 220, 159,
  120902. /* 1270 */ 201, 158, 189, 69, 137, 201, 235, 19, 20, 46,
  120903. /* 1280 */ 22, 159, 159, 234, 158, 27, 28, 22, 132, 133,
  120904. /* 1290 */ 134, 135, 136, 89, 90, 177, 38, 159, 158, 158,
  120905. /* 1300 */ 96, 97, 98, 159, 177, 101, 107, 174, 174, 174,
  120906. /* 1310 */ 48, 182, 106, 177, 182, 57, 174, 125, 216, 176,
  120907. /* 1320 */ 174, 174, 174, 107, 215, 159, 215, 69, 216, 159,
  120908. /* 1330 */ 216, 215, 137, 216, 215, 177, 132, 133, 134, 135,
  120909. /* 1340 */ 136, 95, 177, 129, 126, 225, 127, 89, 90, 228,
  120910. /* 1350 */ 205, 128, 228, 204, 96, 97, 98, 25, 203, 101,
  120911. /* 1360 */ 5, 202, 201, 162, 26, 10, 11, 12, 13, 14,
  120912. /* 1370 */ 161, 13, 17, 153, 6, 153, 151, 151, 151, 151,
  120913. /* 1380 */ 165, 178, 165, 178, 4, 3, 22, 32, 15, 34,
  120914. /* 1390 */ 132, 133, 134, 135, 136, 245, 165, 142, 43, 248,
  120915. /* 1400 */ 248, 68, 16, 120, 23, 131, 23, 111, 123, 20,
  120916. /* 1410 */ 16, 56, 125, 1, 123, 131, 79, 111, 63, 79,
  120917. /* 1420 */ 28, 66, 67, 36, 122, 1, 5, 22, 107, 140,
  120918. /* 1430 */ 54, 54, 26, 61, 44, 107, 20, 24, 19, 112,
  120919. /* 1440 */ 105, 53, 22, 40, 22, 22, 53, 30, 23, 22,
  120920. /* 1450 */ 22, 53, 23, 23, 23, 116, 22, 11, 23, 22,
  120921. /* 1460 */ 28, 23, 26, 122, 23, 22, 124, 122, 26, 114,
  120922. /* 1470 */ 26, 23, 23, 23, 22, 36, 36, 26, 23, 23,
  120923. /* 1480 */ 22, 36, 122, 24, 23, 22, 26, 22, 24, 23,
  120924. /* 1490 */ 23, 122, 23, 22, 15, 23, 141, 122, 1,
  120925. };
  120926. #define YY_SHIFT_USE_DFLT (-72)
  120927. #define YY_SHIFT_COUNT (439)
  120928. #define YY_SHIFT_MIN (-71)
  120929. #define YY_SHIFT_MAX (1497)
  120930. static const short yy_shift_ofst[] = {
  120931. /* 0 */ 5, 1057, 1355, 1070, 1204, 1204, 1204, 138, -19, 58,
  120932. /* 10 */ 58, 186, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 67,
  120933. /* 20 */ 67, 90, 132, 336, 76, 135, 263, 340, 417, 494,
  120934. /* 30 */ 571, 622, 699, 776, 827, 827, 827, 827, 827, 827,
  120935. /* 40 */ 827, 827, 827, 827, 827, 827, 827, 827, 827, 878,
  120936. /* 50 */ 827, 929, 980, 980, 1156, 1204, 1204, 1204, 1204, 1204,
  120937. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  120938. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  120939. /* 80 */ 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204, 1204,
  120940. /* 90 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, -71, -47, -47,
  120941. /* 100 */ -47, -47, -47, -6, 88, -66, 23, 458, 505, 468,
  120942. /* 110 */ 468, 23, 201, 343, -58, -72, -72, -72, 11, 11,
  120943. /* 120 */ 11, 412, 412, 341, 537, 605, 23, 23, 23, 23,
  120944. /* 130 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
  120945. /* 140 */ 23, 23, 23, 23, 23, 23, 635, 298, 74, 74,
  120946. /* 150 */ 343, -1, -1, -1, -1, -1, -1, -72, -72, -72,
  120947. /* 160 */ 228, 101, 101, 203, 75, 71, 273, 284, 345, 23,
  120948. /* 170 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
  120949. /* 180 */ 23, 23, 23, 23, 23, 23, 421, 421, 421, 23,
  120950. /* 190 */ 23, 582, 23, 23, 23, 356, 23, 23, 585, 23,
  120951. /* 200 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 568,
  120952. /* 210 */ 575, 456, 456, 456, 704, 171, 645, 674, 858, 590,
  120953. /* 220 */ 590, 914, 858, 914, 370, 963, 886, 948, 590, 425,
  120954. /* 230 */ 948, 948, 864, 641, 527, 1196, 1115, 1115, 1197, 1197,
  120955. /* 240 */ 1115, 1221, 1179, 1125, 1240, 1240, 1240, 1240, 1115, 1244,
  120956. /* 250 */ 1125, 1221, 1179, 1179, 1125, 1115, 1244, 1137, 1233, 1115,
  120957. /* 260 */ 1115, 1244, 1265, 1115, 1244, 1115, 1244, 1265, 1199, 1199,
  120958. /* 270 */ 1199, 1262, 1265, 1199, 1206, 1199, 1262, 1199, 1199, 1192,
  120959. /* 280 */ 1216, 1192, 1216, 1192, 1216, 1192, 1216, 1115, 1115, 1195,
  120960. /* 290 */ 1265, 1246, 1246, 1265, 1214, 1218, 1223, 1219, 1125, 1332,
  120961. /* 300 */ 1338, 1358, 1358, 1368, 1368, 1368, 1368, -72, -72, -72,
  120962. /* 310 */ -72, -72, -72, -72, -72, 400, 623, 742, 816, 658,
  120963. /* 320 */ 697, 227, 1012, 664, 1013, 1014, 1018, 1026, 1051, 891,
  120964. /* 330 */ 1021, 1040, 1068, 1084, 1066, 1139, 910, 954, 1154, 1088,
  120965. /* 340 */ 978, 1380, 1382, 1364, 1255, 1373, 1333, 1386, 1381, 1383,
  120966. /* 350 */ 1283, 1274, 1296, 1285, 1389, 1287, 1394, 1412, 1291, 1284,
  120967. /* 360 */ 1337, 1340, 1306, 1392, 1387, 1302, 1424, 1421, 1405, 1321,
  120968. /* 370 */ 1289, 1376, 1406, 1377, 1372, 1390, 1328, 1413, 1416, 1419,
  120969. /* 380 */ 1327, 1335, 1420, 1388, 1422, 1423, 1425, 1427, 1393, 1417,
  120970. /* 390 */ 1428, 1398, 1403, 1429, 1430, 1431, 1339, 1434, 1435, 1437,
  120971. /* 400 */ 1436, 1341, 1438, 1441, 1432, 1439, 1443, 1342, 1442, 1440,
  120972. /* 410 */ 1444, 1445, 1442, 1448, 1449, 1450, 1451, 1455, 1452, 1446,
  120973. /* 420 */ 1456, 1458, 1459, 1460, 1461, 1463, 1464, 1460, 1466, 1465,
  120974. /* 430 */ 1467, 1469, 1471, 1345, 1360, 1369, 1375, 1472, 1479, 1497,
  120975. };
  120976. #define YY_REDUCE_USE_DFLT (-144)
  120977. #define YY_REDUCE_COUNT (314)
  120978. #define YY_REDUCE_MIN (-143)
  120979. #define YY_REDUCE_MAX (1231)
  120980. static const short yy_reduce_ofst[] = {
  120981. /* 0 */ -143, 949, 136, 131, -48, -45, 158, 241, 22, 153,
  120982. /* 10 */ 226, 163, 362, 364, 366, 312, 314, 368, 237, 236,
  120983. /* 20 */ 300, 440, 114, 359, 319, 100, 100, 100, 100, 100,
  120984. /* 30 */ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
  120985. /* 40 */ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
  120986. /* 50 */ 100, 100, 100, 100, 374, 447, 461, 516, 518, 567,
  120987. /* 60 */ 569, 572, 574, 579, 581, 583, 586, 596, 631, 644,
  120988. /* 70 */ 646, 649, 657, 659, 661, 663, 671, 708, 720, 722,
  120989. /* 80 */ 759, 771, 773, 810, 822, 824, 861, 873, 875, 930,
  120990. /* 90 */ 944, 947, 952, 957, 959, 961, 997, 100, 100, 100,
  120991. /* 100 */ 100, 100, 100, 100, 100, 100, 486, -108, -83, 224,
  120992. /* 110 */ 286, 451, 100, 681, 100, 100, 100, 100, 354, 354,
  120993. /* 120 */ 354, 337, 352, 49, 482, 482, 503, 532, -60, 615,
  120994. /* 130 */ 647, 689, 690, 737, 782, -62, 517, 789, 474, 795,
  120995. /* 140 */ 580, 733, 32, 662, 488, 139, 678, 433, 769, 772,
  120996. /* 150 */ 396, 728, 887, 942, 955, 965, 977, 740, 766, 178,
  120997. /* 160 */ -46, -17, 59, 53, 118, 141, 167, 248, 255, 326,
  120998. /* 170 */ 441, 464, 519, 668, 693, 721, 736, 744, 775, 788,
  120999. /* 180 */ 846, 899, 912, 936, 983, 985, 72, 134, 542, 990,
  121000. /* 190 */ 991, 597, 992, 998, 1020, 871, 1022, 1027, 915, 1029,
  121001. /* 200 */ 1030, 1034, 118, 1035, 1036, 1043, 1044, 1045, 1046, 931,
  121002. /* 210 */ 967, 999, 1000, 1001, 597, 1003, 1009, 1058, 1011, 987,
  121003. /* 220 */ 1002, 976, 1016, 981, 1039, 1037, 1038, 1047, 1006, 1004,
  121004. /* 230 */ 1052, 1053, 1033, 1031, 1079, 994, 1080, 1081, 1005, 1010,
  121005. /* 240 */ 1082, 1028, 1062, 1055, 1067, 1071, 1072, 1073, 1101, 1108,
  121006. /* 250 */ 1069, 1048, 1078, 1083, 1074, 1110, 1113, 1041, 1049, 1122,
  121007. /* 260 */ 1123, 1126, 1118, 1138, 1140, 1144, 1141, 1127, 1133, 1134,
  121008. /* 270 */ 1135, 1129, 1136, 1142, 1143, 1146, 1132, 1147, 1148, 1102,
  121009. /* 280 */ 1109, 1112, 1111, 1114, 1116, 1117, 1119, 1166, 1170, 1120,
  121010. /* 290 */ 1158, 1121, 1124, 1165, 1145, 1149, 1155, 1159, 1161, 1201,
  121011. /* 300 */ 1209, 1220, 1222, 1225, 1226, 1227, 1228, 1151, 1152, 1150,
  121012. /* 310 */ 1215, 1217, 1203, 1205, 1231,
  121013. };
  121014. static const YYACTIONTYPE yy_default[] = {
  121015. /* 0 */ 1250, 1240, 1240, 1240, 1174, 1174, 1174, 1240, 1071, 1100,
  121016. /* 10 */ 1100, 1224, 1301, 1301, 1301, 1301, 1301, 1301, 1173, 1301,
  121017. /* 20 */ 1301, 1301, 1301, 1240, 1075, 1106, 1301, 1301, 1301, 1301,
  121018. /* 30 */ 1301, 1301, 1301, 1301, 1223, 1225, 1114, 1113, 1206, 1087,
  121019. /* 40 */ 1111, 1104, 1108, 1175, 1169, 1170, 1168, 1172, 1176, 1301,
  121020. /* 50 */ 1107, 1138, 1153, 1137, 1301, 1301, 1301, 1301, 1301, 1301,
  121021. /* 60 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121022. /* 70 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121023. /* 80 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121024. /* 90 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1147, 1152, 1159,
  121025. /* 100 */ 1151, 1148, 1140, 1139, 1141, 1142, 1301, 994, 1042, 1301,
  121026. /* 110 */ 1301, 1301, 1143, 1301, 1144, 1156, 1155, 1154, 1231, 1258,
  121027. /* 120 */ 1257, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121028. /* 130 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121029. /* 140 */ 1301, 1301, 1301, 1301, 1301, 1301, 1250, 1240, 1000, 1000,
  121030. /* 150 */ 1301, 1240, 1240, 1240, 1240, 1240, 1240, 1236, 1075, 1066,
  121031. /* 160 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121032. /* 170 */ 1228, 1226, 1301, 1187, 1301, 1301, 1301, 1301, 1301, 1301,
  121033. /* 180 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121034. /* 190 */ 1301, 1301, 1301, 1301, 1301, 1071, 1301, 1301, 1301, 1301,
  121035. /* 200 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1252, 1301,
  121036. /* 210 */ 1201, 1071, 1071, 1071, 1073, 1055, 1065, 979, 1110, 1089,
  121037. /* 220 */ 1089, 1290, 1110, 1290, 1017, 1272, 1014, 1100, 1089, 1171,
  121038. /* 230 */ 1100, 1100, 1072, 1065, 1301, 1293, 1080, 1080, 1292, 1292,
  121039. /* 240 */ 1080, 1119, 1045, 1110, 1051, 1051, 1051, 1051, 1080, 991,
  121040. /* 250 */ 1110, 1119, 1045, 1045, 1110, 1080, 991, 1205, 1287, 1080,
  121041. /* 260 */ 1080, 991, 1180, 1080, 991, 1080, 991, 1180, 1043, 1043,
  121042. /* 270 */ 1043, 1032, 1180, 1043, 1017, 1043, 1032, 1043, 1043, 1093,
  121043. /* 280 */ 1088, 1093, 1088, 1093, 1088, 1093, 1088, 1080, 1080, 1301,
  121044. /* 290 */ 1180, 1184, 1184, 1180, 1105, 1094, 1103, 1101, 1110, 997,
  121045. /* 300 */ 1035, 1255, 1255, 1251, 1251, 1251, 1251, 1298, 1298, 1236,
  121046. /* 310 */ 1267, 1267, 1019, 1019, 1267, 1301, 1301, 1301, 1301, 1301,
  121047. /* 320 */ 1301, 1262, 1301, 1189, 1301, 1301, 1301, 1301, 1301, 1301,
  121048. /* 330 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121049. /* 340 */ 1125, 1301, 975, 1233, 1301, 1301, 1232, 1301, 1301, 1301,
  121050. /* 350 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121051. /* 360 */ 1301, 1301, 1301, 1301, 1301, 1289, 1301, 1301, 1301, 1301,
  121052. /* 370 */ 1301, 1301, 1204, 1203, 1301, 1301, 1301, 1301, 1301, 1301,
  121053. /* 380 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121054. /* 390 */ 1301, 1301, 1301, 1301, 1301, 1301, 1057, 1301, 1301, 1301,
  121055. /* 400 */ 1276, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1102, 1301,
  121056. /* 410 */ 1095, 1301, 1280, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
  121057. /* 420 */ 1301, 1301, 1301, 1242, 1301, 1301, 1301, 1241, 1301, 1301,
  121058. /* 430 */ 1301, 1301, 1301, 1127, 1301, 1126, 1130, 1301, 985, 1301,
  121059. };
  121060. /********** End of lemon-generated parsing tables *****************************/
  121061. /* The next table maps tokens (terminal symbols) into fallback tokens.
  121062. ** If a construct like the following:
  121063. **
  121064. ** %fallback ID X Y Z.
  121065. **
  121066. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  121067. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  121068. ** but it does not parse, the type of the token is changed to ID and
  121069. ** the parse is retried before an error is thrown.
  121070. **
  121071. ** This feature can be used, for example, to cause some keywords in a language
  121072. ** to revert to identifiers if they keyword does not apply in the context where
  121073. ** it appears.
  121074. */
  121075. #ifdef YYFALLBACK
  121076. static const YYCODETYPE yyFallback[] = {
  121077. 0, /* $ => nothing */
  121078. 0, /* SEMI => nothing */
  121079. 27, /* EXPLAIN => ID */
  121080. 27, /* QUERY => ID */
  121081. 27, /* PLAN => ID */
  121082. 27, /* BEGIN => ID */
  121083. 0, /* TRANSACTION => nothing */
  121084. 27, /* DEFERRED => ID */
  121085. 27, /* IMMEDIATE => ID */
  121086. 27, /* EXCLUSIVE => ID */
  121087. 0, /* COMMIT => nothing */
  121088. 27, /* END => ID */
  121089. 27, /* ROLLBACK => ID */
  121090. 27, /* SAVEPOINT => ID */
  121091. 27, /* RELEASE => ID */
  121092. 0, /* TO => nothing */
  121093. 0, /* TABLE => nothing */
  121094. 0, /* CREATE => nothing */
  121095. 27, /* IF => ID */
  121096. 0, /* NOT => nothing */
  121097. 0, /* EXISTS => nothing */
  121098. 27, /* TEMP => ID */
  121099. 0, /* LP => nothing */
  121100. 0, /* RP => nothing */
  121101. 0, /* AS => nothing */
  121102. 27, /* WITHOUT => ID */
  121103. 0, /* COMMA => nothing */
  121104. 0, /* ID => nothing */
  121105. 0, /* INDEXED => nothing */
  121106. 27, /* ABORT => ID */
  121107. 27, /* ACTION => ID */
  121108. 27, /* AFTER => ID */
  121109. 27, /* ANALYZE => ID */
  121110. 27, /* ASC => ID */
  121111. 27, /* ATTACH => ID */
  121112. 27, /* BEFORE => ID */
  121113. 27, /* BY => ID */
  121114. 27, /* CASCADE => ID */
  121115. 27, /* CAST => ID */
  121116. 27, /* COLUMNKW => ID */
  121117. 27, /* CONFLICT => ID */
  121118. 27, /* DATABASE => ID */
  121119. 27, /* DESC => ID */
  121120. 27, /* DETACH => ID */
  121121. 27, /* EACH => ID */
  121122. 27, /* FAIL => ID */
  121123. 27, /* FOR => ID */
  121124. 27, /* IGNORE => ID */
  121125. 27, /* INITIALLY => ID */
  121126. 27, /* INSTEAD => ID */
  121127. 27, /* LIKE_KW => ID */
  121128. 27, /* MATCH => ID */
  121129. 27, /* NO => ID */
  121130. 27, /* KEY => ID */
  121131. 27, /* OF => ID */
  121132. 27, /* OFFSET => ID */
  121133. 27, /* PRAGMA => ID */
  121134. 27, /* RAISE => ID */
  121135. 27, /* RECURSIVE => ID */
  121136. 27, /* REPLACE => ID */
  121137. 27, /* RESTRICT => ID */
  121138. 27, /* ROW => ID */
  121139. 27, /* TRIGGER => ID */
  121140. 27, /* VACUUM => ID */
  121141. 27, /* VIEW => ID */
  121142. 27, /* VIRTUAL => ID */
  121143. 27, /* WITH => ID */
  121144. 27, /* REINDEX => ID */
  121145. 27, /* RENAME => ID */
  121146. 27, /* CTIME_KW => ID */
  121147. };
  121148. #endif /* YYFALLBACK */
  121149. /* The following structure represents a single element of the
  121150. ** parser's stack. Information stored includes:
  121151. **
  121152. ** + The state number for the parser at this level of the stack.
  121153. **
  121154. ** + The value of the token stored at this level of the stack.
  121155. ** (In other words, the "major" token.)
  121156. **
  121157. ** + The semantic value stored at this level of the stack. This is
  121158. ** the information used by the action routines in the grammar.
  121159. ** It is sometimes called the "minor" token.
  121160. **
  121161. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  121162. ** actually contains the reduce action for the second half of the
  121163. ** SHIFTREDUCE.
  121164. */
  121165. struct yyStackEntry {
  121166. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  121167. YYCODETYPE major; /* The major token value. This is the code
  121168. ** number for the token at this stack level */
  121169. YYMINORTYPE minor; /* The user-supplied minor token value. This
  121170. ** is the value of the token */
  121171. };
  121172. typedef struct yyStackEntry yyStackEntry;
  121173. /* The state of the parser is completely contained in an instance of
  121174. ** the following structure */
  121175. struct yyParser {
  121176. int yyidx; /* Index of top element in stack */
  121177. #ifdef YYTRACKMAXSTACKDEPTH
  121178. int yyidxMax; /* Maximum value of yyidx */
  121179. #endif
  121180. #ifndef YYNOERRORRECOVERY
  121181. int yyerrcnt; /* Shifts left before out of the error */
  121182. #endif
  121183. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  121184. #if YYSTACKDEPTH<=0
  121185. int yystksz; /* Current side of the stack */
  121186. yyStackEntry *yystack; /* The parser's stack */
  121187. #else
  121188. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  121189. #endif
  121190. };
  121191. typedef struct yyParser yyParser;
  121192. #ifndef NDEBUG
  121193. /* #include <stdio.h> */
  121194. static FILE *yyTraceFILE = 0;
  121195. static char *yyTracePrompt = 0;
  121196. #endif /* NDEBUG */
  121197. #ifndef NDEBUG
  121198. /*
  121199. ** Turn parser tracing on by giving a stream to which to write the trace
  121200. ** and a prompt to preface each trace message. Tracing is turned off
  121201. ** by making either argument NULL
  121202. **
  121203. ** Inputs:
  121204. ** <ul>
  121205. ** <li> A FILE* to which trace output should be written.
  121206. ** If NULL, then tracing is turned off.
  121207. ** <li> A prefix string written at the beginning of every
  121208. ** line of trace output. If NULL, then tracing is
  121209. ** turned off.
  121210. ** </ul>
  121211. **
  121212. ** Outputs:
  121213. ** None.
  121214. */
  121215. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  121216. yyTraceFILE = TraceFILE;
  121217. yyTracePrompt = zTracePrompt;
  121218. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  121219. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  121220. }
  121221. #endif /* NDEBUG */
  121222. #ifndef NDEBUG
  121223. /* For tracing shifts, the names of all terminals and nonterminals
  121224. ** are required. The following table supplies these names */
  121225. static const char *const yyTokenName[] = {
  121226. "$", "SEMI", "EXPLAIN", "QUERY",
  121227. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  121228. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  121229. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  121230. "TABLE", "CREATE", "IF", "NOT",
  121231. "EXISTS", "TEMP", "LP", "RP",
  121232. "AS", "WITHOUT", "COMMA", "ID",
  121233. "INDEXED", "ABORT", "ACTION", "AFTER",
  121234. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  121235. "BY", "CASCADE", "CAST", "COLUMNKW",
  121236. "CONFLICT", "DATABASE", "DESC", "DETACH",
  121237. "EACH", "FAIL", "FOR", "IGNORE",
  121238. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  121239. "NO", "KEY", "OF", "OFFSET",
  121240. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  121241. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  121242. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  121243. "RENAME", "CTIME_KW", "ANY", "OR",
  121244. "AND", "IS", "BETWEEN", "IN",
  121245. "ISNULL", "NOTNULL", "NE", "EQ",
  121246. "GT", "LE", "LT", "GE",
  121247. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  121248. "RSHIFT", "PLUS", "MINUS", "STAR",
  121249. "SLASH", "REM", "CONCAT", "COLLATE",
  121250. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  121251. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  121252. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  121253. "INSERT", "DELETE", "UPDATE", "SET",
  121254. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  121255. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  121256. "VALUES", "DISTINCT", "DOT", "FROM",
  121257. "JOIN", "USING", "ORDER", "GROUP",
  121258. "HAVING", "LIMIT", "WHERE", "INTO",
  121259. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  121260. "CASE", "WHEN", "THEN", "ELSE",
  121261. "INDEX", "ALTER", "ADD", "error",
  121262. "input", "cmdlist", "ecmd", "explain",
  121263. "cmdx", "cmd", "transtype", "trans_opt",
  121264. "nm", "savepoint_opt", "create_table", "create_table_args",
  121265. "createkw", "temp", "ifnotexists", "dbnm",
  121266. "columnlist", "conslist_opt", "table_options", "select",
  121267. "columnname", "carglist", "typetoken", "typename",
  121268. "signed", "plus_num", "minus_num", "ccons",
  121269. "term", "expr", "onconf", "sortorder",
  121270. "autoinc", "eidlist_opt", "refargs", "defer_subclause",
  121271. "refarg", "refact", "init_deferred_pred_opt", "conslist",
  121272. "tconscomma", "tcons", "sortlist", "eidlist",
  121273. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  121274. "ifexists", "fullname", "selectnowith", "oneselect",
  121275. "with", "multiselect_op", "distinct", "selcollist",
  121276. "from", "where_opt", "groupby_opt", "having_opt",
  121277. "orderby_opt", "limit_opt", "values", "nexprlist",
  121278. "exprlist", "sclp", "as", "seltablist",
  121279. "stl_prefix", "joinop", "indexed_opt", "on_opt",
  121280. "using_opt", "idlist", "setlist", "insert_cmd",
  121281. "idlist_opt", "likeop", "between_op", "in_op",
  121282. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  121283. "collate", "nmnum", "trigger_decl", "trigger_cmd_list",
  121284. "trigger_time", "trigger_event", "foreach_clause", "when_clause",
  121285. "trigger_cmd", "trnm", "tridxby", "database_kw_opt",
  121286. "key_opt", "add_column_fullname", "kwcolumn_opt", "create_vtab",
  121287. "vtabarglist", "vtabarg", "vtabargtoken", "lp",
  121288. "anylist", "wqlist",
  121289. };
  121290. #endif /* NDEBUG */
  121291. #ifndef NDEBUG
  121292. /* For tracing reduce actions, the names of all rules are required.
  121293. */
  121294. static const char *const yyRuleName[] = {
  121295. /* 0 */ "explain ::= EXPLAIN",
  121296. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  121297. /* 2 */ "cmdx ::= cmd",
  121298. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  121299. /* 4 */ "transtype ::=",
  121300. /* 5 */ "transtype ::= DEFERRED",
  121301. /* 6 */ "transtype ::= IMMEDIATE",
  121302. /* 7 */ "transtype ::= EXCLUSIVE",
  121303. /* 8 */ "cmd ::= COMMIT trans_opt",
  121304. /* 9 */ "cmd ::= END trans_opt",
  121305. /* 10 */ "cmd ::= ROLLBACK trans_opt",
  121306. /* 11 */ "cmd ::= SAVEPOINT nm",
  121307. /* 12 */ "cmd ::= RELEASE savepoint_opt nm",
  121308. /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  121309. /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  121310. /* 15 */ "createkw ::= CREATE",
  121311. /* 16 */ "ifnotexists ::=",
  121312. /* 17 */ "ifnotexists ::= IF NOT EXISTS",
  121313. /* 18 */ "temp ::= TEMP",
  121314. /* 19 */ "temp ::=",
  121315. /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  121316. /* 21 */ "create_table_args ::= AS select",
  121317. /* 22 */ "table_options ::=",
  121318. /* 23 */ "table_options ::= WITHOUT nm",
  121319. /* 24 */ "columnname ::= nm typetoken",
  121320. /* 25 */ "typetoken ::=",
  121321. /* 26 */ "typetoken ::= typename LP signed RP",
  121322. /* 27 */ "typetoken ::= typename LP signed COMMA signed RP",
  121323. /* 28 */ "typename ::= typename ID|STRING",
  121324. /* 29 */ "ccons ::= CONSTRAINT nm",
  121325. /* 30 */ "ccons ::= DEFAULT term",
  121326. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  121327. /* 32 */ "ccons ::= DEFAULT PLUS term",
  121328. /* 33 */ "ccons ::= DEFAULT MINUS term",
  121329. /* 34 */ "ccons ::= DEFAULT ID|INDEXED",
  121330. /* 35 */ "ccons ::= NOT NULL onconf",
  121331. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  121332. /* 37 */ "ccons ::= UNIQUE onconf",
  121333. /* 38 */ "ccons ::= CHECK LP expr RP",
  121334. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  121335. /* 40 */ "ccons ::= defer_subclause",
  121336. /* 41 */ "ccons ::= COLLATE ID|STRING",
  121337. /* 42 */ "autoinc ::=",
  121338. /* 43 */ "autoinc ::= AUTOINCR",
  121339. /* 44 */ "refargs ::=",
  121340. /* 45 */ "refargs ::= refargs refarg",
  121341. /* 46 */ "refarg ::= MATCH nm",
  121342. /* 47 */ "refarg ::= ON INSERT refact",
  121343. /* 48 */ "refarg ::= ON DELETE refact",
  121344. /* 49 */ "refarg ::= ON UPDATE refact",
  121345. /* 50 */ "refact ::= SET NULL",
  121346. /* 51 */ "refact ::= SET DEFAULT",
  121347. /* 52 */ "refact ::= CASCADE",
  121348. /* 53 */ "refact ::= RESTRICT",
  121349. /* 54 */ "refact ::= NO ACTION",
  121350. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  121351. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  121352. /* 57 */ "init_deferred_pred_opt ::=",
  121353. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  121354. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  121355. /* 60 */ "conslist_opt ::=",
  121356. /* 61 */ "tconscomma ::= COMMA",
  121357. /* 62 */ "tcons ::= CONSTRAINT nm",
  121358. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  121359. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  121360. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  121361. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  121362. /* 67 */ "defer_subclause_opt ::=",
  121363. /* 68 */ "onconf ::=",
  121364. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  121365. /* 70 */ "orconf ::=",
  121366. /* 71 */ "orconf ::= OR resolvetype",
  121367. /* 72 */ "resolvetype ::= IGNORE",
  121368. /* 73 */ "resolvetype ::= REPLACE",
  121369. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  121370. /* 75 */ "ifexists ::= IF EXISTS",
  121371. /* 76 */ "ifexists ::=",
  121372. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  121373. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  121374. /* 79 */ "cmd ::= select",
  121375. /* 80 */ "select ::= with selectnowith",
  121376. /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  121377. /* 82 */ "multiselect_op ::= UNION",
  121378. /* 83 */ "multiselect_op ::= UNION ALL",
  121379. /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT",
  121380. /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  121381. /* 86 */ "values ::= VALUES LP nexprlist RP",
  121382. /* 87 */ "values ::= values COMMA LP exprlist RP",
  121383. /* 88 */ "distinct ::= DISTINCT",
  121384. /* 89 */ "distinct ::= ALL",
  121385. /* 90 */ "distinct ::=",
  121386. /* 91 */ "sclp ::=",
  121387. /* 92 */ "selcollist ::= sclp expr as",
  121388. /* 93 */ "selcollist ::= sclp STAR",
  121389. /* 94 */ "selcollist ::= sclp nm DOT STAR",
  121390. /* 95 */ "as ::= AS nm",
  121391. /* 96 */ "as ::=",
  121392. /* 97 */ "from ::=",
  121393. /* 98 */ "from ::= FROM seltablist",
  121394. /* 99 */ "stl_prefix ::= seltablist joinop",
  121395. /* 100 */ "stl_prefix ::=",
  121396. /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  121397. /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  121398. /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  121399. /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  121400. /* 105 */ "dbnm ::=",
  121401. /* 106 */ "dbnm ::= DOT nm",
  121402. /* 107 */ "fullname ::= nm dbnm",
  121403. /* 108 */ "joinop ::= COMMA|JOIN",
  121404. /* 109 */ "joinop ::= JOIN_KW JOIN",
  121405. /* 110 */ "joinop ::= JOIN_KW nm JOIN",
  121406. /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
  121407. /* 112 */ "on_opt ::= ON expr",
  121408. /* 113 */ "on_opt ::=",
  121409. /* 114 */ "indexed_opt ::=",
  121410. /* 115 */ "indexed_opt ::= INDEXED BY nm",
  121411. /* 116 */ "indexed_opt ::= NOT INDEXED",
  121412. /* 117 */ "using_opt ::= USING LP idlist RP",
  121413. /* 118 */ "using_opt ::=",
  121414. /* 119 */ "orderby_opt ::=",
  121415. /* 120 */ "orderby_opt ::= ORDER BY sortlist",
  121416. /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
  121417. /* 122 */ "sortlist ::= expr sortorder",
  121418. /* 123 */ "sortorder ::= ASC",
  121419. /* 124 */ "sortorder ::= DESC",
  121420. /* 125 */ "sortorder ::=",
  121421. /* 126 */ "groupby_opt ::=",
  121422. /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
  121423. /* 128 */ "having_opt ::=",
  121424. /* 129 */ "having_opt ::= HAVING expr",
  121425. /* 130 */ "limit_opt ::=",
  121426. /* 131 */ "limit_opt ::= LIMIT expr",
  121427. /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
  121428. /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
  121429. /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  121430. /* 135 */ "where_opt ::=",
  121431. /* 136 */ "where_opt ::= WHERE expr",
  121432. /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  121433. /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
  121434. /* 139 */ "setlist ::= nm EQ expr",
  121435. /* 140 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  121436. /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  121437. /* 142 */ "insert_cmd ::= INSERT orconf",
  121438. /* 143 */ "insert_cmd ::= REPLACE",
  121439. /* 144 */ "idlist_opt ::=",
  121440. /* 145 */ "idlist_opt ::= LP idlist RP",
  121441. /* 146 */ "idlist ::= idlist COMMA nm",
  121442. /* 147 */ "idlist ::= nm",
  121443. /* 148 */ "expr ::= LP expr RP",
  121444. /* 149 */ "term ::= NULL",
  121445. /* 150 */ "expr ::= ID|INDEXED",
  121446. /* 151 */ "expr ::= JOIN_KW",
  121447. /* 152 */ "expr ::= nm DOT nm",
  121448. /* 153 */ "expr ::= nm DOT nm DOT nm",
  121449. /* 154 */ "term ::= INTEGER|FLOAT|BLOB",
  121450. /* 155 */ "term ::= STRING",
  121451. /* 156 */ "expr ::= VARIABLE",
  121452. /* 157 */ "expr ::= expr COLLATE ID|STRING",
  121453. /* 158 */ "expr ::= CAST LP expr AS typetoken RP",
  121454. /* 159 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  121455. /* 160 */ "expr ::= ID|INDEXED LP STAR RP",
  121456. /* 161 */ "term ::= CTIME_KW",
  121457. /* 162 */ "expr ::= expr AND expr",
  121458. /* 163 */ "expr ::= expr OR expr",
  121459. /* 164 */ "expr ::= expr LT|GT|GE|LE expr",
  121460. /* 165 */ "expr ::= expr EQ|NE expr",
  121461. /* 166 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  121462. /* 167 */ "expr ::= expr PLUS|MINUS expr",
  121463. /* 168 */ "expr ::= expr STAR|SLASH|REM expr",
  121464. /* 169 */ "expr ::= expr CONCAT expr",
  121465. /* 170 */ "likeop ::= LIKE_KW|MATCH",
  121466. /* 171 */ "likeop ::= NOT LIKE_KW|MATCH",
  121467. /* 172 */ "expr ::= expr likeop expr",
  121468. /* 173 */ "expr ::= expr likeop expr ESCAPE expr",
  121469. /* 174 */ "expr ::= expr ISNULL|NOTNULL",
  121470. /* 175 */ "expr ::= expr NOT NULL",
  121471. /* 176 */ "expr ::= expr IS expr",
  121472. /* 177 */ "expr ::= expr IS NOT expr",
  121473. /* 178 */ "expr ::= NOT expr",
  121474. /* 179 */ "expr ::= BITNOT expr",
  121475. /* 180 */ "expr ::= MINUS expr",
  121476. /* 181 */ "expr ::= PLUS expr",
  121477. /* 182 */ "between_op ::= BETWEEN",
  121478. /* 183 */ "between_op ::= NOT BETWEEN",
  121479. /* 184 */ "expr ::= expr between_op expr AND expr",
  121480. /* 185 */ "in_op ::= IN",
  121481. /* 186 */ "in_op ::= NOT IN",
  121482. /* 187 */ "expr ::= expr in_op LP exprlist RP",
  121483. /* 188 */ "expr ::= LP select RP",
  121484. /* 189 */ "expr ::= expr in_op LP select RP",
  121485. /* 190 */ "expr ::= expr in_op nm dbnm",
  121486. /* 191 */ "expr ::= EXISTS LP select RP",
  121487. /* 192 */ "expr ::= CASE case_operand case_exprlist case_else END",
  121488. /* 193 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  121489. /* 194 */ "case_exprlist ::= WHEN expr THEN expr",
  121490. /* 195 */ "case_else ::= ELSE expr",
  121491. /* 196 */ "case_else ::=",
  121492. /* 197 */ "case_operand ::= expr",
  121493. /* 198 */ "case_operand ::=",
  121494. /* 199 */ "exprlist ::=",
  121495. /* 200 */ "nexprlist ::= nexprlist COMMA expr",
  121496. /* 201 */ "nexprlist ::= expr",
  121497. /* 202 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  121498. /* 203 */ "uniqueflag ::= UNIQUE",
  121499. /* 204 */ "uniqueflag ::=",
  121500. /* 205 */ "eidlist_opt ::=",
  121501. /* 206 */ "eidlist_opt ::= LP eidlist RP",
  121502. /* 207 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  121503. /* 208 */ "eidlist ::= nm collate sortorder",
  121504. /* 209 */ "collate ::=",
  121505. /* 210 */ "collate ::= COLLATE ID|STRING",
  121506. /* 211 */ "cmd ::= DROP INDEX ifexists fullname",
  121507. /* 212 */ "cmd ::= VACUUM",
  121508. /* 213 */ "cmd ::= VACUUM nm",
  121509. /* 214 */ "cmd ::= PRAGMA nm dbnm",
  121510. /* 215 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  121511. /* 216 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  121512. /* 217 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  121513. /* 218 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  121514. /* 219 */ "plus_num ::= PLUS INTEGER|FLOAT",
  121515. /* 220 */ "minus_num ::= MINUS INTEGER|FLOAT",
  121516. /* 221 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  121517. /* 222 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  121518. /* 223 */ "trigger_time ::= BEFORE",
  121519. /* 224 */ "trigger_time ::= AFTER",
  121520. /* 225 */ "trigger_time ::= INSTEAD OF",
  121521. /* 226 */ "trigger_time ::=",
  121522. /* 227 */ "trigger_event ::= DELETE|INSERT",
  121523. /* 228 */ "trigger_event ::= UPDATE",
  121524. /* 229 */ "trigger_event ::= UPDATE OF idlist",
  121525. /* 230 */ "when_clause ::=",
  121526. /* 231 */ "when_clause ::= WHEN expr",
  121527. /* 232 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  121528. /* 233 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  121529. /* 234 */ "trnm ::= nm DOT nm",
  121530. /* 235 */ "tridxby ::= INDEXED BY nm",
  121531. /* 236 */ "tridxby ::= NOT INDEXED",
  121532. /* 237 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  121533. /* 238 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
  121534. /* 239 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  121535. /* 240 */ "trigger_cmd ::= select",
  121536. /* 241 */ "expr ::= RAISE LP IGNORE RP",
  121537. /* 242 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  121538. /* 243 */ "raisetype ::= ROLLBACK",
  121539. /* 244 */ "raisetype ::= ABORT",
  121540. /* 245 */ "raisetype ::= FAIL",
  121541. /* 246 */ "cmd ::= DROP TRIGGER ifexists fullname",
  121542. /* 247 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  121543. /* 248 */ "cmd ::= DETACH database_kw_opt expr",
  121544. /* 249 */ "key_opt ::=",
  121545. /* 250 */ "key_opt ::= KEY expr",
  121546. /* 251 */ "cmd ::= REINDEX",
  121547. /* 252 */ "cmd ::= REINDEX nm dbnm",
  121548. /* 253 */ "cmd ::= ANALYZE",
  121549. /* 254 */ "cmd ::= ANALYZE nm dbnm",
  121550. /* 255 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  121551. /* 256 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  121552. /* 257 */ "add_column_fullname ::= fullname",
  121553. /* 258 */ "cmd ::= create_vtab",
  121554. /* 259 */ "cmd ::= create_vtab LP vtabarglist RP",
  121555. /* 260 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  121556. /* 261 */ "vtabarg ::=",
  121557. /* 262 */ "vtabargtoken ::= ANY",
  121558. /* 263 */ "vtabargtoken ::= lp anylist RP",
  121559. /* 264 */ "lp ::= LP",
  121560. /* 265 */ "with ::=",
  121561. /* 266 */ "with ::= WITH wqlist",
  121562. /* 267 */ "with ::= WITH RECURSIVE wqlist",
  121563. /* 268 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  121564. /* 269 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  121565. /* 270 */ "input ::= cmdlist",
  121566. /* 271 */ "cmdlist ::= cmdlist ecmd",
  121567. /* 272 */ "cmdlist ::= ecmd",
  121568. /* 273 */ "ecmd ::= SEMI",
  121569. /* 274 */ "ecmd ::= explain cmdx SEMI",
  121570. /* 275 */ "explain ::=",
  121571. /* 276 */ "trans_opt ::=",
  121572. /* 277 */ "trans_opt ::= TRANSACTION",
  121573. /* 278 */ "trans_opt ::= TRANSACTION nm",
  121574. /* 279 */ "savepoint_opt ::= SAVEPOINT",
  121575. /* 280 */ "savepoint_opt ::=",
  121576. /* 281 */ "cmd ::= create_table create_table_args",
  121577. /* 282 */ "columnlist ::= columnlist COMMA columnname carglist",
  121578. /* 283 */ "columnlist ::= columnname carglist",
  121579. /* 284 */ "nm ::= ID|INDEXED",
  121580. /* 285 */ "nm ::= STRING",
  121581. /* 286 */ "nm ::= JOIN_KW",
  121582. /* 287 */ "typetoken ::= typename",
  121583. /* 288 */ "typename ::= ID|STRING",
  121584. /* 289 */ "signed ::= plus_num",
  121585. /* 290 */ "signed ::= minus_num",
  121586. /* 291 */ "carglist ::= carglist ccons",
  121587. /* 292 */ "carglist ::=",
  121588. /* 293 */ "ccons ::= NULL onconf",
  121589. /* 294 */ "conslist_opt ::= COMMA conslist",
  121590. /* 295 */ "conslist ::= conslist tconscomma tcons",
  121591. /* 296 */ "conslist ::= tcons",
  121592. /* 297 */ "tconscomma ::=",
  121593. /* 298 */ "defer_subclause_opt ::= defer_subclause",
  121594. /* 299 */ "resolvetype ::= raisetype",
  121595. /* 300 */ "selectnowith ::= oneselect",
  121596. /* 301 */ "oneselect ::= values",
  121597. /* 302 */ "sclp ::= selcollist COMMA",
  121598. /* 303 */ "as ::= ID|STRING",
  121599. /* 304 */ "expr ::= term",
  121600. /* 305 */ "exprlist ::= nexprlist",
  121601. /* 306 */ "nmnum ::= plus_num",
  121602. /* 307 */ "nmnum ::= nm",
  121603. /* 308 */ "nmnum ::= ON",
  121604. /* 309 */ "nmnum ::= DELETE",
  121605. /* 310 */ "nmnum ::= DEFAULT",
  121606. /* 311 */ "plus_num ::= INTEGER|FLOAT",
  121607. /* 312 */ "foreach_clause ::=",
  121608. /* 313 */ "foreach_clause ::= FOR EACH ROW",
  121609. /* 314 */ "trnm ::= nm",
  121610. /* 315 */ "tridxby ::=",
  121611. /* 316 */ "database_kw_opt ::= DATABASE",
  121612. /* 317 */ "database_kw_opt ::=",
  121613. /* 318 */ "kwcolumn_opt ::=",
  121614. /* 319 */ "kwcolumn_opt ::= COLUMNKW",
  121615. /* 320 */ "vtabarglist ::= vtabarg",
  121616. /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  121617. /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
  121618. /* 323 */ "anylist ::=",
  121619. /* 324 */ "anylist ::= anylist LP anylist RP",
  121620. /* 325 */ "anylist ::= anylist ANY",
  121621. };
  121622. #endif /* NDEBUG */
  121623. #if YYSTACKDEPTH<=0
  121624. /*
  121625. ** Try to increase the size of the parser stack.
  121626. */
  121627. static void yyGrowStack(yyParser *p){
  121628. int newSize;
  121629. yyStackEntry *pNew;
  121630. newSize = p->yystksz*2 + 100;
  121631. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  121632. if( pNew ){
  121633. p->yystack = pNew;
  121634. p->yystksz = newSize;
  121635. #ifndef NDEBUG
  121636. if( yyTraceFILE ){
  121637. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  121638. yyTracePrompt, p->yystksz);
  121639. }
  121640. #endif
  121641. }
  121642. }
  121643. #endif
  121644. /* Datatype of the argument to the memory allocated passed as the
  121645. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  121646. ** putting an appropriate #define in the %include section of the input
  121647. ** grammar.
  121648. */
  121649. #ifndef YYMALLOCARGTYPE
  121650. # define YYMALLOCARGTYPE size_t
  121651. #endif
  121652. /*
  121653. ** This function allocates a new parser.
  121654. ** The only argument is a pointer to a function which works like
  121655. ** malloc.
  121656. **
  121657. ** Inputs:
  121658. ** A pointer to the function used to allocate memory.
  121659. **
  121660. ** Outputs:
  121661. ** A pointer to a parser. This pointer is used in subsequent calls
  121662. ** to sqlite3Parser and sqlite3ParserFree.
  121663. */
  121664. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
  121665. yyParser *pParser;
  121666. pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  121667. if( pParser ){
  121668. pParser->yyidx = -1;
  121669. #ifdef YYTRACKMAXSTACKDEPTH
  121670. pParser->yyidxMax = 0;
  121671. #endif
  121672. #if YYSTACKDEPTH<=0
  121673. pParser->yystack = NULL;
  121674. pParser->yystksz = 0;
  121675. yyGrowStack(pParser);
  121676. #endif
  121677. }
  121678. return pParser;
  121679. }
  121680. /* The following function deletes the "minor type" or semantic value
  121681. ** associated with a symbol. The symbol can be either a terminal
  121682. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  121683. ** a pointer to the value to be deleted. The code used to do the
  121684. ** deletions is derived from the %destructor and/or %token_destructor
  121685. ** directives of the input grammar.
  121686. */
  121687. static void yy_destructor(
  121688. yyParser *yypParser, /* The parser */
  121689. YYCODETYPE yymajor, /* Type code for object to destroy */
  121690. YYMINORTYPE *yypminor /* The object to be destroyed */
  121691. ){
  121692. sqlite3ParserARG_FETCH;
  121693. switch( yymajor ){
  121694. /* Here is inserted the actions which take place when a
  121695. ** terminal or non-terminal is destroyed. This can happen
  121696. ** when the symbol is popped from the stack during a
  121697. ** reduce or during error processing or when a parser is
  121698. ** being destroyed before it is finished parsing.
  121699. **
  121700. ** Note: during a reduce, the only symbols destroyed are those
  121701. ** which appear on the RHS of the rule, but which are *not* used
  121702. ** inside the C code.
  121703. */
  121704. /********* Begin destructor definitions ***************************************/
  121705. case 163: /* select */
  121706. case 194: /* selectnowith */
  121707. case 195: /* oneselect */
  121708. case 206: /* values */
  121709. {
  121710. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  121711. }
  121712. break;
  121713. case 172: /* term */
  121714. case 173: /* expr */
  121715. {
  121716. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  121717. }
  121718. break;
  121719. case 177: /* eidlist_opt */
  121720. case 186: /* sortlist */
  121721. case 187: /* eidlist */
  121722. case 199: /* selcollist */
  121723. case 202: /* groupby_opt */
  121724. case 204: /* orderby_opt */
  121725. case 207: /* nexprlist */
  121726. case 208: /* exprlist */
  121727. case 209: /* sclp */
  121728. case 218: /* setlist */
  121729. case 225: /* case_exprlist */
  121730. {
  121731. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  121732. }
  121733. break;
  121734. case 193: /* fullname */
  121735. case 200: /* from */
  121736. case 211: /* seltablist */
  121737. case 212: /* stl_prefix */
  121738. {
  121739. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  121740. }
  121741. break;
  121742. case 196: /* with */
  121743. case 249: /* wqlist */
  121744. {
  121745. sqlite3WithDelete(pParse->db, (yypminor->yy331));
  121746. }
  121747. break;
  121748. case 201: /* where_opt */
  121749. case 203: /* having_opt */
  121750. case 215: /* on_opt */
  121751. case 224: /* case_operand */
  121752. case 226: /* case_else */
  121753. case 235: /* when_clause */
  121754. case 240: /* key_opt */
  121755. {
  121756. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  121757. }
  121758. break;
  121759. case 216: /* using_opt */
  121760. case 217: /* idlist */
  121761. case 220: /* idlist_opt */
  121762. {
  121763. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  121764. }
  121765. break;
  121766. case 231: /* trigger_cmd_list */
  121767. case 236: /* trigger_cmd */
  121768. {
  121769. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  121770. }
  121771. break;
  121772. case 233: /* trigger_event */
  121773. {
  121774. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  121775. }
  121776. break;
  121777. /********* End destructor definitions *****************************************/
  121778. default: break; /* If no destructor action specified: do nothing */
  121779. }
  121780. }
  121781. /*
  121782. ** Pop the parser's stack once.
  121783. **
  121784. ** If there is a destructor routine associated with the token which
  121785. ** is popped from the stack, then call it.
  121786. */
  121787. static void yy_pop_parser_stack(yyParser *pParser){
  121788. yyStackEntry *yytos;
  121789. assert( pParser->yyidx>=0 );
  121790. yytos = &pParser->yystack[pParser->yyidx--];
  121791. #ifndef NDEBUG
  121792. if( yyTraceFILE ){
  121793. fprintf(yyTraceFILE,"%sPopping %s\n",
  121794. yyTracePrompt,
  121795. yyTokenName[yytos->major]);
  121796. }
  121797. #endif
  121798. yy_destructor(pParser, yytos->major, &yytos->minor);
  121799. }
  121800. /*
  121801. ** Deallocate and destroy a parser. Destructors are called for
  121802. ** all stack elements before shutting the parser down.
  121803. **
  121804. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  121805. ** is defined in a %include section of the input grammar) then it is
  121806. ** assumed that the input pointer is never NULL.
  121807. */
  121808. SQLITE_PRIVATE void sqlite3ParserFree(
  121809. void *p, /* The parser to be deleted */
  121810. void (*freeProc)(void*) /* Function used to reclaim memory */
  121811. ){
  121812. yyParser *pParser = (yyParser*)p;
  121813. #ifndef YYPARSEFREENEVERNULL
  121814. if( pParser==0 ) return;
  121815. #endif
  121816. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  121817. #if YYSTACKDEPTH<=0
  121818. free(pParser->yystack);
  121819. #endif
  121820. (*freeProc)((void*)pParser);
  121821. }
  121822. /*
  121823. ** Return the peak depth of the stack for a parser.
  121824. */
  121825. #ifdef YYTRACKMAXSTACKDEPTH
  121826. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  121827. yyParser *pParser = (yyParser*)p;
  121828. return pParser->yyidxMax;
  121829. }
  121830. #endif
  121831. /*
  121832. ** Find the appropriate action for a parser given the terminal
  121833. ** look-ahead token iLookAhead.
  121834. */
  121835. static unsigned int yy_find_shift_action(
  121836. yyParser *pParser, /* The parser */
  121837. YYCODETYPE iLookAhead /* The look-ahead token */
  121838. ){
  121839. int i;
  121840. int stateno = pParser->yystack[pParser->yyidx].stateno;
  121841. if( stateno>=YY_MIN_REDUCE ) return stateno;
  121842. assert( stateno <= YY_SHIFT_COUNT );
  121843. do{
  121844. i = yy_shift_ofst[stateno];
  121845. if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
  121846. assert( iLookAhead!=YYNOCODE );
  121847. i += iLookAhead;
  121848. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  121849. if( iLookAhead>0 ){
  121850. #ifdef YYFALLBACK
  121851. YYCODETYPE iFallback; /* Fallback token */
  121852. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  121853. && (iFallback = yyFallback[iLookAhead])!=0 ){
  121854. #ifndef NDEBUG
  121855. if( yyTraceFILE ){
  121856. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  121857. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  121858. }
  121859. #endif
  121860. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  121861. iLookAhead = iFallback;
  121862. continue;
  121863. }
  121864. #endif
  121865. #ifdef YYWILDCARD
  121866. {
  121867. int j = i - iLookAhead + YYWILDCARD;
  121868. if(
  121869. #if YY_SHIFT_MIN+YYWILDCARD<0
  121870. j>=0 &&
  121871. #endif
  121872. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  121873. j<YY_ACTTAB_COUNT &&
  121874. #endif
  121875. yy_lookahead[j]==YYWILDCARD
  121876. ){
  121877. #ifndef NDEBUG
  121878. if( yyTraceFILE ){
  121879. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  121880. yyTracePrompt, yyTokenName[iLookAhead],
  121881. yyTokenName[YYWILDCARD]);
  121882. }
  121883. #endif /* NDEBUG */
  121884. return yy_action[j];
  121885. }
  121886. }
  121887. #endif /* YYWILDCARD */
  121888. }
  121889. return yy_default[stateno];
  121890. }else{
  121891. return yy_action[i];
  121892. }
  121893. }while(1);
  121894. }
  121895. /*
  121896. ** Find the appropriate action for a parser given the non-terminal
  121897. ** look-ahead token iLookAhead.
  121898. */
  121899. static int yy_find_reduce_action(
  121900. int stateno, /* Current state number */
  121901. YYCODETYPE iLookAhead /* The look-ahead token */
  121902. ){
  121903. int i;
  121904. #ifdef YYERRORSYMBOL
  121905. if( stateno>YY_REDUCE_COUNT ){
  121906. return yy_default[stateno];
  121907. }
  121908. #else
  121909. assert( stateno<=YY_REDUCE_COUNT );
  121910. #endif
  121911. i = yy_reduce_ofst[stateno];
  121912. assert( i!=YY_REDUCE_USE_DFLT );
  121913. assert( iLookAhead!=YYNOCODE );
  121914. i += iLookAhead;
  121915. #ifdef YYERRORSYMBOL
  121916. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  121917. return yy_default[stateno];
  121918. }
  121919. #else
  121920. assert( i>=0 && i<YY_ACTTAB_COUNT );
  121921. assert( yy_lookahead[i]==iLookAhead );
  121922. #endif
  121923. return yy_action[i];
  121924. }
  121925. /*
  121926. ** The following routine is called if the stack overflows.
  121927. */
  121928. static void yyStackOverflow(yyParser *yypParser){
  121929. sqlite3ParserARG_FETCH;
  121930. yypParser->yyidx--;
  121931. #ifndef NDEBUG
  121932. if( yyTraceFILE ){
  121933. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  121934. }
  121935. #endif
  121936. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  121937. /* Here code is inserted which will execute if the parser
  121938. ** stack every overflows */
  121939. /******** Begin %stack_overflow code ******************************************/
  121940. sqlite3ErrorMsg(pParse, "parser stack overflow");
  121941. /******** End %stack_overflow code ********************************************/
  121942. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  121943. }
  121944. /*
  121945. ** Print tracing information for a SHIFT action
  121946. */
  121947. #ifndef NDEBUG
  121948. static void yyTraceShift(yyParser *yypParser, int yyNewState){
  121949. if( yyTraceFILE ){
  121950. if( yyNewState<YYNSTATE ){
  121951. fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
  121952. yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major],
  121953. yyNewState);
  121954. }else{
  121955. fprintf(yyTraceFILE,"%sShift '%s'\n",
  121956. yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major]);
  121957. }
  121958. }
  121959. }
  121960. #else
  121961. # define yyTraceShift(X,Y)
  121962. #endif
  121963. /*
  121964. ** Perform a shift action.
  121965. */
  121966. static void yy_shift(
  121967. yyParser *yypParser, /* The parser to be shifted */
  121968. int yyNewState, /* The new state to shift in */
  121969. int yyMajor, /* The major token to shift in */
  121970. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  121971. ){
  121972. yyStackEntry *yytos;
  121973. yypParser->yyidx++;
  121974. #ifdef YYTRACKMAXSTACKDEPTH
  121975. if( yypParser->yyidx>yypParser->yyidxMax ){
  121976. yypParser->yyidxMax = yypParser->yyidx;
  121977. }
  121978. #endif
  121979. #if YYSTACKDEPTH>0
  121980. if( yypParser->yyidx>=YYSTACKDEPTH ){
  121981. yyStackOverflow(yypParser);
  121982. return;
  121983. }
  121984. #else
  121985. if( yypParser->yyidx>=yypParser->yystksz ){
  121986. yyGrowStack(yypParser);
  121987. if( yypParser->yyidx>=yypParser->yystksz ){
  121988. yyStackOverflow(yypParser);
  121989. return;
  121990. }
  121991. }
  121992. #endif
  121993. yytos = &yypParser->yystack[yypParser->yyidx];
  121994. yytos->stateno = (YYACTIONTYPE)yyNewState;
  121995. yytos->major = (YYCODETYPE)yyMajor;
  121996. yytos->minor.yy0 = yyMinor;
  121997. yyTraceShift(yypParser, yyNewState);
  121998. }
  121999. /* The following table contains information about every rule that
  122000. ** is used during the reduce.
  122001. */
  122002. static const struct {
  122003. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  122004. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  122005. } yyRuleInfo[] = {
  122006. { 147, 1 },
  122007. { 147, 3 },
  122008. { 148, 1 },
  122009. { 149, 3 },
  122010. { 150, 0 },
  122011. { 150, 1 },
  122012. { 150, 1 },
  122013. { 150, 1 },
  122014. { 149, 2 },
  122015. { 149, 2 },
  122016. { 149, 2 },
  122017. { 149, 2 },
  122018. { 149, 3 },
  122019. { 149, 5 },
  122020. { 154, 6 },
  122021. { 156, 1 },
  122022. { 158, 0 },
  122023. { 158, 3 },
  122024. { 157, 1 },
  122025. { 157, 0 },
  122026. { 155, 5 },
  122027. { 155, 2 },
  122028. { 162, 0 },
  122029. { 162, 2 },
  122030. { 164, 2 },
  122031. { 166, 0 },
  122032. { 166, 4 },
  122033. { 166, 6 },
  122034. { 167, 2 },
  122035. { 171, 2 },
  122036. { 171, 2 },
  122037. { 171, 4 },
  122038. { 171, 3 },
  122039. { 171, 3 },
  122040. { 171, 2 },
  122041. { 171, 3 },
  122042. { 171, 5 },
  122043. { 171, 2 },
  122044. { 171, 4 },
  122045. { 171, 4 },
  122046. { 171, 1 },
  122047. { 171, 2 },
  122048. { 176, 0 },
  122049. { 176, 1 },
  122050. { 178, 0 },
  122051. { 178, 2 },
  122052. { 180, 2 },
  122053. { 180, 3 },
  122054. { 180, 3 },
  122055. { 180, 3 },
  122056. { 181, 2 },
  122057. { 181, 2 },
  122058. { 181, 1 },
  122059. { 181, 1 },
  122060. { 181, 2 },
  122061. { 179, 3 },
  122062. { 179, 2 },
  122063. { 182, 0 },
  122064. { 182, 2 },
  122065. { 182, 2 },
  122066. { 161, 0 },
  122067. { 184, 1 },
  122068. { 185, 2 },
  122069. { 185, 7 },
  122070. { 185, 5 },
  122071. { 185, 5 },
  122072. { 185, 10 },
  122073. { 188, 0 },
  122074. { 174, 0 },
  122075. { 174, 3 },
  122076. { 189, 0 },
  122077. { 189, 2 },
  122078. { 190, 1 },
  122079. { 190, 1 },
  122080. { 149, 4 },
  122081. { 192, 2 },
  122082. { 192, 0 },
  122083. { 149, 9 },
  122084. { 149, 4 },
  122085. { 149, 1 },
  122086. { 163, 2 },
  122087. { 194, 3 },
  122088. { 197, 1 },
  122089. { 197, 2 },
  122090. { 197, 1 },
  122091. { 195, 9 },
  122092. { 206, 4 },
  122093. { 206, 5 },
  122094. { 198, 1 },
  122095. { 198, 1 },
  122096. { 198, 0 },
  122097. { 209, 0 },
  122098. { 199, 3 },
  122099. { 199, 2 },
  122100. { 199, 4 },
  122101. { 210, 2 },
  122102. { 210, 0 },
  122103. { 200, 0 },
  122104. { 200, 2 },
  122105. { 212, 2 },
  122106. { 212, 0 },
  122107. { 211, 7 },
  122108. { 211, 9 },
  122109. { 211, 7 },
  122110. { 211, 7 },
  122111. { 159, 0 },
  122112. { 159, 2 },
  122113. { 193, 2 },
  122114. { 213, 1 },
  122115. { 213, 2 },
  122116. { 213, 3 },
  122117. { 213, 4 },
  122118. { 215, 2 },
  122119. { 215, 0 },
  122120. { 214, 0 },
  122121. { 214, 3 },
  122122. { 214, 2 },
  122123. { 216, 4 },
  122124. { 216, 0 },
  122125. { 204, 0 },
  122126. { 204, 3 },
  122127. { 186, 4 },
  122128. { 186, 2 },
  122129. { 175, 1 },
  122130. { 175, 1 },
  122131. { 175, 0 },
  122132. { 202, 0 },
  122133. { 202, 3 },
  122134. { 203, 0 },
  122135. { 203, 2 },
  122136. { 205, 0 },
  122137. { 205, 2 },
  122138. { 205, 4 },
  122139. { 205, 4 },
  122140. { 149, 6 },
  122141. { 201, 0 },
  122142. { 201, 2 },
  122143. { 149, 8 },
  122144. { 218, 5 },
  122145. { 218, 3 },
  122146. { 149, 6 },
  122147. { 149, 7 },
  122148. { 219, 2 },
  122149. { 219, 1 },
  122150. { 220, 0 },
  122151. { 220, 3 },
  122152. { 217, 3 },
  122153. { 217, 1 },
  122154. { 173, 3 },
  122155. { 172, 1 },
  122156. { 173, 1 },
  122157. { 173, 1 },
  122158. { 173, 3 },
  122159. { 173, 5 },
  122160. { 172, 1 },
  122161. { 172, 1 },
  122162. { 173, 1 },
  122163. { 173, 3 },
  122164. { 173, 6 },
  122165. { 173, 5 },
  122166. { 173, 4 },
  122167. { 172, 1 },
  122168. { 173, 3 },
  122169. { 173, 3 },
  122170. { 173, 3 },
  122171. { 173, 3 },
  122172. { 173, 3 },
  122173. { 173, 3 },
  122174. { 173, 3 },
  122175. { 173, 3 },
  122176. { 221, 1 },
  122177. { 221, 2 },
  122178. { 173, 3 },
  122179. { 173, 5 },
  122180. { 173, 2 },
  122181. { 173, 3 },
  122182. { 173, 3 },
  122183. { 173, 4 },
  122184. { 173, 2 },
  122185. { 173, 2 },
  122186. { 173, 2 },
  122187. { 173, 2 },
  122188. { 222, 1 },
  122189. { 222, 2 },
  122190. { 173, 5 },
  122191. { 223, 1 },
  122192. { 223, 2 },
  122193. { 173, 5 },
  122194. { 173, 3 },
  122195. { 173, 5 },
  122196. { 173, 4 },
  122197. { 173, 4 },
  122198. { 173, 5 },
  122199. { 225, 5 },
  122200. { 225, 4 },
  122201. { 226, 2 },
  122202. { 226, 0 },
  122203. { 224, 1 },
  122204. { 224, 0 },
  122205. { 208, 0 },
  122206. { 207, 3 },
  122207. { 207, 1 },
  122208. { 149, 12 },
  122209. { 227, 1 },
  122210. { 227, 0 },
  122211. { 177, 0 },
  122212. { 177, 3 },
  122213. { 187, 5 },
  122214. { 187, 3 },
  122215. { 228, 0 },
  122216. { 228, 2 },
  122217. { 149, 4 },
  122218. { 149, 1 },
  122219. { 149, 2 },
  122220. { 149, 3 },
  122221. { 149, 5 },
  122222. { 149, 6 },
  122223. { 149, 5 },
  122224. { 149, 6 },
  122225. { 169, 2 },
  122226. { 170, 2 },
  122227. { 149, 5 },
  122228. { 230, 11 },
  122229. { 232, 1 },
  122230. { 232, 1 },
  122231. { 232, 2 },
  122232. { 232, 0 },
  122233. { 233, 1 },
  122234. { 233, 1 },
  122235. { 233, 3 },
  122236. { 235, 0 },
  122237. { 235, 2 },
  122238. { 231, 3 },
  122239. { 231, 2 },
  122240. { 237, 3 },
  122241. { 238, 3 },
  122242. { 238, 2 },
  122243. { 236, 7 },
  122244. { 236, 5 },
  122245. { 236, 5 },
  122246. { 236, 1 },
  122247. { 173, 4 },
  122248. { 173, 6 },
  122249. { 191, 1 },
  122250. { 191, 1 },
  122251. { 191, 1 },
  122252. { 149, 4 },
  122253. { 149, 6 },
  122254. { 149, 3 },
  122255. { 240, 0 },
  122256. { 240, 2 },
  122257. { 149, 1 },
  122258. { 149, 3 },
  122259. { 149, 1 },
  122260. { 149, 3 },
  122261. { 149, 6 },
  122262. { 149, 7 },
  122263. { 241, 1 },
  122264. { 149, 1 },
  122265. { 149, 4 },
  122266. { 243, 8 },
  122267. { 245, 0 },
  122268. { 246, 1 },
  122269. { 246, 3 },
  122270. { 247, 1 },
  122271. { 196, 0 },
  122272. { 196, 2 },
  122273. { 196, 3 },
  122274. { 249, 6 },
  122275. { 249, 8 },
  122276. { 144, 1 },
  122277. { 145, 2 },
  122278. { 145, 1 },
  122279. { 146, 1 },
  122280. { 146, 3 },
  122281. { 147, 0 },
  122282. { 151, 0 },
  122283. { 151, 1 },
  122284. { 151, 2 },
  122285. { 153, 1 },
  122286. { 153, 0 },
  122287. { 149, 2 },
  122288. { 160, 4 },
  122289. { 160, 2 },
  122290. { 152, 1 },
  122291. { 152, 1 },
  122292. { 152, 1 },
  122293. { 166, 1 },
  122294. { 167, 1 },
  122295. { 168, 1 },
  122296. { 168, 1 },
  122297. { 165, 2 },
  122298. { 165, 0 },
  122299. { 171, 2 },
  122300. { 161, 2 },
  122301. { 183, 3 },
  122302. { 183, 1 },
  122303. { 184, 0 },
  122304. { 188, 1 },
  122305. { 190, 1 },
  122306. { 194, 1 },
  122307. { 195, 1 },
  122308. { 209, 2 },
  122309. { 210, 1 },
  122310. { 173, 1 },
  122311. { 208, 1 },
  122312. { 229, 1 },
  122313. { 229, 1 },
  122314. { 229, 1 },
  122315. { 229, 1 },
  122316. { 229, 1 },
  122317. { 169, 1 },
  122318. { 234, 0 },
  122319. { 234, 3 },
  122320. { 237, 1 },
  122321. { 238, 0 },
  122322. { 239, 1 },
  122323. { 239, 0 },
  122324. { 242, 0 },
  122325. { 242, 1 },
  122326. { 244, 1 },
  122327. { 244, 3 },
  122328. { 245, 2 },
  122329. { 248, 0 },
  122330. { 248, 4 },
  122331. { 248, 2 },
  122332. };
  122333. static void yy_accept(yyParser*); /* Forward Declaration */
  122334. /*
  122335. ** Perform a reduce action and the shift that must immediately
  122336. ** follow the reduce.
  122337. */
  122338. static void yy_reduce(
  122339. yyParser *yypParser, /* The parser */
  122340. unsigned int yyruleno /* Number of the rule by which to reduce */
  122341. ){
  122342. int yygoto; /* The next state */
  122343. int yyact; /* The next action */
  122344. yyStackEntry *yymsp; /* The top of the parser's stack */
  122345. int yysize; /* Amount to pop the stack */
  122346. sqlite3ParserARG_FETCH;
  122347. yymsp = &yypParser->yystack[yypParser->yyidx];
  122348. #ifndef NDEBUG
  122349. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  122350. yysize = yyRuleInfo[yyruleno].nrhs;
  122351. fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
  122352. yyRuleName[yyruleno], yymsp[-yysize].stateno);
  122353. }
  122354. #endif /* NDEBUG */
  122355. /* Check that the stack is large enough to grow by a single entry
  122356. ** if the RHS of the rule is empty. This ensures that there is room
  122357. ** enough on the stack to push the LHS value */
  122358. if( yyRuleInfo[yyruleno].nrhs==0 ){
  122359. #ifdef YYTRACKMAXSTACKDEPTH
  122360. if( yypParser->yyidx>yypParser->yyidxMax ){
  122361. yypParser->yyidxMax = yypParser->yyidx;
  122362. }
  122363. #endif
  122364. #if YYSTACKDEPTH>0
  122365. if( yypParser->yyidx>=YYSTACKDEPTH-1 ){
  122366. yyStackOverflow(yypParser);
  122367. return;
  122368. }
  122369. #else
  122370. if( yypParser->yyidx>=yypParser->yystksz-1 ){
  122371. yyGrowStack(yypParser);
  122372. if( yypParser->yyidx>=yypParser->yystksz-1 ){
  122373. yyStackOverflow(yypParser);
  122374. return;
  122375. }
  122376. }
  122377. #endif
  122378. }
  122379. switch( yyruleno ){
  122380. /* Beginning here are the reduction cases. A typical example
  122381. ** follows:
  122382. ** case 0:
  122383. ** #line <lineno> <grammarfile>
  122384. ** { ... } // User supplied code
  122385. ** #line <lineno> <thisfile>
  122386. ** break;
  122387. */
  122388. /********** Begin reduce actions **********************************************/
  122389. YYMINORTYPE yylhsminor;
  122390. case 0: /* explain ::= EXPLAIN */
  122391. { pParse->explain = 1; }
  122392. break;
  122393. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  122394. { pParse->explain = 2; }
  122395. break;
  122396. case 2: /* cmdx ::= cmd */
  122397. { sqlite3FinishCoding(pParse); }
  122398. break;
  122399. case 3: /* cmd ::= BEGIN transtype trans_opt */
  122400. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  122401. break;
  122402. case 4: /* transtype ::= */
  122403. {yymsp[1].minor.yy392 = TK_DEFERRED;}
  122404. break;
  122405. case 5: /* transtype ::= DEFERRED */
  122406. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  122407. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  122408. {yymsp[0].minor.yy392 = yymsp[0].major; /*A-overwrites-X*/}
  122409. break;
  122410. case 8: /* cmd ::= COMMIT trans_opt */
  122411. case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
  122412. {sqlite3CommitTransaction(pParse);}
  122413. break;
  122414. case 10: /* cmd ::= ROLLBACK trans_opt */
  122415. {sqlite3RollbackTransaction(pParse);}
  122416. break;
  122417. case 11: /* cmd ::= SAVEPOINT nm */
  122418. {
  122419. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  122420. }
  122421. break;
  122422. case 12: /* cmd ::= RELEASE savepoint_opt nm */
  122423. {
  122424. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  122425. }
  122426. break;
  122427. case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  122428. {
  122429. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  122430. }
  122431. break;
  122432. case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  122433. {
  122434. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  122435. }
  122436. break;
  122437. case 15: /* createkw ::= CREATE */
  122438. {disableLookaside(pParse);}
  122439. break;
  122440. case 16: /* ifnotexists ::= */
  122441. case 19: /* temp ::= */ yytestcase(yyruleno==19);
  122442. case 22: /* table_options ::= */ yytestcase(yyruleno==22);
  122443. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  122444. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  122445. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  122446. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  122447. case 90: /* distinct ::= */ yytestcase(yyruleno==90);
  122448. case 209: /* collate ::= */ yytestcase(yyruleno==209);
  122449. {yymsp[1].minor.yy392 = 0;}
  122450. break;
  122451. case 17: /* ifnotexists ::= IF NOT EXISTS */
  122452. {yymsp[-2].minor.yy392 = 1;}
  122453. break;
  122454. case 18: /* temp ::= TEMP */
  122455. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  122456. {yymsp[0].minor.yy392 = 1;}
  122457. break;
  122458. case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  122459. {
  122460. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy392,0);
  122461. }
  122462. break;
  122463. case 21: /* create_table_args ::= AS select */
  122464. {
  122465. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy159);
  122466. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  122467. }
  122468. break;
  122469. case 23: /* table_options ::= WITHOUT nm */
  122470. {
  122471. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  122472. yymsp[-1].minor.yy392 = TF_WithoutRowid | TF_NoVisibleRowid;
  122473. }else{
  122474. yymsp[-1].minor.yy392 = 0;
  122475. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  122476. }
  122477. }
  122478. break;
  122479. case 24: /* columnname ::= nm typetoken */
  122480. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  122481. break;
  122482. case 25: /* typetoken ::= */
  122483. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  122484. case 96: /* as ::= */ yytestcase(yyruleno==96);
  122485. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  122486. break;
  122487. case 26: /* typetoken ::= typename LP signed RP */
  122488. {
  122489. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  122490. }
  122491. break;
  122492. case 27: /* typetoken ::= typename LP signed COMMA signed RP */
  122493. {
  122494. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  122495. }
  122496. break;
  122497. case 28: /* typename ::= typename ID|STRING */
  122498. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  122499. break;
  122500. case 29: /* ccons ::= CONSTRAINT nm */
  122501. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  122502. {pParse->constraintName = yymsp[0].minor.yy0;}
  122503. break;
  122504. case 30: /* ccons ::= DEFAULT term */
  122505. case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
  122506. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  122507. break;
  122508. case 31: /* ccons ::= DEFAULT LP expr RP */
  122509. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  122510. break;
  122511. case 33: /* ccons ::= DEFAULT MINUS term */
  122512. {
  122513. ExprSpan v;
  122514. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  122515. v.zStart = yymsp[-1].minor.yy0.z;
  122516. v.zEnd = yymsp[0].minor.yy342.zEnd;
  122517. sqlite3AddDefaultValue(pParse,&v);
  122518. }
  122519. break;
  122520. case 34: /* ccons ::= DEFAULT ID|INDEXED */
  122521. {
  122522. ExprSpan v;
  122523. spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
  122524. sqlite3AddDefaultValue(pParse,&v);
  122525. }
  122526. break;
  122527. case 35: /* ccons ::= NOT NULL onconf */
  122528. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  122529. break;
  122530. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  122531. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  122532. break;
  122533. case 37: /* ccons ::= UNIQUE onconf */
  122534. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  122535. break;
  122536. case 38: /* ccons ::= CHECK LP expr RP */
  122537. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  122538. break;
  122539. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  122540. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  122541. break;
  122542. case 40: /* ccons ::= defer_subclause */
  122543. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  122544. break;
  122545. case 41: /* ccons ::= COLLATE ID|STRING */
  122546. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  122547. break;
  122548. case 44: /* refargs ::= */
  122549. { yymsp[1].minor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  122550. break;
  122551. case 45: /* refargs ::= refargs refarg */
  122552. { yymsp[-1].minor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  122553. break;
  122554. case 46: /* refarg ::= MATCH nm */
  122555. { yymsp[-1].minor.yy207.value = 0; yymsp[-1].minor.yy207.mask = 0x000000; }
  122556. break;
  122557. case 47: /* refarg ::= ON INSERT refact */
  122558. { yymsp[-2].minor.yy207.value = 0; yymsp[-2].minor.yy207.mask = 0x000000; }
  122559. break;
  122560. case 48: /* refarg ::= ON DELETE refact */
  122561. { yymsp[-2].minor.yy207.value = yymsp[0].minor.yy392; yymsp[-2].minor.yy207.mask = 0x0000ff; }
  122562. break;
  122563. case 49: /* refarg ::= ON UPDATE refact */
  122564. { yymsp[-2].minor.yy207.value = yymsp[0].minor.yy392<<8; yymsp[-2].minor.yy207.mask = 0x00ff00; }
  122565. break;
  122566. case 50: /* refact ::= SET NULL */
  122567. { yymsp[-1].minor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  122568. break;
  122569. case 51: /* refact ::= SET DEFAULT */
  122570. { yymsp[-1].minor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  122571. break;
  122572. case 52: /* refact ::= CASCADE */
  122573. { yymsp[0].minor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  122574. break;
  122575. case 53: /* refact ::= RESTRICT */
  122576. { yymsp[0].minor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  122577. break;
  122578. case 54: /* refact ::= NO ACTION */
  122579. { yymsp[-1].minor.yy392 = OE_None; /* EV: R-33326-45252 */}
  122580. break;
  122581. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  122582. {yymsp[-2].minor.yy392 = 0;}
  122583. break;
  122584. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  122585. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  122586. case 142: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==142);
  122587. {yymsp[-1].minor.yy392 = yymsp[0].minor.yy392;}
  122588. break;
  122589. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  122590. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  122591. case 183: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==183);
  122592. case 186: /* in_op ::= NOT IN */ yytestcase(yyruleno==186);
  122593. case 210: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==210);
  122594. {yymsp[-1].minor.yy392 = 1;}
  122595. break;
  122596. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  122597. {yymsp[-1].minor.yy392 = 0;}
  122598. break;
  122599. case 61: /* tconscomma ::= COMMA */
  122600. {pParse->constraintName.n = 0;}
  122601. break;
  122602. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  122603. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  122604. break;
  122605. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  122606. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  122607. break;
  122608. case 65: /* tcons ::= CHECK LP expr RP onconf */
  122609. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  122610. break;
  122611. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  122612. {
  122613. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  122614. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  122615. }
  122616. break;
  122617. case 68: /* onconf ::= */
  122618. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  122619. {yymsp[1].minor.yy392 = OE_Default;}
  122620. break;
  122621. case 69: /* onconf ::= ON CONFLICT resolvetype */
  122622. {yymsp[-2].minor.yy392 = yymsp[0].minor.yy392;}
  122623. break;
  122624. case 72: /* resolvetype ::= IGNORE */
  122625. {yymsp[0].minor.yy392 = OE_Ignore;}
  122626. break;
  122627. case 73: /* resolvetype ::= REPLACE */
  122628. case 143: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==143);
  122629. {yymsp[0].minor.yy392 = OE_Replace;}
  122630. break;
  122631. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  122632. {
  122633. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  122634. }
  122635. break;
  122636. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  122637. {
  122638. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[0].minor.yy159, yymsp[-7].minor.yy392, yymsp[-5].minor.yy392);
  122639. }
  122640. break;
  122641. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  122642. {
  122643. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  122644. }
  122645. break;
  122646. case 79: /* cmd ::= select */
  122647. {
  122648. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  122649. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  122650. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  122651. }
  122652. break;
  122653. case 80: /* select ::= with selectnowith */
  122654. {
  122655. Select *p = yymsp[0].minor.yy159;
  122656. if( p ){
  122657. p->pWith = yymsp[-1].minor.yy331;
  122658. parserDoubleLinkSelect(pParse, p);
  122659. }else{
  122660. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy331);
  122661. }
  122662. yymsp[-1].minor.yy159 = p; /*A-overwrites-W*/
  122663. }
  122664. break;
  122665. case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
  122666. {
  122667. Select *pRhs = yymsp[0].minor.yy159;
  122668. Select *pLhs = yymsp[-2].minor.yy159;
  122669. if( pRhs && pRhs->pPrior ){
  122670. SrcList *pFrom;
  122671. Token x;
  122672. x.n = 0;
  122673. parserDoubleLinkSelect(pParse, pRhs);
  122674. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  122675. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  122676. }
  122677. if( pRhs ){
  122678. pRhs->op = (u8)yymsp[-1].minor.yy392;
  122679. pRhs->pPrior = pLhs;
  122680. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  122681. pRhs->selFlags &= ~SF_MultiValue;
  122682. if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
  122683. }else{
  122684. sqlite3SelectDelete(pParse->db, pLhs);
  122685. }
  122686. yymsp[-2].minor.yy159 = pRhs;
  122687. }
  122688. break;
  122689. case 82: /* multiselect_op ::= UNION */
  122690. case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
  122691. {yymsp[0].minor.yy392 = yymsp[0].major; /*A-overwrites-OP*/}
  122692. break;
  122693. case 83: /* multiselect_op ::= UNION ALL */
  122694. {yymsp[-1].minor.yy392 = TK_ALL;}
  122695. break;
  122696. case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  122697. {
  122698. #if SELECTTRACE_ENABLED
  122699. Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
  122700. #endif
  122701. yymsp[-8].minor.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.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  122702. #if SELECTTRACE_ENABLED
  122703. /* Populate the Select.zSelName[] string that is used to help with
  122704. ** query planner debugging, to differentiate between multiple Select
  122705. ** objects in a complex query.
  122706. **
  122707. ** If the SELECT keyword is immediately followed by a C-style comment
  122708. ** then extract the first few alphanumeric characters from within that
  122709. ** comment to be the zSelName value. Otherwise, the label is #N where
  122710. ** is an integer that is incremented with each SELECT statement seen.
  122711. */
  122712. if( yymsp[-8].minor.yy159!=0 ){
  122713. const char *z = s.z+6;
  122714. int i;
  122715. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy159->zSelName), yymsp[-8].minor.yy159->zSelName, "#%d",
  122716. ++pParse->nSelect);
  122717. while( z[0]==' ' ) z++;
  122718. if( z[0]=='/' && z[1]=='*' ){
  122719. z += 2;
  122720. while( z[0]==' ' ) z++;
  122721. for(i=0; sqlite3Isalnum(z[i]); i++){}
  122722. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy159->zSelName), yymsp[-8].minor.yy159->zSelName, "%.*s", i, z);
  122723. }
  122724. }
  122725. #endif /* SELECTRACE_ENABLED */
  122726. }
  122727. break;
  122728. case 86: /* values ::= VALUES LP nexprlist RP */
  122729. {
  122730. yymsp[-3].minor.yy159 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy442,0,0,0,0,0,SF_Values,0,0);
  122731. }
  122732. break;
  122733. case 87: /* values ::= values COMMA LP exprlist RP */
  122734. {
  122735. Select *pRight, *pLeft = yymsp[-4].minor.yy159;
  122736. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy442,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  122737. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  122738. if( pRight ){
  122739. pRight->op = TK_ALL;
  122740. pRight->pPrior = pLeft;
  122741. yymsp[-4].minor.yy159 = pRight;
  122742. }else{
  122743. yymsp[-4].minor.yy159 = pLeft;
  122744. }
  122745. }
  122746. break;
  122747. case 88: /* distinct ::= DISTINCT */
  122748. {yymsp[0].minor.yy392 = SF_Distinct;}
  122749. break;
  122750. case 89: /* distinct ::= ALL */
  122751. {yymsp[0].minor.yy392 = SF_All;}
  122752. break;
  122753. case 91: /* sclp ::= */
  122754. case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
  122755. case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
  122756. case 199: /* exprlist ::= */ yytestcase(yyruleno==199);
  122757. case 205: /* eidlist_opt ::= */ yytestcase(yyruleno==205);
  122758. {yymsp[1].minor.yy442 = 0;}
  122759. break;
  122760. case 92: /* selcollist ::= sclp expr as */
  122761. {
  122762. yymsp[-2].minor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  122763. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy442, &yymsp[0].minor.yy0, 1);
  122764. sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy442,&yymsp[-1].minor.yy342);
  122765. }
  122766. break;
  122767. case 93: /* selcollist ::= sclp STAR */
  122768. {
  122769. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  122770. yymsp[-1].minor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  122771. }
  122772. break;
  122773. case 94: /* selcollist ::= sclp nm DOT STAR */
  122774. {
  122775. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
  122776. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  122777. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  122778. yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  122779. }
  122780. break;
  122781. case 95: /* as ::= AS nm */
  122782. case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
  122783. case 219: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==219);
  122784. case 220: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==220);
  122785. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  122786. break;
  122787. case 97: /* from ::= */
  122788. {yymsp[1].minor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy347));}
  122789. break;
  122790. case 98: /* from ::= FROM seltablist */
  122791. {
  122792. yymsp[-1].minor.yy347 = yymsp[0].minor.yy347;
  122793. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy347);
  122794. }
  122795. break;
  122796. case 99: /* stl_prefix ::= seltablist joinop */
  122797. {
  122798. if( ALWAYS(yymsp[-1].minor.yy347 && yymsp[-1].minor.yy347->nSrc>0) ) yymsp[-1].minor.yy347->a[yymsp[-1].minor.yy347->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy392;
  122799. }
  122800. break;
  122801. case 100: /* stl_prefix ::= */
  122802. {yymsp[1].minor.yy347 = 0;}
  122803. break;
  122804. case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  122805. {
  122806. yymsp[-6].minor.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);
  122807. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy347, &yymsp[-2].minor.yy0);
  122808. }
  122809. break;
  122810. case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  122811. {
  122812. yymsp[-8].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy347,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  122813. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy347, yymsp[-4].minor.yy442);
  122814. }
  122815. break;
  122816. case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  122817. {
  122818. yymsp[-6].minor.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);
  122819. }
  122820. break;
  122821. case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  122822. {
  122823. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  122824. yymsp[-6].minor.yy347 = yymsp[-4].minor.yy347;
  122825. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  122826. yymsp[-6].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  122827. if( yymsp[-6].minor.yy347 ){
  122828. struct SrcList_item *pNew = &yymsp[-6].minor.yy347->a[yymsp[-6].minor.yy347->nSrc-1];
  122829. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  122830. pNew->zName = pOld->zName;
  122831. pNew->zDatabase = pOld->zDatabase;
  122832. pNew->pSelect = pOld->pSelect;
  122833. pOld->zName = pOld->zDatabase = 0;
  122834. pOld->pSelect = 0;
  122835. }
  122836. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  122837. }else{
  122838. Select *pSubquery;
  122839. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  122840. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  122841. yymsp[-6].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  122842. }
  122843. }
  122844. break;
  122845. case 105: /* dbnm ::= */
  122846. case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
  122847. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  122848. break;
  122849. case 107: /* fullname ::= nm dbnm */
  122850. {yymsp[-1].minor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  122851. break;
  122852. case 108: /* joinop ::= COMMA|JOIN */
  122853. { yymsp[0].minor.yy392 = JT_INNER; }
  122854. break;
  122855. case 109: /* joinop ::= JOIN_KW JOIN */
  122856. {yymsp[-1].minor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  122857. break;
  122858. case 110: /* joinop ::= JOIN_KW nm JOIN */
  122859. {yymsp[-2].minor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  122860. break;
  122861. case 111: /* joinop ::= JOIN_KW nm nm JOIN */
  122862. {yymsp[-3].minor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  122863. break;
  122864. case 112: /* on_opt ::= ON expr */
  122865. case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
  122866. case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
  122867. case 195: /* case_else ::= ELSE expr */ yytestcase(yyruleno==195);
  122868. {yymsp[-1].minor.yy122 = yymsp[0].minor.yy342.pExpr;}
  122869. break;
  122870. case 113: /* on_opt ::= */
  122871. case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
  122872. case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
  122873. case 196: /* case_else ::= */ yytestcase(yyruleno==196);
  122874. case 198: /* case_operand ::= */ yytestcase(yyruleno==198);
  122875. {yymsp[1].minor.yy122 = 0;}
  122876. break;
  122877. case 115: /* indexed_opt ::= INDEXED BY nm */
  122878. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  122879. break;
  122880. case 116: /* indexed_opt ::= NOT INDEXED */
  122881. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  122882. break;
  122883. case 117: /* using_opt ::= USING LP idlist RP */
  122884. {yymsp[-3].minor.yy180 = yymsp[-1].minor.yy180;}
  122885. break;
  122886. case 118: /* using_opt ::= */
  122887. case 144: /* idlist_opt ::= */ yytestcase(yyruleno==144);
  122888. {yymsp[1].minor.yy180 = 0;}
  122889. break;
  122890. case 120: /* orderby_opt ::= ORDER BY sortlist */
  122891. case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
  122892. {yymsp[-2].minor.yy442 = yymsp[0].minor.yy442;}
  122893. break;
  122894. case 121: /* sortlist ::= sortlist COMMA expr sortorder */
  122895. {
  122896. yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  122897. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy442,yymsp[0].minor.yy392);
  122898. }
  122899. break;
  122900. case 122: /* sortlist ::= expr sortorder */
  122901. {
  122902. yymsp[-1].minor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr); /*A-overwrites-Y*/
  122903. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy442,yymsp[0].minor.yy392);
  122904. }
  122905. break;
  122906. case 123: /* sortorder ::= ASC */
  122907. {yymsp[0].minor.yy392 = SQLITE_SO_ASC;}
  122908. break;
  122909. case 124: /* sortorder ::= DESC */
  122910. {yymsp[0].minor.yy392 = SQLITE_SO_DESC;}
  122911. break;
  122912. case 125: /* sortorder ::= */
  122913. {yymsp[1].minor.yy392 = SQLITE_SO_UNDEFINED;}
  122914. break;
  122915. case 130: /* limit_opt ::= */
  122916. {yymsp[1].minor.yy64.pLimit = 0; yymsp[1].minor.yy64.pOffset = 0;}
  122917. break;
  122918. case 131: /* limit_opt ::= LIMIT expr */
  122919. {yymsp[-1].minor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yymsp[-1].minor.yy64.pOffset = 0;}
  122920. break;
  122921. case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
  122922. {yymsp[-3].minor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yymsp[-3].minor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  122923. break;
  122924. case 133: /* limit_opt ::= LIMIT expr COMMA expr */
  122925. {yymsp[-3].minor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yymsp[-3].minor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  122926. break;
  122927. case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  122928. {
  122929. sqlite3WithPush(pParse, yymsp[-5].minor.yy331, 1);
  122930. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  122931. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  122932. }
  122933. break;
  122934. case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  122935. {
  122936. sqlite3WithPush(pParse, yymsp[-7].minor.yy331, 1);
  122937. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  122938. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  122939. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy392);
  122940. }
  122941. break;
  122942. case 138: /* setlist ::= setlist COMMA nm EQ expr */
  122943. {
  122944. yymsp[-4].minor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  122945. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy442, &yymsp[-2].minor.yy0, 1);
  122946. }
  122947. break;
  122948. case 139: /* setlist ::= nm EQ expr */
  122949. {
  122950. yylhsminor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  122951. sqlite3ExprListSetName(pParse, yylhsminor.yy442, &yymsp[-2].minor.yy0, 1);
  122952. }
  122953. yymsp[-2].minor.yy442 = yylhsminor.yy442;
  122954. break;
  122955. case 140: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  122956. {
  122957. sqlite3WithPush(pParse, yymsp[-5].minor.yy331, 1);
  122958. sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy392);
  122959. }
  122960. break;
  122961. case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  122962. {
  122963. sqlite3WithPush(pParse, yymsp[-6].minor.yy331, 1);
  122964. sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy392);
  122965. }
  122966. break;
  122967. case 145: /* idlist_opt ::= LP idlist RP */
  122968. {yymsp[-2].minor.yy180 = yymsp[-1].minor.yy180;}
  122969. break;
  122970. case 146: /* idlist ::= idlist COMMA nm */
  122971. {yymsp[-2].minor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  122972. break;
  122973. case 147: /* idlist ::= nm */
  122974. {yymsp[0].minor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  122975. break;
  122976. case 148: /* expr ::= LP expr RP */
  122977. {spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr;}
  122978. break;
  122979. case 149: /* term ::= NULL */
  122980. case 154: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==154);
  122981. case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
  122982. {spanExpr(&yymsp[0].minor.yy342,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
  122983. break;
  122984. case 150: /* expr ::= ID|INDEXED */
  122985. case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
  122986. {spanExpr(&yymsp[0].minor.yy342,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  122987. break;
  122988. case 152: /* expr ::= nm DOT nm */
  122989. {
  122990. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  122991. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  122992. spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  122993. yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  122994. }
  122995. break;
  122996. case 153: /* expr ::= nm DOT nm DOT nm */
  122997. {
  122998. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  122999. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  123000. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  123001. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  123002. spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  123003. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  123004. }
  123005. break;
  123006. case 156: /* expr ::= VARIABLE */
  123007. {
  123008. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  123009. if( t.n>=2 && t.z[0]=='#' && sqlite3Isdigit(t.z[1]) ){
  123010. /* When doing a nested parse, one can include terms in an expression
  123011. ** that look like this: #1 #2 ... These terms refer to registers
  123012. ** in the virtual machine. #N is the N-th register. */
  123013. spanSet(&yymsp[0].minor.yy342, &t, &t);
  123014. if( pParse->nested==0 ){
  123015. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  123016. yymsp[0].minor.yy342.pExpr = 0;
  123017. }else{
  123018. yymsp[0].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
  123019. if( yymsp[0].minor.yy342.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy342.pExpr->iTable);
  123020. }
  123021. }else{
  123022. spanExpr(&yymsp[0].minor.yy342, pParse, TK_VARIABLE, t);
  123023. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy342.pExpr);
  123024. }
  123025. }
  123026. break;
  123027. case 157: /* expr ::= expr COLLATE ID|STRING */
  123028. {
  123029. yymsp[-2].minor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0, 1);
  123030. yymsp[-2].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  123031. }
  123032. break;
  123033. case 158: /* expr ::= CAST LP expr AS typetoken RP */
  123034. {
  123035. spanSet(&yymsp[-5].minor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  123036. yymsp[-5].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  123037. }
  123038. break;
  123039. case 159: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  123040. {
  123041. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  123042. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  123043. }
  123044. yylhsminor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  123045. spanSet(&yylhsminor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  123046. if( yymsp[-2].minor.yy392==SF_Distinct && yylhsminor.yy342.pExpr ){
  123047. yylhsminor.yy342.pExpr->flags |= EP_Distinct;
  123048. }
  123049. }
  123050. yymsp[-4].minor.yy342 = yylhsminor.yy342;
  123051. break;
  123052. case 160: /* expr ::= ID|INDEXED LP STAR RP */
  123053. {
  123054. yylhsminor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  123055. spanSet(&yylhsminor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  123056. }
  123057. yymsp[-3].minor.yy342 = yylhsminor.yy342;
  123058. break;
  123059. case 161: /* term ::= CTIME_KW */
  123060. {
  123061. yylhsminor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  123062. spanSet(&yylhsminor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  123063. }
  123064. yymsp[0].minor.yy342 = yylhsminor.yy342;
  123065. break;
  123066. case 162: /* expr ::= expr AND expr */
  123067. case 163: /* expr ::= expr OR expr */ yytestcase(yyruleno==163);
  123068. case 164: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==164);
  123069. case 165: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==165);
  123070. case 166: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==166);
  123071. case 167: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==167);
  123072. case 168: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==168);
  123073. case 169: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==169);
  123074. {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  123075. break;
  123076. case 170: /* likeop ::= LIKE_KW|MATCH */
  123077. {yymsp[0].minor.yy318.eOperator = yymsp[0].minor.yy0; yymsp[0].minor.yy318.bNot = 0;/*A-overwrites-X*/}
  123078. break;
  123079. case 171: /* likeop ::= NOT LIKE_KW|MATCH */
  123080. {yymsp[-1].minor.yy318.eOperator = yymsp[0].minor.yy0; yymsp[-1].minor.yy318.bNot = 1;}
  123081. break;
  123082. case 172: /* expr ::= expr likeop expr */
  123083. {
  123084. ExprList *pList;
  123085. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  123086. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  123087. yymsp[-2].minor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  123088. exprNot(pParse, yymsp[-1].minor.yy318.bNot, &yymsp[-2].minor.yy342);
  123089. yymsp[-2].minor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  123090. if( yymsp[-2].minor.yy342.pExpr ) yymsp[-2].minor.yy342.pExpr->flags |= EP_InfixFunc;
  123091. }
  123092. break;
  123093. case 173: /* expr ::= expr likeop expr ESCAPE expr */
  123094. {
  123095. ExprList *pList;
  123096. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  123097. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  123098. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  123099. yymsp[-4].minor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  123100. exprNot(pParse, yymsp[-3].minor.yy318.bNot, &yymsp[-4].minor.yy342);
  123101. yymsp[-4].minor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  123102. if( yymsp[-4].minor.yy342.pExpr ) yymsp[-4].minor.yy342.pExpr->flags |= EP_InfixFunc;
  123103. }
  123104. break;
  123105. case 174: /* expr ::= expr ISNULL|NOTNULL */
  123106. {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  123107. break;
  123108. case 175: /* expr ::= expr NOT NULL */
  123109. {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  123110. break;
  123111. case 176: /* expr ::= expr IS expr */
  123112. {
  123113. spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  123114. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yymsp[-2].minor.yy342.pExpr, TK_ISNULL);
  123115. }
  123116. break;
  123117. case 177: /* expr ::= expr IS NOT expr */
  123118. {
  123119. spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  123120. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yymsp[-3].minor.yy342.pExpr, TK_NOTNULL);
  123121. }
  123122. break;
  123123. case 178: /* expr ::= NOT expr */
  123124. case 179: /* expr ::= BITNOT expr */ yytestcase(yyruleno==179);
  123125. {spanUnaryPrefix(&yymsp[-1].minor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  123126. break;
  123127. case 180: /* expr ::= MINUS expr */
  123128. {spanUnaryPrefix(&yymsp[-1].minor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  123129. break;
  123130. case 181: /* expr ::= PLUS expr */
  123131. {spanUnaryPrefix(&yymsp[-1].minor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  123132. break;
  123133. case 182: /* between_op ::= BETWEEN */
  123134. case 185: /* in_op ::= IN */ yytestcase(yyruleno==185);
  123135. {yymsp[0].minor.yy392 = 0;}
  123136. break;
  123137. case 184: /* expr ::= expr between_op expr AND expr */
  123138. {
  123139. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  123140. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  123141. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  123142. if( yymsp[-4].minor.yy342.pExpr ){
  123143. yymsp[-4].minor.yy342.pExpr->x.pList = pList;
  123144. }else{
  123145. sqlite3ExprListDelete(pParse->db, pList);
  123146. }
  123147. exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
  123148. yymsp[-4].minor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  123149. }
  123150. break;
  123151. case 187: /* expr ::= expr in_op LP exprlist RP */
  123152. {
  123153. if( yymsp[-1].minor.yy442==0 ){
  123154. /* Expressions of the form
  123155. **
  123156. ** expr1 IN ()
  123157. ** expr1 NOT IN ()
  123158. **
  123159. ** simplify to constants 0 (false) and 1 (true), respectively,
  123160. ** regardless of the value of expr1.
  123161. */
  123162. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  123163. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  123164. }else if( yymsp[-1].minor.yy442->nExpr==1 ){
  123165. /* Expressions of the form:
  123166. **
  123167. ** expr1 IN (?1)
  123168. ** expr1 NOT IN (?2)
  123169. **
  123170. ** with exactly one value on the RHS can be simplified to something
  123171. ** like this:
  123172. **
  123173. ** expr1 == ?1
  123174. ** expr1 <> ?2
  123175. **
  123176. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  123177. ** so that it may not contribute to the computation of comparison
  123178. ** affinity or the collating sequence to use for comparison. Otherwise,
  123179. ** the semantics would be subtly different from IN or NOT IN.
  123180. */
  123181. Expr *pRHS = yymsp[-1].minor.yy442->a[0].pExpr;
  123182. yymsp[-1].minor.yy442->a[0].pExpr = 0;
  123183. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  123184. /* pRHS cannot be NULL because a malloc error would have been detected
  123185. ** before now and control would have never reached this point */
  123186. if( ALWAYS(pRHS) ){
  123187. pRHS->flags &= ~EP_Collate;
  123188. pRHS->flags |= EP_Generic;
  123189. }
  123190. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy392 ? TK_NE : TK_EQ, yymsp[-4].minor.yy342.pExpr, pRHS, 0);
  123191. }else{
  123192. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  123193. if( yymsp[-4].minor.yy342.pExpr ){
  123194. yymsp[-4].minor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  123195. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
  123196. }else{
  123197. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  123198. }
  123199. exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
  123200. }
  123201. yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  123202. }
  123203. break;
  123204. case 188: /* expr ::= LP select RP */
  123205. {
  123206. spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  123207. yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  123208. if( yymsp[-2].minor.yy342.pExpr ){
  123209. yymsp[-2].minor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  123210. ExprSetProperty(yymsp[-2].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
  123211. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-2].minor.yy342.pExpr);
  123212. }else{
  123213. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  123214. }
  123215. }
  123216. break;
  123217. case 189: /* expr ::= expr in_op LP select RP */
  123218. {
  123219. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  123220. if( yymsp[-4].minor.yy342.pExpr ){
  123221. yymsp[-4].minor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  123222. ExprSetProperty(yymsp[-4].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
  123223. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
  123224. }else{
  123225. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  123226. }
  123227. exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
  123228. yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  123229. }
  123230. break;
  123231. case 190: /* expr ::= expr in_op nm dbnm */
  123232. {
  123233. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  123234. yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  123235. if( yymsp[-3].minor.yy342.pExpr ){
  123236. yymsp[-3].minor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  123237. ExprSetProperty(yymsp[-3].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
  123238. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-3].minor.yy342.pExpr);
  123239. }else{
  123240. sqlite3SrcListDelete(pParse->db, pSrc);
  123241. }
  123242. exprNot(pParse, yymsp[-2].minor.yy392, &yymsp[-3].minor.yy342);
  123243. yymsp[-3].minor.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];
  123244. }
  123245. break;
  123246. case 191: /* expr ::= EXISTS LP select RP */
  123247. {
  123248. Expr *p;
  123249. spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  123250. p = yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  123251. if( p ){
  123252. p->x.pSelect = yymsp[-1].minor.yy159;
  123253. ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
  123254. sqlite3ExprSetHeightAndFlags(pParse, p);
  123255. }else{
  123256. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  123257. }
  123258. }
  123259. break;
  123260. case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
  123261. {
  123262. spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
  123263. yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
  123264. if( yymsp[-4].minor.yy342.pExpr ){
  123265. yymsp[-4].minor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
  123266. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
  123267. }else{
  123268. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  123269. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
  123270. }
  123271. }
  123272. break;
  123273. case 193: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  123274. {
  123275. yymsp[-4].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  123276. yymsp[-4].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  123277. }
  123278. break;
  123279. case 194: /* case_exprlist ::= WHEN expr THEN expr */
  123280. {
  123281. yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  123282. yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, yymsp[0].minor.yy342.pExpr);
  123283. }
  123284. break;
  123285. case 197: /* case_operand ::= expr */
  123286. {yymsp[0].minor.yy122 = yymsp[0].minor.yy342.pExpr; /*A-overwrites-X*/}
  123287. break;
  123288. case 200: /* nexprlist ::= nexprlist COMMA expr */
  123289. {yymsp[-2].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  123290. break;
  123291. case 201: /* nexprlist ::= expr */
  123292. {yymsp[0].minor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr); /*A-overwrites-Y*/}
  123293. break;
  123294. case 202: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  123295. {
  123296. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  123297. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
  123298. &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
  123299. }
  123300. break;
  123301. case 203: /* uniqueflag ::= UNIQUE */
  123302. case 244: /* raisetype ::= ABORT */ yytestcase(yyruleno==244);
  123303. {yymsp[0].minor.yy392 = OE_Abort;}
  123304. break;
  123305. case 204: /* uniqueflag ::= */
  123306. {yymsp[1].minor.yy392 = OE_None;}
  123307. break;
  123308. case 206: /* eidlist_opt ::= LP eidlist RP */
  123309. {yymsp[-2].minor.yy442 = yymsp[-1].minor.yy442;}
  123310. break;
  123311. case 207: /* eidlist ::= eidlist COMMA nm collate sortorder */
  123312. {
  123313. yymsp[-4].minor.yy442 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy442, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy392, yymsp[0].minor.yy392);
  123314. }
  123315. break;
  123316. case 208: /* eidlist ::= nm collate sortorder */
  123317. {
  123318. yymsp[-2].minor.yy442 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy392, yymsp[0].minor.yy392); /*A-overwrites-Y*/
  123319. }
  123320. break;
  123321. case 211: /* cmd ::= DROP INDEX ifexists fullname */
  123322. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  123323. break;
  123324. case 212: /* cmd ::= VACUUM */
  123325. case 213: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==213);
  123326. {sqlite3Vacuum(pParse);}
  123327. break;
  123328. case 214: /* cmd ::= PRAGMA nm dbnm */
  123329. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  123330. break;
  123331. case 215: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  123332. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  123333. break;
  123334. case 216: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  123335. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  123336. break;
  123337. case 217: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  123338. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  123339. break;
  123340. case 218: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  123341. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  123342. break;
  123343. case 221: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  123344. {
  123345. Token all;
  123346. all.z = yymsp[-3].minor.yy0.z;
  123347. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  123348. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  123349. }
  123350. break;
  123351. case 222: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  123352. {
  123353. 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);
  123354. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  123355. }
  123356. break;
  123357. case 223: /* trigger_time ::= BEFORE */
  123358. { yymsp[0].minor.yy392 = TK_BEFORE; }
  123359. break;
  123360. case 224: /* trigger_time ::= AFTER */
  123361. { yymsp[0].minor.yy392 = TK_AFTER; }
  123362. break;
  123363. case 225: /* trigger_time ::= INSTEAD OF */
  123364. { yymsp[-1].minor.yy392 = TK_INSTEAD;}
  123365. break;
  123366. case 226: /* trigger_time ::= */
  123367. { yymsp[1].minor.yy392 = TK_BEFORE; }
  123368. break;
  123369. case 227: /* trigger_event ::= DELETE|INSERT */
  123370. case 228: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==228);
  123371. {yymsp[0].minor.yy410.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy410.b = 0;}
  123372. break;
  123373. case 229: /* trigger_event ::= UPDATE OF idlist */
  123374. {yymsp[-2].minor.yy410.a = TK_UPDATE; yymsp[-2].minor.yy410.b = yymsp[0].minor.yy180;}
  123375. break;
  123376. case 230: /* when_clause ::= */
  123377. case 249: /* key_opt ::= */ yytestcase(yyruleno==249);
  123378. { yymsp[1].minor.yy122 = 0; }
  123379. break;
  123380. case 231: /* when_clause ::= WHEN expr */
  123381. case 250: /* key_opt ::= KEY expr */ yytestcase(yyruleno==250);
  123382. { yymsp[-1].minor.yy122 = yymsp[0].minor.yy342.pExpr; }
  123383. break;
  123384. case 232: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  123385. {
  123386. assert( yymsp[-2].minor.yy327!=0 );
  123387. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  123388. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  123389. }
  123390. break;
  123391. case 233: /* trigger_cmd_list ::= trigger_cmd SEMI */
  123392. {
  123393. assert( yymsp[-1].minor.yy327!=0 );
  123394. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  123395. }
  123396. break;
  123397. case 234: /* trnm ::= nm DOT nm */
  123398. {
  123399. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  123400. sqlite3ErrorMsg(pParse,
  123401. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  123402. "statements within triggers");
  123403. }
  123404. break;
  123405. case 235: /* tridxby ::= INDEXED BY nm */
  123406. {
  123407. sqlite3ErrorMsg(pParse,
  123408. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  123409. "within triggers");
  123410. }
  123411. break;
  123412. case 236: /* tridxby ::= NOT INDEXED */
  123413. {
  123414. sqlite3ErrorMsg(pParse,
  123415. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  123416. "within triggers");
  123417. }
  123418. break;
  123419. case 237: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  123420. {yymsp[-6].minor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy392);}
  123421. break;
  123422. case 238: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
  123423. {yymsp[-4].minor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy159, yymsp[-4].minor.yy392);/*A-overwrites-R*/}
  123424. break;
  123425. case 239: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  123426. {yymsp[-4].minor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  123427. break;
  123428. case 240: /* trigger_cmd ::= select */
  123429. {yymsp[0].minor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); /*A-overwrites-X*/}
  123430. break;
  123431. case 241: /* expr ::= RAISE LP IGNORE RP */
  123432. {
  123433. spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  123434. yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  123435. if( yymsp[-3].minor.yy342.pExpr ){
  123436. yymsp[-3].minor.yy342.pExpr->affinity = OE_Ignore;
  123437. }
  123438. }
  123439. break;
  123440. case 242: /* expr ::= RAISE LP raisetype COMMA nm RP */
  123441. {
  123442. spanSet(&yymsp[-5].minor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  123443. yymsp[-5].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  123444. if( yymsp[-5].minor.yy342.pExpr ) {
  123445. yymsp[-5].minor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  123446. }
  123447. }
  123448. break;
  123449. case 243: /* raisetype ::= ROLLBACK */
  123450. {yymsp[0].minor.yy392 = OE_Rollback;}
  123451. break;
  123452. case 245: /* raisetype ::= FAIL */
  123453. {yymsp[0].minor.yy392 = OE_Fail;}
  123454. break;
  123455. case 246: /* cmd ::= DROP TRIGGER ifexists fullname */
  123456. {
  123457. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  123458. }
  123459. break;
  123460. case 247: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  123461. {
  123462. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  123463. }
  123464. break;
  123465. case 248: /* cmd ::= DETACH database_kw_opt expr */
  123466. {
  123467. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  123468. }
  123469. break;
  123470. case 251: /* cmd ::= REINDEX */
  123471. {sqlite3Reindex(pParse, 0, 0);}
  123472. break;
  123473. case 252: /* cmd ::= REINDEX nm dbnm */
  123474. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  123475. break;
  123476. case 253: /* cmd ::= ANALYZE */
  123477. {sqlite3Analyze(pParse, 0, 0);}
  123478. break;
  123479. case 254: /* cmd ::= ANALYZE nm dbnm */
  123480. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  123481. break;
  123482. case 255: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  123483. {
  123484. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  123485. }
  123486. break;
  123487. case 256: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  123488. {
  123489. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  123490. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  123491. }
  123492. break;
  123493. case 257: /* add_column_fullname ::= fullname */
  123494. {
  123495. disableLookaside(pParse);
  123496. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  123497. }
  123498. break;
  123499. case 258: /* cmd ::= create_vtab */
  123500. {sqlite3VtabFinishParse(pParse,0);}
  123501. break;
  123502. case 259: /* cmd ::= create_vtab LP vtabarglist RP */
  123503. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  123504. break;
  123505. case 260: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  123506. {
  123507. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  123508. }
  123509. break;
  123510. case 261: /* vtabarg ::= */
  123511. {sqlite3VtabArgInit(pParse);}
  123512. break;
  123513. case 262: /* vtabargtoken ::= ANY */
  123514. case 263: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==263);
  123515. case 264: /* lp ::= LP */ yytestcase(yyruleno==264);
  123516. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  123517. break;
  123518. case 265: /* with ::= */
  123519. {yymsp[1].minor.yy331 = 0;}
  123520. break;
  123521. case 266: /* with ::= WITH wqlist */
  123522. { yymsp[-1].minor.yy331 = yymsp[0].minor.yy331; }
  123523. break;
  123524. case 267: /* with ::= WITH RECURSIVE wqlist */
  123525. { yymsp[-2].minor.yy331 = yymsp[0].minor.yy331; }
  123526. break;
  123527. case 268: /* wqlist ::= nm eidlist_opt AS LP select RP */
  123528. {
  123529. yymsp[-5].minor.yy331 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy442, yymsp[-1].minor.yy159); /*A-overwrites-X*/
  123530. }
  123531. break;
  123532. case 269: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  123533. {
  123534. yymsp[-7].minor.yy331 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy331, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy442, yymsp[-1].minor.yy159);
  123535. }
  123536. break;
  123537. default:
  123538. /* (270) input ::= cmdlist */ yytestcase(yyruleno==270);
  123539. /* (271) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==271);
  123540. /* (272) cmdlist ::= ecmd */ yytestcase(yyruleno==272);
  123541. /* (273) ecmd ::= SEMI */ yytestcase(yyruleno==273);
  123542. /* (274) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==274);
  123543. /* (275) explain ::= */ yytestcase(yyruleno==275);
  123544. /* (276) trans_opt ::= */ yytestcase(yyruleno==276);
  123545. /* (277) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==277);
  123546. /* (278) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==278);
  123547. /* (279) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==279);
  123548. /* (280) savepoint_opt ::= */ yytestcase(yyruleno==280);
  123549. /* (281) cmd ::= create_table create_table_args */ yytestcase(yyruleno==281);
  123550. /* (282) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==282);
  123551. /* (283) columnlist ::= columnname carglist */ yytestcase(yyruleno==283);
  123552. /* (284) nm ::= ID|INDEXED */ yytestcase(yyruleno==284);
  123553. /* (285) nm ::= STRING */ yytestcase(yyruleno==285);
  123554. /* (286) nm ::= JOIN_KW */ yytestcase(yyruleno==286);
  123555. /* (287) typetoken ::= typename */ yytestcase(yyruleno==287);
  123556. /* (288) typename ::= ID|STRING */ yytestcase(yyruleno==288);
  123557. /* (289) signed ::= plus_num */ yytestcase(yyruleno==289);
  123558. /* (290) signed ::= minus_num */ yytestcase(yyruleno==290);
  123559. /* (291) carglist ::= carglist ccons */ yytestcase(yyruleno==291);
  123560. /* (292) carglist ::= */ yytestcase(yyruleno==292);
  123561. /* (293) ccons ::= NULL onconf */ yytestcase(yyruleno==293);
  123562. /* (294) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==294);
  123563. /* (295) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==295);
  123564. /* (296) conslist ::= tcons */ yytestcase(yyruleno==296);
  123565. /* (297) tconscomma ::= */ yytestcase(yyruleno==297);
  123566. /* (298) defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==298);
  123567. /* (299) resolvetype ::= raisetype */ yytestcase(yyruleno==299);
  123568. /* (300) selectnowith ::= oneselect */ yytestcase(yyruleno==300);
  123569. /* (301) oneselect ::= values */ yytestcase(yyruleno==301);
  123570. /* (302) sclp ::= selcollist COMMA */ yytestcase(yyruleno==302);
  123571. /* (303) as ::= ID|STRING */ yytestcase(yyruleno==303);
  123572. /* (304) expr ::= term */ yytestcase(yyruleno==304);
  123573. /* (305) exprlist ::= nexprlist */ yytestcase(yyruleno==305);
  123574. /* (306) nmnum ::= plus_num */ yytestcase(yyruleno==306);
  123575. /* (307) nmnum ::= nm */ yytestcase(yyruleno==307);
  123576. /* (308) nmnum ::= ON */ yytestcase(yyruleno==308);
  123577. /* (309) nmnum ::= DELETE */ yytestcase(yyruleno==309);
  123578. /* (310) nmnum ::= DEFAULT */ yytestcase(yyruleno==310);
  123579. /* (311) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==311);
  123580. /* (312) foreach_clause ::= */ yytestcase(yyruleno==312);
  123581. /* (313) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==313);
  123582. /* (314) trnm ::= nm */ yytestcase(yyruleno==314);
  123583. /* (315) tridxby ::= */ yytestcase(yyruleno==315);
  123584. /* (316) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==316);
  123585. /* (317) database_kw_opt ::= */ yytestcase(yyruleno==317);
  123586. /* (318) kwcolumn_opt ::= */ yytestcase(yyruleno==318);
  123587. /* (319) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==319);
  123588. /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
  123589. /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
  123590. /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
  123591. /* (323) anylist ::= */ yytestcase(yyruleno==323);
  123592. /* (324) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==324);
  123593. /* (325) anylist ::= anylist ANY */ yytestcase(yyruleno==325);
  123594. break;
  123595. /********** End reduce actions ************************************************/
  123596. };
  123597. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  123598. yygoto = yyRuleInfo[yyruleno].lhs;
  123599. yysize = yyRuleInfo[yyruleno].nrhs;
  123600. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  123601. if( yyact <= YY_MAX_SHIFTREDUCE ){
  123602. if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  123603. yypParser->yyidx -= yysize - 1;
  123604. yymsp -= yysize-1;
  123605. yymsp->stateno = (YYACTIONTYPE)yyact;
  123606. yymsp->major = (YYCODETYPE)yygoto;
  123607. yyTraceShift(yypParser, yyact);
  123608. }else{
  123609. assert( yyact == YY_ACCEPT_ACTION );
  123610. yypParser->yyidx -= yysize;
  123611. yy_accept(yypParser);
  123612. }
  123613. }
  123614. /*
  123615. ** The following code executes when the parse fails
  123616. */
  123617. #ifndef YYNOERRORRECOVERY
  123618. static void yy_parse_failed(
  123619. yyParser *yypParser /* The parser */
  123620. ){
  123621. sqlite3ParserARG_FETCH;
  123622. #ifndef NDEBUG
  123623. if( yyTraceFILE ){
  123624. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  123625. }
  123626. #endif
  123627. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  123628. /* Here code is inserted which will be executed whenever the
  123629. ** parser fails */
  123630. /************ Begin %parse_failure code ***************************************/
  123631. /************ End %parse_failure code *****************************************/
  123632. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  123633. }
  123634. #endif /* YYNOERRORRECOVERY */
  123635. /*
  123636. ** The following code executes when a syntax error first occurs.
  123637. */
  123638. static void yy_syntax_error(
  123639. yyParser *yypParser, /* The parser */
  123640. int yymajor, /* The major type of the error token */
  123641. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  123642. ){
  123643. sqlite3ParserARG_FETCH;
  123644. #define TOKEN yyminor
  123645. /************ Begin %syntax_error code ****************************************/
  123646. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  123647. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  123648. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  123649. /************ End %syntax_error code ******************************************/
  123650. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  123651. }
  123652. /*
  123653. ** The following is executed when the parser accepts
  123654. */
  123655. static void yy_accept(
  123656. yyParser *yypParser /* The parser */
  123657. ){
  123658. sqlite3ParserARG_FETCH;
  123659. #ifndef NDEBUG
  123660. if( yyTraceFILE ){
  123661. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  123662. }
  123663. #endif
  123664. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  123665. /* Here code is inserted which will be executed whenever the
  123666. ** parser accepts */
  123667. /*********** Begin %parse_accept code *****************************************/
  123668. /*********** End %parse_accept code *******************************************/
  123669. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  123670. }
  123671. /* The main parser program.
  123672. ** The first argument is a pointer to a structure obtained from
  123673. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  123674. ** The second argument is the major token number. The third is
  123675. ** the minor token. The fourth optional argument is whatever the
  123676. ** user wants (and specified in the grammar) and is available for
  123677. ** use by the action routines.
  123678. **
  123679. ** Inputs:
  123680. ** <ul>
  123681. ** <li> A pointer to the parser (an opaque structure.)
  123682. ** <li> The major token number.
  123683. ** <li> The minor token number.
  123684. ** <li> An option argument of a grammar-specified type.
  123685. ** </ul>
  123686. **
  123687. ** Outputs:
  123688. ** None.
  123689. */
  123690. SQLITE_PRIVATE void sqlite3Parser(
  123691. void *yyp, /* The parser */
  123692. int yymajor, /* The major token code number */
  123693. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  123694. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  123695. ){
  123696. YYMINORTYPE yyminorunion;
  123697. unsigned int yyact; /* The parser action. */
  123698. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  123699. int yyendofinput; /* True if we are at the end of input */
  123700. #endif
  123701. #ifdef YYERRORSYMBOL
  123702. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  123703. #endif
  123704. yyParser *yypParser; /* The parser */
  123705. /* (re)initialize the parser, if necessary */
  123706. yypParser = (yyParser*)yyp;
  123707. if( yypParser->yyidx<0 ){
  123708. #if YYSTACKDEPTH<=0
  123709. if( yypParser->yystksz <=0 ){
  123710. yyStackOverflow(yypParser);
  123711. return;
  123712. }
  123713. #endif
  123714. yypParser->yyidx = 0;
  123715. #ifndef YYNOERRORRECOVERY
  123716. yypParser->yyerrcnt = -1;
  123717. #endif
  123718. yypParser->yystack[0].stateno = 0;
  123719. yypParser->yystack[0].major = 0;
  123720. #ifndef NDEBUG
  123721. if( yyTraceFILE ){
  123722. fprintf(yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
  123723. yyTracePrompt);
  123724. }
  123725. #endif
  123726. }
  123727. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  123728. yyendofinput = (yymajor==0);
  123729. #endif
  123730. sqlite3ParserARG_STORE;
  123731. #ifndef NDEBUG
  123732. if( yyTraceFILE ){
  123733. fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
  123734. }
  123735. #endif
  123736. do{
  123737. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  123738. if( yyact <= YY_MAX_SHIFTREDUCE ){
  123739. if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  123740. yy_shift(yypParser,yyact,yymajor,yyminor);
  123741. #ifndef YYNOERRORRECOVERY
  123742. yypParser->yyerrcnt--;
  123743. #endif
  123744. yymajor = YYNOCODE;
  123745. }else if( yyact <= YY_MAX_REDUCE ){
  123746. yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
  123747. }else{
  123748. assert( yyact == YY_ERROR_ACTION );
  123749. yyminorunion.yy0 = yyminor;
  123750. #ifdef YYERRORSYMBOL
  123751. int yymx;
  123752. #endif
  123753. #ifndef NDEBUG
  123754. if( yyTraceFILE ){
  123755. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  123756. }
  123757. #endif
  123758. #ifdef YYERRORSYMBOL
  123759. /* A syntax error has occurred.
  123760. ** The response to an error depends upon whether or not the
  123761. ** grammar defines an error token "ERROR".
  123762. **
  123763. ** This is what we do if the grammar does define ERROR:
  123764. **
  123765. ** * Call the %syntax_error function.
  123766. **
  123767. ** * Begin popping the stack until we enter a state where
  123768. ** it is legal to shift the error symbol, then shift
  123769. ** the error symbol.
  123770. **
  123771. ** * Set the error count to three.
  123772. **
  123773. ** * Begin accepting and shifting new tokens. No new error
  123774. ** processing will occur until three tokens have been
  123775. ** shifted successfully.
  123776. **
  123777. */
  123778. if( yypParser->yyerrcnt<0 ){
  123779. yy_syntax_error(yypParser,yymajor,yyminor);
  123780. }
  123781. yymx = yypParser->yystack[yypParser->yyidx].major;
  123782. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  123783. #ifndef NDEBUG
  123784. if( yyTraceFILE ){
  123785. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  123786. yyTracePrompt,yyTokenName[yymajor]);
  123787. }
  123788. #endif
  123789. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  123790. yymajor = YYNOCODE;
  123791. }else{
  123792. while(
  123793. yypParser->yyidx >= 0 &&
  123794. yymx != YYERRORSYMBOL &&
  123795. (yyact = yy_find_reduce_action(
  123796. yypParser->yystack[yypParser->yyidx].stateno,
  123797. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  123798. ){
  123799. yy_pop_parser_stack(yypParser);
  123800. }
  123801. if( yypParser->yyidx < 0 || yymajor==0 ){
  123802. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  123803. yy_parse_failed(yypParser);
  123804. yymajor = YYNOCODE;
  123805. }else if( yymx!=YYERRORSYMBOL ){
  123806. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  123807. }
  123808. }
  123809. yypParser->yyerrcnt = 3;
  123810. yyerrorhit = 1;
  123811. #elif defined(YYNOERRORRECOVERY)
  123812. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  123813. ** do any kind of error recovery. Instead, simply invoke the syntax
  123814. ** error routine and continue going as if nothing had happened.
  123815. **
  123816. ** Applications can set this macro (for example inside %include) if
  123817. ** they intend to abandon the parse upon the first syntax error seen.
  123818. */
  123819. yy_syntax_error(yypParser,yymajor, yyminor);
  123820. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  123821. yymajor = YYNOCODE;
  123822. #else /* YYERRORSYMBOL is not defined */
  123823. /* This is what we do if the grammar does not define ERROR:
  123824. **
  123825. ** * Report an error message, and throw away the input token.
  123826. **
  123827. ** * If the input token is $, then fail the parse.
  123828. **
  123829. ** As before, subsequent error messages are suppressed until
  123830. ** three input tokens have been successfully shifted.
  123831. */
  123832. if( yypParser->yyerrcnt<=0 ){
  123833. yy_syntax_error(yypParser,yymajor, yyminor);
  123834. }
  123835. yypParser->yyerrcnt = 3;
  123836. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  123837. if( yyendofinput ){
  123838. yy_parse_failed(yypParser);
  123839. }
  123840. yymajor = YYNOCODE;
  123841. #endif
  123842. }
  123843. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  123844. #ifndef NDEBUG
  123845. if( yyTraceFILE ){
  123846. int i;
  123847. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  123848. for(i=1; i<=yypParser->yyidx; i++)
  123849. fprintf(yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
  123850. yyTokenName[yypParser->yystack[i].major]);
  123851. fprintf(yyTraceFILE,"]\n");
  123852. }
  123853. #endif
  123854. return;
  123855. }
  123856. /************** End of parse.c ***********************************************/
  123857. /************** Begin file tokenize.c ****************************************/
  123858. /*
  123859. ** 2001 September 15
  123860. **
  123861. ** The author disclaims copyright to this source code. In place of
  123862. ** a legal notice, here is a blessing:
  123863. **
  123864. ** May you do good and not evil.
  123865. ** May you find forgiveness for yourself and forgive others.
  123866. ** May you share freely, never taking more than you give.
  123867. **
  123868. *************************************************************************
  123869. ** An tokenizer for SQL
  123870. **
  123871. ** This file contains C code that splits an SQL input string up into
  123872. ** individual tokens and sends those tokens one-by-one over to the
  123873. ** parser for analysis.
  123874. */
  123875. /* #include "sqliteInt.h" */
  123876. /* #include <stdlib.h> */
  123877. /* Character classes for tokenizing
  123878. **
  123879. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  123880. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  123881. ** The lookup table is much faster. To maximize speed, and to ensure that
  123882. ** a lookup table is used, all of the classes need to be small integers and
  123883. ** all of them need to be used within the switch.
  123884. */
  123885. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  123886. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  123887. #define CC_ID 2 /* unicode characters usable in IDs */
  123888. #define CC_DIGIT 3 /* Digits */
  123889. #define CC_DOLLAR 4 /* '$' */
  123890. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  123891. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  123892. #define CC_SPACE 7 /* Space characters */
  123893. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  123894. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  123895. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  123896. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  123897. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  123898. #define CC_GT 13 /* '>'. Part of > or >= */
  123899. #define CC_EQ 14 /* '='. Part of = or == */
  123900. #define CC_BANG 15 /* '!'. Part of != */
  123901. #define CC_SLASH 16 /* '/'. / or c-style comment */
  123902. #define CC_LP 17 /* '(' */
  123903. #define CC_RP 18 /* ')' */
  123904. #define CC_SEMI 19 /* ';' */
  123905. #define CC_PLUS 20 /* '+' */
  123906. #define CC_STAR 21 /* '*' */
  123907. #define CC_PERCENT 22 /* '%' */
  123908. #define CC_COMMA 23 /* ',' */
  123909. #define CC_AND 24 /* '&' */
  123910. #define CC_TILDA 25 /* '~' */
  123911. #define CC_DOT 26 /* '.' */
  123912. #define CC_ILLEGAL 27 /* Illegal character */
  123913. static const unsigned char aiClass[] = {
  123914. #ifdef SQLITE_ASCII
  123915. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  123916. /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  123917. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  123918. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  123919. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  123920. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  123921. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  123922. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  123923. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  123924. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123925. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123926. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123927. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123928. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123929. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123930. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  123931. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  123932. #endif
  123933. #ifdef SQLITE_EBCDIC
  123934. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  123935. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  123936. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  123937. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  123938. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  123939. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
  123940. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  123941. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 7,
  123942. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  123943. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  123944. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  123945. /* 9x */ 25, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  123946. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  123947. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  123948. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  123949. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  123950. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  123951. #endif
  123952. };
  123953. /*
  123954. ** The charMap() macro maps alphabetic characters (only) into their
  123955. ** lower-case ASCII equivalent. On ASCII machines, this is just
  123956. ** an upper-to-lower case map. On EBCDIC machines we also need
  123957. ** to adjust the encoding. The mapping is only valid for alphabetics
  123958. ** which are the only characters for which this feature is used.
  123959. **
  123960. ** Used by keywordhash.h
  123961. */
  123962. #ifdef SQLITE_ASCII
  123963. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  123964. #endif
  123965. #ifdef SQLITE_EBCDIC
  123966. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  123967. const unsigned char ebcdicToAscii[] = {
  123968. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  123977. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  123978. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  123979. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  123981. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  123982. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  123983. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  123985. };
  123986. #endif
  123987. /*
  123988. ** The sqlite3KeywordCode function looks up an identifier to determine if
  123989. ** it is a keyword. If it is a keyword, the token code of that keyword is
  123990. ** returned. If the input is not a keyword, TK_ID is returned.
  123991. **
  123992. ** The implementation of this routine was generated by a program,
  123993. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  123994. ** The output of the mkkeywordhash.c program is written into a file
  123995. ** named keywordhash.h and then included into this source file by
  123996. ** the #include below.
  123997. */
  123998. /************** Include keywordhash.h in the middle of tokenize.c ************/
  123999. /************** Begin file keywordhash.h *************************************/
  124000. /***** This file contains automatically generated code ******
  124001. **
  124002. ** The code in this file has been automatically generated by
  124003. **
  124004. ** sqlite/tool/mkkeywordhash.c
  124005. **
  124006. ** The code in this file implements a function that determines whether
  124007. ** or not a given identifier is really an SQL keyword. The same thing
  124008. ** might be implemented more directly using a hand-written hash table.
  124009. ** But by using this automatically generated code, the size of the code
  124010. ** is substantially reduced. This is important for embedded applications
  124011. ** on platforms with limited memory.
  124012. */
  124013. /* Hash score: 182 */
  124014. static int keywordCode(const char *z, int n, int *pType){
  124015. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  124016. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  124017. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  124018. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  124019. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  124020. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  124021. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  124022. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  124023. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  124024. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  124025. /* VACUUMVIEWINITIALLY */
  124026. static const char zText[553] = {
  124027. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  124028. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  124029. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  124030. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  124031. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  124032. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  124033. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  124034. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  124035. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  124036. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  124037. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  124038. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  124039. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  124040. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  124041. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  124042. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  124043. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  124044. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  124045. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  124046. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  124047. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  124048. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  124049. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  124050. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  124051. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  124052. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  124053. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  124054. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  124055. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  124056. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  124057. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  124058. };
  124059. static const unsigned char aHash[127] = {
  124060. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  124061. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  124062. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  124063. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  124064. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  124065. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  124066. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  124067. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  124068. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  124069. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  124070. };
  124071. static const unsigned char aNext[124] = {
  124072. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  124074. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  124076. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  124077. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  124078. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  124079. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  124080. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  124081. 73, 83, 0, 35, 68, 0, 0,
  124082. };
  124083. static const unsigned char aLen[124] = {
  124084. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  124085. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  124086. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  124087. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  124088. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  124089. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  124090. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  124091. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  124092. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  124093. 3, 5, 5, 6, 4, 9, 3,
  124094. };
  124095. static const unsigned short int aOffset[124] = {
  124096. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  124097. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  124098. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  124099. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  124100. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  124101. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  124102. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  124103. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  124104. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  124105. 521, 524, 529, 534, 540, 544, 549,
  124106. };
  124107. static const unsigned char aCode[124] = {
  124108. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  124109. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  124110. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  124111. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  124112. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  124113. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  124114. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  124115. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  124116. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  124117. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  124118. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  124119. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  124120. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  124121. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  124122. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  124123. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  124124. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  124125. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  124126. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  124127. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  124128. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  124129. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  124130. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  124131. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  124132. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  124133. };
  124134. int i, j;
  124135. const char *zKW;
  124136. if( n>=2 ){
  124137. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  124138. for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
  124139. if( aLen[i]!=n ) continue;
  124140. j = 0;
  124141. zKW = &zText[aOffset[i]];
  124142. #ifdef SQLITE_ASCII
  124143. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  124144. #endif
  124145. #ifdef SQLITE_EBCDIC
  124146. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  124147. #endif
  124148. if( j<n ) continue;
  124149. testcase( i==0 ); /* REINDEX */
  124150. testcase( i==1 ); /* INDEXED */
  124151. testcase( i==2 ); /* INDEX */
  124152. testcase( i==3 ); /* DESC */
  124153. testcase( i==4 ); /* ESCAPE */
  124154. testcase( i==5 ); /* EACH */
  124155. testcase( i==6 ); /* CHECK */
  124156. testcase( i==7 ); /* KEY */
  124157. testcase( i==8 ); /* BEFORE */
  124158. testcase( i==9 ); /* FOREIGN */
  124159. testcase( i==10 ); /* FOR */
  124160. testcase( i==11 ); /* IGNORE */
  124161. testcase( i==12 ); /* REGEXP */
  124162. testcase( i==13 ); /* EXPLAIN */
  124163. testcase( i==14 ); /* INSTEAD */
  124164. testcase( i==15 ); /* ADD */
  124165. testcase( i==16 ); /* DATABASE */
  124166. testcase( i==17 ); /* AS */
  124167. testcase( i==18 ); /* SELECT */
  124168. testcase( i==19 ); /* TABLE */
  124169. testcase( i==20 ); /* LEFT */
  124170. testcase( i==21 ); /* THEN */
  124171. testcase( i==22 ); /* END */
  124172. testcase( i==23 ); /* DEFERRABLE */
  124173. testcase( i==24 ); /* ELSE */
  124174. testcase( i==25 ); /* EXCEPT */
  124175. testcase( i==26 ); /* TRANSACTION */
  124176. testcase( i==27 ); /* ACTION */
  124177. testcase( i==28 ); /* ON */
  124178. testcase( i==29 ); /* NATURAL */
  124179. testcase( i==30 ); /* ALTER */
  124180. testcase( i==31 ); /* RAISE */
  124181. testcase( i==32 ); /* EXCLUSIVE */
  124182. testcase( i==33 ); /* EXISTS */
  124183. testcase( i==34 ); /* SAVEPOINT */
  124184. testcase( i==35 ); /* INTERSECT */
  124185. testcase( i==36 ); /* TRIGGER */
  124186. testcase( i==37 ); /* REFERENCES */
  124187. testcase( i==38 ); /* CONSTRAINT */
  124188. testcase( i==39 ); /* INTO */
  124189. testcase( i==40 ); /* OFFSET */
  124190. testcase( i==41 ); /* OF */
  124191. testcase( i==42 ); /* SET */
  124192. testcase( i==43 ); /* TEMPORARY */
  124193. testcase( i==44 ); /* TEMP */
  124194. testcase( i==45 ); /* OR */
  124195. testcase( i==46 ); /* UNIQUE */
  124196. testcase( i==47 ); /* QUERY */
  124197. testcase( i==48 ); /* WITHOUT */
  124198. testcase( i==49 ); /* WITH */
  124199. testcase( i==50 ); /* OUTER */
  124200. testcase( i==51 ); /* RELEASE */
  124201. testcase( i==52 ); /* ATTACH */
  124202. testcase( i==53 ); /* HAVING */
  124203. testcase( i==54 ); /* GROUP */
  124204. testcase( i==55 ); /* UPDATE */
  124205. testcase( i==56 ); /* BEGIN */
  124206. testcase( i==57 ); /* INNER */
  124207. testcase( i==58 ); /* RECURSIVE */
  124208. testcase( i==59 ); /* BETWEEN */
  124209. testcase( i==60 ); /* NOTNULL */
  124210. testcase( i==61 ); /* NOT */
  124211. testcase( i==62 ); /* NO */
  124212. testcase( i==63 ); /* NULL */
  124213. testcase( i==64 ); /* LIKE */
  124214. testcase( i==65 ); /* CASCADE */
  124215. testcase( i==66 ); /* ASC */
  124216. testcase( i==67 ); /* DELETE */
  124217. testcase( i==68 ); /* CASE */
  124218. testcase( i==69 ); /* COLLATE */
  124219. testcase( i==70 ); /* CREATE */
  124220. testcase( i==71 ); /* CURRENT_DATE */
  124221. testcase( i==72 ); /* DETACH */
  124222. testcase( i==73 ); /* IMMEDIATE */
  124223. testcase( i==74 ); /* JOIN */
  124224. testcase( i==75 ); /* INSERT */
  124225. testcase( i==76 ); /* MATCH */
  124226. testcase( i==77 ); /* PLAN */
  124227. testcase( i==78 ); /* ANALYZE */
  124228. testcase( i==79 ); /* PRAGMA */
  124229. testcase( i==80 ); /* ABORT */
  124230. testcase( i==81 ); /* VALUES */
  124231. testcase( i==82 ); /* VIRTUAL */
  124232. testcase( i==83 ); /* LIMIT */
  124233. testcase( i==84 ); /* WHEN */
  124234. testcase( i==85 ); /* WHERE */
  124235. testcase( i==86 ); /* RENAME */
  124236. testcase( i==87 ); /* AFTER */
  124237. testcase( i==88 ); /* REPLACE */
  124238. testcase( i==89 ); /* AND */
  124239. testcase( i==90 ); /* DEFAULT */
  124240. testcase( i==91 ); /* AUTOINCREMENT */
  124241. testcase( i==92 ); /* TO */
  124242. testcase( i==93 ); /* IN */
  124243. testcase( i==94 ); /* CAST */
  124244. testcase( i==95 ); /* COLUMN */
  124245. testcase( i==96 ); /* COMMIT */
  124246. testcase( i==97 ); /* CONFLICT */
  124247. testcase( i==98 ); /* CROSS */
  124248. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  124249. testcase( i==100 ); /* CURRENT_TIME */
  124250. testcase( i==101 ); /* PRIMARY */
  124251. testcase( i==102 ); /* DEFERRED */
  124252. testcase( i==103 ); /* DISTINCT */
  124253. testcase( i==104 ); /* IS */
  124254. testcase( i==105 ); /* DROP */
  124255. testcase( i==106 ); /* FAIL */
  124256. testcase( i==107 ); /* FROM */
  124257. testcase( i==108 ); /* FULL */
  124258. testcase( i==109 ); /* GLOB */
  124259. testcase( i==110 ); /* BY */
  124260. testcase( i==111 ); /* IF */
  124261. testcase( i==112 ); /* ISNULL */
  124262. testcase( i==113 ); /* ORDER */
  124263. testcase( i==114 ); /* RESTRICT */
  124264. testcase( i==115 ); /* RIGHT */
  124265. testcase( i==116 ); /* ROLLBACK */
  124266. testcase( i==117 ); /* ROW */
  124267. testcase( i==118 ); /* UNION */
  124268. testcase( i==119 ); /* USING */
  124269. testcase( i==120 ); /* VACUUM */
  124270. testcase( i==121 ); /* VIEW */
  124271. testcase( i==122 ); /* INITIALLY */
  124272. testcase( i==123 ); /* ALL */
  124273. *pType = aCode[i];
  124274. break;
  124275. }
  124276. }
  124277. return n;
  124278. }
  124279. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  124280. int id = TK_ID;
  124281. keywordCode((char*)z, n, &id);
  124282. return id;
  124283. }
  124284. #define SQLITE_N_KEYWORD 124
  124285. /************** End of keywordhash.h *****************************************/
  124286. /************** Continuing where we left off in tokenize.c *******************/
  124287. /*
  124288. ** If X is a character that can be used in an identifier then
  124289. ** IdChar(X) will be true. Otherwise it is false.
  124290. **
  124291. ** For ASCII, any character with the high-order bit set is
  124292. ** allowed in an identifier. For 7-bit characters,
  124293. ** sqlite3IsIdChar[X] must be 1.
  124294. **
  124295. ** For EBCDIC, the rules are more complex but have the same
  124296. ** end result.
  124297. **
  124298. ** Ticket #1066. the SQL standard does not allow '$' in the
  124299. ** middle of identifiers. But many SQL implementations do.
  124300. ** SQLite will allow '$' in identifiers for compatibility.
  124301. ** But the feature is undocumented.
  124302. */
  124303. #ifdef SQLITE_ASCII
  124304. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  124305. #endif
  124306. #ifdef SQLITE_EBCDIC
  124307. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  124308. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  124309. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  124310. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  124311. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  124312. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  124313. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  124314. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  124315. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  124317. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  124318. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  124319. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  124320. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  124321. };
  124322. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  124323. #endif
  124324. /* Make the IdChar function accessible from ctime.c */
  124325. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  124326. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  124327. #endif
  124328. /*
  124329. ** Return the length (in bytes) of the token that begins at z[0].
  124330. ** Store the token type in *tokenType before returning.
  124331. */
  124332. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  124333. int i, c;
  124334. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  124335. ** of the token. See the comment on the CC_ defines
  124336. ** above. */
  124337. case CC_SPACE: {
  124338. testcase( z[0]==' ' );
  124339. testcase( z[0]=='\t' );
  124340. testcase( z[0]=='\n' );
  124341. testcase( z[0]=='\f' );
  124342. testcase( z[0]=='\r' );
  124343. for(i=1; sqlite3Isspace(z[i]); i++){}
  124344. *tokenType = TK_SPACE;
  124345. return i;
  124346. }
  124347. case CC_MINUS: {
  124348. if( z[1]=='-' ){
  124349. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  124350. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  124351. return i;
  124352. }
  124353. *tokenType = TK_MINUS;
  124354. return 1;
  124355. }
  124356. case CC_LP: {
  124357. *tokenType = TK_LP;
  124358. return 1;
  124359. }
  124360. case CC_RP: {
  124361. *tokenType = TK_RP;
  124362. return 1;
  124363. }
  124364. case CC_SEMI: {
  124365. *tokenType = TK_SEMI;
  124366. return 1;
  124367. }
  124368. case CC_PLUS: {
  124369. *tokenType = TK_PLUS;
  124370. return 1;
  124371. }
  124372. case CC_STAR: {
  124373. *tokenType = TK_STAR;
  124374. return 1;
  124375. }
  124376. case CC_SLASH: {
  124377. if( z[1]!='*' || z[2]==0 ){
  124378. *tokenType = TK_SLASH;
  124379. return 1;
  124380. }
  124381. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  124382. if( c ) i++;
  124383. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  124384. return i;
  124385. }
  124386. case CC_PERCENT: {
  124387. *tokenType = TK_REM;
  124388. return 1;
  124389. }
  124390. case CC_EQ: {
  124391. *tokenType = TK_EQ;
  124392. return 1 + (z[1]=='=');
  124393. }
  124394. case CC_LT: {
  124395. if( (c=z[1])=='=' ){
  124396. *tokenType = TK_LE;
  124397. return 2;
  124398. }else if( c=='>' ){
  124399. *tokenType = TK_NE;
  124400. return 2;
  124401. }else if( c=='<' ){
  124402. *tokenType = TK_LSHIFT;
  124403. return 2;
  124404. }else{
  124405. *tokenType = TK_LT;
  124406. return 1;
  124407. }
  124408. }
  124409. case CC_GT: {
  124410. if( (c=z[1])=='=' ){
  124411. *tokenType = TK_GE;
  124412. return 2;
  124413. }else if( c=='>' ){
  124414. *tokenType = TK_RSHIFT;
  124415. return 2;
  124416. }else{
  124417. *tokenType = TK_GT;
  124418. return 1;
  124419. }
  124420. }
  124421. case CC_BANG: {
  124422. if( z[1]!='=' ){
  124423. *tokenType = TK_ILLEGAL;
  124424. return 1;
  124425. }else{
  124426. *tokenType = TK_NE;
  124427. return 2;
  124428. }
  124429. }
  124430. case CC_PIPE: {
  124431. if( z[1]!='|' ){
  124432. *tokenType = TK_BITOR;
  124433. return 1;
  124434. }else{
  124435. *tokenType = TK_CONCAT;
  124436. return 2;
  124437. }
  124438. }
  124439. case CC_COMMA: {
  124440. *tokenType = TK_COMMA;
  124441. return 1;
  124442. }
  124443. case CC_AND: {
  124444. *tokenType = TK_BITAND;
  124445. return 1;
  124446. }
  124447. case CC_TILDA: {
  124448. *tokenType = TK_BITNOT;
  124449. return 1;
  124450. }
  124451. case CC_QUOTE: {
  124452. int delim = z[0];
  124453. testcase( delim=='`' );
  124454. testcase( delim=='\'' );
  124455. testcase( delim=='"' );
  124456. for(i=1; (c=z[i])!=0; i++){
  124457. if( c==delim ){
  124458. if( z[i+1]==delim ){
  124459. i++;
  124460. }else{
  124461. break;
  124462. }
  124463. }
  124464. }
  124465. if( c=='\'' ){
  124466. *tokenType = TK_STRING;
  124467. return i+1;
  124468. }else if( c!=0 ){
  124469. *tokenType = TK_ID;
  124470. return i+1;
  124471. }else{
  124472. *tokenType = TK_ILLEGAL;
  124473. return i;
  124474. }
  124475. }
  124476. case CC_DOT: {
  124477. #ifndef SQLITE_OMIT_FLOATING_POINT
  124478. if( !sqlite3Isdigit(z[1]) )
  124479. #endif
  124480. {
  124481. *tokenType = TK_DOT;
  124482. return 1;
  124483. }
  124484. /* If the next character is a digit, this is a floating point
  124485. ** number that begins with ".". Fall thru into the next case */
  124486. }
  124487. case CC_DIGIT: {
  124488. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  124489. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  124490. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  124491. testcase( z[0]=='9' );
  124492. *tokenType = TK_INTEGER;
  124493. #ifndef SQLITE_OMIT_HEX_INTEGER
  124494. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  124495. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  124496. return i;
  124497. }
  124498. #endif
  124499. for(i=0; sqlite3Isdigit(z[i]); i++){}
  124500. #ifndef SQLITE_OMIT_FLOATING_POINT
  124501. if( z[i]=='.' ){
  124502. i++;
  124503. while( sqlite3Isdigit(z[i]) ){ i++; }
  124504. *tokenType = TK_FLOAT;
  124505. }
  124506. if( (z[i]=='e' || z[i]=='E') &&
  124507. ( sqlite3Isdigit(z[i+1])
  124508. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  124509. )
  124510. ){
  124511. i += 2;
  124512. while( sqlite3Isdigit(z[i]) ){ i++; }
  124513. *tokenType = TK_FLOAT;
  124514. }
  124515. #endif
  124516. while( IdChar(z[i]) ){
  124517. *tokenType = TK_ILLEGAL;
  124518. i++;
  124519. }
  124520. return i;
  124521. }
  124522. case CC_QUOTE2: {
  124523. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  124524. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  124525. return i;
  124526. }
  124527. case CC_VARNUM: {
  124528. *tokenType = TK_VARIABLE;
  124529. for(i=1; sqlite3Isdigit(z[i]); i++){}
  124530. return i;
  124531. }
  124532. case CC_DOLLAR:
  124533. case CC_VARALPHA: {
  124534. int n = 0;
  124535. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  124536. testcase( z[0]==':' ); testcase( z[0]=='#' );
  124537. *tokenType = TK_VARIABLE;
  124538. for(i=1; (c=z[i])!=0; i++){
  124539. if( IdChar(c) ){
  124540. n++;
  124541. #ifndef SQLITE_OMIT_TCL_VARIABLE
  124542. }else if( c=='(' && n>0 ){
  124543. do{
  124544. i++;
  124545. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  124546. if( c==')' ){
  124547. i++;
  124548. }else{
  124549. *tokenType = TK_ILLEGAL;
  124550. }
  124551. break;
  124552. }else if( c==':' && z[i+1]==':' ){
  124553. i++;
  124554. #endif
  124555. }else{
  124556. break;
  124557. }
  124558. }
  124559. if( n==0 ) *tokenType = TK_ILLEGAL;
  124560. return i;
  124561. }
  124562. case CC_KYWD: {
  124563. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  124564. if( IdChar(z[i]) ){
  124565. /* This token started out using characters that can appear in keywords,
  124566. ** but z[i] is a character not allowed within keywords, so this must
  124567. ** be an identifier instead */
  124568. i++;
  124569. break;
  124570. }
  124571. *tokenType = TK_ID;
  124572. return keywordCode((char*)z, i, tokenType);
  124573. }
  124574. case CC_X: {
  124575. #ifndef SQLITE_OMIT_BLOB_LITERAL
  124576. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  124577. if( z[1]=='\'' ){
  124578. *tokenType = TK_BLOB;
  124579. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  124580. if( z[i]!='\'' || i%2 ){
  124581. *tokenType = TK_ILLEGAL;
  124582. while( z[i] && z[i]!='\'' ){ i++; }
  124583. }
  124584. if( z[i] ) i++;
  124585. return i;
  124586. }
  124587. #endif
  124588. /* If it is not a BLOB literal, then it must be an ID, since no
  124589. ** SQL keywords start with the letter 'x'. Fall through */
  124590. }
  124591. case CC_ID: {
  124592. i = 1;
  124593. break;
  124594. }
  124595. default: {
  124596. *tokenType = TK_ILLEGAL;
  124597. return 1;
  124598. }
  124599. }
  124600. while( IdChar(z[i]) ){ i++; }
  124601. *tokenType = TK_ID;
  124602. return i;
  124603. }
  124604. /*
  124605. ** Run the parser on the given SQL string. The parser structure is
  124606. ** passed in. An SQLITE_ status code is returned. If an error occurs
  124607. ** then an and attempt is made to write an error message into
  124608. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  124609. ** error message.
  124610. */
  124611. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  124612. int nErr = 0; /* Number of errors encountered */
  124613. int i; /* Loop counter */
  124614. void *pEngine; /* The LEMON-generated LALR(1) parser */
  124615. int tokenType; /* type of the next token */
  124616. int lastTokenParsed = -1; /* type of the previous token */
  124617. sqlite3 *db = pParse->db; /* The database connection */
  124618. int mxSqlLen; /* Max length of an SQL string */
  124619. assert( zSql!=0 );
  124620. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  124621. if( db->nVdbeActive==0 ){
  124622. db->u1.isInterrupted = 0;
  124623. }
  124624. pParse->rc = SQLITE_OK;
  124625. pParse->zTail = zSql;
  124626. i = 0;
  124627. assert( pzErrMsg!=0 );
  124628. /* sqlite3ParserTrace(stdout, "parser: "); */
  124629. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  124630. if( pEngine==0 ){
  124631. sqlite3OomFault(db);
  124632. return SQLITE_NOMEM_BKPT;
  124633. }
  124634. assert( pParse->pNewTable==0 );
  124635. assert( pParse->pNewTrigger==0 );
  124636. assert( pParse->nVar==0 );
  124637. assert( pParse->nzVar==0 );
  124638. assert( pParse->azVar==0 );
  124639. while( zSql[i]!=0 ){
  124640. assert( i>=0 );
  124641. pParse->sLastToken.z = &zSql[i];
  124642. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  124643. i += pParse->sLastToken.n;
  124644. if( i>mxSqlLen ){
  124645. pParse->rc = SQLITE_TOOBIG;
  124646. break;
  124647. }
  124648. if( tokenType>=TK_SPACE ){
  124649. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  124650. if( db->u1.isInterrupted ){
  124651. pParse->rc = SQLITE_INTERRUPT;
  124652. break;
  124653. }
  124654. if( tokenType==TK_ILLEGAL ){
  124655. sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
  124656. &pParse->sLastToken);
  124657. break;
  124658. }
  124659. }else{
  124660. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  124661. lastTokenParsed = tokenType;
  124662. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  124663. }
  124664. }
  124665. assert( nErr==0 );
  124666. pParse->zTail = &zSql[i];
  124667. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  124668. assert( zSql[i]==0 );
  124669. if( lastTokenParsed!=TK_SEMI ){
  124670. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  124671. }
  124672. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  124673. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  124674. }
  124675. }
  124676. #ifdef YYTRACKMAXSTACKDEPTH
  124677. sqlite3_mutex_enter(sqlite3MallocMutex());
  124678. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  124679. sqlite3ParserStackPeak(pEngine)
  124680. );
  124681. sqlite3_mutex_leave(sqlite3MallocMutex());
  124682. #endif /* YYDEBUG */
  124683. sqlite3ParserFree(pEngine, sqlite3_free);
  124684. if( db->mallocFailed ){
  124685. pParse->rc = SQLITE_NOMEM_BKPT;
  124686. }
  124687. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  124688. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  124689. }
  124690. assert( pzErrMsg!=0 );
  124691. if( pParse->zErrMsg ){
  124692. *pzErrMsg = pParse->zErrMsg;
  124693. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  124694. pParse->zErrMsg = 0;
  124695. nErr++;
  124696. }
  124697. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  124698. sqlite3VdbeDelete(pParse->pVdbe);
  124699. pParse->pVdbe = 0;
  124700. }
  124701. #ifndef SQLITE_OMIT_SHARED_CACHE
  124702. if( pParse->nested==0 ){
  124703. sqlite3DbFree(db, pParse->aTableLock);
  124704. pParse->aTableLock = 0;
  124705. pParse->nTableLock = 0;
  124706. }
  124707. #endif
  124708. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124709. sqlite3_free(pParse->apVtabLock);
  124710. #endif
  124711. if( !IN_DECLARE_VTAB ){
  124712. /* If the pParse->declareVtab flag is set, do not delete any table
  124713. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  124714. ** will take responsibility for freeing the Table structure.
  124715. */
  124716. sqlite3DeleteTable(db, pParse->pNewTable);
  124717. }
  124718. sqlite3WithDelete(db, pParse->pWithToFree);
  124719. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  124720. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  124721. sqlite3DbFree(db, pParse->azVar);
  124722. while( pParse->pAinc ){
  124723. AutoincInfo *p = pParse->pAinc;
  124724. pParse->pAinc = p->pNext;
  124725. sqlite3DbFree(db, p);
  124726. }
  124727. while( pParse->pZombieTab ){
  124728. Table *p = pParse->pZombieTab;
  124729. pParse->pZombieTab = p->pNextZombie;
  124730. sqlite3DeleteTable(db, p);
  124731. }
  124732. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  124733. return nErr;
  124734. }
  124735. /************** End of tokenize.c ********************************************/
  124736. /************** Begin file complete.c ****************************************/
  124737. /*
  124738. ** 2001 September 15
  124739. **
  124740. ** The author disclaims copyright to this source code. In place of
  124741. ** a legal notice, here is a blessing:
  124742. **
  124743. ** May you do good and not evil.
  124744. ** May you find forgiveness for yourself and forgive others.
  124745. ** May you share freely, never taking more than you give.
  124746. **
  124747. *************************************************************************
  124748. ** An tokenizer for SQL
  124749. **
  124750. ** This file contains C code that implements the sqlite3_complete() API.
  124751. ** This code used to be part of the tokenizer.c source file. But by
  124752. ** separating it out, the code will be automatically omitted from
  124753. ** static links that do not use it.
  124754. */
  124755. /* #include "sqliteInt.h" */
  124756. #ifndef SQLITE_OMIT_COMPLETE
  124757. /*
  124758. ** This is defined in tokenize.c. We just have to import the definition.
  124759. */
  124760. #ifndef SQLITE_AMALGAMATION
  124761. #ifdef SQLITE_ASCII
  124762. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  124763. #endif
  124764. #ifdef SQLITE_EBCDIC
  124765. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  124766. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  124767. #endif
  124768. #endif /* SQLITE_AMALGAMATION */
  124769. /*
  124770. ** Token types used by the sqlite3_complete() routine. See the header
  124771. ** comments on that procedure for additional information.
  124772. */
  124773. #define tkSEMI 0
  124774. #define tkWS 1
  124775. #define tkOTHER 2
  124776. #ifndef SQLITE_OMIT_TRIGGER
  124777. #define tkEXPLAIN 3
  124778. #define tkCREATE 4
  124779. #define tkTEMP 5
  124780. #define tkTRIGGER 6
  124781. #define tkEND 7
  124782. #endif
  124783. /*
  124784. ** Return TRUE if the given SQL string ends in a semicolon.
  124785. **
  124786. ** Special handling is require for CREATE TRIGGER statements.
  124787. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  124788. ** must end with ";END;".
  124789. **
  124790. ** This implementation uses a state machine with 8 states:
  124791. **
  124792. ** (0) INVALID We have not yet seen a non-whitespace character.
  124793. **
  124794. ** (1) START At the beginning or end of an SQL statement. This routine
  124795. ** returns 1 if it ends in the START state and 0 if it ends
  124796. ** in any other state.
  124797. **
  124798. ** (2) NORMAL We are in the middle of statement which ends with a single
  124799. ** semicolon.
  124800. **
  124801. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  124802. ** a statement.
  124803. **
  124804. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  124805. ** statement, possibly preceded by EXPLAIN and/or followed by
  124806. ** TEMP or TEMPORARY
  124807. **
  124808. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  124809. ** ended by a semicolon, the keyword END, and another semicolon.
  124810. **
  124811. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  124812. ** the end of a trigger definition.
  124813. **
  124814. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  124815. ** of a trigger definition.
  124816. **
  124817. ** Transitions between states above are determined by tokens extracted
  124818. ** from the input. The following tokens are significant:
  124819. **
  124820. ** (0) tkSEMI A semicolon.
  124821. ** (1) tkWS Whitespace.
  124822. ** (2) tkOTHER Any other SQL token.
  124823. ** (3) tkEXPLAIN The "explain" keyword.
  124824. ** (4) tkCREATE The "create" keyword.
  124825. ** (5) tkTEMP The "temp" or "temporary" keyword.
  124826. ** (6) tkTRIGGER The "trigger" keyword.
  124827. ** (7) tkEND The "end" keyword.
  124828. **
  124829. ** Whitespace never causes a state transition and is always ignored.
  124830. ** This means that a SQL string of all whitespace is invalid.
  124831. **
  124832. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  124833. ** to recognize the end of a trigger can be omitted. All we have to do
  124834. ** is look for a semicolon that is not part of an string or comment.
  124835. */
  124836. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
  124837. u8 state = 0; /* Current state, using numbers defined in header comment */
  124838. u8 token; /* Value of the next token */
  124839. #ifndef SQLITE_OMIT_TRIGGER
  124840. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  124841. ** statement. This is the normal case.
  124842. */
  124843. static const u8 trans[8][8] = {
  124844. /* Token: */
  124845. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  124846. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  124847. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  124848. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  124849. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  124850. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  124851. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  124852. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  124853. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  124854. };
  124855. #else
  124856. /* If triggers are not supported by this compile then the statement machine
  124857. ** used to detect the end of a statement is much simpler
  124858. */
  124859. static const u8 trans[3][3] = {
  124860. /* Token: */
  124861. /* State: ** SEMI WS OTHER */
  124862. /* 0 INVALID: */ { 1, 0, 2, },
  124863. /* 1 START: */ { 1, 1, 2, },
  124864. /* 2 NORMAL: */ { 1, 2, 2, },
  124865. };
  124866. #endif /* SQLITE_OMIT_TRIGGER */
  124867. #ifdef SQLITE_ENABLE_API_ARMOR
  124868. if( zSql==0 ){
  124869. (void)SQLITE_MISUSE_BKPT;
  124870. return 0;
  124871. }
  124872. #endif
  124873. while( *zSql ){
  124874. switch( *zSql ){
  124875. case ';': { /* A semicolon */
  124876. token = tkSEMI;
  124877. break;
  124878. }
  124879. case ' ':
  124880. case '\r':
  124881. case '\t':
  124882. case '\n':
  124883. case '\f': { /* White space is ignored */
  124884. token = tkWS;
  124885. break;
  124886. }
  124887. case '/': { /* C-style comments */
  124888. if( zSql[1]!='*' ){
  124889. token = tkOTHER;
  124890. break;
  124891. }
  124892. zSql += 2;
  124893. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  124894. if( zSql[0]==0 ) return 0;
  124895. zSql++;
  124896. token = tkWS;
  124897. break;
  124898. }
  124899. case '-': { /* SQL-style comments from "--" to end of line */
  124900. if( zSql[1]!='-' ){
  124901. token = tkOTHER;
  124902. break;
  124903. }
  124904. while( *zSql && *zSql!='\n' ){ zSql++; }
  124905. if( *zSql==0 ) return state==1;
  124906. token = tkWS;
  124907. break;
  124908. }
  124909. case '[': { /* Microsoft-style identifiers in [...] */
  124910. zSql++;
  124911. while( *zSql && *zSql!=']' ){ zSql++; }
  124912. if( *zSql==0 ) return 0;
  124913. token = tkOTHER;
  124914. break;
  124915. }
  124916. case '`': /* Grave-accent quoted symbols used by MySQL */
  124917. case '"': /* single- and double-quoted strings */
  124918. case '\'': {
  124919. int c = *zSql;
  124920. zSql++;
  124921. while( *zSql && *zSql!=c ){ zSql++; }
  124922. if( *zSql==0 ) return 0;
  124923. token = tkOTHER;
  124924. break;
  124925. }
  124926. default: {
  124927. #ifdef SQLITE_EBCDIC
  124928. unsigned char c;
  124929. #endif
  124930. if( IdChar((u8)*zSql) ){
  124931. /* Keywords and unquoted identifiers */
  124932. int nId;
  124933. for(nId=1; IdChar(zSql[nId]); nId++){}
  124934. #ifdef SQLITE_OMIT_TRIGGER
  124935. token = tkOTHER;
  124936. #else
  124937. switch( *zSql ){
  124938. case 'c': case 'C': {
  124939. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  124940. token = tkCREATE;
  124941. }else{
  124942. token = tkOTHER;
  124943. }
  124944. break;
  124945. }
  124946. case 't': case 'T': {
  124947. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  124948. token = tkTRIGGER;
  124949. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  124950. token = tkTEMP;
  124951. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  124952. token = tkTEMP;
  124953. }else{
  124954. token = tkOTHER;
  124955. }
  124956. break;
  124957. }
  124958. case 'e': case 'E': {
  124959. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  124960. token = tkEND;
  124961. }else
  124962. #ifndef SQLITE_OMIT_EXPLAIN
  124963. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  124964. token = tkEXPLAIN;
  124965. }else
  124966. #endif
  124967. {
  124968. token = tkOTHER;
  124969. }
  124970. break;
  124971. }
  124972. default: {
  124973. token = tkOTHER;
  124974. break;
  124975. }
  124976. }
  124977. #endif /* SQLITE_OMIT_TRIGGER */
  124978. zSql += nId-1;
  124979. }else{
  124980. /* Operators and special symbols */
  124981. token = tkOTHER;
  124982. }
  124983. break;
  124984. }
  124985. }
  124986. state = trans[state][token];
  124987. zSql++;
  124988. }
  124989. return state==1;
  124990. }
  124991. #ifndef SQLITE_OMIT_UTF16
  124992. /*
  124993. ** This routine is the same as the sqlite3_complete() routine described
  124994. ** above, except that the parameter is required to be UTF-16 encoded, not
  124995. ** UTF-8.
  124996. */
  124997. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
  124998. sqlite3_value *pVal;
  124999. char const *zSql8;
  125000. int rc;
  125001. #ifndef SQLITE_OMIT_AUTOINIT
  125002. rc = sqlite3_initialize();
  125003. if( rc ) return rc;
  125004. #endif
  125005. pVal = sqlite3ValueNew(0);
  125006. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  125007. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  125008. if( zSql8 ){
  125009. rc = sqlite3_complete(zSql8);
  125010. }else{
  125011. rc = SQLITE_NOMEM_BKPT;
  125012. }
  125013. sqlite3ValueFree(pVal);
  125014. return rc & 0xff;
  125015. }
  125016. #endif /* SQLITE_OMIT_UTF16 */
  125017. #endif /* SQLITE_OMIT_COMPLETE */
  125018. /************** End of complete.c ********************************************/
  125019. /************** Begin file main.c ********************************************/
  125020. /*
  125021. ** 2001 September 15
  125022. **
  125023. ** The author disclaims copyright to this source code. In place of
  125024. ** a legal notice, here is a blessing:
  125025. **
  125026. ** May you do good and not evil.
  125027. ** May you find forgiveness for yourself and forgive others.
  125028. ** May you share freely, never taking more than you give.
  125029. **
  125030. *************************************************************************
  125031. ** Main file for the SQLite library. The routines in this file
  125032. ** implement the programmer interface to the library. Routines in
  125033. ** other files are for internal use by SQLite and should not be
  125034. ** accessed by users of the library.
  125035. */
  125036. /* #include "sqliteInt.h" */
  125037. #ifdef SQLITE_ENABLE_FTS3
  125038. /************** Include fts3.h in the middle of main.c ***********************/
  125039. /************** Begin file fts3.h ********************************************/
  125040. /*
  125041. ** 2006 Oct 10
  125042. **
  125043. ** The author disclaims copyright to this source code. In place of
  125044. ** a legal notice, here is a blessing:
  125045. **
  125046. ** May you do good and not evil.
  125047. ** May you find forgiveness for yourself and forgive others.
  125048. ** May you share freely, never taking more than you give.
  125049. **
  125050. ******************************************************************************
  125051. **
  125052. ** This header file is used by programs that want to link against the
  125053. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  125054. */
  125055. /* #include "sqlite3.h" */
  125056. #if 0
  125057. extern "C" {
  125058. #endif /* __cplusplus */
  125059. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  125060. #if 0
  125061. } /* extern "C" */
  125062. #endif /* __cplusplus */
  125063. /************** End of fts3.h ************************************************/
  125064. /************** Continuing where we left off in main.c ***********************/
  125065. #endif
  125066. #ifdef SQLITE_ENABLE_RTREE
  125067. /************** Include rtree.h in the middle of main.c **********************/
  125068. /************** Begin file rtree.h *******************************************/
  125069. /*
  125070. ** 2008 May 26
  125071. **
  125072. ** The author disclaims copyright to this source code. In place of
  125073. ** a legal notice, here is a blessing:
  125074. **
  125075. ** May you do good and not evil.
  125076. ** May you find forgiveness for yourself and forgive others.
  125077. ** May you share freely, never taking more than you give.
  125078. **
  125079. ******************************************************************************
  125080. **
  125081. ** This header file is used by programs that want to link against the
  125082. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  125083. */
  125084. /* #include "sqlite3.h" */
  125085. #if 0
  125086. extern "C" {
  125087. #endif /* __cplusplus */
  125088. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  125089. #if 0
  125090. } /* extern "C" */
  125091. #endif /* __cplusplus */
  125092. /************** End of rtree.h ***********************************************/
  125093. /************** Continuing where we left off in main.c ***********************/
  125094. #endif
  125095. #ifdef SQLITE_ENABLE_ICU
  125096. /************** Include sqliteicu.h in the middle of main.c ******************/
  125097. /************** Begin file sqliteicu.h ***************************************/
  125098. /*
  125099. ** 2008 May 26
  125100. **
  125101. ** The author disclaims copyright to this source code. In place of
  125102. ** a legal notice, here is a blessing:
  125103. **
  125104. ** May you do good and not evil.
  125105. ** May you find forgiveness for yourself and forgive others.
  125106. ** May you share freely, never taking more than you give.
  125107. **
  125108. ******************************************************************************
  125109. **
  125110. ** This header file is used by programs that want to link against the
  125111. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  125112. */
  125113. /* #include "sqlite3.h" */
  125114. #if 0
  125115. extern "C" {
  125116. #endif /* __cplusplus */
  125117. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  125118. #if 0
  125119. } /* extern "C" */
  125120. #endif /* __cplusplus */
  125121. /************** End of sqliteicu.h *******************************************/
  125122. /************** Continuing where we left off in main.c ***********************/
  125123. #endif
  125124. #ifdef SQLITE_ENABLE_JSON1
  125125. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  125126. #endif
  125127. #ifdef SQLITE_ENABLE_FTS5
  125128. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  125129. #endif
  125130. #ifndef SQLITE_AMALGAMATION
  125131. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  125132. ** contains the text of SQLITE_VERSION macro.
  125133. */
  125134. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  125135. #endif
  125136. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  125137. ** a pointer to the to the sqlite3_version[] string constant.
  125138. */
  125139. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
  125140. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  125141. ** pointer to a string constant whose value is the same as the
  125142. ** SQLITE_SOURCE_ID C preprocessor macro.
  125143. */
  125144. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  125145. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  125146. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  125147. */
  125148. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  125149. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  125150. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  125151. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  125152. */
  125153. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  125154. /*
  125155. ** When compiling the test fixture or with debugging enabled (on Win32),
  125156. ** this variable being set to non-zero will cause OSTRACE macros to emit
  125157. ** extra diagnostic information.
  125158. */
  125159. #ifdef SQLITE_HAVE_OS_TRACE
  125160. # ifndef SQLITE_DEBUG_OS_TRACE
  125161. # define SQLITE_DEBUG_OS_TRACE 0
  125162. # endif
  125163. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  125164. #endif
  125165. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  125166. /*
  125167. ** If the following function pointer is not NULL and if
  125168. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  125169. ** I/O active are written using this function. These messages
  125170. ** are intended for debugging activity only.
  125171. */
  125172. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  125173. #endif
  125174. /*
  125175. ** If the following global variable points to a string which is the
  125176. ** name of a directory, then that directory will be used to store
  125177. ** temporary files.
  125178. **
  125179. ** See also the "PRAGMA temp_store_directory" SQL command.
  125180. */
  125181. SQLITE_API char *sqlite3_temp_directory = 0;
  125182. /*
  125183. ** If the following global variable points to a string which is the
  125184. ** name of a directory, then that directory will be used to store
  125185. ** all database files specified with a relative pathname.
  125186. **
  125187. ** See also the "PRAGMA data_store_directory" SQL command.
  125188. */
  125189. SQLITE_API char *sqlite3_data_directory = 0;
  125190. /*
  125191. ** Initialize SQLite.
  125192. **
  125193. ** This routine must be called to initialize the memory allocation,
  125194. ** VFS, and mutex subsystems prior to doing any serious work with
  125195. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  125196. ** this routine will be called automatically by key routines such as
  125197. ** sqlite3_open().
  125198. **
  125199. ** This routine is a no-op except on its very first call for the process,
  125200. ** or for the first call after a call to sqlite3_shutdown.
  125201. **
  125202. ** The first thread to call this routine runs the initialization to
  125203. ** completion. If subsequent threads call this routine before the first
  125204. ** thread has finished the initialization process, then the subsequent
  125205. ** threads must block until the first thread finishes with the initialization.
  125206. **
  125207. ** The first thread might call this routine recursively. Recursive
  125208. ** calls to this routine should not block, of course. Otherwise the
  125209. ** initialization process would never complete.
  125210. **
  125211. ** Let X be the first thread to enter this routine. Let Y be some other
  125212. ** thread. Then while the initial invocation of this routine by X is
  125213. ** incomplete, it is required that:
  125214. **
  125215. ** * Calls to this routine from Y must block until the outer-most
  125216. ** call by X completes.
  125217. **
  125218. ** * Recursive calls to this routine from thread X return immediately
  125219. ** without blocking.
  125220. */
  125221. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
  125222. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  125223. int rc; /* Result code */
  125224. #ifdef SQLITE_EXTRA_INIT
  125225. int bRunExtraInit = 0; /* Extra initialization needed */
  125226. #endif
  125227. #ifdef SQLITE_OMIT_WSD
  125228. rc = sqlite3_wsd_init(4096, 24);
  125229. if( rc!=SQLITE_OK ){
  125230. return rc;
  125231. }
  125232. #endif
  125233. /* If the following assert() fails on some obscure processor/compiler
  125234. ** combination, the work-around is to set the correct pointer
  125235. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  125236. assert( SQLITE_PTRSIZE==sizeof(char*) );
  125237. /* If SQLite is already completely initialized, then this call
  125238. ** to sqlite3_initialize() should be a no-op. But the initialization
  125239. ** must be complete. So isInit must not be set until the very end
  125240. ** of this routine.
  125241. */
  125242. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  125243. /* Make sure the mutex subsystem is initialized. If unable to
  125244. ** initialize the mutex subsystem, return early with the error.
  125245. ** If the system is so sick that we are unable to allocate a mutex,
  125246. ** there is not much SQLite is going to be able to do.
  125247. **
  125248. ** The mutex subsystem must take care of serializing its own
  125249. ** initialization.
  125250. */
  125251. rc = sqlite3MutexInit();
  125252. if( rc ) return rc;
  125253. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  125254. ** This operation is protected by the STATIC_MASTER mutex. Note that
  125255. ** MutexAlloc() is called for a static mutex prior to initializing the
  125256. ** malloc subsystem - this implies that the allocation of a static
  125257. ** mutex must not require support from the malloc subsystem.
  125258. */
  125259. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  125260. sqlite3_mutex_enter(pMaster);
  125261. sqlite3GlobalConfig.isMutexInit = 1;
  125262. if( !sqlite3GlobalConfig.isMallocInit ){
  125263. rc = sqlite3MallocInit();
  125264. }
  125265. if( rc==SQLITE_OK ){
  125266. sqlite3GlobalConfig.isMallocInit = 1;
  125267. if( !sqlite3GlobalConfig.pInitMutex ){
  125268. sqlite3GlobalConfig.pInitMutex =
  125269. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  125270. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  125271. rc = SQLITE_NOMEM_BKPT;
  125272. }
  125273. }
  125274. }
  125275. if( rc==SQLITE_OK ){
  125276. sqlite3GlobalConfig.nRefInitMutex++;
  125277. }
  125278. sqlite3_mutex_leave(pMaster);
  125279. /* If rc is not SQLITE_OK at this point, then either the malloc
  125280. ** subsystem could not be initialized or the system failed to allocate
  125281. ** the pInitMutex mutex. Return an error in either case. */
  125282. if( rc!=SQLITE_OK ){
  125283. return rc;
  125284. }
  125285. /* Do the rest of the initialization under the recursive mutex so
  125286. ** that we will be able to handle recursive calls into
  125287. ** sqlite3_initialize(). The recursive calls normally come through
  125288. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  125289. ** recursive calls might also be possible.
  125290. **
  125291. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  125292. ** to the xInit method, so the xInit method need not be threadsafe.
  125293. **
  125294. ** The following mutex is what serializes access to the appdef pcache xInit
  125295. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  125296. ** call to sqlite3PcacheInitialize().
  125297. */
  125298. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  125299. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  125300. sqlite3GlobalConfig.inProgress = 1;
  125301. #ifdef SQLITE_ENABLE_SQLLOG
  125302. {
  125303. extern void sqlite3_init_sqllog(void);
  125304. sqlite3_init_sqllog();
  125305. }
  125306. #endif
  125307. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  125308. sqlite3RegisterBuiltinFunctions();
  125309. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  125310. rc = sqlite3PcacheInitialize();
  125311. }
  125312. if( rc==SQLITE_OK ){
  125313. sqlite3GlobalConfig.isPCacheInit = 1;
  125314. rc = sqlite3OsInit();
  125315. }
  125316. if( rc==SQLITE_OK ){
  125317. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  125318. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  125319. sqlite3GlobalConfig.isInit = 1;
  125320. #ifdef SQLITE_EXTRA_INIT
  125321. bRunExtraInit = 1;
  125322. #endif
  125323. }
  125324. sqlite3GlobalConfig.inProgress = 0;
  125325. }
  125326. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  125327. /* Go back under the static mutex and clean up the recursive
  125328. ** mutex to prevent a resource leak.
  125329. */
  125330. sqlite3_mutex_enter(pMaster);
  125331. sqlite3GlobalConfig.nRefInitMutex--;
  125332. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  125333. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  125334. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  125335. sqlite3GlobalConfig.pInitMutex = 0;
  125336. }
  125337. sqlite3_mutex_leave(pMaster);
  125338. /* The following is just a sanity check to make sure SQLite has
  125339. ** been compiled correctly. It is important to run this code, but
  125340. ** we don't want to run it too often and soak up CPU cycles for no
  125341. ** reason. So we run it once during initialization.
  125342. */
  125343. #ifndef NDEBUG
  125344. #ifndef SQLITE_OMIT_FLOATING_POINT
  125345. /* This section of code's only "output" is via assert() statements. */
  125346. if ( rc==SQLITE_OK ){
  125347. u64 x = (((u64)1)<<63)-1;
  125348. double y;
  125349. assert(sizeof(x)==8);
  125350. assert(sizeof(x)==sizeof(y));
  125351. memcpy(&y, &x, 8);
  125352. assert( sqlite3IsNaN(y) );
  125353. }
  125354. #endif
  125355. #endif
  125356. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  125357. ** compile-time option.
  125358. */
  125359. #ifdef SQLITE_EXTRA_INIT
  125360. if( bRunExtraInit ){
  125361. int SQLITE_EXTRA_INIT(const char*);
  125362. rc = SQLITE_EXTRA_INIT(0);
  125363. }
  125364. #endif
  125365. return rc;
  125366. }
  125367. /*
  125368. ** Undo the effects of sqlite3_initialize(). Must not be called while
  125369. ** there are outstanding database connections or memory allocations or
  125370. ** while any part of SQLite is otherwise in use in any thread. This
  125371. ** routine is not threadsafe. But it is safe to invoke this routine
  125372. ** on when SQLite is already shut down. If SQLite is already shut down
  125373. ** when this routine is invoked, then this routine is a harmless no-op.
  125374. */
  125375. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
  125376. #ifdef SQLITE_OMIT_WSD
  125377. int rc = sqlite3_wsd_init(4096, 24);
  125378. if( rc!=SQLITE_OK ){
  125379. return rc;
  125380. }
  125381. #endif
  125382. if( sqlite3GlobalConfig.isInit ){
  125383. #ifdef SQLITE_EXTRA_SHUTDOWN
  125384. void SQLITE_EXTRA_SHUTDOWN(void);
  125385. SQLITE_EXTRA_SHUTDOWN();
  125386. #endif
  125387. sqlite3_os_end();
  125388. sqlite3_reset_auto_extension();
  125389. sqlite3GlobalConfig.isInit = 0;
  125390. }
  125391. if( sqlite3GlobalConfig.isPCacheInit ){
  125392. sqlite3PcacheShutdown();
  125393. sqlite3GlobalConfig.isPCacheInit = 0;
  125394. }
  125395. if( sqlite3GlobalConfig.isMallocInit ){
  125396. sqlite3MallocEnd();
  125397. sqlite3GlobalConfig.isMallocInit = 0;
  125398. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  125399. /* The heap subsystem has now been shutdown and these values are supposed
  125400. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  125401. ** which would rely on that heap subsystem; therefore, make sure these
  125402. ** values cannot refer to heap memory that was just invalidated when the
  125403. ** heap subsystem was shutdown. This is only done if the current call to
  125404. ** this function resulted in the heap subsystem actually being shutdown.
  125405. */
  125406. sqlite3_data_directory = 0;
  125407. sqlite3_temp_directory = 0;
  125408. #endif
  125409. }
  125410. if( sqlite3GlobalConfig.isMutexInit ){
  125411. sqlite3MutexEnd();
  125412. sqlite3GlobalConfig.isMutexInit = 0;
  125413. }
  125414. return SQLITE_OK;
  125415. }
  125416. /*
  125417. ** This API allows applications to modify the global configuration of
  125418. ** the SQLite library at run-time.
  125419. **
  125420. ** This routine should only be called when there are no outstanding
  125421. ** database connections or memory allocations. This routine is not
  125422. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  125423. ** behavior.
  125424. */
  125425. SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
  125426. va_list ap;
  125427. int rc = SQLITE_OK;
  125428. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  125429. ** the SQLite library is in use. */
  125430. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  125431. va_start(ap, op);
  125432. switch( op ){
  125433. /* Mutex configuration options are only available in a threadsafe
  125434. ** compile.
  125435. */
  125436. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  125437. case SQLITE_CONFIG_SINGLETHREAD: {
  125438. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  125439. ** Single-thread. */
  125440. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  125441. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  125442. break;
  125443. }
  125444. #endif
  125445. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  125446. case SQLITE_CONFIG_MULTITHREAD: {
  125447. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  125448. ** Multi-thread. */
  125449. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  125450. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  125451. break;
  125452. }
  125453. #endif
  125454. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  125455. case SQLITE_CONFIG_SERIALIZED: {
  125456. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  125457. ** Serialized. */
  125458. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  125459. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  125460. break;
  125461. }
  125462. #endif
  125463. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  125464. case SQLITE_CONFIG_MUTEX: {
  125465. /* Specify an alternative mutex implementation */
  125466. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  125467. break;
  125468. }
  125469. #endif
  125470. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  125471. case SQLITE_CONFIG_GETMUTEX: {
  125472. /* Retrieve the current mutex implementation */
  125473. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  125474. break;
  125475. }
  125476. #endif
  125477. case SQLITE_CONFIG_MALLOC: {
  125478. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  125479. ** single argument which is a pointer to an instance of the
  125480. ** sqlite3_mem_methods structure. The argument specifies alternative
  125481. ** low-level memory allocation routines to be used in place of the memory
  125482. ** allocation routines built into SQLite. */
  125483. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  125484. break;
  125485. }
  125486. case SQLITE_CONFIG_GETMALLOC: {
  125487. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  125488. ** single argument which is a pointer to an instance of the
  125489. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  125490. ** filled with the currently defined memory allocation routines. */
  125491. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  125492. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  125493. break;
  125494. }
  125495. case SQLITE_CONFIG_MEMSTATUS: {
  125496. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  125497. ** single argument of type int, interpreted as a boolean, which enables
  125498. ** or disables the collection of memory allocation statistics. */
  125499. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  125500. break;
  125501. }
  125502. case SQLITE_CONFIG_SCRATCH: {
  125503. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  125504. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  125505. ** which the scratch allocations will be drawn, the size of each scratch
  125506. ** allocation (sz), and the maximum number of scratch allocations (N). */
  125507. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  125508. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  125509. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  125510. break;
  125511. }
  125512. case SQLITE_CONFIG_PAGECACHE: {
  125513. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  125514. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  125515. ** the size of each page cache line (sz), and the number of cache lines
  125516. ** (N). */
  125517. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  125518. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  125519. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  125520. break;
  125521. }
  125522. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  125523. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  125524. ** a single parameter which is a pointer to an integer and writes into
  125525. ** that integer the number of extra bytes per page required for each page
  125526. ** in SQLITE_CONFIG_PAGECACHE. */
  125527. *va_arg(ap, int*) =
  125528. sqlite3HeaderSizeBtree() +
  125529. sqlite3HeaderSizePcache() +
  125530. sqlite3HeaderSizePcache1();
  125531. break;
  125532. }
  125533. case SQLITE_CONFIG_PCACHE: {
  125534. /* no-op */
  125535. break;
  125536. }
  125537. case SQLITE_CONFIG_GETPCACHE: {
  125538. /* now an error */
  125539. rc = SQLITE_ERROR;
  125540. break;
  125541. }
  125542. case SQLITE_CONFIG_PCACHE2: {
  125543. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  125544. ** single argument which is a pointer to an sqlite3_pcache_methods2
  125545. ** object. This object specifies the interface to a custom page cache
  125546. ** implementation. */
  125547. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  125548. break;
  125549. }
  125550. case SQLITE_CONFIG_GETPCACHE2: {
  125551. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  125552. ** single argument which is a pointer to an sqlite3_pcache_methods2
  125553. ** object. SQLite copies of the current page cache implementation into
  125554. ** that object. */
  125555. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  125556. sqlite3PCacheSetDefault();
  125557. }
  125558. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  125559. break;
  125560. }
  125561. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  125562. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  125563. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  125564. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  125565. case SQLITE_CONFIG_HEAP: {
  125566. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  125567. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  125568. ** number of bytes in the memory buffer, and the minimum allocation size.
  125569. */
  125570. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  125571. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  125572. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  125573. if( sqlite3GlobalConfig.mnReq<1 ){
  125574. sqlite3GlobalConfig.mnReq = 1;
  125575. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  125576. /* cap min request size at 2^12 */
  125577. sqlite3GlobalConfig.mnReq = (1<<12);
  125578. }
  125579. if( sqlite3GlobalConfig.pHeap==0 ){
  125580. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  125581. ** is NULL, then SQLite reverts to using its default memory allocator
  125582. ** (the system malloc() implementation), undoing any prior invocation of
  125583. ** SQLITE_CONFIG_MALLOC.
  125584. **
  125585. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  125586. ** revert to its default implementation when sqlite3_initialize() is run
  125587. */
  125588. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  125589. }else{
  125590. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  125591. ** alternative memory allocator is engaged to handle all of SQLites
  125592. ** memory allocation needs. */
  125593. #ifdef SQLITE_ENABLE_MEMSYS3
  125594. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  125595. #endif
  125596. #ifdef SQLITE_ENABLE_MEMSYS5
  125597. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  125598. #endif
  125599. }
  125600. break;
  125601. }
  125602. #endif
  125603. case SQLITE_CONFIG_LOOKASIDE: {
  125604. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  125605. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  125606. break;
  125607. }
  125608. /* Record a pointer to the logger function and its first argument.
  125609. ** The default is NULL. Logging is disabled if the function pointer is
  125610. ** NULL.
  125611. */
  125612. case SQLITE_CONFIG_LOG: {
  125613. /* MSVC is picky about pulling func ptrs from va lists.
  125614. ** http://support.microsoft.com/kb/47961
  125615. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  125616. */
  125617. typedef void(*LOGFUNC_t)(void*,int,const char*);
  125618. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  125619. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  125620. break;
  125621. }
  125622. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  125623. ** can be changed at start-time using the
  125624. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  125625. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  125626. */
  125627. case SQLITE_CONFIG_URI: {
  125628. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  125629. ** argument of type int. If non-zero, then URI handling is globally
  125630. ** enabled. If the parameter is zero, then URI handling is globally
  125631. ** disabled. */
  125632. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  125633. break;
  125634. }
  125635. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  125636. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  125637. ** option takes a single integer argument which is interpreted as a
  125638. ** boolean in order to enable or disable the use of covering indices for
  125639. ** full table scans in the query optimizer. */
  125640. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  125641. break;
  125642. }
  125643. #ifdef SQLITE_ENABLE_SQLLOG
  125644. case SQLITE_CONFIG_SQLLOG: {
  125645. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  125646. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  125647. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  125648. break;
  125649. }
  125650. #endif
  125651. case SQLITE_CONFIG_MMAP_SIZE: {
  125652. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  125653. ** integer (sqlite3_int64) values that are the default mmap size limit
  125654. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  125655. ** mmap size limit. */
  125656. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  125657. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  125658. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  125659. ** negative, then that argument is changed to its compile-time default.
  125660. **
  125661. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  125662. ** silently truncated if necessary so that it does not exceed the
  125663. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  125664. ** compile-time option.
  125665. */
  125666. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  125667. mxMmap = SQLITE_MAX_MMAP_SIZE;
  125668. }
  125669. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  125670. if( szMmap>mxMmap) szMmap = mxMmap;
  125671. sqlite3GlobalConfig.mxMmap = mxMmap;
  125672. sqlite3GlobalConfig.szMmap = szMmap;
  125673. break;
  125674. }
  125675. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  125676. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  125677. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  125678. ** unsigned integer value that specifies the maximum size of the created
  125679. ** heap. */
  125680. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  125681. break;
  125682. }
  125683. #endif
  125684. case SQLITE_CONFIG_PMASZ: {
  125685. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  125686. break;
  125687. }
  125688. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  125689. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  125690. break;
  125691. }
  125692. default: {
  125693. rc = SQLITE_ERROR;
  125694. break;
  125695. }
  125696. }
  125697. va_end(ap);
  125698. return rc;
  125699. }
  125700. /*
  125701. ** Set up the lookaside buffers for a database connection.
  125702. ** Return SQLITE_OK on success.
  125703. ** If lookaside is already active, return SQLITE_BUSY.
  125704. **
  125705. ** The sz parameter is the number of bytes in each lookaside slot.
  125706. ** The cnt parameter is the number of slots. If pStart is NULL the
  125707. ** space for the lookaside memory is obtained from sqlite3_malloc().
  125708. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  125709. ** the lookaside memory.
  125710. */
  125711. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  125712. #ifndef SQLITE_OMIT_LOOKASIDE
  125713. void *pStart;
  125714. if( db->lookaside.nOut ){
  125715. return SQLITE_BUSY;
  125716. }
  125717. /* Free any existing lookaside buffer for this handle before
  125718. ** allocating a new one so we don't have to have space for
  125719. ** both at the same time.
  125720. */
  125721. if( db->lookaside.bMalloced ){
  125722. sqlite3_free(db->lookaside.pStart);
  125723. }
  125724. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  125725. ** than a pointer to be useful.
  125726. */
  125727. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  125728. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  125729. if( cnt<0 ) cnt = 0;
  125730. if( sz==0 || cnt==0 ){
  125731. sz = 0;
  125732. pStart = 0;
  125733. }else if( pBuf==0 ){
  125734. sqlite3BeginBenignMalloc();
  125735. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  125736. sqlite3EndBenignMalloc();
  125737. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  125738. }else{
  125739. pStart = pBuf;
  125740. }
  125741. db->lookaside.pStart = pStart;
  125742. db->lookaside.pFree = 0;
  125743. db->lookaside.sz = (u16)sz;
  125744. if( pStart ){
  125745. int i;
  125746. LookasideSlot *p;
  125747. assert( sz > (int)sizeof(LookasideSlot*) );
  125748. p = (LookasideSlot*)pStart;
  125749. for(i=cnt-1; i>=0; i--){
  125750. p->pNext = db->lookaside.pFree;
  125751. db->lookaside.pFree = p;
  125752. p = (LookasideSlot*)&((u8*)p)[sz];
  125753. }
  125754. db->lookaside.pEnd = p;
  125755. db->lookaside.bDisable = 0;
  125756. db->lookaside.bMalloced = pBuf==0 ?1:0;
  125757. }else{
  125758. db->lookaside.pStart = db;
  125759. db->lookaside.pEnd = db;
  125760. db->lookaside.bDisable = 1;
  125761. db->lookaside.bMalloced = 0;
  125762. }
  125763. #endif /* SQLITE_OMIT_LOOKASIDE */
  125764. return SQLITE_OK;
  125765. }
  125766. /*
  125767. ** Return the mutex associated with a database connection.
  125768. */
  125769. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
  125770. #ifdef SQLITE_ENABLE_API_ARMOR
  125771. if( !sqlite3SafetyCheckOk(db) ){
  125772. (void)SQLITE_MISUSE_BKPT;
  125773. return 0;
  125774. }
  125775. #endif
  125776. return db->mutex;
  125777. }
  125778. /*
  125779. ** Free up as much memory as we can from the given database
  125780. ** connection.
  125781. */
  125782. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
  125783. int i;
  125784. #ifdef SQLITE_ENABLE_API_ARMOR
  125785. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125786. #endif
  125787. sqlite3_mutex_enter(db->mutex);
  125788. sqlite3BtreeEnterAll(db);
  125789. for(i=0; i<db->nDb; i++){
  125790. Btree *pBt = db->aDb[i].pBt;
  125791. if( pBt ){
  125792. Pager *pPager = sqlite3BtreePager(pBt);
  125793. sqlite3PagerShrink(pPager);
  125794. }
  125795. }
  125796. sqlite3BtreeLeaveAll(db);
  125797. sqlite3_mutex_leave(db->mutex);
  125798. return SQLITE_OK;
  125799. }
  125800. /*
  125801. ** Flush any dirty pages in the pager-cache for any attached database
  125802. ** to disk.
  125803. */
  125804. SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3 *db){
  125805. int i;
  125806. int rc = SQLITE_OK;
  125807. int bSeenBusy = 0;
  125808. #ifdef SQLITE_ENABLE_API_ARMOR
  125809. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125810. #endif
  125811. sqlite3_mutex_enter(db->mutex);
  125812. sqlite3BtreeEnterAll(db);
  125813. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  125814. Btree *pBt = db->aDb[i].pBt;
  125815. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  125816. Pager *pPager = sqlite3BtreePager(pBt);
  125817. rc = sqlite3PagerFlush(pPager);
  125818. if( rc==SQLITE_BUSY ){
  125819. bSeenBusy = 1;
  125820. rc = SQLITE_OK;
  125821. }
  125822. }
  125823. }
  125824. sqlite3BtreeLeaveAll(db);
  125825. sqlite3_mutex_leave(db->mutex);
  125826. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  125827. }
  125828. /*
  125829. ** Configuration settings for an individual database connection
  125830. */
  125831. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
  125832. va_list ap;
  125833. int rc;
  125834. va_start(ap, op);
  125835. switch( op ){
  125836. case SQLITE_DBCONFIG_LOOKASIDE: {
  125837. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  125838. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  125839. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  125840. rc = setupLookaside(db, pBuf, sz, cnt);
  125841. break;
  125842. }
  125843. default: {
  125844. static const struct {
  125845. int op; /* The opcode */
  125846. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  125847. } aFlagOp[] = {
  125848. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  125849. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  125850. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  125851. };
  125852. unsigned int i;
  125853. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  125854. for(i=0; i<ArraySize(aFlagOp); i++){
  125855. if( aFlagOp[i].op==op ){
  125856. int onoff = va_arg(ap, int);
  125857. int *pRes = va_arg(ap, int*);
  125858. int oldFlags = db->flags;
  125859. if( onoff>0 ){
  125860. db->flags |= aFlagOp[i].mask;
  125861. }else if( onoff==0 ){
  125862. db->flags &= ~aFlagOp[i].mask;
  125863. }
  125864. if( oldFlags!=db->flags ){
  125865. sqlite3ExpirePreparedStatements(db);
  125866. }
  125867. if( pRes ){
  125868. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  125869. }
  125870. rc = SQLITE_OK;
  125871. break;
  125872. }
  125873. }
  125874. break;
  125875. }
  125876. }
  125877. va_end(ap);
  125878. return rc;
  125879. }
  125880. /*
  125881. ** Return true if the buffer z[0..n-1] contains all spaces.
  125882. */
  125883. static int allSpaces(const char *z, int n){
  125884. while( n>0 && z[n-1]==' ' ){ n--; }
  125885. return n==0;
  125886. }
  125887. /*
  125888. ** This is the default collating function named "BINARY" which is always
  125889. ** available.
  125890. **
  125891. ** If the padFlag argument is not NULL then space padding at the end
  125892. ** of strings is ignored. This implements the RTRIM collation.
  125893. */
  125894. static int binCollFunc(
  125895. void *padFlag,
  125896. int nKey1, const void *pKey1,
  125897. int nKey2, const void *pKey2
  125898. ){
  125899. int rc, n;
  125900. n = nKey1<nKey2 ? nKey1 : nKey2;
  125901. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  125902. ** strings byte by byte using the memcmp() function from the standard C
  125903. ** library. */
  125904. rc = memcmp(pKey1, pKey2, n);
  125905. if( rc==0 ){
  125906. if( padFlag
  125907. && allSpaces(((char*)pKey1)+n, nKey1-n)
  125908. && allSpaces(((char*)pKey2)+n, nKey2-n)
  125909. ){
  125910. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  125911. ** spaces at the end of either string do not change the result. In other
  125912. ** words, strings will compare equal to one another as long as they
  125913. ** differ only in the number of spaces at the end.
  125914. */
  125915. }else{
  125916. rc = nKey1 - nKey2;
  125917. }
  125918. }
  125919. return rc;
  125920. }
  125921. /*
  125922. ** Another built-in collating sequence: NOCASE.
  125923. **
  125924. ** This collating sequence is intended to be used for "case independent
  125925. ** comparison". SQLite's knowledge of upper and lower case equivalents
  125926. ** extends only to the 26 characters used in the English language.
  125927. **
  125928. ** At the moment there is only a UTF-8 implementation.
  125929. */
  125930. static int nocaseCollatingFunc(
  125931. void *NotUsed,
  125932. int nKey1, const void *pKey1,
  125933. int nKey2, const void *pKey2
  125934. ){
  125935. int r = sqlite3StrNICmp(
  125936. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  125937. UNUSED_PARAMETER(NotUsed);
  125938. if( 0==r ){
  125939. r = nKey1-nKey2;
  125940. }
  125941. return r;
  125942. }
  125943. /*
  125944. ** Return the ROWID of the most recent insert
  125945. */
  125946. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
  125947. #ifdef SQLITE_ENABLE_API_ARMOR
  125948. if( !sqlite3SafetyCheckOk(db) ){
  125949. (void)SQLITE_MISUSE_BKPT;
  125950. return 0;
  125951. }
  125952. #endif
  125953. return db->lastRowid;
  125954. }
  125955. /*
  125956. ** Return the number of changes in the most recent call to sqlite3_exec().
  125957. */
  125958. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
  125959. #ifdef SQLITE_ENABLE_API_ARMOR
  125960. if( !sqlite3SafetyCheckOk(db) ){
  125961. (void)SQLITE_MISUSE_BKPT;
  125962. return 0;
  125963. }
  125964. #endif
  125965. return db->nChange;
  125966. }
  125967. /*
  125968. ** Return the number of changes since the database handle was opened.
  125969. */
  125970. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
  125971. #ifdef SQLITE_ENABLE_API_ARMOR
  125972. if( !sqlite3SafetyCheckOk(db) ){
  125973. (void)SQLITE_MISUSE_BKPT;
  125974. return 0;
  125975. }
  125976. #endif
  125977. return db->nTotalChange;
  125978. }
  125979. /*
  125980. ** Close all open savepoints. This function only manipulates fields of the
  125981. ** database handle object, it does not close any savepoints that may be open
  125982. ** at the b-tree/pager level.
  125983. */
  125984. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  125985. while( db->pSavepoint ){
  125986. Savepoint *pTmp = db->pSavepoint;
  125987. db->pSavepoint = pTmp->pNext;
  125988. sqlite3DbFree(db, pTmp);
  125989. }
  125990. db->nSavepoint = 0;
  125991. db->nStatement = 0;
  125992. db->isTransactionSavepoint = 0;
  125993. }
  125994. /*
  125995. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  125996. ** if this is not the last copy of the function, do not invoke it. Multiple
  125997. ** copies of a single function are created when create_function() is called
  125998. ** with SQLITE_ANY as the encoding.
  125999. */
  126000. static void functionDestroy(sqlite3 *db, FuncDef *p){
  126001. FuncDestructor *pDestructor = p->u.pDestructor;
  126002. if( pDestructor ){
  126003. pDestructor->nRef--;
  126004. if( pDestructor->nRef==0 ){
  126005. pDestructor->xDestroy(pDestructor->pUserData);
  126006. sqlite3DbFree(db, pDestructor);
  126007. }
  126008. }
  126009. }
  126010. /*
  126011. ** Disconnect all sqlite3_vtab objects that belong to database connection
  126012. ** db. This is called when db is being closed.
  126013. */
  126014. static void disconnectAllVtab(sqlite3 *db){
  126015. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126016. int i;
  126017. HashElem *p;
  126018. sqlite3BtreeEnterAll(db);
  126019. for(i=0; i<db->nDb; i++){
  126020. Schema *pSchema = db->aDb[i].pSchema;
  126021. if( db->aDb[i].pSchema ){
  126022. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  126023. Table *pTab = (Table *)sqliteHashData(p);
  126024. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  126025. }
  126026. }
  126027. }
  126028. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  126029. Module *pMod = (Module *)sqliteHashData(p);
  126030. if( pMod->pEpoTab ){
  126031. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  126032. }
  126033. }
  126034. sqlite3VtabUnlockList(db);
  126035. sqlite3BtreeLeaveAll(db);
  126036. #else
  126037. UNUSED_PARAMETER(db);
  126038. #endif
  126039. }
  126040. /*
  126041. ** Return TRUE if database connection db has unfinalized prepared
  126042. ** statements or unfinished sqlite3_backup objects.
  126043. */
  126044. static int connectionIsBusy(sqlite3 *db){
  126045. int j;
  126046. assert( sqlite3_mutex_held(db->mutex) );
  126047. if( db->pVdbe ) return 1;
  126048. for(j=0; j<db->nDb; j++){
  126049. Btree *pBt = db->aDb[j].pBt;
  126050. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  126051. }
  126052. return 0;
  126053. }
  126054. /*
  126055. ** Close an existing SQLite database
  126056. */
  126057. static int sqlite3Close(sqlite3 *db, int forceZombie){
  126058. if( !db ){
  126059. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  126060. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  126061. return SQLITE_OK;
  126062. }
  126063. if( !sqlite3SafetyCheckSickOrOk(db) ){
  126064. return SQLITE_MISUSE_BKPT;
  126065. }
  126066. sqlite3_mutex_enter(db->mutex);
  126067. /* Force xDisconnect calls on all virtual tables */
  126068. disconnectAllVtab(db);
  126069. /* If a transaction is open, the disconnectAllVtab() call above
  126070. ** will not have called the xDisconnect() method on any virtual
  126071. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  126072. ** call will do so. We need to do this before the check for active
  126073. ** SQL statements below, as the v-table implementation may be storing
  126074. ** some prepared statements internally.
  126075. */
  126076. sqlite3VtabRollback(db);
  126077. /* Legacy behavior (sqlite3_close() behavior) is to return
  126078. ** SQLITE_BUSY if the connection can not be closed immediately.
  126079. */
  126080. if( !forceZombie && connectionIsBusy(db) ){
  126081. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  126082. "statements or unfinished backups");
  126083. sqlite3_mutex_leave(db->mutex);
  126084. return SQLITE_BUSY;
  126085. }
  126086. #ifdef SQLITE_ENABLE_SQLLOG
  126087. if( sqlite3GlobalConfig.xSqllog ){
  126088. /* Closing the handle. Fourth parameter is passed the value 2. */
  126089. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  126090. }
  126091. #endif
  126092. /* Convert the connection into a zombie and then close it.
  126093. */
  126094. db->magic = SQLITE_MAGIC_ZOMBIE;
  126095. sqlite3LeaveMutexAndCloseZombie(db);
  126096. return SQLITE_OK;
  126097. }
  126098. /*
  126099. ** Two variations on the public interface for closing a database
  126100. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  126101. ** leaves the connection option if there are unfinalized prepared
  126102. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  126103. ** version forces the connection to become a zombie if there are
  126104. ** unclosed resources, and arranges for deallocation when the last
  126105. ** prepare statement or sqlite3_backup closes.
  126106. */
  126107. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  126108. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  126109. /*
  126110. ** Close the mutex on database connection db.
  126111. **
  126112. ** Furthermore, if database connection db is a zombie (meaning that there
  126113. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  126114. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  126115. ** finished, then free all resources.
  126116. */
  126117. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  126118. HashElem *i; /* Hash table iterator */
  126119. int j;
  126120. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  126121. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  126122. ** then just leave the mutex and return.
  126123. */
  126124. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  126125. sqlite3_mutex_leave(db->mutex);
  126126. return;
  126127. }
  126128. /* If we reach this point, it means that the database connection has
  126129. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  126130. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  126131. ** go ahead and free all resources.
  126132. */
  126133. /* If a transaction is open, roll it back. This also ensures that if
  126134. ** any database schemas have been modified by an uncommitted transaction
  126135. ** they are reset. And that the required b-tree mutex is held to make
  126136. ** the pager rollback and schema reset an atomic operation. */
  126137. sqlite3RollbackAll(db, SQLITE_OK);
  126138. /* Free any outstanding Savepoint structures. */
  126139. sqlite3CloseSavepoints(db);
  126140. /* Close all database connections */
  126141. for(j=0; j<db->nDb; j++){
  126142. struct Db *pDb = &db->aDb[j];
  126143. if( pDb->pBt ){
  126144. sqlite3BtreeClose(pDb->pBt);
  126145. pDb->pBt = 0;
  126146. if( j!=1 ){
  126147. pDb->pSchema = 0;
  126148. }
  126149. }
  126150. }
  126151. /* Clear the TEMP schema separately and last */
  126152. if( db->aDb[1].pSchema ){
  126153. sqlite3SchemaClear(db->aDb[1].pSchema);
  126154. }
  126155. sqlite3VtabUnlockList(db);
  126156. /* Free up the array of auxiliary databases */
  126157. sqlite3CollapseDatabaseArray(db);
  126158. assert( db->nDb<=2 );
  126159. assert( db->aDb==db->aDbStatic );
  126160. /* Tell the code in notify.c that the connection no longer holds any
  126161. ** locks and does not require any further unlock-notify callbacks.
  126162. */
  126163. sqlite3ConnectionClosed(db);
  126164. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  126165. FuncDef *pNext, *p;
  126166. p = sqliteHashData(i);
  126167. do{
  126168. functionDestroy(db, p);
  126169. pNext = p->pNext;
  126170. sqlite3DbFree(db, p);
  126171. p = pNext;
  126172. }while( p );
  126173. }
  126174. sqlite3HashClear(&db->aFunc);
  126175. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  126176. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  126177. /* Invoke any destructors registered for collation sequence user data. */
  126178. for(j=0; j<3; j++){
  126179. if( pColl[j].xDel ){
  126180. pColl[j].xDel(pColl[j].pUser);
  126181. }
  126182. }
  126183. sqlite3DbFree(db, pColl);
  126184. }
  126185. sqlite3HashClear(&db->aCollSeq);
  126186. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126187. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  126188. Module *pMod = (Module *)sqliteHashData(i);
  126189. if( pMod->xDestroy ){
  126190. pMod->xDestroy(pMod->pAux);
  126191. }
  126192. sqlite3VtabEponymousTableClear(db, pMod);
  126193. sqlite3DbFree(db, pMod);
  126194. }
  126195. sqlite3HashClear(&db->aModule);
  126196. #endif
  126197. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  126198. sqlite3ValueFree(db->pErr);
  126199. sqlite3CloseExtensions(db);
  126200. #if SQLITE_USER_AUTHENTICATION
  126201. sqlite3_free(db->auth.zAuthUser);
  126202. sqlite3_free(db->auth.zAuthPW);
  126203. #endif
  126204. db->magic = SQLITE_MAGIC_ERROR;
  126205. /* The temp-database schema is allocated differently from the other schema
  126206. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  126207. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  126208. ** the same sqliteMalloc() as the one that allocates the database
  126209. ** structure?
  126210. */
  126211. sqlite3DbFree(db, db->aDb[1].pSchema);
  126212. sqlite3_mutex_leave(db->mutex);
  126213. db->magic = SQLITE_MAGIC_CLOSED;
  126214. sqlite3_mutex_free(db->mutex);
  126215. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  126216. if( db->lookaside.bMalloced ){
  126217. sqlite3_free(db->lookaside.pStart);
  126218. }
  126219. sqlite3_free(db);
  126220. }
  126221. /*
  126222. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  126223. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  126224. ** breaker") and made to return tripCode if there are any further
  126225. ** attempts to use that cursor. Read cursors remain open and valid
  126226. ** but are "saved" in case the table pages are moved around.
  126227. */
  126228. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  126229. int i;
  126230. int inTrans = 0;
  126231. int schemaChange;
  126232. assert( sqlite3_mutex_held(db->mutex) );
  126233. sqlite3BeginBenignMalloc();
  126234. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  126235. ** This is important in case the transaction being rolled back has
  126236. ** modified the database schema. If the b-tree mutexes are not taken
  126237. ** here, then another shared-cache connection might sneak in between
  126238. ** the database rollback and schema reset, which can cause false
  126239. ** corruption reports in some cases. */
  126240. sqlite3BtreeEnterAll(db);
  126241. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  126242. for(i=0; i<db->nDb; i++){
  126243. Btree *p = db->aDb[i].pBt;
  126244. if( p ){
  126245. if( sqlite3BtreeIsInTrans(p) ){
  126246. inTrans = 1;
  126247. }
  126248. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  126249. }
  126250. }
  126251. sqlite3VtabRollback(db);
  126252. sqlite3EndBenignMalloc();
  126253. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  126254. sqlite3ExpirePreparedStatements(db);
  126255. sqlite3ResetAllSchemasOfConnection(db);
  126256. }
  126257. sqlite3BtreeLeaveAll(db);
  126258. /* Any deferred constraint violations have now been resolved. */
  126259. db->nDeferredCons = 0;
  126260. db->nDeferredImmCons = 0;
  126261. db->flags &= ~SQLITE_DeferFKs;
  126262. /* If one has been configured, invoke the rollback-hook callback */
  126263. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  126264. db->xRollbackCallback(db->pRollbackArg);
  126265. }
  126266. }
  126267. /*
  126268. ** Return a static string containing the name corresponding to the error code
  126269. ** specified in the argument.
  126270. */
  126271. #if defined(SQLITE_NEED_ERR_NAME)
  126272. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  126273. const char *zName = 0;
  126274. int i, origRc = rc;
  126275. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  126276. switch( rc ){
  126277. case SQLITE_OK: zName = "SQLITE_OK"; break;
  126278. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  126279. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  126280. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  126281. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  126282. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  126283. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  126284. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  126285. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  126286. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  126287. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  126288. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  126289. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  126290. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  126291. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  126292. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  126293. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  126294. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  126295. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  126296. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  126297. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  126298. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  126299. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  126300. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  126301. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  126302. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  126303. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  126304. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  126305. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  126306. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  126307. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  126308. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  126309. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  126310. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  126311. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  126312. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  126313. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  126314. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  126315. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  126316. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  126317. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  126318. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  126319. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  126320. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  126321. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  126322. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  126323. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  126324. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  126325. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  126326. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  126327. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  126328. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  126329. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  126330. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  126331. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  126332. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  126333. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  126334. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  126335. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  126336. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  126337. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  126338. case SQLITE_CONSTRAINT_FOREIGNKEY:
  126339. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  126340. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  126341. case SQLITE_CONSTRAINT_PRIMARYKEY:
  126342. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  126343. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  126344. case SQLITE_CONSTRAINT_COMMITHOOK:
  126345. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  126346. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  126347. case SQLITE_CONSTRAINT_FUNCTION:
  126348. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  126349. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  126350. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  126351. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  126352. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  126353. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  126354. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  126355. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  126356. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  126357. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  126358. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  126359. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  126360. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  126361. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  126362. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  126363. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  126364. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  126365. }
  126366. }
  126367. if( zName==0 ){
  126368. static char zBuf[50];
  126369. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  126370. zName = zBuf;
  126371. }
  126372. return zName;
  126373. }
  126374. #endif
  126375. /*
  126376. ** Return a static string that describes the kind of error specified in the
  126377. ** argument.
  126378. */
  126379. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  126380. static const char* const aMsg[] = {
  126381. /* SQLITE_OK */ "not an error",
  126382. /* SQLITE_ERROR */ "SQL logic error or missing database",
  126383. /* SQLITE_INTERNAL */ 0,
  126384. /* SQLITE_PERM */ "access permission denied",
  126385. /* SQLITE_ABORT */ "callback requested query abort",
  126386. /* SQLITE_BUSY */ "database is locked",
  126387. /* SQLITE_LOCKED */ "database table is locked",
  126388. /* SQLITE_NOMEM */ "out of memory",
  126389. /* SQLITE_READONLY */ "attempt to write a readonly database",
  126390. /* SQLITE_INTERRUPT */ "interrupted",
  126391. /* SQLITE_IOERR */ "disk I/O error",
  126392. /* SQLITE_CORRUPT */ "database disk image is malformed",
  126393. /* SQLITE_NOTFOUND */ "unknown operation",
  126394. /* SQLITE_FULL */ "database or disk is full",
  126395. /* SQLITE_CANTOPEN */ "unable to open database file",
  126396. /* SQLITE_PROTOCOL */ "locking protocol",
  126397. /* SQLITE_EMPTY */ "table contains no data",
  126398. /* SQLITE_SCHEMA */ "database schema has changed",
  126399. /* SQLITE_TOOBIG */ "string or blob too big",
  126400. /* SQLITE_CONSTRAINT */ "constraint failed",
  126401. /* SQLITE_MISMATCH */ "datatype mismatch",
  126402. /* SQLITE_MISUSE */ "library routine called out of sequence",
  126403. /* SQLITE_NOLFS */ "large file support is disabled",
  126404. /* SQLITE_AUTH */ "authorization denied",
  126405. /* SQLITE_FORMAT */ "auxiliary database format error",
  126406. /* SQLITE_RANGE */ "bind or column index out of range",
  126407. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  126408. };
  126409. const char *zErr = "unknown error";
  126410. switch( rc ){
  126411. case SQLITE_ABORT_ROLLBACK: {
  126412. zErr = "abort due to ROLLBACK";
  126413. break;
  126414. }
  126415. default: {
  126416. rc &= 0xff;
  126417. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  126418. zErr = aMsg[rc];
  126419. }
  126420. break;
  126421. }
  126422. }
  126423. return zErr;
  126424. }
  126425. /*
  126426. ** This routine implements a busy callback that sleeps and tries
  126427. ** again until a timeout value is reached. The timeout value is
  126428. ** an integer number of milliseconds passed in as the first
  126429. ** argument.
  126430. */
  126431. static int sqliteDefaultBusyCallback(
  126432. void *ptr, /* Database connection */
  126433. int count /* Number of times table has been busy */
  126434. ){
  126435. #if SQLITE_OS_WIN || HAVE_USLEEP
  126436. static const u8 delays[] =
  126437. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  126438. static const u8 totals[] =
  126439. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  126440. # define NDELAY ArraySize(delays)
  126441. sqlite3 *db = (sqlite3 *)ptr;
  126442. int timeout = db->busyTimeout;
  126443. int delay, prior;
  126444. assert( count>=0 );
  126445. if( count < NDELAY ){
  126446. delay = delays[count];
  126447. prior = totals[count];
  126448. }else{
  126449. delay = delays[NDELAY-1];
  126450. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  126451. }
  126452. if( prior + delay > timeout ){
  126453. delay = timeout - prior;
  126454. if( delay<=0 ) return 0;
  126455. }
  126456. sqlite3OsSleep(db->pVfs, delay*1000);
  126457. return 1;
  126458. #else
  126459. sqlite3 *db = (sqlite3 *)ptr;
  126460. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  126461. if( (count+1)*1000 > timeout ){
  126462. return 0;
  126463. }
  126464. sqlite3OsSleep(db->pVfs, 1000000);
  126465. return 1;
  126466. #endif
  126467. }
  126468. /*
  126469. ** Invoke the given busy handler.
  126470. **
  126471. ** This routine is called when an operation failed with a lock.
  126472. ** If this routine returns non-zero, the lock is retried. If it
  126473. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  126474. */
  126475. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  126476. int rc;
  126477. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  126478. rc = p->xFunc(p->pArg, p->nBusy);
  126479. if( rc==0 ){
  126480. p->nBusy = -1;
  126481. }else{
  126482. p->nBusy++;
  126483. }
  126484. return rc;
  126485. }
  126486. /*
  126487. ** This routine sets the busy callback for an Sqlite database to the
  126488. ** given callback function with the given argument.
  126489. */
  126490. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
  126491. sqlite3 *db,
  126492. int (*xBusy)(void*,int),
  126493. void *pArg
  126494. ){
  126495. #ifdef SQLITE_ENABLE_API_ARMOR
  126496. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126497. #endif
  126498. sqlite3_mutex_enter(db->mutex);
  126499. db->busyHandler.xFunc = xBusy;
  126500. db->busyHandler.pArg = pArg;
  126501. db->busyHandler.nBusy = 0;
  126502. db->busyTimeout = 0;
  126503. sqlite3_mutex_leave(db->mutex);
  126504. return SQLITE_OK;
  126505. }
  126506. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  126507. /*
  126508. ** This routine sets the progress callback for an Sqlite database to the
  126509. ** given callback function with the given argument. The progress callback will
  126510. ** be invoked every nOps opcodes.
  126511. */
  126512. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
  126513. sqlite3 *db,
  126514. int nOps,
  126515. int (*xProgress)(void*),
  126516. void *pArg
  126517. ){
  126518. #ifdef SQLITE_ENABLE_API_ARMOR
  126519. if( !sqlite3SafetyCheckOk(db) ){
  126520. (void)SQLITE_MISUSE_BKPT;
  126521. return;
  126522. }
  126523. #endif
  126524. sqlite3_mutex_enter(db->mutex);
  126525. if( nOps>0 ){
  126526. db->xProgress = xProgress;
  126527. db->nProgressOps = (unsigned)nOps;
  126528. db->pProgressArg = pArg;
  126529. }else{
  126530. db->xProgress = 0;
  126531. db->nProgressOps = 0;
  126532. db->pProgressArg = 0;
  126533. }
  126534. sqlite3_mutex_leave(db->mutex);
  126535. }
  126536. #endif
  126537. /*
  126538. ** This routine installs a default busy handler that waits for the
  126539. ** specified number of milliseconds before returning 0.
  126540. */
  126541. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
  126542. #ifdef SQLITE_ENABLE_API_ARMOR
  126543. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126544. #endif
  126545. if( ms>0 ){
  126546. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  126547. db->busyTimeout = ms;
  126548. }else{
  126549. sqlite3_busy_handler(db, 0, 0);
  126550. }
  126551. return SQLITE_OK;
  126552. }
  126553. /*
  126554. ** Cause any pending operation to stop at its earliest opportunity.
  126555. */
  126556. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
  126557. #ifdef SQLITE_ENABLE_API_ARMOR
  126558. if( !sqlite3SafetyCheckOk(db) ){
  126559. (void)SQLITE_MISUSE_BKPT;
  126560. return;
  126561. }
  126562. #endif
  126563. db->u1.isInterrupted = 1;
  126564. }
  126565. /*
  126566. ** This function is exactly the same as sqlite3_create_function(), except
  126567. ** that it is designed to be called by internal code. The difference is
  126568. ** that if a malloc() fails in sqlite3_create_function(), an error code
  126569. ** is returned and the mallocFailed flag cleared.
  126570. */
  126571. SQLITE_PRIVATE int sqlite3CreateFunc(
  126572. sqlite3 *db,
  126573. const char *zFunctionName,
  126574. int nArg,
  126575. int enc,
  126576. void *pUserData,
  126577. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  126578. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  126579. void (*xFinal)(sqlite3_context*),
  126580. FuncDestructor *pDestructor
  126581. ){
  126582. FuncDef *p;
  126583. int nName;
  126584. int extraFlags;
  126585. assert( sqlite3_mutex_held(db->mutex) );
  126586. if( zFunctionName==0 ||
  126587. (xSFunc && (xFinal || xStep)) ||
  126588. (!xSFunc && (xFinal && !xStep)) ||
  126589. (!xSFunc && (!xFinal && xStep)) ||
  126590. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  126591. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  126592. return SQLITE_MISUSE_BKPT;
  126593. }
  126594. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  126595. extraFlags = enc & SQLITE_DETERMINISTIC;
  126596. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  126597. #ifndef SQLITE_OMIT_UTF16
  126598. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  126599. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  126600. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  126601. **
  126602. ** If SQLITE_ANY is specified, add three versions of the function
  126603. ** to the hash table.
  126604. */
  126605. if( enc==SQLITE_UTF16 ){
  126606. enc = SQLITE_UTF16NATIVE;
  126607. }else if( enc==SQLITE_ANY ){
  126608. int rc;
  126609. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  126610. pUserData, xSFunc, xStep, xFinal, pDestructor);
  126611. if( rc==SQLITE_OK ){
  126612. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  126613. pUserData, xSFunc, xStep, xFinal, pDestructor);
  126614. }
  126615. if( rc!=SQLITE_OK ){
  126616. return rc;
  126617. }
  126618. enc = SQLITE_UTF16BE;
  126619. }
  126620. #else
  126621. enc = SQLITE_UTF8;
  126622. #endif
  126623. /* Check if an existing function is being overridden or deleted. If so,
  126624. ** and there are active VMs, then return SQLITE_BUSY. If a function
  126625. ** is being overridden/deleted but there are no active VMs, allow the
  126626. ** operation to continue but invalidate all precompiled statements.
  126627. */
  126628. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  126629. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  126630. if( db->nVdbeActive ){
  126631. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  126632. "unable to delete/modify user-function due to active statements");
  126633. assert( !db->mallocFailed );
  126634. return SQLITE_BUSY;
  126635. }else{
  126636. sqlite3ExpirePreparedStatements(db);
  126637. }
  126638. }
  126639. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  126640. assert(p || db->mallocFailed);
  126641. if( !p ){
  126642. return SQLITE_NOMEM_BKPT;
  126643. }
  126644. /* If an older version of the function with a configured destructor is
  126645. ** being replaced invoke the destructor function here. */
  126646. functionDestroy(db, p);
  126647. if( pDestructor ){
  126648. pDestructor->nRef++;
  126649. }
  126650. p->u.pDestructor = pDestructor;
  126651. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  126652. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  126653. p->xSFunc = xSFunc ? xSFunc : xStep;
  126654. p->xFinalize = xFinal;
  126655. p->pUserData = pUserData;
  126656. p->nArg = (u16)nArg;
  126657. return SQLITE_OK;
  126658. }
  126659. /*
  126660. ** Create new user functions.
  126661. */
  126662. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  126663. sqlite3 *db,
  126664. const char *zFunc,
  126665. int nArg,
  126666. int enc,
  126667. void *p,
  126668. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  126669. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  126670. void (*xFinal)(sqlite3_context*)
  126671. ){
  126672. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
  126673. xFinal, 0);
  126674. }
  126675. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  126676. sqlite3 *db,
  126677. const char *zFunc,
  126678. int nArg,
  126679. int enc,
  126680. void *p,
  126681. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  126682. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  126683. void (*xFinal)(sqlite3_context*),
  126684. void (*xDestroy)(void *)
  126685. ){
  126686. int rc = SQLITE_ERROR;
  126687. FuncDestructor *pArg = 0;
  126688. #ifdef SQLITE_ENABLE_API_ARMOR
  126689. if( !sqlite3SafetyCheckOk(db) ){
  126690. return SQLITE_MISUSE_BKPT;
  126691. }
  126692. #endif
  126693. sqlite3_mutex_enter(db->mutex);
  126694. if( xDestroy ){
  126695. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  126696. if( !pArg ){
  126697. xDestroy(p);
  126698. goto out;
  126699. }
  126700. pArg->xDestroy = xDestroy;
  126701. pArg->pUserData = p;
  126702. }
  126703. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
  126704. if( pArg && pArg->nRef==0 ){
  126705. assert( rc!=SQLITE_OK );
  126706. xDestroy(p);
  126707. sqlite3DbFree(db, pArg);
  126708. }
  126709. out:
  126710. rc = sqlite3ApiExit(db, rc);
  126711. sqlite3_mutex_leave(db->mutex);
  126712. return rc;
  126713. }
  126714. #ifndef SQLITE_OMIT_UTF16
  126715. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  126716. sqlite3 *db,
  126717. const void *zFunctionName,
  126718. int nArg,
  126719. int eTextRep,
  126720. void *p,
  126721. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  126722. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  126723. void (*xFinal)(sqlite3_context*)
  126724. ){
  126725. int rc;
  126726. char *zFunc8;
  126727. #ifdef SQLITE_ENABLE_API_ARMOR
  126728. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  126729. #endif
  126730. sqlite3_mutex_enter(db->mutex);
  126731. assert( !db->mallocFailed );
  126732. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  126733. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
  126734. sqlite3DbFree(db, zFunc8);
  126735. rc = sqlite3ApiExit(db, rc);
  126736. sqlite3_mutex_leave(db->mutex);
  126737. return rc;
  126738. }
  126739. #endif
  126740. /*
  126741. ** Declare that a function has been overloaded by a virtual table.
  126742. **
  126743. ** If the function already exists as a regular global function, then
  126744. ** this routine is a no-op. If the function does not exist, then create
  126745. ** a new one that always throws a run-time error.
  126746. **
  126747. ** When virtual tables intend to provide an overloaded function, they
  126748. ** should call this routine to make sure the global function exists.
  126749. ** A global function must exist in order for name resolution to work
  126750. ** properly.
  126751. */
  126752. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
  126753. sqlite3 *db,
  126754. const char *zName,
  126755. int nArg
  126756. ){
  126757. int rc = SQLITE_OK;
  126758. #ifdef SQLITE_ENABLE_API_ARMOR
  126759. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  126760. return SQLITE_MISUSE_BKPT;
  126761. }
  126762. #endif
  126763. sqlite3_mutex_enter(db->mutex);
  126764. if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
  126765. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  126766. 0, sqlite3InvalidFunction, 0, 0, 0);
  126767. }
  126768. rc = sqlite3ApiExit(db, rc);
  126769. sqlite3_mutex_leave(db->mutex);
  126770. return rc;
  126771. }
  126772. #ifndef SQLITE_OMIT_TRACE
  126773. /*
  126774. ** Register a trace function. The pArg from the previously registered trace
  126775. ** is returned.
  126776. **
  126777. ** A NULL trace function means that no tracing is executes. A non-NULL
  126778. ** trace is a pointer to a function that is invoked at the start of each
  126779. ** SQL statement.
  126780. */
  126781. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  126782. void *pOld;
  126783. #ifdef SQLITE_ENABLE_API_ARMOR
  126784. if( !sqlite3SafetyCheckOk(db) ){
  126785. (void)SQLITE_MISUSE_BKPT;
  126786. return 0;
  126787. }
  126788. #endif
  126789. sqlite3_mutex_enter(db->mutex);
  126790. pOld = db->pTraceArg;
  126791. db->xTrace = xTrace;
  126792. db->pTraceArg = pArg;
  126793. sqlite3_mutex_leave(db->mutex);
  126794. return pOld;
  126795. }
  126796. /*
  126797. ** Register a profile function. The pArg from the previously registered
  126798. ** profile function is returned.
  126799. **
  126800. ** A NULL profile function means that no profiling is executes. A non-NULL
  126801. ** profile is a pointer to a function that is invoked at the conclusion of
  126802. ** each SQL statement that is run.
  126803. */
  126804. SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
  126805. sqlite3 *db,
  126806. void (*xProfile)(void*,const char*,sqlite_uint64),
  126807. void *pArg
  126808. ){
  126809. void *pOld;
  126810. #ifdef SQLITE_ENABLE_API_ARMOR
  126811. if( !sqlite3SafetyCheckOk(db) ){
  126812. (void)SQLITE_MISUSE_BKPT;
  126813. return 0;
  126814. }
  126815. #endif
  126816. sqlite3_mutex_enter(db->mutex);
  126817. pOld = db->pProfileArg;
  126818. db->xProfile = xProfile;
  126819. db->pProfileArg = pArg;
  126820. sqlite3_mutex_leave(db->mutex);
  126821. return pOld;
  126822. }
  126823. #endif /* SQLITE_OMIT_TRACE */
  126824. /*
  126825. ** Register a function to be invoked when a transaction commits.
  126826. ** If the invoked function returns non-zero, then the commit becomes a
  126827. ** rollback.
  126828. */
  126829. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
  126830. sqlite3 *db, /* Attach the hook to this database */
  126831. int (*xCallback)(void*), /* Function to invoke on each commit */
  126832. void *pArg /* Argument to the function */
  126833. ){
  126834. void *pOld;
  126835. #ifdef SQLITE_ENABLE_API_ARMOR
  126836. if( !sqlite3SafetyCheckOk(db) ){
  126837. (void)SQLITE_MISUSE_BKPT;
  126838. return 0;
  126839. }
  126840. #endif
  126841. sqlite3_mutex_enter(db->mutex);
  126842. pOld = db->pCommitArg;
  126843. db->xCommitCallback = xCallback;
  126844. db->pCommitArg = pArg;
  126845. sqlite3_mutex_leave(db->mutex);
  126846. return pOld;
  126847. }
  126848. /*
  126849. ** Register a callback to be invoked each time a row is updated,
  126850. ** inserted or deleted using this database connection.
  126851. */
  126852. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  126853. sqlite3 *db, /* Attach the hook to this database */
  126854. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  126855. void *pArg /* Argument to the function */
  126856. ){
  126857. void *pRet;
  126858. #ifdef SQLITE_ENABLE_API_ARMOR
  126859. if( !sqlite3SafetyCheckOk(db) ){
  126860. (void)SQLITE_MISUSE_BKPT;
  126861. return 0;
  126862. }
  126863. #endif
  126864. sqlite3_mutex_enter(db->mutex);
  126865. pRet = db->pUpdateArg;
  126866. db->xUpdateCallback = xCallback;
  126867. db->pUpdateArg = pArg;
  126868. sqlite3_mutex_leave(db->mutex);
  126869. return pRet;
  126870. }
  126871. /*
  126872. ** Register a callback to be invoked each time a transaction is rolled
  126873. ** back by this database connection.
  126874. */
  126875. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
  126876. sqlite3 *db, /* Attach the hook to this database */
  126877. void (*xCallback)(void*), /* Callback function */
  126878. void *pArg /* Argument to the function */
  126879. ){
  126880. void *pRet;
  126881. #ifdef SQLITE_ENABLE_API_ARMOR
  126882. if( !sqlite3SafetyCheckOk(db) ){
  126883. (void)SQLITE_MISUSE_BKPT;
  126884. return 0;
  126885. }
  126886. #endif
  126887. sqlite3_mutex_enter(db->mutex);
  126888. pRet = db->pRollbackArg;
  126889. db->xRollbackCallback = xCallback;
  126890. db->pRollbackArg = pArg;
  126891. sqlite3_mutex_leave(db->mutex);
  126892. return pRet;
  126893. }
  126894. #ifndef SQLITE_OMIT_WAL
  126895. /*
  126896. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  126897. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  126898. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  126899. ** wal_autocheckpoint()).
  126900. */
  126901. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  126902. void *pClientData, /* Argument */
  126903. sqlite3 *db, /* Connection */
  126904. const char *zDb, /* Database */
  126905. int nFrame /* Size of WAL */
  126906. ){
  126907. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  126908. sqlite3BeginBenignMalloc();
  126909. sqlite3_wal_checkpoint(db, zDb);
  126910. sqlite3EndBenignMalloc();
  126911. }
  126912. return SQLITE_OK;
  126913. }
  126914. #endif /* SQLITE_OMIT_WAL */
  126915. /*
  126916. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  126917. ** a database after committing a transaction if there are nFrame or
  126918. ** more frames in the log file. Passing zero or a negative value as the
  126919. ** nFrame parameter disables automatic checkpoints entirely.
  126920. **
  126921. ** The callback registered by this function replaces any existing callback
  126922. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  126923. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  126924. ** configured by this function.
  126925. */
  126926. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  126927. #ifdef SQLITE_OMIT_WAL
  126928. UNUSED_PARAMETER(db);
  126929. UNUSED_PARAMETER(nFrame);
  126930. #else
  126931. #ifdef SQLITE_ENABLE_API_ARMOR
  126932. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126933. #endif
  126934. if( nFrame>0 ){
  126935. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  126936. }else{
  126937. sqlite3_wal_hook(db, 0, 0);
  126938. }
  126939. #endif
  126940. return SQLITE_OK;
  126941. }
  126942. /*
  126943. ** Register a callback to be invoked each time a transaction is written
  126944. ** into the write-ahead-log by this database connection.
  126945. */
  126946. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  126947. sqlite3 *db, /* Attach the hook to this db handle */
  126948. int(*xCallback)(void *, sqlite3*, const char*, int),
  126949. void *pArg /* First argument passed to xCallback() */
  126950. ){
  126951. #ifndef SQLITE_OMIT_WAL
  126952. void *pRet;
  126953. #ifdef SQLITE_ENABLE_API_ARMOR
  126954. if( !sqlite3SafetyCheckOk(db) ){
  126955. (void)SQLITE_MISUSE_BKPT;
  126956. return 0;
  126957. }
  126958. #endif
  126959. sqlite3_mutex_enter(db->mutex);
  126960. pRet = db->pWalArg;
  126961. db->xWalCallback = xCallback;
  126962. db->pWalArg = pArg;
  126963. sqlite3_mutex_leave(db->mutex);
  126964. return pRet;
  126965. #else
  126966. return 0;
  126967. #endif
  126968. }
  126969. /*
  126970. ** Checkpoint database zDb.
  126971. */
  126972. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  126973. sqlite3 *db, /* Database handle */
  126974. const char *zDb, /* Name of attached database (or NULL) */
  126975. int eMode, /* SQLITE_CHECKPOINT_* value */
  126976. int *pnLog, /* OUT: Size of WAL log in frames */
  126977. int *pnCkpt /* OUT: Total number of frames checkpointed */
  126978. ){
  126979. #ifdef SQLITE_OMIT_WAL
  126980. return SQLITE_OK;
  126981. #else
  126982. int rc; /* Return code */
  126983. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  126984. #ifdef SQLITE_ENABLE_API_ARMOR
  126985. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126986. #endif
  126987. /* Initialize the output variables to -1 in case an error occurs. */
  126988. if( pnLog ) *pnLog = -1;
  126989. if( pnCkpt ) *pnCkpt = -1;
  126990. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  126991. assert( SQLITE_CHECKPOINT_FULL==1 );
  126992. assert( SQLITE_CHECKPOINT_RESTART==2 );
  126993. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  126994. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  126995. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  126996. ** mode: */
  126997. return SQLITE_MISUSE;
  126998. }
  126999. sqlite3_mutex_enter(db->mutex);
  127000. if( zDb && zDb[0] ){
  127001. iDb = sqlite3FindDbName(db, zDb);
  127002. }
  127003. if( iDb<0 ){
  127004. rc = SQLITE_ERROR;
  127005. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  127006. }else{
  127007. db->busyHandler.nBusy = 0;
  127008. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  127009. sqlite3Error(db, rc);
  127010. }
  127011. rc = sqlite3ApiExit(db, rc);
  127012. sqlite3_mutex_leave(db->mutex);
  127013. return rc;
  127014. #endif
  127015. }
  127016. /*
  127017. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  127018. ** to contains a zero-length string, all attached databases are
  127019. ** checkpointed.
  127020. */
  127021. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  127022. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  127023. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  127024. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  127025. }
  127026. #ifndef SQLITE_OMIT_WAL
  127027. /*
  127028. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  127029. ** not currently open in WAL mode.
  127030. **
  127031. ** If a transaction is open on the database being checkpointed, this
  127032. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  127033. ** an error occurs while running the checkpoint, an SQLite error code is
  127034. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  127035. **
  127036. ** The mutex on database handle db should be held by the caller. The mutex
  127037. ** associated with the specific b-tree being checkpointed is taken by
  127038. ** this function while the checkpoint is running.
  127039. **
  127040. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  127041. ** checkpointed. If an error is encountered it is returned immediately -
  127042. ** no attempt is made to checkpoint any remaining databases.
  127043. **
  127044. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  127045. */
  127046. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  127047. int rc = SQLITE_OK; /* Return code */
  127048. int i; /* Used to iterate through attached dbs */
  127049. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  127050. assert( sqlite3_mutex_held(db->mutex) );
  127051. assert( !pnLog || *pnLog==-1 );
  127052. assert( !pnCkpt || *pnCkpt==-1 );
  127053. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  127054. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  127055. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  127056. pnLog = 0;
  127057. pnCkpt = 0;
  127058. if( rc==SQLITE_BUSY ){
  127059. bBusy = 1;
  127060. rc = SQLITE_OK;
  127061. }
  127062. }
  127063. }
  127064. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  127065. }
  127066. #endif /* SQLITE_OMIT_WAL */
  127067. /*
  127068. ** This function returns true if main-memory should be used instead of
  127069. ** a temporary file for transient pager files and statement journals.
  127070. ** The value returned depends on the value of db->temp_store (runtime
  127071. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  127072. ** following table describes the relationship between these two values
  127073. ** and this functions return value.
  127074. **
  127075. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  127076. ** ----------------- -------------- ------------------------------
  127077. ** 0 any file (return 0)
  127078. ** 1 1 file (return 0)
  127079. ** 1 2 memory (return 1)
  127080. ** 1 0 file (return 0)
  127081. ** 2 1 file (return 0)
  127082. ** 2 2 memory (return 1)
  127083. ** 2 0 memory (return 1)
  127084. ** 3 any memory (return 1)
  127085. */
  127086. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  127087. #if SQLITE_TEMP_STORE==1
  127088. return ( db->temp_store==2 );
  127089. #endif
  127090. #if SQLITE_TEMP_STORE==2
  127091. return ( db->temp_store!=1 );
  127092. #endif
  127093. #if SQLITE_TEMP_STORE==3
  127094. UNUSED_PARAMETER(db);
  127095. return 1;
  127096. #endif
  127097. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  127098. UNUSED_PARAMETER(db);
  127099. return 0;
  127100. #endif
  127101. }
  127102. /*
  127103. ** Return UTF-8 encoded English language explanation of the most recent
  127104. ** error.
  127105. */
  127106. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
  127107. const char *z;
  127108. if( !db ){
  127109. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  127110. }
  127111. if( !sqlite3SafetyCheckSickOrOk(db) ){
  127112. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  127113. }
  127114. sqlite3_mutex_enter(db->mutex);
  127115. if( db->mallocFailed ){
  127116. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  127117. }else{
  127118. testcase( db->pErr==0 );
  127119. z = (char*)sqlite3_value_text(db->pErr);
  127120. assert( !db->mallocFailed );
  127121. if( z==0 ){
  127122. z = sqlite3ErrStr(db->errCode);
  127123. }
  127124. }
  127125. sqlite3_mutex_leave(db->mutex);
  127126. return z;
  127127. }
  127128. #ifndef SQLITE_OMIT_UTF16
  127129. /*
  127130. ** Return UTF-16 encoded English language explanation of the most recent
  127131. ** error.
  127132. */
  127133. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
  127134. static const u16 outOfMem[] = {
  127135. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  127136. };
  127137. static const u16 misuse[] = {
  127138. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  127139. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  127140. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  127141. 'o', 'u', 't', ' ',
  127142. 'o', 'f', ' ',
  127143. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  127144. };
  127145. const void *z;
  127146. if( !db ){
  127147. return (void *)outOfMem;
  127148. }
  127149. if( !sqlite3SafetyCheckSickOrOk(db) ){
  127150. return (void *)misuse;
  127151. }
  127152. sqlite3_mutex_enter(db->mutex);
  127153. if( db->mallocFailed ){
  127154. z = (void *)outOfMem;
  127155. }else{
  127156. z = sqlite3_value_text16(db->pErr);
  127157. if( z==0 ){
  127158. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  127159. z = sqlite3_value_text16(db->pErr);
  127160. }
  127161. /* A malloc() may have failed within the call to sqlite3_value_text16()
  127162. ** above. If this is the case, then the db->mallocFailed flag needs to
  127163. ** be cleared before returning. Do this directly, instead of via
  127164. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  127165. */
  127166. sqlite3OomClear(db);
  127167. }
  127168. sqlite3_mutex_leave(db->mutex);
  127169. return z;
  127170. }
  127171. #endif /* SQLITE_OMIT_UTF16 */
  127172. /*
  127173. ** Return the most recent error code generated by an SQLite routine. If NULL is
  127174. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  127175. */
  127176. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
  127177. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  127178. return SQLITE_MISUSE_BKPT;
  127179. }
  127180. if( !db || db->mallocFailed ){
  127181. return SQLITE_NOMEM_BKPT;
  127182. }
  127183. return db->errCode & db->errMask;
  127184. }
  127185. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
  127186. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  127187. return SQLITE_MISUSE_BKPT;
  127188. }
  127189. if( !db || db->mallocFailed ){
  127190. return SQLITE_NOMEM_BKPT;
  127191. }
  127192. return db->errCode;
  127193. }
  127194. SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3 *db){
  127195. return db ? db->iSysErrno : 0;
  127196. }
  127197. /*
  127198. ** Return a string that describes the kind of error specified in the
  127199. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  127200. ** function.
  127201. */
  127202. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
  127203. return sqlite3ErrStr(rc);
  127204. }
  127205. /*
  127206. ** Create a new collating function for database "db". The name is zName
  127207. ** and the encoding is enc.
  127208. */
  127209. static int createCollation(
  127210. sqlite3* db,
  127211. const char *zName,
  127212. u8 enc,
  127213. void* pCtx,
  127214. int(*xCompare)(void*,int,const void*,int,const void*),
  127215. void(*xDel)(void*)
  127216. ){
  127217. CollSeq *pColl;
  127218. int enc2;
  127219. assert( sqlite3_mutex_held(db->mutex) );
  127220. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  127221. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  127222. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  127223. */
  127224. enc2 = enc;
  127225. testcase( enc2==SQLITE_UTF16 );
  127226. testcase( enc2==SQLITE_UTF16_ALIGNED );
  127227. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  127228. enc2 = SQLITE_UTF16NATIVE;
  127229. }
  127230. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  127231. return SQLITE_MISUSE_BKPT;
  127232. }
  127233. /* Check if this call is removing or replacing an existing collation
  127234. ** sequence. If so, and there are active VMs, return busy. If there
  127235. ** are no active VMs, invalidate any pre-compiled statements.
  127236. */
  127237. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  127238. if( pColl && pColl->xCmp ){
  127239. if( db->nVdbeActive ){
  127240. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  127241. "unable to delete/modify collation sequence due to active statements");
  127242. return SQLITE_BUSY;
  127243. }
  127244. sqlite3ExpirePreparedStatements(db);
  127245. /* If collation sequence pColl was created directly by a call to
  127246. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  127247. ** then any copies made by synthCollSeq() need to be invalidated.
  127248. ** Also, collation destructor - CollSeq.xDel() - function may need
  127249. ** to be called.
  127250. */
  127251. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  127252. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  127253. int j;
  127254. for(j=0; j<3; j++){
  127255. CollSeq *p = &aColl[j];
  127256. if( p->enc==pColl->enc ){
  127257. if( p->xDel ){
  127258. p->xDel(p->pUser);
  127259. }
  127260. p->xCmp = 0;
  127261. }
  127262. }
  127263. }
  127264. }
  127265. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  127266. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  127267. pColl->xCmp = xCompare;
  127268. pColl->pUser = pCtx;
  127269. pColl->xDel = xDel;
  127270. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  127271. sqlite3Error(db, SQLITE_OK);
  127272. return SQLITE_OK;
  127273. }
  127274. /*
  127275. ** This array defines hard upper bounds on limit values. The
  127276. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  127277. ** #defines in sqlite3.h.
  127278. */
  127279. static const int aHardLimit[] = {
  127280. SQLITE_MAX_LENGTH,
  127281. SQLITE_MAX_SQL_LENGTH,
  127282. SQLITE_MAX_COLUMN,
  127283. SQLITE_MAX_EXPR_DEPTH,
  127284. SQLITE_MAX_COMPOUND_SELECT,
  127285. SQLITE_MAX_VDBE_OP,
  127286. SQLITE_MAX_FUNCTION_ARG,
  127287. SQLITE_MAX_ATTACHED,
  127288. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  127289. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  127290. SQLITE_MAX_TRIGGER_DEPTH,
  127291. SQLITE_MAX_WORKER_THREADS,
  127292. };
  127293. /*
  127294. ** Make sure the hard limits are set to reasonable values
  127295. */
  127296. #if SQLITE_MAX_LENGTH<100
  127297. # error SQLITE_MAX_LENGTH must be at least 100
  127298. #endif
  127299. #if SQLITE_MAX_SQL_LENGTH<100
  127300. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  127301. #endif
  127302. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  127303. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  127304. #endif
  127305. #if SQLITE_MAX_COMPOUND_SELECT<2
  127306. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  127307. #endif
  127308. #if SQLITE_MAX_VDBE_OP<40
  127309. # error SQLITE_MAX_VDBE_OP must be at least 40
  127310. #endif
  127311. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  127312. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  127313. #endif
  127314. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  127315. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  127316. #endif
  127317. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  127318. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  127319. #endif
  127320. #if SQLITE_MAX_COLUMN>32767
  127321. # error SQLITE_MAX_COLUMN must not exceed 32767
  127322. #endif
  127323. #if SQLITE_MAX_TRIGGER_DEPTH<1
  127324. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  127325. #endif
  127326. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  127327. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  127328. #endif
  127329. /*
  127330. ** Change the value of a limit. Report the old value.
  127331. ** If an invalid limit index is supplied, report -1.
  127332. ** Make no changes but still report the old value if the
  127333. ** new limit is negative.
  127334. **
  127335. ** A new lower limit does not shrink existing constructs.
  127336. ** It merely prevents new constructs that exceed the limit
  127337. ** from forming.
  127338. */
  127339. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  127340. int oldLimit;
  127341. #ifdef SQLITE_ENABLE_API_ARMOR
  127342. if( !sqlite3SafetyCheckOk(db) ){
  127343. (void)SQLITE_MISUSE_BKPT;
  127344. return -1;
  127345. }
  127346. #endif
  127347. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  127348. ** there is a hard upper bound set at compile-time by a C preprocessor
  127349. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  127350. ** "_MAX_".)
  127351. */
  127352. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  127353. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  127354. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  127355. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  127356. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  127357. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  127358. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  127359. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  127360. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  127361. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  127362. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  127363. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  127364. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  127365. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  127366. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  127367. return -1;
  127368. }
  127369. oldLimit = db->aLimit[limitId];
  127370. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  127371. if( newLimit>aHardLimit[limitId] ){
  127372. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  127373. }
  127374. db->aLimit[limitId] = newLimit;
  127375. }
  127376. return oldLimit; /* IMP: R-53341-35419 */
  127377. }
  127378. /*
  127379. ** This function is used to parse both URIs and non-URI filenames passed by the
  127380. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  127381. ** URIs specified as part of ATTACH statements.
  127382. **
  127383. ** The first argument to this function is the name of the VFS to use (or
  127384. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  127385. ** query parameter. The second argument contains the URI (or non-URI filename)
  127386. ** itself. When this function is called the *pFlags variable should contain
  127387. ** the default flags to open the database handle with. The value stored in
  127388. ** *pFlags may be updated before returning if the URI filename contains
  127389. ** "cache=xxx" or "mode=xxx" query parameters.
  127390. **
  127391. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  127392. ** the VFS that should be used to open the database file. *pzFile is set to
  127393. ** point to a buffer containing the name of the file to open. It is the
  127394. ** responsibility of the caller to eventually call sqlite3_free() to release
  127395. ** this buffer.
  127396. **
  127397. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  127398. ** may be set to point to a buffer containing an English language error
  127399. ** message. It is the responsibility of the caller to eventually release
  127400. ** this buffer by calling sqlite3_free().
  127401. */
  127402. SQLITE_PRIVATE int sqlite3ParseUri(
  127403. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  127404. const char *zUri, /* Nul-terminated URI to parse */
  127405. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  127406. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  127407. char **pzFile, /* OUT: Filename component of URI */
  127408. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  127409. ){
  127410. int rc = SQLITE_OK;
  127411. unsigned int flags = *pFlags;
  127412. const char *zVfs = zDefaultVfs;
  127413. char *zFile;
  127414. char c;
  127415. int nUri = sqlite3Strlen30(zUri);
  127416. assert( *pzErrMsg==0 );
  127417. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  127418. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  127419. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  127420. ){
  127421. char *zOpt;
  127422. int eState; /* Parser state when parsing URI */
  127423. int iIn; /* Input character index */
  127424. int iOut = 0; /* Output character index */
  127425. u64 nByte = nUri+2; /* Bytes of space to allocate */
  127426. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  127427. ** method that there may be extra parameters following the file-name. */
  127428. flags |= SQLITE_OPEN_URI;
  127429. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  127430. zFile = sqlite3_malloc64(nByte);
  127431. if( !zFile ) return SQLITE_NOMEM_BKPT;
  127432. iIn = 5;
  127433. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  127434. if( strncmp(zUri+5, "///", 3)==0 ){
  127435. iIn = 7;
  127436. /* The following condition causes URIs with five leading / characters
  127437. ** like file://///host/path to be converted into UNCs like //host/path.
  127438. ** The correct URI for that UNC has only two or four leading / characters
  127439. ** file://host/path or file:////host/path. But 5 leading slashes is a
  127440. ** common error, we are told, so we handle it as a special case. */
  127441. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  127442. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  127443. iIn = 16;
  127444. }
  127445. #else
  127446. /* Discard the scheme and authority segments of the URI. */
  127447. if( zUri[5]=='/' && zUri[6]=='/' ){
  127448. iIn = 7;
  127449. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  127450. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  127451. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  127452. iIn-7, &zUri[7]);
  127453. rc = SQLITE_ERROR;
  127454. goto parse_uri_out;
  127455. }
  127456. }
  127457. #endif
  127458. /* Copy the filename and any query parameters into the zFile buffer.
  127459. ** Decode %HH escape codes along the way.
  127460. **
  127461. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  127462. ** on the parsing context. As follows:
  127463. **
  127464. ** 0: Parsing file-name.
  127465. ** 1: Parsing name section of a name=value query parameter.
  127466. ** 2: Parsing value section of a name=value query parameter.
  127467. */
  127468. eState = 0;
  127469. while( (c = zUri[iIn])!=0 && c!='#' ){
  127470. iIn++;
  127471. if( c=='%'
  127472. && sqlite3Isxdigit(zUri[iIn])
  127473. && sqlite3Isxdigit(zUri[iIn+1])
  127474. ){
  127475. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  127476. octet += sqlite3HexToInt(zUri[iIn++]);
  127477. assert( octet>=0 && octet<256 );
  127478. if( octet==0 ){
  127479. /* This branch is taken when "%00" appears within the URI. In this
  127480. ** case we ignore all text in the remainder of the path, name or
  127481. ** value currently being parsed. So ignore the current character
  127482. ** and skip to the next "?", "=" or "&", as appropriate. */
  127483. while( (c = zUri[iIn])!=0 && c!='#'
  127484. && (eState!=0 || c!='?')
  127485. && (eState!=1 || (c!='=' && c!='&'))
  127486. && (eState!=2 || c!='&')
  127487. ){
  127488. iIn++;
  127489. }
  127490. continue;
  127491. }
  127492. c = octet;
  127493. }else if( eState==1 && (c=='&' || c=='=') ){
  127494. if( zFile[iOut-1]==0 ){
  127495. /* An empty option name. Ignore this option altogether. */
  127496. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  127497. continue;
  127498. }
  127499. if( c=='&' ){
  127500. zFile[iOut++] = '\0';
  127501. }else{
  127502. eState = 2;
  127503. }
  127504. c = 0;
  127505. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  127506. c = 0;
  127507. eState = 1;
  127508. }
  127509. zFile[iOut++] = c;
  127510. }
  127511. if( eState==1 ) zFile[iOut++] = '\0';
  127512. zFile[iOut++] = '\0';
  127513. zFile[iOut++] = '\0';
  127514. /* Check if there were any options specified that should be interpreted
  127515. ** here. Options that are interpreted here include "vfs" and those that
  127516. ** correspond to flags that may be passed to the sqlite3_open_v2()
  127517. ** method. */
  127518. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  127519. while( zOpt[0] ){
  127520. int nOpt = sqlite3Strlen30(zOpt);
  127521. char *zVal = &zOpt[nOpt+1];
  127522. int nVal = sqlite3Strlen30(zVal);
  127523. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  127524. zVfs = zVal;
  127525. }else{
  127526. struct OpenMode {
  127527. const char *z;
  127528. int mode;
  127529. } *aMode = 0;
  127530. char *zModeType = 0;
  127531. int mask = 0;
  127532. int limit = 0;
  127533. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  127534. static struct OpenMode aCacheMode[] = {
  127535. { "shared", SQLITE_OPEN_SHAREDCACHE },
  127536. { "private", SQLITE_OPEN_PRIVATECACHE },
  127537. { 0, 0 }
  127538. };
  127539. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  127540. aMode = aCacheMode;
  127541. limit = mask;
  127542. zModeType = "cache";
  127543. }
  127544. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  127545. static struct OpenMode aOpenMode[] = {
  127546. { "ro", SQLITE_OPEN_READONLY },
  127547. { "rw", SQLITE_OPEN_READWRITE },
  127548. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  127549. { "memory", SQLITE_OPEN_MEMORY },
  127550. { 0, 0 }
  127551. };
  127552. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  127553. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  127554. aMode = aOpenMode;
  127555. limit = mask & flags;
  127556. zModeType = "access";
  127557. }
  127558. if( aMode ){
  127559. int i;
  127560. int mode = 0;
  127561. for(i=0; aMode[i].z; i++){
  127562. const char *z = aMode[i].z;
  127563. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  127564. mode = aMode[i].mode;
  127565. break;
  127566. }
  127567. }
  127568. if( mode==0 ){
  127569. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  127570. rc = SQLITE_ERROR;
  127571. goto parse_uri_out;
  127572. }
  127573. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  127574. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  127575. zModeType, zVal);
  127576. rc = SQLITE_PERM;
  127577. goto parse_uri_out;
  127578. }
  127579. flags = (flags & ~mask) | mode;
  127580. }
  127581. }
  127582. zOpt = &zVal[nVal+1];
  127583. }
  127584. }else{
  127585. zFile = sqlite3_malloc64(nUri+2);
  127586. if( !zFile ) return SQLITE_NOMEM_BKPT;
  127587. memcpy(zFile, zUri, nUri);
  127588. zFile[nUri] = '\0';
  127589. zFile[nUri+1] = '\0';
  127590. flags &= ~SQLITE_OPEN_URI;
  127591. }
  127592. *ppVfs = sqlite3_vfs_find(zVfs);
  127593. if( *ppVfs==0 ){
  127594. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  127595. rc = SQLITE_ERROR;
  127596. }
  127597. parse_uri_out:
  127598. if( rc!=SQLITE_OK ){
  127599. sqlite3_free(zFile);
  127600. zFile = 0;
  127601. }
  127602. *pFlags = flags;
  127603. *pzFile = zFile;
  127604. return rc;
  127605. }
  127606. /*
  127607. ** This routine does the work of opening a database on behalf of
  127608. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  127609. ** is UTF-8 encoded.
  127610. */
  127611. static int openDatabase(
  127612. const char *zFilename, /* Database filename UTF-8 encoded */
  127613. sqlite3 **ppDb, /* OUT: Returned database handle */
  127614. unsigned int flags, /* Operational flags */
  127615. const char *zVfs /* Name of the VFS to use */
  127616. ){
  127617. sqlite3 *db; /* Store allocated handle here */
  127618. int rc; /* Return code */
  127619. int isThreadsafe; /* True for threadsafe connections */
  127620. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  127621. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  127622. #ifdef SQLITE_ENABLE_API_ARMOR
  127623. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  127624. #endif
  127625. *ppDb = 0;
  127626. #ifndef SQLITE_OMIT_AUTOINIT
  127627. rc = sqlite3_initialize();
  127628. if( rc ) return rc;
  127629. #endif
  127630. /* Only allow sensible combinations of bits in the flags argument.
  127631. ** Throw an error if any non-sense combination is used. If we
  127632. ** do not block illegal combinations here, it could trigger
  127633. ** assert() statements in deeper layers. Sensible combinations
  127634. ** are:
  127635. **
  127636. ** 1: SQLITE_OPEN_READONLY
  127637. ** 2: SQLITE_OPEN_READWRITE
  127638. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  127639. */
  127640. assert( SQLITE_OPEN_READONLY == 0x01 );
  127641. assert( SQLITE_OPEN_READWRITE == 0x02 );
  127642. assert( SQLITE_OPEN_CREATE == 0x04 );
  127643. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  127644. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  127645. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  127646. if( ((1<<(flags&7)) & 0x46)==0 ){
  127647. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  127648. }
  127649. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  127650. isThreadsafe = 0;
  127651. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  127652. isThreadsafe = 0;
  127653. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  127654. isThreadsafe = 1;
  127655. }else{
  127656. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  127657. }
  127658. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  127659. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  127660. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  127661. flags |= SQLITE_OPEN_SHAREDCACHE;
  127662. }
  127663. /* Remove harmful bits from the flags parameter
  127664. **
  127665. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  127666. ** dealt with in the previous code block. Besides these, the only
  127667. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  127668. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  127669. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  127670. ** off all other flags.
  127671. */
  127672. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  127673. SQLITE_OPEN_EXCLUSIVE |
  127674. SQLITE_OPEN_MAIN_DB |
  127675. SQLITE_OPEN_TEMP_DB |
  127676. SQLITE_OPEN_TRANSIENT_DB |
  127677. SQLITE_OPEN_MAIN_JOURNAL |
  127678. SQLITE_OPEN_TEMP_JOURNAL |
  127679. SQLITE_OPEN_SUBJOURNAL |
  127680. SQLITE_OPEN_MASTER_JOURNAL |
  127681. SQLITE_OPEN_NOMUTEX |
  127682. SQLITE_OPEN_FULLMUTEX |
  127683. SQLITE_OPEN_WAL
  127684. );
  127685. /* Allocate the sqlite data structure */
  127686. db = sqlite3MallocZero( sizeof(sqlite3) );
  127687. if( db==0 ) goto opendb_out;
  127688. if( isThreadsafe ){
  127689. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  127690. if( db->mutex==0 ){
  127691. sqlite3_free(db);
  127692. db = 0;
  127693. goto opendb_out;
  127694. }
  127695. }
  127696. sqlite3_mutex_enter(db->mutex);
  127697. db->errMask = 0xff;
  127698. db->nDb = 2;
  127699. db->magic = SQLITE_MAGIC_BUSY;
  127700. db->aDb = db->aDbStatic;
  127701. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  127702. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  127703. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  127704. db->autoCommit = 1;
  127705. db->nextAutovac = -1;
  127706. db->szMmap = sqlite3GlobalConfig.szMmap;
  127707. db->nextPagesize = 0;
  127708. db->nMaxSorterMmap = 0x7FFFFFFF;
  127709. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  127710. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  127711. | SQLITE_AutoIndex
  127712. #endif
  127713. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  127714. | SQLITE_CkptFullFSync
  127715. #endif
  127716. #if SQLITE_DEFAULT_FILE_FORMAT<4
  127717. | SQLITE_LegacyFileFmt
  127718. #endif
  127719. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  127720. | SQLITE_LoadExtension
  127721. #endif
  127722. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  127723. | SQLITE_RecTriggers
  127724. #endif
  127725. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  127726. | SQLITE_ForeignKeys
  127727. #endif
  127728. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  127729. | SQLITE_ReverseOrder
  127730. #endif
  127731. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  127732. | SQLITE_CellSizeCk
  127733. #endif
  127734. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  127735. | SQLITE_Fts3Tokenizer
  127736. #endif
  127737. ;
  127738. sqlite3HashInit(&db->aCollSeq);
  127739. #ifndef SQLITE_OMIT_VIRTUALTABLE
  127740. sqlite3HashInit(&db->aModule);
  127741. #endif
  127742. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  127743. ** and UTF-16, so add a version for each to avoid any unnecessary
  127744. ** conversions. The only error that can occur here is a malloc() failure.
  127745. **
  127746. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  127747. ** functions:
  127748. */
  127749. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  127750. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  127751. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  127752. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  127753. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  127754. if( db->mallocFailed ){
  127755. goto opendb_out;
  127756. }
  127757. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  127758. ** strings is BINARY.
  127759. */
  127760. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  127761. assert( db->pDfltColl!=0 );
  127762. /* Parse the filename/URI argument. */
  127763. db->openFlags = flags;
  127764. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  127765. if( rc!=SQLITE_OK ){
  127766. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  127767. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  127768. sqlite3_free(zErrMsg);
  127769. goto opendb_out;
  127770. }
  127771. /* Open the backend database driver */
  127772. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  127773. flags | SQLITE_OPEN_MAIN_DB);
  127774. if( rc!=SQLITE_OK ){
  127775. if( rc==SQLITE_IOERR_NOMEM ){
  127776. rc = SQLITE_NOMEM_BKPT;
  127777. }
  127778. sqlite3Error(db, rc);
  127779. goto opendb_out;
  127780. }
  127781. sqlite3BtreeEnter(db->aDb[0].pBt);
  127782. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  127783. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  127784. sqlite3BtreeLeave(db->aDb[0].pBt);
  127785. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  127786. /* The default safety_level for the main database is FULL; for the temp
  127787. ** database it is OFF. This matches the pager layer defaults.
  127788. */
  127789. db->aDb[0].zName = "main";
  127790. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  127791. db->aDb[1].zName = "temp";
  127792. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  127793. db->magic = SQLITE_MAGIC_OPEN;
  127794. if( db->mallocFailed ){
  127795. goto opendb_out;
  127796. }
  127797. /* Register all built-in functions, but do not attempt to read the
  127798. ** database schema yet. This is delayed until the first time the database
  127799. ** is accessed.
  127800. */
  127801. sqlite3Error(db, SQLITE_OK);
  127802. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  127803. /* Load automatic extensions - extensions that have been registered
  127804. ** using the sqlite3_automatic_extension() API.
  127805. */
  127806. rc = sqlite3_errcode(db);
  127807. if( rc==SQLITE_OK ){
  127808. sqlite3AutoLoadExtensions(db);
  127809. rc = sqlite3_errcode(db);
  127810. if( rc!=SQLITE_OK ){
  127811. goto opendb_out;
  127812. }
  127813. }
  127814. #ifdef SQLITE_ENABLE_FTS1
  127815. if( !db->mallocFailed ){
  127816. extern int sqlite3Fts1Init(sqlite3*);
  127817. rc = sqlite3Fts1Init(db);
  127818. }
  127819. #endif
  127820. #ifdef SQLITE_ENABLE_FTS2
  127821. if( !db->mallocFailed && rc==SQLITE_OK ){
  127822. extern int sqlite3Fts2Init(sqlite3*);
  127823. rc = sqlite3Fts2Init(db);
  127824. }
  127825. #endif
  127826. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  127827. if( !db->mallocFailed && rc==SQLITE_OK ){
  127828. rc = sqlite3Fts3Init(db);
  127829. }
  127830. #endif
  127831. #ifdef SQLITE_ENABLE_FTS5
  127832. if( !db->mallocFailed && rc==SQLITE_OK ){
  127833. rc = sqlite3Fts5Init(db);
  127834. }
  127835. #endif
  127836. #ifdef SQLITE_ENABLE_ICU
  127837. if( !db->mallocFailed && rc==SQLITE_OK ){
  127838. rc = sqlite3IcuInit(db);
  127839. }
  127840. #endif
  127841. #ifdef SQLITE_ENABLE_RTREE
  127842. if( !db->mallocFailed && rc==SQLITE_OK){
  127843. rc = sqlite3RtreeInit(db);
  127844. }
  127845. #endif
  127846. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  127847. if( !db->mallocFailed && rc==SQLITE_OK){
  127848. rc = sqlite3DbstatRegister(db);
  127849. }
  127850. #endif
  127851. #ifdef SQLITE_ENABLE_JSON1
  127852. if( !db->mallocFailed && rc==SQLITE_OK){
  127853. rc = sqlite3Json1Init(db);
  127854. }
  127855. #endif
  127856. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  127857. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  127858. ** mode. Doing nothing at all also makes NORMAL the default.
  127859. */
  127860. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  127861. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  127862. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  127863. SQLITE_DEFAULT_LOCKING_MODE);
  127864. #endif
  127865. if( rc ) sqlite3Error(db, rc);
  127866. /* Enable the lookaside-malloc subsystem */
  127867. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  127868. sqlite3GlobalConfig.nLookaside);
  127869. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  127870. opendb_out:
  127871. if( db ){
  127872. assert( db->mutex!=0 || isThreadsafe==0
  127873. || sqlite3GlobalConfig.bFullMutex==0 );
  127874. sqlite3_mutex_leave(db->mutex);
  127875. }
  127876. rc = sqlite3_errcode(db);
  127877. assert( db!=0 || rc==SQLITE_NOMEM );
  127878. if( rc==SQLITE_NOMEM ){
  127879. sqlite3_close(db);
  127880. db = 0;
  127881. }else if( rc!=SQLITE_OK ){
  127882. db->magic = SQLITE_MAGIC_SICK;
  127883. }
  127884. *ppDb = db;
  127885. #ifdef SQLITE_ENABLE_SQLLOG
  127886. if( sqlite3GlobalConfig.xSqllog ){
  127887. /* Opening a db handle. Fourth parameter is passed 0. */
  127888. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  127889. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  127890. }
  127891. #endif
  127892. #if defined(SQLITE_HAS_CODEC)
  127893. if( rc==SQLITE_OK ){
  127894. const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
  127895. if( zHexKey && zHexKey[0] ){
  127896. u8 iByte;
  127897. int i;
  127898. char zKey[40];
  127899. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
  127900. iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
  127901. if( (i&1)!=0 ) zKey[i/2] = iByte;
  127902. }
  127903. sqlite3_key_v2(db, 0, zKey, i/2);
  127904. }
  127905. }
  127906. #endif
  127907. sqlite3_free(zOpen);
  127908. return rc & 0xff;
  127909. }
  127910. /*
  127911. ** Open a new database handle.
  127912. */
  127913. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  127914. const char *zFilename,
  127915. sqlite3 **ppDb
  127916. ){
  127917. return openDatabase(zFilename, ppDb,
  127918. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  127919. }
  127920. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  127921. const char *filename, /* Database filename (UTF-8) */
  127922. sqlite3 **ppDb, /* OUT: SQLite db handle */
  127923. int flags, /* Flags */
  127924. const char *zVfs /* Name of VFS module to use */
  127925. ){
  127926. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  127927. }
  127928. #ifndef SQLITE_OMIT_UTF16
  127929. /*
  127930. ** Open a new database handle.
  127931. */
  127932. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  127933. const void *zFilename,
  127934. sqlite3 **ppDb
  127935. ){
  127936. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  127937. sqlite3_value *pVal;
  127938. int rc;
  127939. #ifdef SQLITE_ENABLE_API_ARMOR
  127940. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  127941. #endif
  127942. *ppDb = 0;
  127943. #ifndef SQLITE_OMIT_AUTOINIT
  127944. rc = sqlite3_initialize();
  127945. if( rc ) return rc;
  127946. #endif
  127947. if( zFilename==0 ) zFilename = "\000\000";
  127948. pVal = sqlite3ValueNew(0);
  127949. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  127950. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  127951. if( zFilename8 ){
  127952. rc = openDatabase(zFilename8, ppDb,
  127953. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  127954. assert( *ppDb || rc==SQLITE_NOMEM );
  127955. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  127956. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  127957. }
  127958. }else{
  127959. rc = SQLITE_NOMEM_BKPT;
  127960. }
  127961. sqlite3ValueFree(pVal);
  127962. return rc & 0xff;
  127963. }
  127964. #endif /* SQLITE_OMIT_UTF16 */
  127965. /*
  127966. ** Register a new collation sequence with the database handle db.
  127967. */
  127968. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  127969. sqlite3* db,
  127970. const char *zName,
  127971. int enc,
  127972. void* pCtx,
  127973. int(*xCompare)(void*,int,const void*,int,const void*)
  127974. ){
  127975. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  127976. }
  127977. /*
  127978. ** Register a new collation sequence with the database handle db.
  127979. */
  127980. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  127981. sqlite3* db,
  127982. const char *zName,
  127983. int enc,
  127984. void* pCtx,
  127985. int(*xCompare)(void*,int,const void*,int,const void*),
  127986. void(*xDel)(void*)
  127987. ){
  127988. int rc;
  127989. #ifdef SQLITE_ENABLE_API_ARMOR
  127990. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  127991. #endif
  127992. sqlite3_mutex_enter(db->mutex);
  127993. assert( !db->mallocFailed );
  127994. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  127995. rc = sqlite3ApiExit(db, rc);
  127996. sqlite3_mutex_leave(db->mutex);
  127997. return rc;
  127998. }
  127999. #ifndef SQLITE_OMIT_UTF16
  128000. /*
  128001. ** Register a new collation sequence with the database handle db.
  128002. */
  128003. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  128004. sqlite3* db,
  128005. const void *zName,
  128006. int enc,
  128007. void* pCtx,
  128008. int(*xCompare)(void*,int,const void*,int,const void*)
  128009. ){
  128010. int rc = SQLITE_OK;
  128011. char *zName8;
  128012. #ifdef SQLITE_ENABLE_API_ARMOR
  128013. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  128014. #endif
  128015. sqlite3_mutex_enter(db->mutex);
  128016. assert( !db->mallocFailed );
  128017. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  128018. if( zName8 ){
  128019. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  128020. sqlite3DbFree(db, zName8);
  128021. }
  128022. rc = sqlite3ApiExit(db, rc);
  128023. sqlite3_mutex_leave(db->mutex);
  128024. return rc;
  128025. }
  128026. #endif /* SQLITE_OMIT_UTF16 */
  128027. /*
  128028. ** Register a collation sequence factory callback with the database handle
  128029. ** db. Replace any previously installed collation sequence factory.
  128030. */
  128031. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  128032. sqlite3 *db,
  128033. void *pCollNeededArg,
  128034. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  128035. ){
  128036. #ifdef SQLITE_ENABLE_API_ARMOR
  128037. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  128038. #endif
  128039. sqlite3_mutex_enter(db->mutex);
  128040. db->xCollNeeded = xCollNeeded;
  128041. db->xCollNeeded16 = 0;
  128042. db->pCollNeededArg = pCollNeededArg;
  128043. sqlite3_mutex_leave(db->mutex);
  128044. return SQLITE_OK;
  128045. }
  128046. #ifndef SQLITE_OMIT_UTF16
  128047. /*
  128048. ** Register a collation sequence factory callback with the database handle
  128049. ** db. Replace any previously installed collation sequence factory.
  128050. */
  128051. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  128052. sqlite3 *db,
  128053. void *pCollNeededArg,
  128054. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  128055. ){
  128056. #ifdef SQLITE_ENABLE_API_ARMOR
  128057. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  128058. #endif
  128059. sqlite3_mutex_enter(db->mutex);
  128060. db->xCollNeeded = 0;
  128061. db->xCollNeeded16 = xCollNeeded16;
  128062. db->pCollNeededArg = pCollNeededArg;
  128063. sqlite3_mutex_leave(db->mutex);
  128064. return SQLITE_OK;
  128065. }
  128066. #endif /* SQLITE_OMIT_UTF16 */
  128067. #ifndef SQLITE_OMIT_DEPRECATED
  128068. /*
  128069. ** This function is now an anachronism. It used to be used to recover from a
  128070. ** malloc() failure, but SQLite now does this automatically.
  128071. */
  128072. SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
  128073. return SQLITE_OK;
  128074. }
  128075. #endif
  128076. /*
  128077. ** Test to see whether or not the database connection is in autocommit
  128078. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  128079. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  128080. ** by the next COMMIT or ROLLBACK.
  128081. */
  128082. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
  128083. #ifdef SQLITE_ENABLE_API_ARMOR
  128084. if( !sqlite3SafetyCheckOk(db) ){
  128085. (void)SQLITE_MISUSE_BKPT;
  128086. return 0;
  128087. }
  128088. #endif
  128089. return db->autoCommit;
  128090. }
  128091. /*
  128092. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  128093. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  128094. ** constants. They serve two purposes:
  128095. **
  128096. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  128097. ** to detect when version error conditions occurs.
  128098. **
  128099. ** 2. Invoke sqlite3_log() to provide the source code location where
  128100. ** a low-level error is first detected.
  128101. */
  128102. static int reportError(int iErr, int lineno, const char *zType){
  128103. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  128104. zType, lineno, 20+sqlite3_sourceid());
  128105. return iErr;
  128106. }
  128107. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  128108. testcase( sqlite3GlobalConfig.xLog!=0 );
  128109. return reportError(SQLITE_CORRUPT, lineno, "database corruption");
  128110. }
  128111. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  128112. testcase( sqlite3GlobalConfig.xLog!=0 );
  128113. return reportError(SQLITE_MISUSE, lineno, "misuse");
  128114. }
  128115. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  128116. testcase( sqlite3GlobalConfig.xLog!=0 );
  128117. return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  128118. }
  128119. #ifdef SQLITE_DEBUG
  128120. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  128121. testcase( sqlite3GlobalConfig.xLog!=0 );
  128122. return reportError(SQLITE_NOMEM, lineno, "OOM");
  128123. }
  128124. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  128125. testcase( sqlite3GlobalConfig.xLog!=0 );
  128126. return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  128127. }
  128128. #endif
  128129. #ifndef SQLITE_OMIT_DEPRECATED
  128130. /*
  128131. ** This is a convenience routine that makes sure that all thread-specific
  128132. ** data for this thread has been deallocated.
  128133. **
  128134. ** SQLite no longer uses thread-specific data so this routine is now a
  128135. ** no-op. It is retained for historical compatibility.
  128136. */
  128137. SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
  128138. }
  128139. #endif
  128140. /*
  128141. ** Return meta information about a specific column of a database table.
  128142. ** See comment in sqlite3.h (sqlite.h.in) for details.
  128143. */
  128144. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  128145. sqlite3 *db, /* Connection handle */
  128146. const char *zDbName, /* Database name or NULL */
  128147. const char *zTableName, /* Table name */
  128148. const char *zColumnName, /* Column name */
  128149. char const **pzDataType, /* OUTPUT: Declared data type */
  128150. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  128151. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  128152. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  128153. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  128154. ){
  128155. int rc;
  128156. char *zErrMsg = 0;
  128157. Table *pTab = 0;
  128158. Column *pCol = 0;
  128159. int iCol = 0;
  128160. char const *zDataType = 0;
  128161. char const *zCollSeq = 0;
  128162. int notnull = 0;
  128163. int primarykey = 0;
  128164. int autoinc = 0;
  128165. #ifdef SQLITE_ENABLE_API_ARMOR
  128166. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  128167. return SQLITE_MISUSE_BKPT;
  128168. }
  128169. #endif
  128170. /* Ensure the database schema has been loaded */
  128171. sqlite3_mutex_enter(db->mutex);
  128172. sqlite3BtreeEnterAll(db);
  128173. rc = sqlite3Init(db, &zErrMsg);
  128174. if( SQLITE_OK!=rc ){
  128175. goto error_out;
  128176. }
  128177. /* Locate the table in question */
  128178. pTab = sqlite3FindTable(db, zTableName, zDbName);
  128179. if( !pTab || pTab->pSelect ){
  128180. pTab = 0;
  128181. goto error_out;
  128182. }
  128183. /* Find the column for which info is requested */
  128184. if( zColumnName==0 ){
  128185. /* Query for existance of table only */
  128186. }else{
  128187. for(iCol=0; iCol<pTab->nCol; iCol++){
  128188. pCol = &pTab->aCol[iCol];
  128189. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  128190. break;
  128191. }
  128192. }
  128193. if( iCol==pTab->nCol ){
  128194. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  128195. iCol = pTab->iPKey;
  128196. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  128197. }else{
  128198. pTab = 0;
  128199. goto error_out;
  128200. }
  128201. }
  128202. }
  128203. /* The following block stores the meta information that will be returned
  128204. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  128205. ** and autoinc. At this point there are two possibilities:
  128206. **
  128207. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  128208. ** and there is no explicitly declared IPK column.
  128209. **
  128210. ** 2. The table is not a view and the column name identified an
  128211. ** explicitly declared column. Copy meta information from *pCol.
  128212. */
  128213. if( pCol ){
  128214. zDataType = sqlite3ColumnType(pCol,0);
  128215. zCollSeq = pCol->zColl;
  128216. notnull = pCol->notNull!=0;
  128217. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  128218. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  128219. }else{
  128220. zDataType = "INTEGER";
  128221. primarykey = 1;
  128222. }
  128223. if( !zCollSeq ){
  128224. zCollSeq = sqlite3StrBINARY;
  128225. }
  128226. error_out:
  128227. sqlite3BtreeLeaveAll(db);
  128228. /* Whether the function call succeeded or failed, set the output parameters
  128229. ** to whatever their local counterparts contain. If an error did occur,
  128230. ** this has the effect of zeroing all output parameters.
  128231. */
  128232. if( pzDataType ) *pzDataType = zDataType;
  128233. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  128234. if( pNotNull ) *pNotNull = notnull;
  128235. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  128236. if( pAutoinc ) *pAutoinc = autoinc;
  128237. if( SQLITE_OK==rc && !pTab ){
  128238. sqlite3DbFree(db, zErrMsg);
  128239. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  128240. zColumnName);
  128241. rc = SQLITE_ERROR;
  128242. }
  128243. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  128244. sqlite3DbFree(db, zErrMsg);
  128245. rc = sqlite3ApiExit(db, rc);
  128246. sqlite3_mutex_leave(db->mutex);
  128247. return rc;
  128248. }
  128249. /*
  128250. ** Sleep for a little while. Return the amount of time slept.
  128251. */
  128252. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
  128253. sqlite3_vfs *pVfs;
  128254. int rc;
  128255. pVfs = sqlite3_vfs_find(0);
  128256. if( pVfs==0 ) return 0;
  128257. /* This function works in milliseconds, but the underlying OsSleep()
  128258. ** API uses microseconds. Hence the 1000's.
  128259. */
  128260. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  128261. return rc;
  128262. }
  128263. /*
  128264. ** Enable or disable the extended result codes.
  128265. */
  128266. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  128267. #ifdef SQLITE_ENABLE_API_ARMOR
  128268. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  128269. #endif
  128270. sqlite3_mutex_enter(db->mutex);
  128271. db->errMask = onoff ? 0xffffffff : 0xff;
  128272. sqlite3_mutex_leave(db->mutex);
  128273. return SQLITE_OK;
  128274. }
  128275. /*
  128276. ** Invoke the xFileControl method on a particular database.
  128277. */
  128278. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  128279. int rc = SQLITE_ERROR;
  128280. Btree *pBtree;
  128281. #ifdef SQLITE_ENABLE_API_ARMOR
  128282. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  128283. #endif
  128284. sqlite3_mutex_enter(db->mutex);
  128285. pBtree = sqlite3DbNameToBtree(db, zDbName);
  128286. if( pBtree ){
  128287. Pager *pPager;
  128288. sqlite3_file *fd;
  128289. sqlite3BtreeEnter(pBtree);
  128290. pPager = sqlite3BtreePager(pBtree);
  128291. assert( pPager!=0 );
  128292. fd = sqlite3PagerFile(pPager);
  128293. assert( fd!=0 );
  128294. if( op==SQLITE_FCNTL_FILE_POINTER ){
  128295. *(sqlite3_file**)pArg = fd;
  128296. rc = SQLITE_OK;
  128297. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  128298. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  128299. rc = SQLITE_OK;
  128300. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  128301. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  128302. rc = SQLITE_OK;
  128303. }else if( fd->pMethods ){
  128304. rc = sqlite3OsFileControl(fd, op, pArg);
  128305. }else{
  128306. rc = SQLITE_NOTFOUND;
  128307. }
  128308. sqlite3BtreeLeave(pBtree);
  128309. }
  128310. sqlite3_mutex_leave(db->mutex);
  128311. return rc;
  128312. }
  128313. /*
  128314. ** Interface to the testing logic.
  128315. */
  128316. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
  128317. int rc = 0;
  128318. #ifdef SQLITE_OMIT_BUILTIN_TEST
  128319. UNUSED_PARAMETER(op);
  128320. #else
  128321. va_list ap;
  128322. va_start(ap, op);
  128323. switch( op ){
  128324. /*
  128325. ** Save the current state of the PRNG.
  128326. */
  128327. case SQLITE_TESTCTRL_PRNG_SAVE: {
  128328. sqlite3PrngSaveState();
  128329. break;
  128330. }
  128331. /*
  128332. ** Restore the state of the PRNG to the last state saved using
  128333. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  128334. ** this verb acts like PRNG_RESET.
  128335. */
  128336. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  128337. sqlite3PrngRestoreState();
  128338. break;
  128339. }
  128340. /*
  128341. ** Reset the PRNG back to its uninitialized state. The next call
  128342. ** to sqlite3_randomness() will reseed the PRNG using a single call
  128343. ** to the xRandomness method of the default VFS.
  128344. */
  128345. case SQLITE_TESTCTRL_PRNG_RESET: {
  128346. sqlite3_randomness(0,0);
  128347. break;
  128348. }
  128349. /*
  128350. ** sqlite3_test_control(BITVEC_TEST, size, program)
  128351. **
  128352. ** Run a test against a Bitvec object of size. The program argument
  128353. ** is an array of integers that defines the test. Return -1 on a
  128354. ** memory allocation error, 0 on success, or non-zero for an error.
  128355. ** See the sqlite3BitvecBuiltinTest() for additional information.
  128356. */
  128357. case SQLITE_TESTCTRL_BITVEC_TEST: {
  128358. int sz = va_arg(ap, int);
  128359. int *aProg = va_arg(ap, int*);
  128360. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  128361. break;
  128362. }
  128363. /*
  128364. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  128365. **
  128366. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  128367. ** if xCallback is not NULL.
  128368. **
  128369. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  128370. ** is called immediately after installing the new callback and the return
  128371. ** value from sqlite3FaultSim(0) becomes the return from
  128372. ** sqlite3_test_control().
  128373. */
  128374. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  128375. /* MSVC is picky about pulling func ptrs from va lists.
  128376. ** http://support.microsoft.com/kb/47961
  128377. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  128378. */
  128379. typedef int(*TESTCALLBACKFUNC_t)(int);
  128380. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  128381. rc = sqlite3FaultSim(0);
  128382. break;
  128383. }
  128384. /*
  128385. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  128386. **
  128387. ** Register hooks to call to indicate which malloc() failures
  128388. ** are benign.
  128389. */
  128390. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  128391. typedef void (*void_function)(void);
  128392. void_function xBenignBegin;
  128393. void_function xBenignEnd;
  128394. xBenignBegin = va_arg(ap, void_function);
  128395. xBenignEnd = va_arg(ap, void_function);
  128396. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  128397. break;
  128398. }
  128399. /*
  128400. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  128401. **
  128402. ** Set the PENDING byte to the value in the argument, if X>0.
  128403. ** Make no changes if X==0. Return the value of the pending byte
  128404. ** as it existing before this routine was called.
  128405. **
  128406. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  128407. ** an incompatible database file format. Changing the PENDING byte
  128408. ** while any database connection is open results in undefined and
  128409. ** deleterious behavior.
  128410. */
  128411. case SQLITE_TESTCTRL_PENDING_BYTE: {
  128412. rc = PENDING_BYTE;
  128413. #ifndef SQLITE_OMIT_WSD
  128414. {
  128415. unsigned int newVal = va_arg(ap, unsigned int);
  128416. if( newVal ) sqlite3PendingByte = newVal;
  128417. }
  128418. #endif
  128419. break;
  128420. }
  128421. /*
  128422. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  128423. **
  128424. ** This action provides a run-time test to see whether or not
  128425. ** assert() was enabled at compile-time. If X is true and assert()
  128426. ** is enabled, then the return value is true. If X is true and
  128427. ** assert() is disabled, then the return value is zero. If X is
  128428. ** false and assert() is enabled, then the assertion fires and the
  128429. ** process aborts. If X is false and assert() is disabled, then the
  128430. ** return value is zero.
  128431. */
  128432. case SQLITE_TESTCTRL_ASSERT: {
  128433. volatile int x = 0;
  128434. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  128435. rc = x;
  128436. break;
  128437. }
  128438. /*
  128439. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  128440. **
  128441. ** This action provides a run-time test to see how the ALWAYS and
  128442. ** NEVER macros were defined at compile-time.
  128443. **
  128444. ** The return value is ALWAYS(X).
  128445. **
  128446. ** The recommended test is X==2. If the return value is 2, that means
  128447. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  128448. ** default setting. If the return value is 1, then ALWAYS() is either
  128449. ** hard-coded to true or else it asserts if its argument is false.
  128450. ** The first behavior (hard-coded to true) is the case if
  128451. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  128452. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  128453. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  128454. **
  128455. ** The run-time test procedure might look something like this:
  128456. **
  128457. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  128458. ** // ALWAYS() and NEVER() are no-op pass-through macros
  128459. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  128460. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  128461. ** }else{
  128462. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  128463. ** }
  128464. */
  128465. case SQLITE_TESTCTRL_ALWAYS: {
  128466. int x = va_arg(ap,int);
  128467. rc = ALWAYS(x);
  128468. break;
  128469. }
  128470. /*
  128471. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  128472. **
  128473. ** The integer returned reveals the byte-order of the computer on which
  128474. ** SQLite is running:
  128475. **
  128476. ** 1 big-endian, determined at run-time
  128477. ** 10 little-endian, determined at run-time
  128478. ** 432101 big-endian, determined at compile-time
  128479. ** 123410 little-endian, determined at compile-time
  128480. */
  128481. case SQLITE_TESTCTRL_BYTEORDER: {
  128482. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  128483. break;
  128484. }
  128485. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  128486. **
  128487. ** Set the nReserve size to N for the main database on the database
  128488. ** connection db.
  128489. */
  128490. case SQLITE_TESTCTRL_RESERVE: {
  128491. sqlite3 *db = va_arg(ap, sqlite3*);
  128492. int x = va_arg(ap,int);
  128493. sqlite3_mutex_enter(db->mutex);
  128494. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  128495. sqlite3_mutex_leave(db->mutex);
  128496. break;
  128497. }
  128498. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  128499. **
  128500. ** Enable or disable various optimizations for testing purposes. The
  128501. ** argument N is a bitmask of optimizations to be disabled. For normal
  128502. ** operation N should be 0. The idea is that a test program (like the
  128503. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  128504. ** with various optimizations disabled to verify that the same answer
  128505. ** is obtained in every case.
  128506. */
  128507. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  128508. sqlite3 *db = va_arg(ap, sqlite3*);
  128509. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  128510. break;
  128511. }
  128512. #ifdef SQLITE_N_KEYWORD
  128513. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  128514. **
  128515. ** If zWord is a keyword recognized by the parser, then return the
  128516. ** number of keywords. Or if zWord is not a keyword, return 0.
  128517. **
  128518. ** This test feature is only available in the amalgamation since
  128519. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  128520. ** is built using separate source files.
  128521. */
  128522. case SQLITE_TESTCTRL_ISKEYWORD: {
  128523. const char *zWord = va_arg(ap, const char*);
  128524. int n = sqlite3Strlen30(zWord);
  128525. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  128526. break;
  128527. }
  128528. #endif
  128529. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  128530. **
  128531. ** Pass pFree into sqlite3ScratchFree().
  128532. ** If sz>0 then allocate a scratch buffer into pNew.
  128533. */
  128534. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  128535. void *pFree, **ppNew;
  128536. int sz;
  128537. sz = va_arg(ap, int);
  128538. ppNew = va_arg(ap, void**);
  128539. pFree = va_arg(ap, void*);
  128540. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  128541. sqlite3ScratchFree(pFree);
  128542. break;
  128543. }
  128544. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  128545. **
  128546. ** If parameter onoff is non-zero, configure the wrappers so that all
  128547. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  128548. ** undo this setting.
  128549. */
  128550. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  128551. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  128552. break;
  128553. }
  128554. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  128555. **
  128556. ** Set or clear a flag that indicates that the database file is always well-
  128557. ** formed and never corrupt. This flag is clear by default, indicating that
  128558. ** database files might have arbitrary corruption. Setting the flag during
  128559. ** testing causes certain assert() statements in the code to be activated
  128560. ** that demonstrat invariants on well-formed database files.
  128561. */
  128562. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  128563. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  128564. break;
  128565. }
  128566. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  128567. **
  128568. ** Set the VDBE coverage callback function to xCallback with context
  128569. ** pointer ptr.
  128570. */
  128571. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  128572. #ifdef SQLITE_VDBE_COVERAGE
  128573. typedef void (*branch_callback)(void*,int,u8,u8);
  128574. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  128575. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  128576. #endif
  128577. break;
  128578. }
  128579. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  128580. case SQLITE_TESTCTRL_SORTER_MMAP: {
  128581. sqlite3 *db = va_arg(ap, sqlite3*);
  128582. db->nMaxSorterMmap = va_arg(ap, int);
  128583. break;
  128584. }
  128585. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  128586. **
  128587. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  128588. ** not.
  128589. */
  128590. case SQLITE_TESTCTRL_ISINIT: {
  128591. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  128592. break;
  128593. }
  128594. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  128595. **
  128596. ** This test control is used to create imposter tables. "db" is a pointer
  128597. ** to the database connection. dbName is the database name (ex: "main" or
  128598. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  128599. ** or off. "tnum" is the root page of the b-tree to which the imposter
  128600. ** table should connect.
  128601. **
  128602. ** Enable imposter mode only when the schema has already been parsed. Then
  128603. ** run a single CREATE TABLE statement to construct the imposter table in
  128604. ** the parsed schema. Then turn imposter mode back off again.
  128605. **
  128606. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  128607. ** the schema to be reparsed the next time it is needed. This has the
  128608. ** effect of erasing all imposter tables.
  128609. */
  128610. case SQLITE_TESTCTRL_IMPOSTER: {
  128611. sqlite3 *db = va_arg(ap, sqlite3*);
  128612. sqlite3_mutex_enter(db->mutex);
  128613. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  128614. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  128615. db->init.newTnum = va_arg(ap,int);
  128616. if( db->init.busy==0 && db->init.newTnum>0 ){
  128617. sqlite3ResetAllSchemasOfConnection(db);
  128618. }
  128619. sqlite3_mutex_leave(db->mutex);
  128620. break;
  128621. }
  128622. }
  128623. va_end(ap);
  128624. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  128625. return rc;
  128626. }
  128627. /*
  128628. ** This is a utility routine, useful to VFS implementations, that checks
  128629. ** to see if a database file was a URI that contained a specific query
  128630. ** parameter, and if so obtains the value of the query parameter.
  128631. **
  128632. ** The zFilename argument is the filename pointer passed into the xOpen()
  128633. ** method of a VFS implementation. The zParam argument is the name of the
  128634. ** query parameter we seek. This routine returns the value of the zParam
  128635. ** parameter if it exists. If the parameter does not exist, this routine
  128636. ** returns a NULL pointer.
  128637. */
  128638. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  128639. if( zFilename==0 || zParam==0 ) return 0;
  128640. zFilename += sqlite3Strlen30(zFilename) + 1;
  128641. while( zFilename[0] ){
  128642. int x = strcmp(zFilename, zParam);
  128643. zFilename += sqlite3Strlen30(zFilename) + 1;
  128644. if( x==0 ) return zFilename;
  128645. zFilename += sqlite3Strlen30(zFilename) + 1;
  128646. }
  128647. return 0;
  128648. }
  128649. /*
  128650. ** Return a boolean value for a query parameter.
  128651. */
  128652. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  128653. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  128654. bDflt = bDflt!=0;
  128655. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  128656. }
  128657. /*
  128658. ** Return a 64-bit integer value for a query parameter.
  128659. */
  128660. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
  128661. const char *zFilename, /* Filename as passed to xOpen */
  128662. const char *zParam, /* URI parameter sought */
  128663. sqlite3_int64 bDflt /* return if parameter is missing */
  128664. ){
  128665. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  128666. sqlite3_int64 v;
  128667. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  128668. bDflt = v;
  128669. }
  128670. return bDflt;
  128671. }
  128672. /*
  128673. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  128674. */
  128675. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  128676. int i;
  128677. for(i=0; i<db->nDb; i++){
  128678. if( db->aDb[i].pBt
  128679. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  128680. ){
  128681. return db->aDb[i].pBt;
  128682. }
  128683. }
  128684. return 0;
  128685. }
  128686. /*
  128687. ** Return the filename of the database associated with a database
  128688. ** connection.
  128689. */
  128690. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  128691. Btree *pBt;
  128692. #ifdef SQLITE_ENABLE_API_ARMOR
  128693. if( !sqlite3SafetyCheckOk(db) ){
  128694. (void)SQLITE_MISUSE_BKPT;
  128695. return 0;
  128696. }
  128697. #endif
  128698. pBt = sqlite3DbNameToBtree(db, zDbName);
  128699. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  128700. }
  128701. /*
  128702. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  128703. ** no such database exists.
  128704. */
  128705. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  128706. Btree *pBt;
  128707. #ifdef SQLITE_ENABLE_API_ARMOR
  128708. if( !sqlite3SafetyCheckOk(db) ){
  128709. (void)SQLITE_MISUSE_BKPT;
  128710. return -1;
  128711. }
  128712. #endif
  128713. pBt = sqlite3DbNameToBtree(db, zDbName);
  128714. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  128715. }
  128716. #ifdef SQLITE_ENABLE_SNAPSHOT
  128717. /*
  128718. ** Obtain a snapshot handle for the snapshot of database zDb currently
  128719. ** being read by handle db.
  128720. */
  128721. SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_get(
  128722. sqlite3 *db,
  128723. const char *zDb,
  128724. sqlite3_snapshot **ppSnapshot
  128725. ){
  128726. int rc = SQLITE_ERROR;
  128727. #ifndef SQLITE_OMIT_WAL
  128728. int iDb;
  128729. #ifdef SQLITE_ENABLE_API_ARMOR
  128730. if( !sqlite3SafetyCheckOk(db) ){
  128731. return SQLITE_MISUSE_BKPT;
  128732. }
  128733. #endif
  128734. sqlite3_mutex_enter(db->mutex);
  128735. iDb = sqlite3FindDbName(db, zDb);
  128736. if( iDb==0 || iDb>1 ){
  128737. Btree *pBt = db->aDb[iDb].pBt;
  128738. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  128739. rc = sqlite3BtreeBeginTrans(pBt, 0);
  128740. if( rc==SQLITE_OK ){
  128741. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  128742. }
  128743. }
  128744. }
  128745. sqlite3_mutex_leave(db->mutex);
  128746. #endif /* SQLITE_OMIT_WAL */
  128747. return rc;
  128748. }
  128749. /*
  128750. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  128751. */
  128752. SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_open(
  128753. sqlite3 *db,
  128754. const char *zDb,
  128755. sqlite3_snapshot *pSnapshot
  128756. ){
  128757. int rc = SQLITE_ERROR;
  128758. #ifndef SQLITE_OMIT_WAL
  128759. #ifdef SQLITE_ENABLE_API_ARMOR
  128760. if( !sqlite3SafetyCheckOk(db) ){
  128761. return SQLITE_MISUSE_BKPT;
  128762. }
  128763. #endif
  128764. sqlite3_mutex_enter(db->mutex);
  128765. if( db->autoCommit==0 ){
  128766. int iDb;
  128767. iDb = sqlite3FindDbName(db, zDb);
  128768. if( iDb==0 || iDb>1 ){
  128769. Btree *pBt = db->aDb[iDb].pBt;
  128770. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  128771. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  128772. if( rc==SQLITE_OK ){
  128773. rc = sqlite3BtreeBeginTrans(pBt, 0);
  128774. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  128775. }
  128776. }
  128777. }
  128778. }
  128779. sqlite3_mutex_leave(db->mutex);
  128780. #endif /* SQLITE_OMIT_WAL */
  128781. return rc;
  128782. }
  128783. /*
  128784. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  128785. */
  128786. SQLITE_API void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  128787. sqlite3_free(pSnapshot);
  128788. }
  128789. #endif /* SQLITE_ENABLE_SNAPSHOT */
  128790. /************** End of main.c ************************************************/
  128791. /************** Begin file notify.c ******************************************/
  128792. /*
  128793. ** 2009 March 3
  128794. **
  128795. ** The author disclaims copyright to this source code. In place of
  128796. ** a legal notice, here is a blessing:
  128797. **
  128798. ** May you do good and not evil.
  128799. ** May you find forgiveness for yourself and forgive others.
  128800. ** May you share freely, never taking more than you give.
  128801. **
  128802. *************************************************************************
  128803. **
  128804. ** This file contains the implementation of the sqlite3_unlock_notify()
  128805. ** API method and its associated functionality.
  128806. */
  128807. /* #include "sqliteInt.h" */
  128808. /* #include "btreeInt.h" */
  128809. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  128810. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  128811. /*
  128812. ** Public interfaces:
  128813. **
  128814. ** sqlite3ConnectionBlocked()
  128815. ** sqlite3ConnectionUnlocked()
  128816. ** sqlite3ConnectionClosed()
  128817. ** sqlite3_unlock_notify()
  128818. */
  128819. #define assertMutexHeld() \
  128820. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  128821. /*
  128822. ** Head of a linked list of all sqlite3 objects created by this process
  128823. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  128824. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  128825. ** mutex is held.
  128826. */
  128827. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  128828. #ifndef NDEBUG
  128829. /*
  128830. ** This function is a complex assert() that verifies the following
  128831. ** properties of the blocked connections list:
  128832. **
  128833. ** 1) Each entry in the list has a non-NULL value for either
  128834. ** pUnlockConnection or pBlockingConnection, or both.
  128835. **
  128836. ** 2) All entries in the list that share a common value for
  128837. ** xUnlockNotify are grouped together.
  128838. **
  128839. ** 3) If the argument db is not NULL, then none of the entries in the
  128840. ** blocked connections list have pUnlockConnection or pBlockingConnection
  128841. ** set to db. This is used when closing connection db.
  128842. */
  128843. static void checkListProperties(sqlite3 *db){
  128844. sqlite3 *p;
  128845. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  128846. int seen = 0;
  128847. sqlite3 *p2;
  128848. /* Verify property (1) */
  128849. assert( p->pUnlockConnection || p->pBlockingConnection );
  128850. /* Verify property (2) */
  128851. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  128852. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  128853. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  128854. assert( db==0 || p->pUnlockConnection!=db );
  128855. assert( db==0 || p->pBlockingConnection!=db );
  128856. }
  128857. }
  128858. }
  128859. #else
  128860. # define checkListProperties(x)
  128861. #endif
  128862. /*
  128863. ** Remove connection db from the blocked connections list. If connection
  128864. ** db is not currently a part of the list, this function is a no-op.
  128865. */
  128866. static void removeFromBlockedList(sqlite3 *db){
  128867. sqlite3 **pp;
  128868. assertMutexHeld();
  128869. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  128870. if( *pp==db ){
  128871. *pp = (*pp)->pNextBlocked;
  128872. break;
  128873. }
  128874. }
  128875. }
  128876. /*
  128877. ** Add connection db to the blocked connections list. It is assumed
  128878. ** that it is not already a part of the list.
  128879. */
  128880. static void addToBlockedList(sqlite3 *db){
  128881. sqlite3 **pp;
  128882. assertMutexHeld();
  128883. for(
  128884. pp=&sqlite3BlockedList;
  128885. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  128886. pp=&(*pp)->pNextBlocked
  128887. );
  128888. db->pNextBlocked = *pp;
  128889. *pp = db;
  128890. }
  128891. /*
  128892. ** Obtain the STATIC_MASTER mutex.
  128893. */
  128894. static void enterMutex(void){
  128895. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  128896. checkListProperties(0);
  128897. }
  128898. /*
  128899. ** Release the STATIC_MASTER mutex.
  128900. */
  128901. static void leaveMutex(void){
  128902. assertMutexHeld();
  128903. checkListProperties(0);
  128904. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  128905. }
  128906. /*
  128907. ** Register an unlock-notify callback.
  128908. **
  128909. ** This is called after connection "db" has attempted some operation
  128910. ** but has received an SQLITE_LOCKED error because another connection
  128911. ** (call it pOther) in the same process was busy using the same shared
  128912. ** cache. pOther is found by looking at db->pBlockingConnection.
  128913. **
  128914. ** If there is no blocking connection, the callback is invoked immediately,
  128915. ** before this routine returns.
  128916. **
  128917. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  128918. ** a deadlock.
  128919. **
  128920. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  128921. ** its locks.
  128922. **
  128923. ** Each call to this routine overrides any prior callbacks registered
  128924. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  128925. ** cancelled.
  128926. */
  128927. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  128928. sqlite3 *db,
  128929. void (*xNotify)(void **, int),
  128930. void *pArg
  128931. ){
  128932. int rc = SQLITE_OK;
  128933. sqlite3_mutex_enter(db->mutex);
  128934. enterMutex();
  128935. if( xNotify==0 ){
  128936. removeFromBlockedList(db);
  128937. db->pBlockingConnection = 0;
  128938. db->pUnlockConnection = 0;
  128939. db->xUnlockNotify = 0;
  128940. db->pUnlockArg = 0;
  128941. }else if( 0==db->pBlockingConnection ){
  128942. /* The blocking transaction has been concluded. Or there never was a
  128943. ** blocking transaction. In either case, invoke the notify callback
  128944. ** immediately.
  128945. */
  128946. xNotify(&pArg, 1);
  128947. }else{
  128948. sqlite3 *p;
  128949. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  128950. if( p ){
  128951. rc = SQLITE_LOCKED; /* Deadlock detected. */
  128952. }else{
  128953. db->pUnlockConnection = db->pBlockingConnection;
  128954. db->xUnlockNotify = xNotify;
  128955. db->pUnlockArg = pArg;
  128956. removeFromBlockedList(db);
  128957. addToBlockedList(db);
  128958. }
  128959. }
  128960. leaveMutex();
  128961. assert( !db->mallocFailed );
  128962. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  128963. sqlite3_mutex_leave(db->mutex);
  128964. return rc;
  128965. }
  128966. /*
  128967. ** This function is called while stepping or preparing a statement
  128968. ** associated with connection db. The operation will return SQLITE_LOCKED
  128969. ** to the user because it requires a lock that will not be available
  128970. ** until connection pBlocker concludes its current transaction.
  128971. */
  128972. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  128973. enterMutex();
  128974. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  128975. addToBlockedList(db);
  128976. }
  128977. db->pBlockingConnection = pBlocker;
  128978. leaveMutex();
  128979. }
  128980. /*
  128981. ** This function is called when
  128982. ** the transaction opened by database db has just finished. Locks held
  128983. ** by database connection db have been released.
  128984. **
  128985. ** This function loops through each entry in the blocked connections
  128986. ** list and does the following:
  128987. **
  128988. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  128989. ** set to db, then set pBlockingConnection=0.
  128990. **
  128991. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  128992. ** set to db, then invoke the configured unlock-notify callback and
  128993. ** set pUnlockConnection=0.
  128994. **
  128995. ** 3) If the two steps above mean that pBlockingConnection==0 and
  128996. ** pUnlockConnection==0, remove the entry from the blocked connections
  128997. ** list.
  128998. */
  128999. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  129000. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  129001. int nArg = 0; /* Number of entries in aArg[] */
  129002. sqlite3 **pp; /* Iterator variable */
  129003. void **aArg; /* Arguments to the unlock callback */
  129004. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  129005. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  129006. aArg = aStatic;
  129007. enterMutex(); /* Enter STATIC_MASTER mutex */
  129008. /* This loop runs once for each entry in the blocked-connections list. */
  129009. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  129010. sqlite3 *p = *pp;
  129011. /* Step 1. */
  129012. if( p->pBlockingConnection==db ){
  129013. p->pBlockingConnection = 0;
  129014. }
  129015. /* Step 2. */
  129016. if( p->pUnlockConnection==db ){
  129017. assert( p->xUnlockNotify );
  129018. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  129019. xUnlockNotify(aArg, nArg);
  129020. nArg = 0;
  129021. }
  129022. sqlite3BeginBenignMalloc();
  129023. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  129024. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  129025. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  129026. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  129027. ){
  129028. /* The aArg[] array needs to grow. */
  129029. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  129030. if( pNew ){
  129031. memcpy(pNew, aArg, nArg*sizeof(void *));
  129032. sqlite3_free(aDyn);
  129033. aDyn = aArg = pNew;
  129034. }else{
  129035. /* This occurs when the array of context pointers that need to
  129036. ** be passed to the unlock-notify callback is larger than the
  129037. ** aStatic[] array allocated on the stack and the attempt to
  129038. ** allocate a larger array from the heap has failed.
  129039. **
  129040. ** This is a difficult situation to handle. Returning an error
  129041. ** code to the caller is insufficient, as even if an error code
  129042. ** is returned the transaction on connection db will still be
  129043. ** closed and the unlock-notify callbacks on blocked connections
  129044. ** will go unissued. This might cause the application to wait
  129045. ** indefinitely for an unlock-notify callback that will never
  129046. ** arrive.
  129047. **
  129048. ** Instead, invoke the unlock-notify callback with the context
  129049. ** array already accumulated. We can then clear the array and
  129050. ** begin accumulating any further context pointers without
  129051. ** requiring any dynamic allocation. This is sub-optimal because
  129052. ** it means that instead of one callback with a large array of
  129053. ** context pointers the application will receive two or more
  129054. ** callbacks with smaller arrays of context pointers, which will
  129055. ** reduce the applications ability to prioritize multiple
  129056. ** connections. But it is the best that can be done under the
  129057. ** circumstances.
  129058. */
  129059. xUnlockNotify(aArg, nArg);
  129060. nArg = 0;
  129061. }
  129062. }
  129063. sqlite3EndBenignMalloc();
  129064. aArg[nArg++] = p->pUnlockArg;
  129065. xUnlockNotify = p->xUnlockNotify;
  129066. p->pUnlockConnection = 0;
  129067. p->xUnlockNotify = 0;
  129068. p->pUnlockArg = 0;
  129069. }
  129070. /* Step 3. */
  129071. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  129072. /* Remove connection p from the blocked connections list. */
  129073. *pp = p->pNextBlocked;
  129074. p->pNextBlocked = 0;
  129075. }else{
  129076. pp = &p->pNextBlocked;
  129077. }
  129078. }
  129079. if( nArg!=0 ){
  129080. xUnlockNotify(aArg, nArg);
  129081. }
  129082. sqlite3_free(aDyn);
  129083. leaveMutex(); /* Leave STATIC_MASTER mutex */
  129084. }
  129085. /*
  129086. ** This is called when the database connection passed as an argument is
  129087. ** being closed. The connection is removed from the blocked list.
  129088. */
  129089. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  129090. sqlite3ConnectionUnlocked(db);
  129091. enterMutex();
  129092. removeFromBlockedList(db);
  129093. checkListProperties(db);
  129094. leaveMutex();
  129095. }
  129096. #endif
  129097. /************** End of notify.c **********************************************/
  129098. /************** Begin file fts3.c ********************************************/
  129099. /*
  129100. ** 2006 Oct 10
  129101. **
  129102. ** The author disclaims copyright to this source code. In place of
  129103. ** a legal notice, here is a blessing:
  129104. **
  129105. ** May you do good and not evil.
  129106. ** May you find forgiveness for yourself and forgive others.
  129107. ** May you share freely, never taking more than you give.
  129108. **
  129109. ******************************************************************************
  129110. **
  129111. ** This is an SQLite module implementing full-text search.
  129112. */
  129113. /*
  129114. ** The code in this file is only compiled if:
  129115. **
  129116. ** * The FTS3 module is being built as an extension
  129117. ** (in which case SQLITE_CORE is not defined), or
  129118. **
  129119. ** * The FTS3 module is being built into the core of
  129120. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  129121. */
  129122. /* The full-text index is stored in a series of b+tree (-like)
  129123. ** structures called segments which map terms to doclists. The
  129124. ** structures are like b+trees in layout, but are constructed from the
  129125. ** bottom up in optimal fashion and are not updatable. Since trees
  129126. ** are built from the bottom up, things will be described from the
  129127. ** bottom up.
  129128. **
  129129. **
  129130. **** Varints ****
  129131. ** The basic unit of encoding is a variable-length integer called a
  129132. ** varint. We encode variable-length integers in little-endian order
  129133. ** using seven bits * per byte as follows:
  129134. **
  129135. ** KEY:
  129136. ** A = 0xxxxxxx 7 bits of data and one flag bit
  129137. ** B = 1xxxxxxx 7 bits of data and one flag bit
  129138. **
  129139. ** 7 bits - A
  129140. ** 14 bits - BA
  129141. ** 21 bits - BBA
  129142. ** and so on.
  129143. **
  129144. ** This is similar in concept to how sqlite encodes "varints" but
  129145. ** the encoding is not the same. SQLite varints are big-endian
  129146. ** are are limited to 9 bytes in length whereas FTS3 varints are
  129147. ** little-endian and can be up to 10 bytes in length (in theory).
  129148. **
  129149. ** Example encodings:
  129150. **
  129151. ** 1: 0x01
  129152. ** 127: 0x7f
  129153. ** 128: 0x81 0x00
  129154. **
  129155. **
  129156. **** Document lists ****
  129157. ** A doclist (document list) holds a docid-sorted list of hits for a
  129158. ** given term. Doclists hold docids and associated token positions.
  129159. ** A docid is the unique integer identifier for a single document.
  129160. ** A position is the index of a word within the document. The first
  129161. ** word of the document has a position of 0.
  129162. **
  129163. ** FTS3 used to optionally store character offsets using a compile-time
  129164. ** option. But that functionality is no longer supported.
  129165. **
  129166. ** A doclist is stored like this:
  129167. **
  129168. ** array {
  129169. ** varint docid; (delta from previous doclist)
  129170. ** array { (position list for column 0)
  129171. ** varint position; (2 more than the delta from previous position)
  129172. ** }
  129173. ** array {
  129174. ** varint POS_COLUMN; (marks start of position list for new column)
  129175. ** varint column; (index of new column)
  129176. ** array {
  129177. ** varint position; (2 more than the delta from previous position)
  129178. ** }
  129179. ** }
  129180. ** varint POS_END; (marks end of positions for this document.
  129181. ** }
  129182. **
  129183. ** Here, array { X } means zero or more occurrences of X, adjacent in
  129184. ** memory. A "position" is an index of a token in the token stream
  129185. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  129186. ** in the same logical place as the position element, and act as sentinals
  129187. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  129188. ** The positions numbers are not stored literally but rather as two more
  129189. ** than the difference from the prior position, or the just the position plus
  129190. ** 2 for the first position. Example:
  129191. **
  129192. ** label: A B C D E F G H I J K
  129193. ** value: 123 5 9 1 1 14 35 0 234 72 0
  129194. **
  129195. ** The 123 value is the first docid. For column zero in this document
  129196. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  129197. ** at D signals the start of a new column; the 1 at E indicates that the
  129198. ** new column is column number 1. There are two positions at 12 and 45
  129199. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  129200. ** 234 at I is the delta to next docid (357). It has one position 70
  129201. ** (72-2) and then terminates with the 0 at K.
  129202. **
  129203. ** A "position-list" is the list of positions for multiple columns for
  129204. ** a single docid. A "column-list" is the set of positions for a single
  129205. ** column. Hence, a position-list consists of one or more column-lists,
  129206. ** a document record consists of a docid followed by a position-list and
  129207. ** a doclist consists of one or more document records.
  129208. **
  129209. ** A bare doclist omits the position information, becoming an
  129210. ** array of varint-encoded docids.
  129211. **
  129212. **** Segment leaf nodes ****
  129213. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  129214. ** nodes are written using LeafWriter, and read using LeafReader (to
  129215. ** iterate through a single leaf node's data) and LeavesReader (to
  129216. ** iterate through a segment's entire leaf layer). Leaf nodes have
  129217. ** the format:
  129218. **
  129219. ** varint iHeight; (height from leaf level, always 0)
  129220. ** varint nTerm; (length of first term)
  129221. ** char pTerm[nTerm]; (content of first term)
  129222. ** varint nDoclist; (length of term's associated doclist)
  129223. ** char pDoclist[nDoclist]; (content of doclist)
  129224. ** array {
  129225. ** (further terms are delta-encoded)
  129226. ** varint nPrefix; (length of prefix shared with previous term)
  129227. ** varint nSuffix; (length of unshared suffix)
  129228. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  129229. ** varint nDoclist; (length of term's associated doclist)
  129230. ** char pDoclist[nDoclist]; (content of doclist)
  129231. ** }
  129232. **
  129233. ** Here, array { X } means zero or more occurrences of X, adjacent in
  129234. ** memory.
  129235. **
  129236. ** Leaf nodes are broken into blocks which are stored contiguously in
  129237. ** the %_segments table in sorted order. This means that when the end
  129238. ** of a node is reached, the next term is in the node with the next
  129239. ** greater node id.
  129240. **
  129241. ** New data is spilled to a new leaf node when the current node
  129242. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  129243. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  129244. ** node (a leaf node with a single term and doclist). The goal of
  129245. ** these settings is to pack together groups of small doclists while
  129246. ** making it efficient to directly access large doclists. The
  129247. ** assumption is that large doclists represent terms which are more
  129248. ** likely to be query targets.
  129249. **
  129250. ** TODO(shess) It may be useful for blocking decisions to be more
  129251. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  129252. ** node rather than splitting into 2k and .5k nodes. My intuition is
  129253. ** that this might extend through 2x or 4x the pagesize.
  129254. **
  129255. **
  129256. **** Segment interior nodes ****
  129257. ** Segment interior nodes store blockids for subtree nodes and terms
  129258. ** to describe what data is stored by the each subtree. Interior
  129259. ** nodes are written using InteriorWriter, and read using
  129260. ** InteriorReader. InteriorWriters are created as needed when
  129261. ** SegmentWriter creates new leaf nodes, or when an interior node
  129262. ** itself grows too big and must be split. The format of interior
  129263. ** nodes:
  129264. **
  129265. ** varint iHeight; (height from leaf level, always >0)
  129266. ** varint iBlockid; (block id of node's leftmost subtree)
  129267. ** optional {
  129268. ** varint nTerm; (length of first term)
  129269. ** char pTerm[nTerm]; (content of first term)
  129270. ** array {
  129271. ** (further terms are delta-encoded)
  129272. ** varint nPrefix; (length of shared prefix with previous term)
  129273. ** varint nSuffix; (length of unshared suffix)
  129274. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  129275. ** }
  129276. ** }
  129277. **
  129278. ** Here, optional { X } means an optional element, while array { X }
  129279. ** means zero or more occurrences of X, adjacent in memory.
  129280. **
  129281. ** An interior node encodes n terms separating n+1 subtrees. The
  129282. ** subtree blocks are contiguous, so only the first subtree's blockid
  129283. ** is encoded. The subtree at iBlockid will contain all terms less
  129284. ** than the first term encoded (or all terms if no term is encoded).
  129285. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  129286. ** than pTerm[i+1], the subtree for that term will be rooted at
  129287. ** iBlockid+i. Interior nodes only store enough term data to
  129288. ** distinguish adjacent children (if the rightmost term of the left
  129289. ** child is "something", and the leftmost term of the right child is
  129290. ** "wicked", only "w" is stored).
  129291. **
  129292. ** New data is spilled to a new interior node at the same height when
  129293. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  129294. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  129295. ** interior nodes and making the tree too skinny. The interior nodes
  129296. ** at a given height are naturally tracked by interior nodes at
  129297. ** height+1, and so on.
  129298. **
  129299. **
  129300. **** Segment directory ****
  129301. ** The segment directory in table %_segdir stores meta-information for
  129302. ** merging and deleting segments, and also the root node of the
  129303. ** segment's tree.
  129304. **
  129305. ** The root node is the top node of the segment's tree after encoding
  129306. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  129307. ** This could be either a leaf node or an interior node. If the top
  129308. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  129309. ** and a new root interior node is generated (which should always fit
  129310. ** within ROOT_MAX because it only needs space for 2 varints, the
  129311. ** height and the blockid of the previous root).
  129312. **
  129313. ** The meta-information in the segment directory is:
  129314. ** level - segment level (see below)
  129315. ** idx - index within level
  129316. ** - (level,idx uniquely identify a segment)
  129317. ** start_block - first leaf node
  129318. ** leaves_end_block - last leaf node
  129319. ** end_block - last block (including interior nodes)
  129320. ** root - contents of root node
  129321. **
  129322. ** If the root node is a leaf node, then start_block,
  129323. ** leaves_end_block, and end_block are all 0.
  129324. **
  129325. **
  129326. **** Segment merging ****
  129327. ** To amortize update costs, segments are grouped into levels and
  129328. ** merged in batches. Each increase in level represents exponentially
  129329. ** more documents.
  129330. **
  129331. ** New documents (actually, document updates) are tokenized and
  129332. ** written individually (using LeafWriter) to a level 0 segment, with
  129333. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  129334. ** level 0 segments are merged into a single level 1 segment. Level 1
  129335. ** is populated like level 0, and eventually MERGE_COUNT level 1
  129336. ** segments are merged to a single level 2 segment (representing
  129337. ** MERGE_COUNT^2 updates), and so on.
  129338. **
  129339. ** A segment merge traverses all segments at a given level in
  129340. ** parallel, performing a straightforward sorted merge. Since segment
  129341. ** leaf nodes are written in to the %_segments table in order, this
  129342. ** merge traverses the underlying sqlite disk structures efficiently.
  129343. ** After the merge, all segment blocks from the merged level are
  129344. ** deleted.
  129345. **
  129346. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  129347. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  129348. ** very similar performance numbers to 16 on insertion, though they're
  129349. ** a tiny bit slower (perhaps due to more overhead in merge-time
  129350. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  129351. ** 16, 2 about 66% slower than 16.
  129352. **
  129353. ** At query time, high MERGE_COUNT increases the number of segments
  129354. ** which need to be scanned and merged. For instance, with 100k docs
  129355. ** inserted:
  129356. **
  129357. ** MERGE_COUNT segments
  129358. ** 16 25
  129359. ** 8 12
  129360. ** 4 10
  129361. ** 2 6
  129362. **
  129363. ** This appears to have only a moderate impact on queries for very
  129364. ** frequent terms (which are somewhat dominated by segment merge
  129365. ** costs), and infrequent and non-existent terms still seem to be fast
  129366. ** even with many segments.
  129367. **
  129368. ** TODO(shess) That said, it would be nice to have a better query-side
  129369. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  129370. ** optimizations to things like doclist merging will swing the sweet
  129371. ** spot around.
  129372. **
  129373. **
  129374. **
  129375. **** Handling of deletions and updates ****
  129376. ** Since we're using a segmented structure, with no docid-oriented
  129377. ** index into the term index, we clearly cannot simply update the term
  129378. ** index when a document is deleted or updated. For deletions, we
  129379. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  129380. ** we simply write the new doclist. Segment merges overwrite older
  129381. ** data for a particular docid with newer data, so deletes or updates
  129382. ** will eventually overtake the earlier data and knock it out. The
  129383. ** query logic likewise merges doclists so that newer data knocks out
  129384. ** older data.
  129385. */
  129386. /************** Include fts3Int.h in the middle of fts3.c ********************/
  129387. /************** Begin file fts3Int.h *****************************************/
  129388. /*
  129389. ** 2009 Nov 12
  129390. **
  129391. ** The author disclaims copyright to this source code. In place of
  129392. ** a legal notice, here is a blessing:
  129393. **
  129394. ** May you do good and not evil.
  129395. ** May you find forgiveness for yourself and forgive others.
  129396. ** May you share freely, never taking more than you give.
  129397. **
  129398. ******************************************************************************
  129399. **
  129400. */
  129401. #ifndef _FTSINT_H
  129402. #define _FTSINT_H
  129403. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  129404. # define NDEBUG 1
  129405. #endif
  129406. /* FTS3/FTS4 require virtual tables */
  129407. #ifdef SQLITE_OMIT_VIRTUALTABLE
  129408. # undef SQLITE_ENABLE_FTS3
  129409. # undef SQLITE_ENABLE_FTS4
  129410. #endif
  129411. /*
  129412. ** FTS4 is really an extension for FTS3. It is enabled using the
  129413. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  129414. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  129415. */
  129416. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  129417. # define SQLITE_ENABLE_FTS3
  129418. #endif
  129419. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129420. /* If not building as part of the core, include sqlite3ext.h. */
  129421. #ifndef SQLITE_CORE
  129422. /* # include "sqlite3ext.h" */
  129423. SQLITE_EXTENSION_INIT3
  129424. #endif
  129425. /* #include "sqlite3.h" */
  129426. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  129427. /************** Begin file fts3_tokenizer.h **********************************/
  129428. /*
  129429. ** 2006 July 10
  129430. **
  129431. ** The author disclaims copyright to this source code.
  129432. **
  129433. *************************************************************************
  129434. ** Defines the interface to tokenizers used by fulltext-search. There
  129435. ** are three basic components:
  129436. **
  129437. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  129438. ** interface functions. This is essentially the class structure for
  129439. ** tokenizers.
  129440. **
  129441. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  129442. ** including customization information defined at creation time.
  129443. **
  129444. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  129445. ** tokens from a particular input.
  129446. */
  129447. #ifndef _FTS3_TOKENIZER_H_
  129448. #define _FTS3_TOKENIZER_H_
  129449. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  129450. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  129451. ** we will need a way to register the API consistently.
  129452. */
  129453. /* #include "sqlite3.h" */
  129454. /*
  129455. ** Structures used by the tokenizer interface. When a new tokenizer
  129456. ** implementation is registered, the caller provides a pointer to
  129457. ** an sqlite3_tokenizer_module containing pointers to the callback
  129458. ** functions that make up an implementation.
  129459. **
  129460. ** When an fts3 table is created, it passes any arguments passed to
  129461. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  129462. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  129463. ** implementation. The xCreate() function in turn returns an
  129464. ** sqlite3_tokenizer structure representing the specific tokenizer to
  129465. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  129466. **
  129467. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  129468. ** method is called. It returns an sqlite3_tokenizer_cursor object
  129469. ** that may be used to tokenize a specific input buffer based on
  129470. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  129471. ** object.
  129472. */
  129473. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  129474. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  129475. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  129476. struct sqlite3_tokenizer_module {
  129477. /*
  129478. ** Structure version. Should always be set to 0 or 1.
  129479. */
  129480. int iVersion;
  129481. /*
  129482. ** Create a new tokenizer. The values in the argv[] array are the
  129483. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  129484. ** TABLE statement that created the fts3 table. For example, if
  129485. ** the following SQL is executed:
  129486. **
  129487. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  129488. **
  129489. ** then argc is set to 2, and the argv[] array contains pointers
  129490. ** to the strings "arg1" and "arg2".
  129491. **
  129492. ** This method should return either SQLITE_OK (0), or an SQLite error
  129493. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  129494. ** to point at the newly created tokenizer structure. The generic
  129495. ** sqlite3_tokenizer.pModule variable should not be initialized by
  129496. ** this callback. The caller will do so.
  129497. */
  129498. int (*xCreate)(
  129499. int argc, /* Size of argv array */
  129500. const char *const*argv, /* Tokenizer argument strings */
  129501. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  129502. );
  129503. /*
  129504. ** Destroy an existing tokenizer. The fts3 module calls this method
  129505. ** exactly once for each successful call to xCreate().
  129506. */
  129507. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  129508. /*
  129509. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  129510. ** is responsible for ensuring that the input buffer remains valid
  129511. ** until the cursor is closed (using the xClose() method).
  129512. */
  129513. int (*xOpen)(
  129514. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  129515. const char *pInput, int nBytes, /* Input buffer */
  129516. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  129517. );
  129518. /*
  129519. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  129520. ** method exactly once for each successful call to xOpen().
  129521. */
  129522. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  129523. /*
  129524. ** Retrieve the next token from the tokenizer cursor pCursor. This
  129525. ** method should either return SQLITE_OK and set the values of the
  129526. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  129527. ** the end of the buffer has been reached, or an SQLite error code.
  129528. **
  129529. ** *ppToken should be set to point at a buffer containing the
  129530. ** normalized version of the token (i.e. after any case-folding and/or
  129531. ** stemming has been performed). *pnBytes should be set to the length
  129532. ** of this buffer in bytes. The input text that generated the token is
  129533. ** identified by the byte offsets returned in *piStartOffset and
  129534. ** *piEndOffset. *piStartOffset should be set to the index of the first
  129535. ** byte of the token in the input buffer. *piEndOffset should be set
  129536. ** to the index of the first byte just past the end of the token in
  129537. ** the input buffer.
  129538. **
  129539. ** The buffer *ppToken is set to point at is managed by the tokenizer
  129540. ** implementation. It is only required to be valid until the next call
  129541. ** to xNext() or xClose().
  129542. */
  129543. /* TODO(shess) current implementation requires pInput to be
  129544. ** nul-terminated. This should either be fixed, or pInput/nBytes
  129545. ** should be converted to zInput.
  129546. */
  129547. int (*xNext)(
  129548. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  129549. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  129550. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  129551. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  129552. int *piPosition /* OUT: Number of tokens returned before this one */
  129553. );
  129554. /***********************************************************************
  129555. ** Methods below this point are only available if iVersion>=1.
  129556. */
  129557. /*
  129558. ** Configure the language id of a tokenizer cursor.
  129559. */
  129560. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  129561. };
  129562. struct sqlite3_tokenizer {
  129563. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  129564. /* Tokenizer implementations will typically add additional fields */
  129565. };
  129566. struct sqlite3_tokenizer_cursor {
  129567. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  129568. /* Tokenizer implementations will typically add additional fields */
  129569. };
  129570. int fts3_global_term_cnt(int iTerm, int iCol);
  129571. int fts3_term_cnt(int iTerm, int iCol);
  129572. #endif /* _FTS3_TOKENIZER_H_ */
  129573. /************** End of fts3_tokenizer.h **************************************/
  129574. /************** Continuing where we left off in fts3Int.h ********************/
  129575. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  129576. /************** Begin file fts3_hash.h ***************************************/
  129577. /*
  129578. ** 2001 September 22
  129579. **
  129580. ** The author disclaims copyright to this source code. In place of
  129581. ** a legal notice, here is a blessing:
  129582. **
  129583. ** May you do good and not evil.
  129584. ** May you find forgiveness for yourself and forgive others.
  129585. ** May you share freely, never taking more than you give.
  129586. **
  129587. *************************************************************************
  129588. ** This is the header file for the generic hash-table implementation
  129589. ** used in SQLite. We've modified it slightly to serve as a standalone
  129590. ** hash table implementation for the full-text indexing module.
  129591. **
  129592. */
  129593. #ifndef _FTS3_HASH_H_
  129594. #define _FTS3_HASH_H_
  129595. /* Forward declarations of structures. */
  129596. typedef struct Fts3Hash Fts3Hash;
  129597. typedef struct Fts3HashElem Fts3HashElem;
  129598. /* A complete hash table is an instance of the following structure.
  129599. ** The internals of this structure are intended to be opaque -- client
  129600. ** code should not attempt to access or modify the fields of this structure
  129601. ** directly. Change this structure only by using the routines below.
  129602. ** However, many of the "procedures" and "functions" for modifying and
  129603. ** accessing this structure are really macros, so we can't really make
  129604. ** this structure opaque.
  129605. */
  129606. struct Fts3Hash {
  129607. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  129608. char copyKey; /* True if copy of key made on insert */
  129609. int count; /* Number of entries in this table */
  129610. Fts3HashElem *first; /* The first element of the array */
  129611. int htsize; /* Number of buckets in the hash table */
  129612. struct _fts3ht { /* the hash table */
  129613. int count; /* Number of entries with this hash */
  129614. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  129615. } *ht;
  129616. };
  129617. /* Each element in the hash table is an instance of the following
  129618. ** structure. All elements are stored on a single doubly-linked list.
  129619. **
  129620. ** Again, this structure is intended to be opaque, but it can't really
  129621. ** be opaque because it is used by macros.
  129622. */
  129623. struct Fts3HashElem {
  129624. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  129625. void *data; /* Data associated with this element */
  129626. void *pKey; int nKey; /* Key associated with this element */
  129627. };
  129628. /*
  129629. ** There are 2 different modes of operation for a hash table:
  129630. **
  129631. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  129632. ** (including the null-terminator, if any). Case
  129633. ** is respected in comparisons.
  129634. **
  129635. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  129636. ** memcmp() is used to compare keys.
  129637. **
  129638. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  129639. */
  129640. #define FTS3_HASH_STRING 1
  129641. #define FTS3_HASH_BINARY 2
  129642. /*
  129643. ** Access routines. To delete, insert a NULL pointer.
  129644. */
  129645. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  129646. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  129647. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  129648. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  129649. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  129650. /*
  129651. ** Shorthand for the functions above
  129652. */
  129653. #define fts3HashInit sqlite3Fts3HashInit
  129654. #define fts3HashInsert sqlite3Fts3HashInsert
  129655. #define fts3HashFind sqlite3Fts3HashFind
  129656. #define fts3HashClear sqlite3Fts3HashClear
  129657. #define fts3HashFindElem sqlite3Fts3HashFindElem
  129658. /*
  129659. ** Macros for looping over all elements of a hash table. The idiom is
  129660. ** like this:
  129661. **
  129662. ** Fts3Hash h;
  129663. ** Fts3HashElem *p;
  129664. ** ...
  129665. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  129666. ** SomeStructure *pData = fts3HashData(p);
  129667. ** // do something with pData
  129668. ** }
  129669. */
  129670. #define fts3HashFirst(H) ((H)->first)
  129671. #define fts3HashNext(E) ((E)->next)
  129672. #define fts3HashData(E) ((E)->data)
  129673. #define fts3HashKey(E) ((E)->pKey)
  129674. #define fts3HashKeysize(E) ((E)->nKey)
  129675. /*
  129676. ** Number of entries in a hash table
  129677. */
  129678. #define fts3HashCount(H) ((H)->count)
  129679. #endif /* _FTS3_HASH_H_ */
  129680. /************** End of fts3_hash.h *******************************************/
  129681. /************** Continuing where we left off in fts3Int.h ********************/
  129682. /*
  129683. ** This constant determines the maximum depth of an FTS expression tree
  129684. ** that the library will create and use. FTS uses recursion to perform
  129685. ** various operations on the query tree, so the disadvantage of a large
  129686. ** limit is that it may allow very large queries to use large amounts
  129687. ** of stack space (perhaps causing a stack overflow).
  129688. */
  129689. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  129690. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  129691. #endif
  129692. /*
  129693. ** This constant controls how often segments are merged. Once there are
  129694. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  129695. ** segment of level N+1.
  129696. */
  129697. #define FTS3_MERGE_COUNT 16
  129698. /*
  129699. ** This is the maximum amount of data (in bytes) to store in the
  129700. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  129701. ** populated as documents are inserted/updated/deleted in a transaction
  129702. ** and used to create a new segment when the transaction is committed.
  129703. ** However if this limit is reached midway through a transaction, a new
  129704. ** segment is created and the hash table cleared immediately.
  129705. */
  129706. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  129707. /*
  129708. ** Macro to return the number of elements in an array. SQLite has a
  129709. ** similar macro called ArraySize(). Use a different name to avoid
  129710. ** a collision when building an amalgamation with built-in FTS3.
  129711. */
  129712. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  129713. #ifndef MIN
  129714. # define MIN(x,y) ((x)<(y)?(x):(y))
  129715. #endif
  129716. #ifndef MAX
  129717. # define MAX(x,y) ((x)>(y)?(x):(y))
  129718. #endif
  129719. /*
  129720. ** Maximum length of a varint encoded integer. The varint format is different
  129721. ** from that used by SQLite, so the maximum length is 10, not 9.
  129722. */
  129723. #define FTS3_VARINT_MAX 10
  129724. /*
  129725. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  129726. ** in the document set and zero or more prefix indexes. All indexes are stored
  129727. ** as one or more b+-trees in the %_segments and %_segdir tables.
  129728. **
  129729. ** It is possible to determine which index a b+-tree belongs to based on the
  129730. ** value stored in the "%_segdir.level" column. Given this value L, the index
  129731. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  129732. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  129733. ** between 1024 and 2047 to index 1, and so on.
  129734. **
  129735. ** It is considered impossible for an index to use more than 1024 levels. In
  129736. ** theory though this may happen, but only after at least
  129737. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  129738. */
  129739. #define FTS3_SEGDIR_MAXLEVEL 1024
  129740. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  129741. /*
  129742. ** The testcase() macro is only used by the amalgamation. If undefined,
  129743. ** make it a no-op.
  129744. */
  129745. #ifndef testcase
  129746. # define testcase(X)
  129747. #endif
  129748. /*
  129749. ** Terminator values for position-lists and column-lists.
  129750. */
  129751. #define POS_COLUMN (1) /* Column-list terminator */
  129752. #define POS_END (0) /* Position-list terminator */
  129753. /*
  129754. ** This section provides definitions to allow the
  129755. ** FTS3 extension to be compiled outside of the
  129756. ** amalgamation.
  129757. */
  129758. #ifndef SQLITE_AMALGAMATION
  129759. /*
  129760. ** Macros indicating that conditional expressions are always true or
  129761. ** false.
  129762. */
  129763. #ifdef SQLITE_COVERAGE_TEST
  129764. # define ALWAYS(x) (1)
  129765. # define NEVER(X) (0)
  129766. #elif defined(SQLITE_DEBUG)
  129767. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  129768. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  129769. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  129770. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  129771. #else
  129772. # define ALWAYS(x) (x)
  129773. # define NEVER(x) (x)
  129774. #endif
  129775. /*
  129776. ** Internal types used by SQLite.
  129777. */
  129778. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  129779. typedef short int i16; /* 2-byte (or larger) signed integer */
  129780. typedef unsigned int u32; /* 4-byte unsigned integer */
  129781. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  129782. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  129783. /*
  129784. ** Macro used to suppress compiler warnings for unused parameters.
  129785. */
  129786. #define UNUSED_PARAMETER(x) (void)(x)
  129787. /*
  129788. ** Activate assert() only if SQLITE_TEST is enabled.
  129789. */
  129790. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  129791. # define NDEBUG 1
  129792. #endif
  129793. /*
  129794. ** The TESTONLY macro is used to enclose variable declarations or
  129795. ** other bits of code that are needed to support the arguments
  129796. ** within testcase() and assert() macros.
  129797. */
  129798. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  129799. # define TESTONLY(X) X
  129800. #else
  129801. # define TESTONLY(X)
  129802. #endif
  129803. #endif /* SQLITE_AMALGAMATION */
  129804. #ifdef SQLITE_DEBUG
  129805. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  129806. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  129807. #else
  129808. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  129809. #endif
  129810. typedef struct Fts3Table Fts3Table;
  129811. typedef struct Fts3Cursor Fts3Cursor;
  129812. typedef struct Fts3Expr Fts3Expr;
  129813. typedef struct Fts3Phrase Fts3Phrase;
  129814. typedef struct Fts3PhraseToken Fts3PhraseToken;
  129815. typedef struct Fts3Doclist Fts3Doclist;
  129816. typedef struct Fts3SegFilter Fts3SegFilter;
  129817. typedef struct Fts3DeferredToken Fts3DeferredToken;
  129818. typedef struct Fts3SegReader Fts3SegReader;
  129819. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  129820. typedef struct MatchinfoBuffer MatchinfoBuffer;
  129821. /*
  129822. ** A connection to a fulltext index is an instance of the following
  129823. ** structure. The xCreate and xConnect methods create an instance
  129824. ** of this structure and xDestroy and xDisconnect free that instance.
  129825. ** All other methods receive a pointer to the structure as one of their
  129826. ** arguments.
  129827. */
  129828. struct Fts3Table {
  129829. sqlite3_vtab base; /* Base class used by SQLite core */
  129830. sqlite3 *db; /* The database connection */
  129831. const char *zDb; /* logical database name */
  129832. const char *zName; /* virtual table name */
  129833. int nColumn; /* number of named columns in virtual table */
  129834. char **azColumn; /* column names. malloced */
  129835. u8 *abNotindexed; /* True for 'notindexed' columns */
  129836. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  129837. char *zContentTbl; /* content=xxx option, or NULL */
  129838. char *zLanguageid; /* languageid=xxx option, or NULL */
  129839. int nAutoincrmerge; /* Value configured by 'automerge' */
  129840. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  129841. /* Precompiled statements used by the implementation. Each of these
  129842. ** statements is run and reset within a single virtual table API call.
  129843. */
  129844. sqlite3_stmt *aStmt[40];
  129845. char *zReadExprlist;
  129846. char *zWriteExprlist;
  129847. int nNodeSize; /* Soft limit for node size */
  129848. u8 bFts4; /* True for FTS4, false for FTS3 */
  129849. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  129850. u8 bHasDocsize; /* True if %_docsize table exists */
  129851. u8 bDescIdx; /* True if doclists are in reverse order */
  129852. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  129853. int nPgsz; /* Page size for host database */
  129854. char *zSegmentsTbl; /* Name of %_segments table */
  129855. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  129856. /*
  129857. ** The following array of hash tables is used to buffer pending index
  129858. ** updates during transactions. All pending updates buffered at any one
  129859. ** time must share a common language-id (see the FTS4 langid= feature).
  129860. ** The current language id is stored in variable iPrevLangid.
  129861. **
  129862. ** A single FTS4 table may have multiple full-text indexes. For each index
  129863. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  129864. ** terms that appear in the document set. Each subsequent index in aIndex[]
  129865. ** is an index of prefixes of a specific length.
  129866. **
  129867. ** Variable nPendingData contains an estimate the memory consumed by the
  129868. ** pending data structures, including hash table overhead, but not including
  129869. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  129870. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  129871. ** recently inserted record.
  129872. */
  129873. int nIndex; /* Size of aIndex[] */
  129874. struct Fts3Index {
  129875. int nPrefix; /* Prefix length (0 for main terms index) */
  129876. Fts3Hash hPending; /* Pending terms table for this index */
  129877. } *aIndex;
  129878. int nMaxPendingData; /* Max pending data before flush to disk */
  129879. int nPendingData; /* Current bytes of pending data */
  129880. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  129881. int iPrevLangid; /* Langid of recently inserted document */
  129882. int bPrevDelete; /* True if last operation was a delete */
  129883. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  129884. /* State variables used for validating that the transaction control
  129885. ** methods of the virtual table are called at appropriate times. These
  129886. ** values do not contribute to FTS functionality; they are used for
  129887. ** verifying the operation of the SQLite core.
  129888. */
  129889. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  129890. int mxSavepoint; /* Largest valid xSavepoint integer */
  129891. #endif
  129892. #ifdef SQLITE_TEST
  129893. /* True to disable the incremental doclist optimization. This is controled
  129894. ** by special insert command 'test-no-incr-doclist'. */
  129895. int bNoIncrDoclist;
  129896. #endif
  129897. };
  129898. /*
  129899. ** When the core wants to read from the virtual table, it creates a
  129900. ** virtual table cursor (an instance of the following structure) using
  129901. ** the xOpen method. Cursors are destroyed using the xClose method.
  129902. */
  129903. struct Fts3Cursor {
  129904. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  129905. i16 eSearch; /* Search strategy (see below) */
  129906. u8 isEof; /* True if at End Of Results */
  129907. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  129908. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  129909. Fts3Expr *pExpr; /* Parsed MATCH query string */
  129910. int iLangid; /* Language being queried for */
  129911. int nPhrase; /* Number of matchable phrases in query */
  129912. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  129913. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  129914. char *pNextId; /* Pointer into the body of aDoclist */
  129915. char *aDoclist; /* List of docids for full-text queries */
  129916. int nDoclist; /* Size of buffer at aDoclist */
  129917. u8 bDesc; /* True to sort in descending order */
  129918. int eEvalmode; /* An FTS3_EVAL_XX constant */
  129919. int nRowAvg; /* Average size of database rows, in pages */
  129920. sqlite3_int64 nDoc; /* Documents in table */
  129921. i64 iMinDocid; /* Minimum docid to return */
  129922. i64 iMaxDocid; /* Maximum docid to return */
  129923. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  129924. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  129925. };
  129926. #define FTS3_EVAL_FILTER 0
  129927. #define FTS3_EVAL_NEXT 1
  129928. #define FTS3_EVAL_MATCHINFO 2
  129929. /*
  129930. ** The Fts3Cursor.eSearch member is always set to one of the following.
  129931. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  129932. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  129933. ** of the column to be searched. For example, in
  129934. **
  129935. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  129936. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  129937. **
  129938. ** Because the LHS of the MATCH operator is 2nd column "b",
  129939. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  129940. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  129941. ** indicating that all columns should be searched,
  129942. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  129943. */
  129944. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  129945. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  129946. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  129947. /*
  129948. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  129949. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  129950. ** above. The upper 16-bits contain a combination of the following
  129951. ** bits, used to describe extra constraints on full-text searches.
  129952. */
  129953. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  129954. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  129955. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  129956. struct Fts3Doclist {
  129957. char *aAll; /* Array containing doclist (or NULL) */
  129958. int nAll; /* Size of a[] in bytes */
  129959. char *pNextDocid; /* Pointer to next docid */
  129960. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  129961. int bFreeList; /* True if pList should be sqlite3_free()d */
  129962. char *pList; /* Pointer to position list following iDocid */
  129963. int nList; /* Length of position list */
  129964. };
  129965. /*
  129966. ** A "phrase" is a sequence of one or more tokens that must match in
  129967. ** sequence. A single token is the base case and the most common case.
  129968. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  129969. ** nToken will be the number of tokens in the string.
  129970. */
  129971. struct Fts3PhraseToken {
  129972. char *z; /* Text of the token */
  129973. int n; /* Number of bytes in buffer z */
  129974. int isPrefix; /* True if token ends with a "*" character */
  129975. int bFirst; /* True if token must appear at position 0 */
  129976. /* Variables above this point are populated when the expression is
  129977. ** parsed (by code in fts3_expr.c). Below this point the variables are
  129978. ** used when evaluating the expression. */
  129979. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  129980. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  129981. };
  129982. struct Fts3Phrase {
  129983. /* Cache of doclist for this phrase. */
  129984. Fts3Doclist doclist;
  129985. int bIncr; /* True if doclist is loaded incrementally */
  129986. int iDoclistToken;
  129987. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  129988. ** OR condition. */
  129989. char *pOrPoslist;
  129990. i64 iOrDocid;
  129991. /* Variables below this point are populated by fts3_expr.c when parsing
  129992. ** a MATCH expression. Everything above is part of the evaluation phase.
  129993. */
  129994. int nToken; /* Number of tokens in the phrase */
  129995. int iColumn; /* Index of column this phrase must match */
  129996. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  129997. };
  129998. /*
  129999. ** A tree of these objects forms the RHS of a MATCH operator.
  130000. **
  130001. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  130002. ** points to a malloced buffer, size nDoclist bytes, containing the results
  130003. ** of this phrase query in FTS3 doclist format. As usual, the initial
  130004. ** "Length" field found in doclists stored on disk is omitted from this
  130005. ** buffer.
  130006. **
  130007. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  130008. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  130009. ** where nCol is the number of columns in the queried FTS table. The array
  130010. ** is populated as follows:
  130011. **
  130012. ** aMI[iCol*3 + 0] = Undefined
  130013. ** aMI[iCol*3 + 1] = Number of occurrences
  130014. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  130015. **
  130016. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  130017. ** when the expression node is.
  130018. */
  130019. struct Fts3Expr {
  130020. int eType; /* One of the FTSQUERY_XXX values defined below */
  130021. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  130022. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  130023. Fts3Expr *pLeft; /* Left operand */
  130024. Fts3Expr *pRight; /* Right operand */
  130025. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  130026. /* The following are used by the fts3_eval.c module. */
  130027. sqlite3_int64 iDocid; /* Current docid */
  130028. u8 bEof; /* True this expression is at EOF already */
  130029. u8 bStart; /* True if iDocid is valid */
  130030. u8 bDeferred; /* True if this expression is entirely deferred */
  130031. /* The following are used by the fts3_snippet.c module. */
  130032. int iPhrase; /* Index of this phrase in matchinfo() results */
  130033. u32 *aMI; /* See above */
  130034. };
  130035. /*
  130036. ** Candidate values for Fts3Query.eType. Note that the order of the first
  130037. ** four values is in order of precedence when parsing expressions. For
  130038. ** example, the following:
  130039. **
  130040. ** "a OR b AND c NOT d NEAR e"
  130041. **
  130042. ** is equivalent to:
  130043. **
  130044. ** "a OR (b AND (c NOT (d NEAR e)))"
  130045. */
  130046. #define FTSQUERY_NEAR 1
  130047. #define FTSQUERY_NOT 2
  130048. #define FTSQUERY_AND 3
  130049. #define FTSQUERY_OR 4
  130050. #define FTSQUERY_PHRASE 5
  130051. /* fts3_write.c */
  130052. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  130053. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  130054. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  130055. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  130056. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  130057. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  130058. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  130059. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  130060. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  130061. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  130062. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  130063. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  130064. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  130065. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  130066. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  130067. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  130068. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  130069. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  130070. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  130071. #else
  130072. # define sqlite3Fts3FreeDeferredTokens(x)
  130073. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  130074. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  130075. # define sqlite3Fts3FreeDeferredDoclists(x)
  130076. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  130077. #endif
  130078. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  130079. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  130080. /* Special values interpreted by sqlite3SegReaderCursor() */
  130081. #define FTS3_SEGCURSOR_PENDING -1
  130082. #define FTS3_SEGCURSOR_ALL -2
  130083. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  130084. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  130085. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  130086. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  130087. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  130088. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  130089. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  130090. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  130091. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  130092. #define FTS3_SEGMENT_PREFIX 0x00000008
  130093. #define FTS3_SEGMENT_SCAN 0x00000010
  130094. #define FTS3_SEGMENT_FIRST 0x00000020
  130095. /* Type passed as 4th argument to SegmentReaderIterate() */
  130096. struct Fts3SegFilter {
  130097. const char *zTerm;
  130098. int nTerm;
  130099. int iCol;
  130100. int flags;
  130101. };
  130102. struct Fts3MultiSegReader {
  130103. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  130104. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  130105. int nSegment; /* Size of apSegment array */
  130106. int nAdvance; /* How many seg-readers to advance */
  130107. Fts3SegFilter *pFilter; /* Pointer to filter object */
  130108. char *aBuffer; /* Buffer to merge doclists in */
  130109. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  130110. int iColFilter; /* If >=0, filter for this column */
  130111. int bRestart;
  130112. /* Used by fts3.c only. */
  130113. int nCost; /* Cost of running iterator */
  130114. int bLookup; /* True if a lookup of a single entry. */
  130115. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  130116. char *zTerm; /* Pointer to term buffer */
  130117. int nTerm; /* Size of zTerm in bytes */
  130118. char *aDoclist; /* Pointer to doclist buffer */
  130119. int nDoclist; /* Size of aDoclist[] in bytes */
  130120. };
  130121. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  130122. #define fts3GetVarint32(p, piVal) ( \
  130123. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  130124. )
  130125. /* fts3.c */
  130126. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  130127. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  130128. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  130129. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  130130. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  130131. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  130132. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  130133. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  130134. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  130135. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  130136. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  130137. /* fts3_tokenizer.c */
  130138. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  130139. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  130140. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  130141. sqlite3_tokenizer **, char **
  130142. );
  130143. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  130144. /* fts3_snippet.c */
  130145. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  130146. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  130147. const char *, const char *, int, int
  130148. );
  130149. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  130150. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  130151. /* fts3_expr.c */
  130152. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  130153. char **, int, int, int, const char *, int, Fts3Expr **, char **
  130154. );
  130155. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  130156. #ifdef SQLITE_TEST
  130157. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  130158. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  130159. #endif
  130160. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  130161. sqlite3_tokenizer_cursor **
  130162. );
  130163. /* fts3_aux.c */
  130164. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  130165. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  130166. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  130167. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  130168. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  130169. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  130170. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  130171. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  130172. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  130173. /* fts3_tokenize_vtab.c */
  130174. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  130175. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  130176. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  130177. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  130178. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  130179. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  130180. #endif
  130181. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  130182. #endif /* _FTSINT_H */
  130183. /************** End of fts3Int.h *********************************************/
  130184. /************** Continuing where we left off in fts3.c ***********************/
  130185. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130186. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  130187. # define SQLITE_CORE 1
  130188. #endif
  130189. /* #include <assert.h> */
  130190. /* #include <stdlib.h> */
  130191. /* #include <stddef.h> */
  130192. /* #include <stdio.h> */
  130193. /* #include <string.h> */
  130194. /* #include <stdarg.h> */
  130195. /* #include "fts3.h" */
  130196. #ifndef SQLITE_CORE
  130197. /* # include "sqlite3ext.h" */
  130198. SQLITE_EXTENSION_INIT1
  130199. #endif
  130200. static int fts3EvalNext(Fts3Cursor *pCsr);
  130201. static int fts3EvalStart(Fts3Cursor *pCsr);
  130202. static int fts3TermSegReaderCursor(
  130203. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  130204. #ifndef SQLITE_AMALGAMATION
  130205. # if defined(SQLITE_DEBUG)
  130206. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  130207. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  130208. # endif
  130209. #endif
  130210. /*
  130211. ** Write a 64-bit variable-length integer to memory starting at p[0].
  130212. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  130213. ** The number of bytes written is returned.
  130214. */
  130215. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  130216. unsigned char *q = (unsigned char *) p;
  130217. sqlite_uint64 vu = v;
  130218. do{
  130219. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  130220. vu >>= 7;
  130221. }while( vu!=0 );
  130222. q[-1] &= 0x7f; /* turn off high bit in final byte */
  130223. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  130224. return (int) (q - (unsigned char *)p);
  130225. }
  130226. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  130227. v = (v & mask1) | ( (*ptr++) << shift ); \
  130228. if( (v & mask2)==0 ){ var = v; return ret; }
  130229. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  130230. v = (*ptr++); \
  130231. if( (v & mask2)==0 ){ var = v; return ret; }
  130232. /*
  130233. ** Read a 64-bit variable-length integer from memory starting at p[0].
  130234. ** Return the number of bytes read, or 0 on error.
  130235. ** The value is stored in *v.
  130236. */
  130237. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  130238. const char *pStart = p;
  130239. u32 a;
  130240. u64 b;
  130241. int shift;
  130242. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  130243. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  130244. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  130245. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  130246. b = (a & 0x0FFFFFFF );
  130247. for(shift=28; shift<=63; shift+=7){
  130248. u64 c = *p++;
  130249. b += (c&0x7F) << shift;
  130250. if( (c & 0x80)==0 ) break;
  130251. }
  130252. *v = b;
  130253. return (int)(p - pStart);
  130254. }
  130255. /*
  130256. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  130257. ** 32-bit integer before it is returned.
  130258. */
  130259. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  130260. u32 a;
  130261. #ifndef fts3GetVarint32
  130262. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  130263. #else
  130264. a = (*p++);
  130265. assert( a & 0x80 );
  130266. #endif
  130267. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  130268. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  130269. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  130270. a = (a & 0x0FFFFFFF );
  130271. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  130272. return 5;
  130273. }
  130274. /*
  130275. ** Return the number of bytes required to encode v as a varint
  130276. */
  130277. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  130278. int i = 0;
  130279. do{
  130280. i++;
  130281. v >>= 7;
  130282. }while( v!=0 );
  130283. return i;
  130284. }
  130285. /*
  130286. ** Convert an SQL-style quoted string into a normal string by removing
  130287. ** the quote characters. The conversion is done in-place. If the
  130288. ** input does not begin with a quote character, then this routine
  130289. ** is a no-op.
  130290. **
  130291. ** Examples:
  130292. **
  130293. ** "abc" becomes abc
  130294. ** 'xyz' becomes xyz
  130295. ** [pqr] becomes pqr
  130296. ** `mno` becomes mno
  130297. **
  130298. */
  130299. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  130300. char quote; /* Quote character (if any ) */
  130301. quote = z[0];
  130302. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  130303. int iIn = 1; /* Index of next byte to read from input */
  130304. int iOut = 0; /* Index of next byte to write to output */
  130305. /* If the first byte was a '[', then the close-quote character is a ']' */
  130306. if( quote=='[' ) quote = ']';
  130307. while( z[iIn] ){
  130308. if( z[iIn]==quote ){
  130309. if( z[iIn+1]!=quote ) break;
  130310. z[iOut++] = quote;
  130311. iIn += 2;
  130312. }else{
  130313. z[iOut++] = z[iIn++];
  130314. }
  130315. }
  130316. z[iOut] = '\0';
  130317. }
  130318. }
  130319. /*
  130320. ** Read a single varint from the doclist at *pp and advance *pp to point
  130321. ** to the first byte past the end of the varint. Add the value of the varint
  130322. ** to *pVal.
  130323. */
  130324. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  130325. sqlite3_int64 iVal;
  130326. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  130327. *pVal += iVal;
  130328. }
  130329. /*
  130330. ** When this function is called, *pp points to the first byte following a
  130331. ** varint that is part of a doclist (or position-list, or any other list
  130332. ** of varints). This function moves *pp to point to the start of that varint,
  130333. ** and sets *pVal by the varint value.
  130334. **
  130335. ** Argument pStart points to the first byte of the doclist that the
  130336. ** varint is part of.
  130337. */
  130338. static void fts3GetReverseVarint(
  130339. char **pp,
  130340. char *pStart,
  130341. sqlite3_int64 *pVal
  130342. ){
  130343. sqlite3_int64 iVal;
  130344. char *p;
  130345. /* Pointer p now points at the first byte past the varint we are
  130346. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  130347. ** clear on character p[-1]. */
  130348. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  130349. p++;
  130350. *pp = p;
  130351. sqlite3Fts3GetVarint(p, &iVal);
  130352. *pVal = iVal;
  130353. }
  130354. /*
  130355. ** The xDisconnect() virtual table method.
  130356. */
  130357. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  130358. Fts3Table *p = (Fts3Table *)pVtab;
  130359. int i;
  130360. assert( p->nPendingData==0 );
  130361. assert( p->pSegments==0 );
  130362. /* Free any prepared statements held */
  130363. for(i=0; i<SizeofArray(p->aStmt); i++){
  130364. sqlite3_finalize(p->aStmt[i]);
  130365. }
  130366. sqlite3_free(p->zSegmentsTbl);
  130367. sqlite3_free(p->zReadExprlist);
  130368. sqlite3_free(p->zWriteExprlist);
  130369. sqlite3_free(p->zContentTbl);
  130370. sqlite3_free(p->zLanguageid);
  130371. /* Invoke the tokenizer destructor to free the tokenizer. */
  130372. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  130373. sqlite3_free(p);
  130374. return SQLITE_OK;
  130375. }
  130376. /*
  130377. ** Write an error message into *pzErr
  130378. */
  130379. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  130380. va_list ap;
  130381. sqlite3_free(*pzErr);
  130382. va_start(ap, zFormat);
  130383. *pzErr = sqlite3_vmprintf(zFormat, ap);
  130384. va_end(ap);
  130385. }
  130386. /*
  130387. ** Construct one or more SQL statements from the format string given
  130388. ** and then evaluate those statements. The success code is written
  130389. ** into *pRc.
  130390. **
  130391. ** If *pRc is initially non-zero then this routine is a no-op.
  130392. */
  130393. static void fts3DbExec(
  130394. int *pRc, /* Success code */
  130395. sqlite3 *db, /* Database in which to run SQL */
  130396. const char *zFormat, /* Format string for SQL */
  130397. ... /* Arguments to the format string */
  130398. ){
  130399. va_list ap;
  130400. char *zSql;
  130401. if( *pRc ) return;
  130402. va_start(ap, zFormat);
  130403. zSql = sqlite3_vmprintf(zFormat, ap);
  130404. va_end(ap);
  130405. if( zSql==0 ){
  130406. *pRc = SQLITE_NOMEM;
  130407. }else{
  130408. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  130409. sqlite3_free(zSql);
  130410. }
  130411. }
  130412. /*
  130413. ** The xDestroy() virtual table method.
  130414. */
  130415. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  130416. Fts3Table *p = (Fts3Table *)pVtab;
  130417. int rc = SQLITE_OK; /* Return code */
  130418. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  130419. sqlite3 *db = p->db; /* Database handle */
  130420. /* Drop the shadow tables */
  130421. if( p->zContentTbl==0 ){
  130422. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  130423. }
  130424. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  130425. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  130426. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  130427. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  130428. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  130429. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  130430. ** Otherwise, return an SQLite error code.
  130431. */
  130432. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  130433. }
  130434. /*
  130435. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  130436. ** passed as the first argument. This is done as part of the xConnect()
  130437. ** and xCreate() methods.
  130438. **
  130439. ** If *pRc is non-zero when this function is called, it is a no-op.
  130440. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  130441. ** before returning.
  130442. */
  130443. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  130444. if( *pRc==SQLITE_OK ){
  130445. int i; /* Iterator variable */
  130446. int rc; /* Return code */
  130447. char *zSql; /* SQL statement passed to declare_vtab() */
  130448. char *zCols; /* List of user defined columns */
  130449. const char *zLanguageid;
  130450. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  130451. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  130452. /* Create a list of user columns for the virtual table */
  130453. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  130454. for(i=1; zCols && i<p->nColumn; i++){
  130455. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  130456. }
  130457. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  130458. zSql = sqlite3_mprintf(
  130459. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  130460. zCols, p->zName, zLanguageid
  130461. );
  130462. if( !zCols || !zSql ){
  130463. rc = SQLITE_NOMEM;
  130464. }else{
  130465. rc = sqlite3_declare_vtab(p->db, zSql);
  130466. }
  130467. sqlite3_free(zSql);
  130468. sqlite3_free(zCols);
  130469. *pRc = rc;
  130470. }
  130471. }
  130472. /*
  130473. ** Create the %_stat table if it does not already exist.
  130474. */
  130475. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  130476. fts3DbExec(pRc, p->db,
  130477. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  130478. "(id INTEGER PRIMARY KEY, value BLOB);",
  130479. p->zDb, p->zName
  130480. );
  130481. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  130482. }
  130483. /*
  130484. ** Create the backing store tables (%_content, %_segments and %_segdir)
  130485. ** required by the FTS3 table passed as the only argument. This is done
  130486. ** as part of the vtab xCreate() method.
  130487. **
  130488. ** If the p->bHasDocsize boolean is true (indicating that this is an
  130489. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  130490. ** %_stat tables required by FTS4.
  130491. */
  130492. static int fts3CreateTables(Fts3Table *p){
  130493. int rc = SQLITE_OK; /* Return code */
  130494. int i; /* Iterator variable */
  130495. sqlite3 *db = p->db; /* The database connection */
  130496. if( p->zContentTbl==0 ){
  130497. const char *zLanguageid = p->zLanguageid;
  130498. char *zContentCols; /* Columns of %_content table */
  130499. /* Create a list of user columns for the content table */
  130500. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  130501. for(i=0; zContentCols && i<p->nColumn; i++){
  130502. char *z = p->azColumn[i];
  130503. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  130504. }
  130505. if( zLanguageid && zContentCols ){
  130506. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  130507. }
  130508. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  130509. /* Create the content table */
  130510. fts3DbExec(&rc, db,
  130511. "CREATE TABLE %Q.'%q_content'(%s)",
  130512. p->zDb, p->zName, zContentCols
  130513. );
  130514. sqlite3_free(zContentCols);
  130515. }
  130516. /* Create other tables */
  130517. fts3DbExec(&rc, db,
  130518. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  130519. p->zDb, p->zName
  130520. );
  130521. fts3DbExec(&rc, db,
  130522. "CREATE TABLE %Q.'%q_segdir'("
  130523. "level INTEGER,"
  130524. "idx INTEGER,"
  130525. "start_block INTEGER,"
  130526. "leaves_end_block INTEGER,"
  130527. "end_block INTEGER,"
  130528. "root BLOB,"
  130529. "PRIMARY KEY(level, idx)"
  130530. ");",
  130531. p->zDb, p->zName
  130532. );
  130533. if( p->bHasDocsize ){
  130534. fts3DbExec(&rc, db,
  130535. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  130536. p->zDb, p->zName
  130537. );
  130538. }
  130539. assert( p->bHasStat==p->bFts4 );
  130540. if( p->bHasStat ){
  130541. sqlite3Fts3CreateStatTable(&rc, p);
  130542. }
  130543. return rc;
  130544. }
  130545. /*
  130546. ** Store the current database page-size in bytes in p->nPgsz.
  130547. **
  130548. ** If *pRc is non-zero when this function is called, it is a no-op.
  130549. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  130550. ** before returning.
  130551. */
  130552. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  130553. if( *pRc==SQLITE_OK ){
  130554. int rc; /* Return code */
  130555. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  130556. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  130557. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  130558. if( !zSql ){
  130559. rc = SQLITE_NOMEM;
  130560. }else{
  130561. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  130562. if( rc==SQLITE_OK ){
  130563. sqlite3_step(pStmt);
  130564. p->nPgsz = sqlite3_column_int(pStmt, 0);
  130565. rc = sqlite3_finalize(pStmt);
  130566. }else if( rc==SQLITE_AUTH ){
  130567. p->nPgsz = 1024;
  130568. rc = SQLITE_OK;
  130569. }
  130570. }
  130571. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  130572. sqlite3_free(zSql);
  130573. *pRc = rc;
  130574. }
  130575. }
  130576. /*
  130577. ** "Special" FTS4 arguments are column specifications of the following form:
  130578. **
  130579. ** <key> = <value>
  130580. **
  130581. ** There may not be whitespace surrounding the "=" character. The <value>
  130582. ** term may be quoted, but the <key> may not.
  130583. */
  130584. static int fts3IsSpecialColumn(
  130585. const char *z,
  130586. int *pnKey,
  130587. char **pzValue
  130588. ){
  130589. char *zValue;
  130590. const char *zCsr = z;
  130591. while( *zCsr!='=' ){
  130592. if( *zCsr=='\0' ) return 0;
  130593. zCsr++;
  130594. }
  130595. *pnKey = (int)(zCsr-z);
  130596. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  130597. if( zValue ){
  130598. sqlite3Fts3Dequote(zValue);
  130599. }
  130600. *pzValue = zValue;
  130601. return 1;
  130602. }
  130603. /*
  130604. ** Append the output of a printf() style formatting to an existing string.
  130605. */
  130606. static void fts3Appendf(
  130607. int *pRc, /* IN/OUT: Error code */
  130608. char **pz, /* IN/OUT: Pointer to string buffer */
  130609. const char *zFormat, /* Printf format string to append */
  130610. ... /* Arguments for printf format string */
  130611. ){
  130612. if( *pRc==SQLITE_OK ){
  130613. va_list ap;
  130614. char *z;
  130615. va_start(ap, zFormat);
  130616. z = sqlite3_vmprintf(zFormat, ap);
  130617. va_end(ap);
  130618. if( z && *pz ){
  130619. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  130620. sqlite3_free(z);
  130621. z = z2;
  130622. }
  130623. if( z==0 ) *pRc = SQLITE_NOMEM;
  130624. sqlite3_free(*pz);
  130625. *pz = z;
  130626. }
  130627. }
  130628. /*
  130629. ** Return a copy of input string zInput enclosed in double-quotes (") and
  130630. ** with all double quote characters escaped. For example:
  130631. **
  130632. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  130633. **
  130634. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  130635. ** is the callers responsibility to call sqlite3_free() to release this
  130636. ** memory.
  130637. */
  130638. static char *fts3QuoteId(char const *zInput){
  130639. int nRet;
  130640. char *zRet;
  130641. nRet = 2 + (int)strlen(zInput)*2 + 1;
  130642. zRet = sqlite3_malloc(nRet);
  130643. if( zRet ){
  130644. int i;
  130645. char *z = zRet;
  130646. *(z++) = '"';
  130647. for(i=0; zInput[i]; i++){
  130648. if( zInput[i]=='"' ) *(z++) = '"';
  130649. *(z++) = zInput[i];
  130650. }
  130651. *(z++) = '"';
  130652. *(z++) = '\0';
  130653. }
  130654. return zRet;
  130655. }
  130656. /*
  130657. ** Return a list of comma separated SQL expressions and a FROM clause that
  130658. ** could be used in a SELECT statement such as the following:
  130659. **
  130660. ** SELECT <list of expressions> FROM %_content AS x ...
  130661. **
  130662. ** to return the docid, followed by each column of text data in order
  130663. ** from left to write. If parameter zFunc is not NULL, then instead of
  130664. ** being returned directly each column of text data is passed to an SQL
  130665. ** function named zFunc first. For example, if zFunc is "unzip" and the
  130666. ** table has the three user-defined columns "a", "b", and "c", the following
  130667. ** string is returned:
  130668. **
  130669. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  130670. **
  130671. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  130672. ** is the responsibility of the caller to eventually free it.
  130673. **
  130674. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  130675. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  130676. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  130677. ** no error occurs, *pRc is left unmodified.
  130678. */
  130679. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  130680. char *zRet = 0;
  130681. char *zFree = 0;
  130682. char *zFunction;
  130683. int i;
  130684. if( p->zContentTbl==0 ){
  130685. if( !zFunc ){
  130686. zFunction = "";
  130687. }else{
  130688. zFree = zFunction = fts3QuoteId(zFunc);
  130689. }
  130690. fts3Appendf(pRc, &zRet, "docid");
  130691. for(i=0; i<p->nColumn; i++){
  130692. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  130693. }
  130694. if( p->zLanguageid ){
  130695. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  130696. }
  130697. sqlite3_free(zFree);
  130698. }else{
  130699. fts3Appendf(pRc, &zRet, "rowid");
  130700. for(i=0; i<p->nColumn; i++){
  130701. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  130702. }
  130703. if( p->zLanguageid ){
  130704. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  130705. }
  130706. }
  130707. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  130708. p->zDb,
  130709. (p->zContentTbl ? p->zContentTbl : p->zName),
  130710. (p->zContentTbl ? "" : "_content")
  130711. );
  130712. return zRet;
  130713. }
  130714. /*
  130715. ** Return a list of N comma separated question marks, where N is the number
  130716. ** of columns in the %_content table (one for the docid plus one for each
  130717. ** user-defined text column).
  130718. **
  130719. ** If argument zFunc is not NULL, then all but the first question mark
  130720. ** is preceded by zFunc and an open bracket, and followed by a closed
  130721. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  130722. ** user-defined text columns, the following string is returned:
  130723. **
  130724. ** "?, zip(?), zip(?), zip(?)"
  130725. **
  130726. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  130727. ** is the responsibility of the caller to eventually free it.
  130728. **
  130729. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  130730. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  130731. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  130732. ** no error occurs, *pRc is left unmodified.
  130733. */
  130734. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  130735. char *zRet = 0;
  130736. char *zFree = 0;
  130737. char *zFunction;
  130738. int i;
  130739. if( !zFunc ){
  130740. zFunction = "";
  130741. }else{
  130742. zFree = zFunction = fts3QuoteId(zFunc);
  130743. }
  130744. fts3Appendf(pRc, &zRet, "?");
  130745. for(i=0; i<p->nColumn; i++){
  130746. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  130747. }
  130748. if( p->zLanguageid ){
  130749. fts3Appendf(pRc, &zRet, ", ?");
  130750. }
  130751. sqlite3_free(zFree);
  130752. return zRet;
  130753. }
  130754. /*
  130755. ** This function interprets the string at (*pp) as a non-negative integer
  130756. ** value. It reads the integer and sets *pnOut to the value read, then
  130757. ** sets *pp to point to the byte immediately following the last byte of
  130758. ** the integer value.
  130759. **
  130760. ** Only decimal digits ('0'..'9') may be part of an integer value.
  130761. **
  130762. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  130763. ** the output value undefined. Otherwise SQLITE_OK is returned.
  130764. **
  130765. ** This function is used when parsing the "prefix=" FTS4 parameter.
  130766. */
  130767. static int fts3GobbleInt(const char **pp, int *pnOut){
  130768. const int MAX_NPREFIX = 10000000;
  130769. const char *p; /* Iterator pointer */
  130770. int nInt = 0; /* Output value */
  130771. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  130772. nInt = nInt * 10 + (p[0] - '0');
  130773. if( nInt>MAX_NPREFIX ){
  130774. nInt = 0;
  130775. break;
  130776. }
  130777. }
  130778. if( p==*pp ) return SQLITE_ERROR;
  130779. *pnOut = nInt;
  130780. *pp = p;
  130781. return SQLITE_OK;
  130782. }
  130783. /*
  130784. ** This function is called to allocate an array of Fts3Index structures
  130785. ** representing the indexes maintained by the current FTS table. FTS tables
  130786. ** always maintain the main "terms" index, but may also maintain one or
  130787. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  130788. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  130789. **
  130790. ** Argument zParam is passed the value of the "prefix=" option if one was
  130791. ** specified, or NULL otherwise.
  130792. **
  130793. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  130794. ** the allocated array. *pnIndex is set to the number of elements in the
  130795. ** array. If an error does occur, an SQLite error code is returned.
  130796. **
  130797. ** Regardless of whether or not an error is returned, it is the responsibility
  130798. ** of the caller to call sqlite3_free() on the output array to free it.
  130799. */
  130800. static int fts3PrefixParameter(
  130801. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  130802. int *pnIndex, /* OUT: size of *apIndex[] array */
  130803. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  130804. ){
  130805. struct Fts3Index *aIndex; /* Allocated array */
  130806. int nIndex = 1; /* Number of entries in array */
  130807. if( zParam && zParam[0] ){
  130808. const char *p;
  130809. nIndex++;
  130810. for(p=zParam; *p; p++){
  130811. if( *p==',' ) nIndex++;
  130812. }
  130813. }
  130814. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  130815. *apIndex = aIndex;
  130816. if( !aIndex ){
  130817. return SQLITE_NOMEM;
  130818. }
  130819. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  130820. if( zParam ){
  130821. const char *p = zParam;
  130822. int i;
  130823. for(i=1; i<nIndex; i++){
  130824. int nPrefix = 0;
  130825. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  130826. assert( nPrefix>=0 );
  130827. if( nPrefix==0 ){
  130828. nIndex--;
  130829. i--;
  130830. }else{
  130831. aIndex[i].nPrefix = nPrefix;
  130832. }
  130833. p++;
  130834. }
  130835. }
  130836. *pnIndex = nIndex;
  130837. return SQLITE_OK;
  130838. }
  130839. /*
  130840. ** This function is called when initializing an FTS4 table that uses the
  130841. ** content=xxx option. It determines the number of and names of the columns
  130842. ** of the new FTS4 table.
  130843. **
  130844. ** The third argument passed to this function is the value passed to the
  130845. ** config=xxx option (i.e. "xxx"). This function queries the database for
  130846. ** a table of that name. If found, the output variables are populated
  130847. ** as follows:
  130848. **
  130849. ** *pnCol: Set to the number of columns table xxx has,
  130850. **
  130851. ** *pnStr: Set to the total amount of space required to store a copy
  130852. ** of each columns name, including the nul-terminator.
  130853. **
  130854. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  130855. ** the name of the corresponding column in table xxx. The array
  130856. ** and its contents are allocated using a single allocation. It
  130857. ** is the responsibility of the caller to free this allocation
  130858. ** by eventually passing the *pazCol value to sqlite3_free().
  130859. **
  130860. ** If the table cannot be found, an error code is returned and the output
  130861. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  130862. ** returned (and the output variables are undefined).
  130863. */
  130864. static int fts3ContentColumns(
  130865. sqlite3 *db, /* Database handle */
  130866. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  130867. const char *zTbl, /* Name of content table */
  130868. const char ***pazCol, /* OUT: Malloc'd array of column names */
  130869. int *pnCol, /* OUT: Size of array *pazCol */
  130870. int *pnStr, /* OUT: Bytes of string content */
  130871. char **pzErr /* OUT: error message */
  130872. ){
  130873. int rc = SQLITE_OK; /* Return code */
  130874. char *zSql; /* "SELECT *" statement on zTbl */
  130875. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  130876. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  130877. if( !zSql ){
  130878. rc = SQLITE_NOMEM;
  130879. }else{
  130880. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  130881. if( rc!=SQLITE_OK ){
  130882. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  130883. }
  130884. }
  130885. sqlite3_free(zSql);
  130886. if( rc==SQLITE_OK ){
  130887. const char **azCol; /* Output array */
  130888. int nStr = 0; /* Size of all column names (incl. 0x00) */
  130889. int nCol; /* Number of table columns */
  130890. int i; /* Used to iterate through columns */
  130891. /* Loop through the returned columns. Set nStr to the number of bytes of
  130892. ** space required to store a copy of each column name, including the
  130893. ** nul-terminator byte. */
  130894. nCol = sqlite3_column_count(pStmt);
  130895. for(i=0; i<nCol; i++){
  130896. const char *zCol = sqlite3_column_name(pStmt, i);
  130897. nStr += (int)strlen(zCol) + 1;
  130898. }
  130899. /* Allocate and populate the array to return. */
  130900. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  130901. if( azCol==0 ){
  130902. rc = SQLITE_NOMEM;
  130903. }else{
  130904. char *p = (char *)&azCol[nCol];
  130905. for(i=0; i<nCol; i++){
  130906. const char *zCol = sqlite3_column_name(pStmt, i);
  130907. int n = (int)strlen(zCol)+1;
  130908. memcpy(p, zCol, n);
  130909. azCol[i] = p;
  130910. p += n;
  130911. }
  130912. }
  130913. sqlite3_finalize(pStmt);
  130914. /* Set the output variables. */
  130915. *pnCol = nCol;
  130916. *pnStr = nStr;
  130917. *pazCol = azCol;
  130918. }
  130919. return rc;
  130920. }
  130921. /*
  130922. ** This function is the implementation of both the xConnect and xCreate
  130923. ** methods of the FTS3 virtual table.
  130924. **
  130925. ** The argv[] array contains the following:
  130926. **
  130927. ** argv[0] -> module name ("fts3" or "fts4")
  130928. ** argv[1] -> database name
  130929. ** argv[2] -> table name
  130930. ** argv[...] -> "column name" and other module argument fields.
  130931. */
  130932. static int fts3InitVtab(
  130933. int isCreate, /* True for xCreate, false for xConnect */
  130934. sqlite3 *db, /* The SQLite database connection */
  130935. void *pAux, /* Hash table containing tokenizers */
  130936. int argc, /* Number of elements in argv array */
  130937. const char * const *argv, /* xCreate/xConnect argument array */
  130938. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  130939. char **pzErr /* Write any error message here */
  130940. ){
  130941. Fts3Hash *pHash = (Fts3Hash *)pAux;
  130942. Fts3Table *p = 0; /* Pointer to allocated vtab */
  130943. int rc = SQLITE_OK; /* Return code */
  130944. int i; /* Iterator variable */
  130945. int nByte; /* Size of allocation used for *p */
  130946. int iCol; /* Column index */
  130947. int nString = 0; /* Bytes required to hold all column names */
  130948. int nCol = 0; /* Number of columns in the FTS table */
  130949. char *zCsr; /* Space for holding column names */
  130950. int nDb; /* Bytes required to hold database name */
  130951. int nName; /* Bytes required to hold table name */
  130952. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  130953. const char **aCol; /* Array of column names */
  130954. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  130955. int nIndex = 0; /* Size of aIndex[] array */
  130956. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  130957. /* The results of parsing supported FTS4 key=value options: */
  130958. int bNoDocsize = 0; /* True to omit %_docsize table */
  130959. int bDescIdx = 0; /* True to store descending indexes */
  130960. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  130961. char *zCompress = 0; /* compress=? parameter (or NULL) */
  130962. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  130963. char *zContent = 0; /* content=? parameter (or NULL) */
  130964. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  130965. char **azNotindexed = 0; /* The set of notindexed= columns */
  130966. int nNotindexed = 0; /* Size of azNotindexed[] array */
  130967. assert( strlen(argv[0])==4 );
  130968. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  130969. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  130970. );
  130971. nDb = (int)strlen(argv[1]) + 1;
  130972. nName = (int)strlen(argv[2]) + 1;
  130973. nByte = sizeof(const char *) * (argc-2);
  130974. aCol = (const char **)sqlite3_malloc(nByte);
  130975. if( aCol ){
  130976. memset((void*)aCol, 0, nByte);
  130977. azNotindexed = (char **)sqlite3_malloc(nByte);
  130978. }
  130979. if( azNotindexed ){
  130980. memset(azNotindexed, 0, nByte);
  130981. }
  130982. if( !aCol || !azNotindexed ){
  130983. rc = SQLITE_NOMEM;
  130984. goto fts3_init_out;
  130985. }
  130986. /* Loop through all of the arguments passed by the user to the FTS3/4
  130987. ** module (i.e. all the column names and special arguments). This loop
  130988. ** does the following:
  130989. **
  130990. ** + Figures out the number of columns the FTSX table will have, and
  130991. ** the number of bytes of space that must be allocated to store copies
  130992. ** of the column names.
  130993. **
  130994. ** + If there is a tokenizer specification included in the arguments,
  130995. ** initializes the tokenizer pTokenizer.
  130996. */
  130997. for(i=3; rc==SQLITE_OK && i<argc; i++){
  130998. char const *z = argv[i];
  130999. int nKey;
  131000. char *zVal;
  131001. /* Check if this is a tokenizer specification */
  131002. if( !pTokenizer
  131003. && strlen(z)>8
  131004. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  131005. && 0==sqlite3Fts3IsIdChar(z[8])
  131006. ){
  131007. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  131008. }
  131009. /* Check if it is an FTS4 special argument. */
  131010. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  131011. struct Fts4Option {
  131012. const char *zOpt;
  131013. int nOpt;
  131014. } aFts4Opt[] = {
  131015. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  131016. { "prefix", 6 }, /* 1 -> PREFIX */
  131017. { "compress", 8 }, /* 2 -> COMPRESS */
  131018. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  131019. { "order", 5 }, /* 4 -> ORDER */
  131020. { "content", 7 }, /* 5 -> CONTENT */
  131021. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  131022. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  131023. };
  131024. int iOpt;
  131025. if( !zVal ){
  131026. rc = SQLITE_NOMEM;
  131027. }else{
  131028. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  131029. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  131030. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  131031. break;
  131032. }
  131033. }
  131034. if( iOpt==SizeofArray(aFts4Opt) ){
  131035. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  131036. rc = SQLITE_ERROR;
  131037. }else{
  131038. switch( iOpt ){
  131039. case 0: /* MATCHINFO */
  131040. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  131041. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  131042. rc = SQLITE_ERROR;
  131043. }
  131044. bNoDocsize = 1;
  131045. break;
  131046. case 1: /* PREFIX */
  131047. sqlite3_free(zPrefix);
  131048. zPrefix = zVal;
  131049. zVal = 0;
  131050. break;
  131051. case 2: /* COMPRESS */
  131052. sqlite3_free(zCompress);
  131053. zCompress = zVal;
  131054. zVal = 0;
  131055. break;
  131056. case 3: /* UNCOMPRESS */
  131057. sqlite3_free(zUncompress);
  131058. zUncompress = zVal;
  131059. zVal = 0;
  131060. break;
  131061. case 4: /* ORDER */
  131062. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  131063. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  131064. ){
  131065. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  131066. rc = SQLITE_ERROR;
  131067. }
  131068. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  131069. break;
  131070. case 5: /* CONTENT */
  131071. sqlite3_free(zContent);
  131072. zContent = zVal;
  131073. zVal = 0;
  131074. break;
  131075. case 6: /* LANGUAGEID */
  131076. assert( iOpt==6 );
  131077. sqlite3_free(zLanguageid);
  131078. zLanguageid = zVal;
  131079. zVal = 0;
  131080. break;
  131081. case 7: /* NOTINDEXED */
  131082. azNotindexed[nNotindexed++] = zVal;
  131083. zVal = 0;
  131084. break;
  131085. }
  131086. }
  131087. sqlite3_free(zVal);
  131088. }
  131089. }
  131090. /* Otherwise, the argument is a column name. */
  131091. else {
  131092. nString += (int)(strlen(z) + 1);
  131093. aCol[nCol++] = z;
  131094. }
  131095. }
  131096. /* If a content=xxx option was specified, the following:
  131097. **
  131098. ** 1. Ignore any compress= and uncompress= options.
  131099. **
  131100. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  131101. ** TABLE statement, use all columns from the content table.
  131102. */
  131103. if( rc==SQLITE_OK && zContent ){
  131104. sqlite3_free(zCompress);
  131105. sqlite3_free(zUncompress);
  131106. zCompress = 0;
  131107. zUncompress = 0;
  131108. if( nCol==0 ){
  131109. sqlite3_free((void*)aCol);
  131110. aCol = 0;
  131111. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  131112. /* If a languageid= option was specified, remove the language id
  131113. ** column from the aCol[] array. */
  131114. if( rc==SQLITE_OK && zLanguageid ){
  131115. int j;
  131116. for(j=0; j<nCol; j++){
  131117. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  131118. int k;
  131119. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  131120. nCol--;
  131121. break;
  131122. }
  131123. }
  131124. }
  131125. }
  131126. }
  131127. if( rc!=SQLITE_OK ) goto fts3_init_out;
  131128. if( nCol==0 ){
  131129. assert( nString==0 );
  131130. aCol[0] = "content";
  131131. nString = 8;
  131132. nCol = 1;
  131133. }
  131134. if( pTokenizer==0 ){
  131135. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  131136. if( rc!=SQLITE_OK ) goto fts3_init_out;
  131137. }
  131138. assert( pTokenizer );
  131139. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  131140. if( rc==SQLITE_ERROR ){
  131141. assert( zPrefix );
  131142. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  131143. }
  131144. if( rc!=SQLITE_OK ) goto fts3_init_out;
  131145. /* Allocate and populate the Fts3Table structure. */
  131146. nByte = sizeof(Fts3Table) + /* Fts3Table */
  131147. nCol * sizeof(char *) + /* azColumn */
  131148. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  131149. nCol * sizeof(u8) + /* abNotindexed */
  131150. nName + /* zName */
  131151. nDb + /* zDb */
  131152. nString; /* Space for azColumn strings */
  131153. p = (Fts3Table*)sqlite3_malloc(nByte);
  131154. if( p==0 ){
  131155. rc = SQLITE_NOMEM;
  131156. goto fts3_init_out;
  131157. }
  131158. memset(p, 0, nByte);
  131159. p->db = db;
  131160. p->nColumn = nCol;
  131161. p->nPendingData = 0;
  131162. p->azColumn = (char **)&p[1];
  131163. p->pTokenizer = pTokenizer;
  131164. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  131165. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  131166. p->bHasStat = isFts4;
  131167. p->bFts4 = isFts4;
  131168. p->bDescIdx = bDescIdx;
  131169. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  131170. p->zContentTbl = zContent;
  131171. p->zLanguageid = zLanguageid;
  131172. zContent = 0;
  131173. zLanguageid = 0;
  131174. TESTONLY( p->inTransaction = -1 );
  131175. TESTONLY( p->mxSavepoint = -1 );
  131176. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  131177. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  131178. p->nIndex = nIndex;
  131179. for(i=0; i<nIndex; i++){
  131180. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  131181. }
  131182. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  131183. /* Fill in the zName and zDb fields of the vtab structure. */
  131184. zCsr = (char *)&p->abNotindexed[nCol];
  131185. p->zName = zCsr;
  131186. memcpy(zCsr, argv[2], nName);
  131187. zCsr += nName;
  131188. p->zDb = zCsr;
  131189. memcpy(zCsr, argv[1], nDb);
  131190. zCsr += nDb;
  131191. /* Fill in the azColumn array */
  131192. for(iCol=0; iCol<nCol; iCol++){
  131193. char *z;
  131194. int n = 0;
  131195. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  131196. memcpy(zCsr, z, n);
  131197. zCsr[n] = '\0';
  131198. sqlite3Fts3Dequote(zCsr);
  131199. p->azColumn[iCol] = zCsr;
  131200. zCsr += n+1;
  131201. assert( zCsr <= &((char *)p)[nByte] );
  131202. }
  131203. /* Fill in the abNotindexed array */
  131204. for(iCol=0; iCol<nCol; iCol++){
  131205. int n = (int)strlen(p->azColumn[iCol]);
  131206. for(i=0; i<nNotindexed; i++){
  131207. char *zNot = azNotindexed[i];
  131208. if( zNot && n==(int)strlen(zNot)
  131209. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  131210. ){
  131211. p->abNotindexed[iCol] = 1;
  131212. sqlite3_free(zNot);
  131213. azNotindexed[i] = 0;
  131214. }
  131215. }
  131216. }
  131217. for(i=0; i<nNotindexed; i++){
  131218. if( azNotindexed[i] ){
  131219. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  131220. rc = SQLITE_ERROR;
  131221. }
  131222. }
  131223. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  131224. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  131225. rc = SQLITE_ERROR;
  131226. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  131227. }
  131228. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  131229. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  131230. if( rc!=SQLITE_OK ) goto fts3_init_out;
  131231. /* If this is an xCreate call, create the underlying tables in the
  131232. ** database. TODO: For xConnect(), it could verify that said tables exist.
  131233. */
  131234. if( isCreate ){
  131235. rc = fts3CreateTables(p);
  131236. }
  131237. /* Check to see if a legacy fts3 table has been "upgraded" by the
  131238. ** addition of a %_stat table so that it can use incremental merge.
  131239. */
  131240. if( !isFts4 && !isCreate ){
  131241. p->bHasStat = 2;
  131242. }
  131243. /* Figure out the page-size for the database. This is required in order to
  131244. ** estimate the cost of loading large doclists from the database. */
  131245. fts3DatabasePageSize(&rc, p);
  131246. p->nNodeSize = p->nPgsz-35;
  131247. /* Declare the table schema to SQLite. */
  131248. fts3DeclareVtab(&rc, p);
  131249. fts3_init_out:
  131250. sqlite3_free(zPrefix);
  131251. sqlite3_free(aIndex);
  131252. sqlite3_free(zCompress);
  131253. sqlite3_free(zUncompress);
  131254. sqlite3_free(zContent);
  131255. sqlite3_free(zLanguageid);
  131256. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  131257. sqlite3_free((void *)aCol);
  131258. sqlite3_free((void *)azNotindexed);
  131259. if( rc!=SQLITE_OK ){
  131260. if( p ){
  131261. fts3DisconnectMethod((sqlite3_vtab *)p);
  131262. }else if( pTokenizer ){
  131263. pTokenizer->pModule->xDestroy(pTokenizer);
  131264. }
  131265. }else{
  131266. assert( p->pSegments==0 );
  131267. *ppVTab = &p->base;
  131268. }
  131269. return rc;
  131270. }
  131271. /*
  131272. ** The xConnect() and xCreate() methods for the virtual table. All the
  131273. ** work is done in function fts3InitVtab().
  131274. */
  131275. static int fts3ConnectMethod(
  131276. sqlite3 *db, /* Database connection */
  131277. void *pAux, /* Pointer to tokenizer hash table */
  131278. int argc, /* Number of elements in argv array */
  131279. const char * const *argv, /* xCreate/xConnect argument array */
  131280. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  131281. char **pzErr /* OUT: sqlite3_malloc'd error message */
  131282. ){
  131283. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  131284. }
  131285. static int fts3CreateMethod(
  131286. sqlite3 *db, /* Database connection */
  131287. void *pAux, /* Pointer to tokenizer hash table */
  131288. int argc, /* Number of elements in argv array */
  131289. const char * const *argv, /* xCreate/xConnect argument array */
  131290. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  131291. char **pzErr /* OUT: sqlite3_malloc'd error message */
  131292. ){
  131293. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  131294. }
  131295. /*
  131296. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  131297. ** extension is currently being used by a version of SQLite too old to
  131298. ** support estimatedRows. In that case this function is a no-op.
  131299. */
  131300. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  131301. #if SQLITE_VERSION_NUMBER>=3008002
  131302. if( sqlite3_libversion_number()>=3008002 ){
  131303. pIdxInfo->estimatedRows = nRow;
  131304. }
  131305. #endif
  131306. }
  131307. /*
  131308. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  131309. ** extension is currently being used by a version of SQLite too old to
  131310. ** support index-info flags. In that case this function is a no-op.
  131311. */
  131312. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  131313. #if SQLITE_VERSION_NUMBER>=3008012
  131314. if( sqlite3_libversion_number()>=3008012 ){
  131315. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  131316. }
  131317. #endif
  131318. }
  131319. /*
  131320. ** Implementation of the xBestIndex method for FTS3 tables. There
  131321. ** are three possible strategies, in order of preference:
  131322. **
  131323. ** 1. Direct lookup by rowid or docid.
  131324. ** 2. Full-text search using a MATCH operator on a non-docid column.
  131325. ** 3. Linear scan of %_content table.
  131326. */
  131327. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  131328. Fts3Table *p = (Fts3Table *)pVTab;
  131329. int i; /* Iterator variable */
  131330. int iCons = -1; /* Index of constraint to use */
  131331. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  131332. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  131333. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  131334. int iIdx;
  131335. /* By default use a full table scan. This is an expensive option,
  131336. ** so search through the constraints to see if a more efficient
  131337. ** strategy is possible.
  131338. */
  131339. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  131340. pInfo->estimatedCost = 5000000;
  131341. for(i=0; i<pInfo->nConstraint; i++){
  131342. int bDocid; /* True if this constraint is on docid */
  131343. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  131344. if( pCons->usable==0 ){
  131345. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  131346. /* There exists an unusable MATCH constraint. This means that if
  131347. ** the planner does elect to use the results of this call as part
  131348. ** of the overall query plan the user will see an "unable to use
  131349. ** function MATCH in the requested context" error. To discourage
  131350. ** this, return a very high cost here. */
  131351. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  131352. pInfo->estimatedCost = 1e50;
  131353. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  131354. return SQLITE_OK;
  131355. }
  131356. continue;
  131357. }
  131358. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  131359. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  131360. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  131361. pInfo->idxNum = FTS3_DOCID_SEARCH;
  131362. pInfo->estimatedCost = 1.0;
  131363. iCons = i;
  131364. }
  131365. /* A MATCH constraint. Use a full-text search.
  131366. **
  131367. ** If there is more than one MATCH constraint available, use the first
  131368. ** one encountered. If there is both a MATCH constraint and a direct
  131369. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  131370. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  131371. ** it would lead to an "unable to use function MATCH in the requested
  131372. ** context" error.
  131373. */
  131374. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  131375. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  131376. ){
  131377. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  131378. pInfo->estimatedCost = 2.0;
  131379. iCons = i;
  131380. }
  131381. /* Equality constraint on the langid column */
  131382. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  131383. && pCons->iColumn==p->nColumn + 2
  131384. ){
  131385. iLangidCons = i;
  131386. }
  131387. if( bDocid ){
  131388. switch( pCons->op ){
  131389. case SQLITE_INDEX_CONSTRAINT_GE:
  131390. case SQLITE_INDEX_CONSTRAINT_GT:
  131391. iDocidGe = i;
  131392. break;
  131393. case SQLITE_INDEX_CONSTRAINT_LE:
  131394. case SQLITE_INDEX_CONSTRAINT_LT:
  131395. iDocidLe = i;
  131396. break;
  131397. }
  131398. }
  131399. }
  131400. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  131401. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  131402. iIdx = 1;
  131403. if( iCons>=0 ){
  131404. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  131405. pInfo->aConstraintUsage[iCons].omit = 1;
  131406. }
  131407. if( iLangidCons>=0 ){
  131408. pInfo->idxNum |= FTS3_HAVE_LANGID;
  131409. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  131410. }
  131411. if( iDocidGe>=0 ){
  131412. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  131413. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  131414. }
  131415. if( iDocidLe>=0 ){
  131416. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  131417. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  131418. }
  131419. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  131420. ** docid) order. Both ascending and descending are possible.
  131421. */
  131422. if( pInfo->nOrderBy==1 ){
  131423. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  131424. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  131425. if( pOrder->desc ){
  131426. pInfo->idxStr = "DESC";
  131427. }else{
  131428. pInfo->idxStr = "ASC";
  131429. }
  131430. pInfo->orderByConsumed = 1;
  131431. }
  131432. }
  131433. assert( p->pSegments==0 );
  131434. return SQLITE_OK;
  131435. }
  131436. /*
  131437. ** Implementation of xOpen method.
  131438. */
  131439. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  131440. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  131441. UNUSED_PARAMETER(pVTab);
  131442. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  131443. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  131444. ** if the allocation fails, return SQLITE_NOMEM.
  131445. */
  131446. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  131447. if( !pCsr ){
  131448. return SQLITE_NOMEM;
  131449. }
  131450. memset(pCsr, 0, sizeof(Fts3Cursor));
  131451. return SQLITE_OK;
  131452. }
  131453. /*
  131454. ** Close the cursor. For additional information see the documentation
  131455. ** on the xClose method of the virtual table interface.
  131456. */
  131457. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  131458. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  131459. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  131460. sqlite3_finalize(pCsr->pStmt);
  131461. sqlite3Fts3ExprFree(pCsr->pExpr);
  131462. sqlite3Fts3FreeDeferredTokens(pCsr);
  131463. sqlite3_free(pCsr->aDoclist);
  131464. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  131465. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  131466. sqlite3_free(pCsr);
  131467. return SQLITE_OK;
  131468. }
  131469. /*
  131470. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  131471. ** compose and prepare an SQL statement of the form:
  131472. **
  131473. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  131474. **
  131475. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  131476. ** it. If an error occurs, return an SQLite error code.
  131477. **
  131478. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  131479. */
  131480. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  131481. int rc = SQLITE_OK;
  131482. if( pCsr->pStmt==0 ){
  131483. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  131484. char *zSql;
  131485. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  131486. if( !zSql ) return SQLITE_NOMEM;
  131487. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  131488. sqlite3_free(zSql);
  131489. }
  131490. *ppStmt = pCsr->pStmt;
  131491. return rc;
  131492. }
  131493. /*
  131494. ** Position the pCsr->pStmt statement so that it is on the row
  131495. ** of the %_content table that contains the last match. Return
  131496. ** SQLITE_OK on success.
  131497. */
  131498. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  131499. int rc = SQLITE_OK;
  131500. if( pCsr->isRequireSeek ){
  131501. sqlite3_stmt *pStmt = 0;
  131502. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  131503. if( rc==SQLITE_OK ){
  131504. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  131505. pCsr->isRequireSeek = 0;
  131506. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  131507. return SQLITE_OK;
  131508. }else{
  131509. rc = sqlite3_reset(pCsr->pStmt);
  131510. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  131511. /* If no row was found and no error has occurred, then the %_content
  131512. ** table is missing a row that is present in the full-text index.
  131513. ** The data structures are corrupt. */
  131514. rc = FTS_CORRUPT_VTAB;
  131515. pCsr->isEof = 1;
  131516. }
  131517. }
  131518. }
  131519. }
  131520. if( rc!=SQLITE_OK && pContext ){
  131521. sqlite3_result_error_code(pContext, rc);
  131522. }
  131523. return rc;
  131524. }
  131525. /*
  131526. ** This function is used to process a single interior node when searching
  131527. ** a b-tree for a term or term prefix. The node data is passed to this
  131528. ** function via the zNode/nNode parameters. The term to search for is
  131529. ** passed in zTerm/nTerm.
  131530. **
  131531. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  131532. ** of the child node that heads the sub-tree that may contain the term.
  131533. **
  131534. ** If piLast is not NULL, then *piLast is set to the right-most child node
  131535. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  131536. ** a prefix.
  131537. **
  131538. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  131539. */
  131540. static int fts3ScanInteriorNode(
  131541. const char *zTerm, /* Term to select leaves for */
  131542. int nTerm, /* Size of term zTerm in bytes */
  131543. const char *zNode, /* Buffer containing segment interior node */
  131544. int nNode, /* Size of buffer at zNode */
  131545. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  131546. sqlite3_int64 *piLast /* OUT: Selected child node */
  131547. ){
  131548. int rc = SQLITE_OK; /* Return code */
  131549. const char *zCsr = zNode; /* Cursor to iterate through node */
  131550. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  131551. char *zBuffer = 0; /* Buffer to load terms into */
  131552. int nAlloc = 0; /* Size of allocated buffer */
  131553. int isFirstTerm = 1; /* True when processing first term on page */
  131554. sqlite3_int64 iChild; /* Block id of child node to descend to */
  131555. /* Skip over the 'height' varint that occurs at the start of every
  131556. ** interior node. Then load the blockid of the left-child of the b-tree
  131557. ** node into variable iChild.
  131558. **
  131559. ** Even if the data structure on disk is corrupted, this (reading two
  131560. ** varints from the buffer) does not risk an overread. If zNode is a
  131561. ** root node, then the buffer comes from a SELECT statement. SQLite does
  131562. ** not make this guarantee explicitly, but in practice there are always
  131563. ** either more than 20 bytes of allocated space following the nNode bytes of
  131564. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  131565. ** table, then there are always 20 bytes of zeroed padding following the
  131566. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  131567. */
  131568. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  131569. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  131570. if( zCsr>zEnd ){
  131571. return FTS_CORRUPT_VTAB;
  131572. }
  131573. while( zCsr<zEnd && (piFirst || piLast) ){
  131574. int cmp; /* memcmp() result */
  131575. int nSuffix; /* Size of term suffix */
  131576. int nPrefix = 0; /* Size of term prefix */
  131577. int nBuffer; /* Total term size */
  131578. /* Load the next term on the node into zBuffer. Use realloc() to expand
  131579. ** the size of zBuffer if required. */
  131580. if( !isFirstTerm ){
  131581. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  131582. }
  131583. isFirstTerm = 0;
  131584. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  131585. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  131586. rc = FTS_CORRUPT_VTAB;
  131587. goto finish_scan;
  131588. }
  131589. if( nPrefix+nSuffix>nAlloc ){
  131590. char *zNew;
  131591. nAlloc = (nPrefix+nSuffix) * 2;
  131592. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  131593. if( !zNew ){
  131594. rc = SQLITE_NOMEM;
  131595. goto finish_scan;
  131596. }
  131597. zBuffer = zNew;
  131598. }
  131599. assert( zBuffer );
  131600. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  131601. nBuffer = nPrefix + nSuffix;
  131602. zCsr += nSuffix;
  131603. /* Compare the term we are searching for with the term just loaded from
  131604. ** the interior node. If the specified term is greater than or equal
  131605. ** to the term from the interior node, then all terms on the sub-tree
  131606. ** headed by node iChild are smaller than zTerm. No need to search
  131607. ** iChild.
  131608. **
  131609. ** If the interior node term is larger than the specified term, then
  131610. ** the tree headed by iChild may contain the specified term.
  131611. */
  131612. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  131613. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  131614. *piFirst = iChild;
  131615. piFirst = 0;
  131616. }
  131617. if( piLast && cmp<0 ){
  131618. *piLast = iChild;
  131619. piLast = 0;
  131620. }
  131621. iChild++;
  131622. };
  131623. if( piFirst ) *piFirst = iChild;
  131624. if( piLast ) *piLast = iChild;
  131625. finish_scan:
  131626. sqlite3_free(zBuffer);
  131627. return rc;
  131628. }
  131629. /*
  131630. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  131631. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  131632. ** contains a term. This function searches the sub-tree headed by the zNode
  131633. ** node for the range of leaf nodes that may contain the specified term
  131634. ** or terms for which the specified term is a prefix.
  131635. **
  131636. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  131637. ** left-most leaf node in the tree that may contain the specified term.
  131638. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  131639. ** right-most leaf node that may contain a term for which the specified
  131640. ** term is a prefix.
  131641. **
  131642. ** It is possible that the range of returned leaf nodes does not contain
  131643. ** the specified term or any terms for which it is a prefix. However, if the
  131644. ** segment does contain any such terms, they are stored within the identified
  131645. ** range. Because this function only inspects interior segment nodes (and
  131646. ** never loads leaf nodes into memory), it is not possible to be sure.
  131647. **
  131648. ** If an error occurs, an error code other than SQLITE_OK is returned.
  131649. */
  131650. static int fts3SelectLeaf(
  131651. Fts3Table *p, /* Virtual table handle */
  131652. const char *zTerm, /* Term to select leaves for */
  131653. int nTerm, /* Size of term zTerm in bytes */
  131654. const char *zNode, /* Buffer containing segment interior node */
  131655. int nNode, /* Size of buffer at zNode */
  131656. sqlite3_int64 *piLeaf, /* Selected leaf node */
  131657. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  131658. ){
  131659. int rc = SQLITE_OK; /* Return code */
  131660. int iHeight; /* Height of this node in tree */
  131661. assert( piLeaf || piLeaf2 );
  131662. fts3GetVarint32(zNode, &iHeight);
  131663. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  131664. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  131665. if( rc==SQLITE_OK && iHeight>1 ){
  131666. char *zBlob = 0; /* Blob read from %_segments table */
  131667. int nBlob = 0; /* Size of zBlob in bytes */
  131668. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  131669. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  131670. if( rc==SQLITE_OK ){
  131671. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  131672. }
  131673. sqlite3_free(zBlob);
  131674. piLeaf = 0;
  131675. zBlob = 0;
  131676. }
  131677. if( rc==SQLITE_OK ){
  131678. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  131679. }
  131680. if( rc==SQLITE_OK ){
  131681. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  131682. }
  131683. sqlite3_free(zBlob);
  131684. }
  131685. return rc;
  131686. }
  131687. /*
  131688. ** This function is used to create delta-encoded serialized lists of FTS3
  131689. ** varints. Each call to this function appends a single varint to a list.
  131690. */
  131691. static void fts3PutDeltaVarint(
  131692. char **pp, /* IN/OUT: Output pointer */
  131693. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  131694. sqlite3_int64 iVal /* Write this value to the list */
  131695. ){
  131696. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  131697. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  131698. *piPrev = iVal;
  131699. }
  131700. /*
  131701. ** When this function is called, *ppPoslist is assumed to point to the
  131702. ** start of a position-list. After it returns, *ppPoslist points to the
  131703. ** first byte after the position-list.
  131704. **
  131705. ** A position list is list of positions (delta encoded) and columns for
  131706. ** a single document record of a doclist. So, in other words, this
  131707. ** routine advances *ppPoslist so that it points to the next docid in
  131708. ** the doclist, or to the first byte past the end of the doclist.
  131709. **
  131710. ** If pp is not NULL, then the contents of the position list are copied
  131711. ** to *pp. *pp is set to point to the first byte past the last byte copied
  131712. ** before this function returns.
  131713. */
  131714. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  131715. char *pEnd = *ppPoslist;
  131716. char c = 0;
  131717. /* The end of a position list is marked by a zero encoded as an FTS3
  131718. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  131719. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  131720. ** of some other, multi-byte, value.
  131721. **
  131722. ** The following while-loop moves pEnd to point to the first byte that is not
  131723. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  131724. ** pEnd once more so that it points to the byte immediately following the
  131725. ** last byte in the position-list.
  131726. */
  131727. while( *pEnd | c ){
  131728. c = *pEnd++ & 0x80;
  131729. testcase( c!=0 && (*pEnd)==0 );
  131730. }
  131731. pEnd++; /* Advance past the POS_END terminator byte */
  131732. if( pp ){
  131733. int n = (int)(pEnd - *ppPoslist);
  131734. char *p = *pp;
  131735. memcpy(p, *ppPoslist, n);
  131736. p += n;
  131737. *pp = p;
  131738. }
  131739. *ppPoslist = pEnd;
  131740. }
  131741. /*
  131742. ** When this function is called, *ppPoslist is assumed to point to the
  131743. ** start of a column-list. After it returns, *ppPoslist points to the
  131744. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  131745. **
  131746. ** A column-list is list of delta-encoded positions for a single column
  131747. ** within a single document within a doclist.
  131748. **
  131749. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  131750. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  131751. ** the POS_COLUMN or POS_END that terminates the column-list.
  131752. **
  131753. ** If pp is not NULL, then the contents of the column-list are copied
  131754. ** to *pp. *pp is set to point to the first byte past the last byte copied
  131755. ** before this function returns. The POS_COLUMN or POS_END terminator
  131756. ** is not copied into *pp.
  131757. */
  131758. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  131759. char *pEnd = *ppPoslist;
  131760. char c = 0;
  131761. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  131762. ** not part of a multi-byte varint.
  131763. */
  131764. while( 0xFE & (*pEnd | c) ){
  131765. c = *pEnd++ & 0x80;
  131766. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  131767. }
  131768. if( pp ){
  131769. int n = (int)(pEnd - *ppPoslist);
  131770. char *p = *pp;
  131771. memcpy(p, *ppPoslist, n);
  131772. p += n;
  131773. *pp = p;
  131774. }
  131775. *ppPoslist = pEnd;
  131776. }
  131777. /*
  131778. ** Value used to signify the end of an position-list. This is safe because
  131779. ** it is not possible to have a document with 2^31 terms.
  131780. */
  131781. #define POSITION_LIST_END 0x7fffffff
  131782. /*
  131783. ** This function is used to help parse position-lists. When this function is
  131784. ** called, *pp may point to the start of the next varint in the position-list
  131785. ** being parsed, or it may point to 1 byte past the end of the position-list
  131786. ** (in which case **pp will be a terminator bytes POS_END (0) or
  131787. ** (1)).
  131788. **
  131789. ** If *pp points past the end of the current position-list, set *pi to
  131790. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  131791. ** increment the current value of *pi by the value read, and set *pp to
  131792. ** point to the next value before returning.
  131793. **
  131794. ** Before calling this routine *pi must be initialized to the value of
  131795. ** the previous position, or zero if we are reading the first position
  131796. ** in the position-list. Because positions are delta-encoded, the value
  131797. ** of the previous position is needed in order to compute the value of
  131798. ** the next position.
  131799. */
  131800. static void fts3ReadNextPos(
  131801. char **pp, /* IN/OUT: Pointer into position-list buffer */
  131802. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  131803. ){
  131804. if( (**pp)&0xFE ){
  131805. fts3GetDeltaVarint(pp, pi);
  131806. *pi -= 2;
  131807. }else{
  131808. *pi = POSITION_LIST_END;
  131809. }
  131810. }
  131811. /*
  131812. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  131813. ** the value of iCol encoded as a varint to *pp. This will start a new
  131814. ** column list.
  131815. **
  131816. ** Set *pp to point to the byte just after the last byte written before
  131817. ** returning (do not modify it if iCol==0). Return the total number of bytes
  131818. ** written (0 if iCol==0).
  131819. */
  131820. static int fts3PutColNumber(char **pp, int iCol){
  131821. int n = 0; /* Number of bytes written */
  131822. if( iCol ){
  131823. char *p = *pp; /* Output pointer */
  131824. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  131825. *p = 0x01;
  131826. *pp = &p[n];
  131827. }
  131828. return n;
  131829. }
  131830. /*
  131831. ** Compute the union of two position lists. The output written
  131832. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  131833. ** order and with any duplicates removed. All pointers are
  131834. ** updated appropriately. The caller is responsible for insuring
  131835. ** that there is enough space in *pp to hold the complete output.
  131836. */
  131837. static void fts3PoslistMerge(
  131838. char **pp, /* Output buffer */
  131839. char **pp1, /* Left input list */
  131840. char **pp2 /* Right input list */
  131841. ){
  131842. char *p = *pp;
  131843. char *p1 = *pp1;
  131844. char *p2 = *pp2;
  131845. while( *p1 || *p2 ){
  131846. int iCol1; /* The current column index in pp1 */
  131847. int iCol2; /* The current column index in pp2 */
  131848. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  131849. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  131850. else iCol1 = 0;
  131851. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  131852. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  131853. else iCol2 = 0;
  131854. if( iCol1==iCol2 ){
  131855. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  131856. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  131857. sqlite3_int64 iPrev = 0;
  131858. int n = fts3PutColNumber(&p, iCol1);
  131859. p1 += n;
  131860. p2 += n;
  131861. /* At this point, both p1 and p2 point to the start of column-lists
  131862. ** for the same column (the column with index iCol1 and iCol2).
  131863. ** A column-list is a list of non-negative delta-encoded varints, each
  131864. ** incremented by 2 before being stored. Each list is terminated by a
  131865. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  131866. ** and writes the results to buffer p. p is left pointing to the byte
  131867. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  131868. ** written to the output.
  131869. */
  131870. fts3GetDeltaVarint(&p1, &i1);
  131871. fts3GetDeltaVarint(&p2, &i2);
  131872. do {
  131873. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  131874. iPrev -= 2;
  131875. if( i1==i2 ){
  131876. fts3ReadNextPos(&p1, &i1);
  131877. fts3ReadNextPos(&p2, &i2);
  131878. }else if( i1<i2 ){
  131879. fts3ReadNextPos(&p1, &i1);
  131880. }else{
  131881. fts3ReadNextPos(&p2, &i2);
  131882. }
  131883. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  131884. }else if( iCol1<iCol2 ){
  131885. p1 += fts3PutColNumber(&p, iCol1);
  131886. fts3ColumnlistCopy(&p, &p1);
  131887. }else{
  131888. p2 += fts3PutColNumber(&p, iCol2);
  131889. fts3ColumnlistCopy(&p, &p2);
  131890. }
  131891. }
  131892. *p++ = POS_END;
  131893. *pp = p;
  131894. *pp1 = p1 + 1;
  131895. *pp2 = p2 + 1;
  131896. }
  131897. /*
  131898. ** This function is used to merge two position lists into one. When it is
  131899. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  131900. ** the part of a doclist that follows each document id. For example, if a row
  131901. ** contains:
  131902. **
  131903. ** 'a b c'|'x y z'|'a b b a'
  131904. **
  131905. ** Then the position list for this row for token 'b' would consist of:
  131906. **
  131907. ** 0x02 0x01 0x02 0x03 0x03 0x00
  131908. **
  131909. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  131910. ** byte following the 0x00 terminator of their respective position lists.
  131911. **
  131912. ** If isSaveLeft is 0, an entry is added to the output position list for
  131913. ** each position in *pp2 for which there exists one or more positions in
  131914. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  131915. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  131916. ** slots before it.
  131917. **
  131918. ** e.g. nToken==1 searches for adjacent positions.
  131919. */
  131920. static int fts3PoslistPhraseMerge(
  131921. char **pp, /* IN/OUT: Preallocated output buffer */
  131922. int nToken, /* Maximum difference in token positions */
  131923. int isSaveLeft, /* Save the left position */
  131924. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  131925. char **pp1, /* IN/OUT: Left input list */
  131926. char **pp2 /* IN/OUT: Right input list */
  131927. ){
  131928. char *p = *pp;
  131929. char *p1 = *pp1;
  131930. char *p2 = *pp2;
  131931. int iCol1 = 0;
  131932. int iCol2 = 0;
  131933. /* Never set both isSaveLeft and isExact for the same invocation. */
  131934. assert( isSaveLeft==0 || isExact==0 );
  131935. assert( p!=0 && *p1!=0 && *p2!=0 );
  131936. if( *p1==POS_COLUMN ){
  131937. p1++;
  131938. p1 += fts3GetVarint32(p1, &iCol1);
  131939. }
  131940. if( *p2==POS_COLUMN ){
  131941. p2++;
  131942. p2 += fts3GetVarint32(p2, &iCol2);
  131943. }
  131944. while( 1 ){
  131945. if( iCol1==iCol2 ){
  131946. char *pSave = p;
  131947. sqlite3_int64 iPrev = 0;
  131948. sqlite3_int64 iPos1 = 0;
  131949. sqlite3_int64 iPos2 = 0;
  131950. if( iCol1 ){
  131951. *p++ = POS_COLUMN;
  131952. p += sqlite3Fts3PutVarint(p, iCol1);
  131953. }
  131954. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  131955. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  131956. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  131957. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  131958. while( 1 ){
  131959. if( iPos2==iPos1+nToken
  131960. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  131961. ){
  131962. sqlite3_int64 iSave;
  131963. iSave = isSaveLeft ? iPos1 : iPos2;
  131964. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  131965. pSave = 0;
  131966. assert( p );
  131967. }
  131968. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  131969. if( (*p2&0xFE)==0 ) break;
  131970. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  131971. }else{
  131972. if( (*p1&0xFE)==0 ) break;
  131973. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  131974. }
  131975. }
  131976. if( pSave ){
  131977. assert( pp && p );
  131978. p = pSave;
  131979. }
  131980. fts3ColumnlistCopy(0, &p1);
  131981. fts3ColumnlistCopy(0, &p2);
  131982. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  131983. if( 0==*p1 || 0==*p2 ) break;
  131984. p1++;
  131985. p1 += fts3GetVarint32(p1, &iCol1);
  131986. p2++;
  131987. p2 += fts3GetVarint32(p2, &iCol2);
  131988. }
  131989. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  131990. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  131991. ** end of the position list, or the 0x01 that precedes the next
  131992. ** column-number in the position list.
  131993. */
  131994. else if( iCol1<iCol2 ){
  131995. fts3ColumnlistCopy(0, &p1);
  131996. if( 0==*p1 ) break;
  131997. p1++;
  131998. p1 += fts3GetVarint32(p1, &iCol1);
  131999. }else{
  132000. fts3ColumnlistCopy(0, &p2);
  132001. if( 0==*p2 ) break;
  132002. p2++;
  132003. p2 += fts3GetVarint32(p2, &iCol2);
  132004. }
  132005. }
  132006. fts3PoslistCopy(0, &p2);
  132007. fts3PoslistCopy(0, &p1);
  132008. *pp1 = p1;
  132009. *pp2 = p2;
  132010. if( *pp==p ){
  132011. return 0;
  132012. }
  132013. *p++ = 0x00;
  132014. *pp = p;
  132015. return 1;
  132016. }
  132017. /*
  132018. ** Merge two position-lists as required by the NEAR operator. The argument
  132019. ** position lists correspond to the left and right phrases of an expression
  132020. ** like:
  132021. **
  132022. ** "phrase 1" NEAR "phrase number 2"
  132023. **
  132024. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  132025. ** expression and *pp2 to the right. As usual, the indexes in the position
  132026. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  132027. ** in the example above).
  132028. **
  132029. ** The output position list - written to *pp - is a copy of *pp2 with those
  132030. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  132031. */
  132032. static int fts3PoslistNearMerge(
  132033. char **pp, /* Output buffer */
  132034. char *aTmp, /* Temporary buffer space */
  132035. int nRight, /* Maximum difference in token positions */
  132036. int nLeft, /* Maximum difference in token positions */
  132037. char **pp1, /* IN/OUT: Left input list */
  132038. char **pp2 /* IN/OUT: Right input list */
  132039. ){
  132040. char *p1 = *pp1;
  132041. char *p2 = *pp2;
  132042. char *pTmp1 = aTmp;
  132043. char *pTmp2;
  132044. char *aTmp2;
  132045. int res = 1;
  132046. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  132047. aTmp2 = pTmp2 = pTmp1;
  132048. *pp1 = p1;
  132049. *pp2 = p2;
  132050. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  132051. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  132052. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  132053. }else if( pTmp1!=aTmp ){
  132054. fts3PoslistCopy(pp, &aTmp);
  132055. }else if( pTmp2!=aTmp2 ){
  132056. fts3PoslistCopy(pp, &aTmp2);
  132057. }else{
  132058. res = 0;
  132059. }
  132060. return res;
  132061. }
  132062. /*
  132063. ** An instance of this function is used to merge together the (potentially
  132064. ** large number of) doclists for each term that matches a prefix query.
  132065. ** See function fts3TermSelectMerge() for details.
  132066. */
  132067. typedef struct TermSelect TermSelect;
  132068. struct TermSelect {
  132069. char *aaOutput[16]; /* Malloc'd output buffers */
  132070. int anOutput[16]; /* Size each output buffer in bytes */
  132071. };
  132072. /*
  132073. ** This function is used to read a single varint from a buffer. Parameter
  132074. ** pEnd points 1 byte past the end of the buffer. When this function is
  132075. ** called, if *pp points to pEnd or greater, then the end of the buffer
  132076. ** has been reached. In this case *pp is set to 0 and the function returns.
  132077. **
  132078. ** If *pp does not point to or past pEnd, then a single varint is read
  132079. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  132080. **
  132081. ** If bDescIdx is false, the value read is added to *pVal before returning.
  132082. ** If it is true, the value read is subtracted from *pVal before this
  132083. ** function returns.
  132084. */
  132085. static void fts3GetDeltaVarint3(
  132086. char **pp, /* IN/OUT: Point to read varint from */
  132087. char *pEnd, /* End of buffer */
  132088. int bDescIdx, /* True if docids are descending */
  132089. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  132090. ){
  132091. if( *pp>=pEnd ){
  132092. *pp = 0;
  132093. }else{
  132094. sqlite3_int64 iVal;
  132095. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  132096. if( bDescIdx ){
  132097. *pVal -= iVal;
  132098. }else{
  132099. *pVal += iVal;
  132100. }
  132101. }
  132102. }
  132103. /*
  132104. ** This function is used to write a single varint to a buffer. The varint
  132105. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  132106. ** end of the value written.
  132107. **
  132108. ** If *pbFirst is zero when this function is called, the value written to
  132109. ** the buffer is that of parameter iVal.
  132110. **
  132111. ** If *pbFirst is non-zero when this function is called, then the value
  132112. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  132113. ** (if bDescIdx is non-zero).
  132114. **
  132115. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  132116. ** to the value of parameter iVal.
  132117. */
  132118. static void fts3PutDeltaVarint3(
  132119. char **pp, /* IN/OUT: Output pointer */
  132120. int bDescIdx, /* True for descending docids */
  132121. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  132122. int *pbFirst, /* IN/OUT: True after first int written */
  132123. sqlite3_int64 iVal /* Write this value to the list */
  132124. ){
  132125. sqlite3_int64 iWrite;
  132126. if( bDescIdx==0 || *pbFirst==0 ){
  132127. iWrite = iVal - *piPrev;
  132128. }else{
  132129. iWrite = *piPrev - iVal;
  132130. }
  132131. assert( *pbFirst || *piPrev==0 );
  132132. assert( *pbFirst==0 || iWrite>0 );
  132133. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  132134. *piPrev = iVal;
  132135. *pbFirst = 1;
  132136. }
  132137. /*
  132138. ** This macro is used by various functions that merge doclists. The two
  132139. ** arguments are 64-bit docid values. If the value of the stack variable
  132140. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  132141. ** Otherwise, (i2-i1).
  132142. **
  132143. ** Using this makes it easier to write code that can merge doclists that are
  132144. ** sorted in either ascending or descending order.
  132145. */
  132146. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  132147. /*
  132148. ** This function does an "OR" merge of two doclists (output contains all
  132149. ** positions contained in either argument doclist). If the docids in the
  132150. ** input doclists are sorted in ascending order, parameter bDescDoclist
  132151. ** should be false. If they are sorted in ascending order, it should be
  132152. ** passed a non-zero value.
  132153. **
  132154. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  132155. ** containing the output doclist and SQLITE_OK is returned. In this case
  132156. ** *pnOut is set to the number of bytes in the output doclist.
  132157. **
  132158. ** If an error occurs, an SQLite error code is returned. The output values
  132159. ** are undefined in this case.
  132160. */
  132161. static int fts3DoclistOrMerge(
  132162. int bDescDoclist, /* True if arguments are desc */
  132163. char *a1, int n1, /* First doclist */
  132164. char *a2, int n2, /* Second doclist */
  132165. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  132166. ){
  132167. sqlite3_int64 i1 = 0;
  132168. sqlite3_int64 i2 = 0;
  132169. sqlite3_int64 iPrev = 0;
  132170. char *pEnd1 = &a1[n1];
  132171. char *pEnd2 = &a2[n2];
  132172. char *p1 = a1;
  132173. char *p2 = a2;
  132174. char *p;
  132175. char *aOut;
  132176. int bFirstOut = 0;
  132177. *paOut = 0;
  132178. *pnOut = 0;
  132179. /* Allocate space for the output. Both the input and output doclists
  132180. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  132181. ** then the first docid in each list is simply encoded as a varint. For
  132182. ** each subsequent docid, the varint stored is the difference between the
  132183. ** current and previous docid (a positive number - since the list is in
  132184. ** ascending order).
  132185. **
  132186. ** The first docid written to the output is therefore encoded using the
  132187. ** same number of bytes as it is in whichever of the input lists it is
  132188. ** read from. And each subsequent docid read from the same input list
  132189. ** consumes either the same or less bytes as it did in the input (since
  132190. ** the difference between it and the previous value in the output must
  132191. ** be a positive value less than or equal to the delta value read from
  132192. ** the input list). The same argument applies to all but the first docid
  132193. ** read from the 'other' list. And to the contents of all position lists
  132194. ** that will be copied and merged from the input to the output.
  132195. **
  132196. ** However, if the first docid copied to the output is a negative number,
  132197. ** then the encoding of the first docid from the 'other' input list may
  132198. ** be larger in the output than it was in the input (since the delta value
  132199. ** may be a larger positive integer than the actual docid).
  132200. **
  132201. ** The space required to store the output is therefore the sum of the
  132202. ** sizes of the two inputs, plus enough space for exactly one of the input
  132203. ** docids to grow.
  132204. **
  132205. ** A symetric argument may be made if the doclists are in descending
  132206. ** order.
  132207. */
  132208. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  132209. if( !aOut ) return SQLITE_NOMEM;
  132210. p = aOut;
  132211. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  132212. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  132213. while( p1 || p2 ){
  132214. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  132215. if( p2 && p1 && iDiff==0 ){
  132216. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  132217. fts3PoslistMerge(&p, &p1, &p2);
  132218. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  132219. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  132220. }else if( !p2 || (p1 && iDiff<0) ){
  132221. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  132222. fts3PoslistCopy(&p, &p1);
  132223. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  132224. }else{
  132225. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  132226. fts3PoslistCopy(&p, &p2);
  132227. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  132228. }
  132229. }
  132230. *paOut = aOut;
  132231. *pnOut = (int)(p-aOut);
  132232. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  132233. return SQLITE_OK;
  132234. }
  132235. /*
  132236. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  132237. ** the output contains a copy of each position from the right-hand input
  132238. ** doclist for which there is a position in the left-hand input doclist
  132239. ** exactly nDist tokens before it.
  132240. **
  132241. ** If the docids in the input doclists are sorted in ascending order,
  132242. ** parameter bDescDoclist should be false. If they are sorted in ascending
  132243. ** order, it should be passed a non-zero value.
  132244. **
  132245. ** The right-hand input doclist is overwritten by this function.
  132246. */
  132247. static int fts3DoclistPhraseMerge(
  132248. int bDescDoclist, /* True if arguments are desc */
  132249. int nDist, /* Distance from left to right (1=adjacent) */
  132250. char *aLeft, int nLeft, /* Left doclist */
  132251. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  132252. ){
  132253. sqlite3_int64 i1 = 0;
  132254. sqlite3_int64 i2 = 0;
  132255. sqlite3_int64 iPrev = 0;
  132256. char *aRight = *paRight;
  132257. char *pEnd1 = &aLeft[nLeft];
  132258. char *pEnd2 = &aRight[*pnRight];
  132259. char *p1 = aLeft;
  132260. char *p2 = aRight;
  132261. char *p;
  132262. int bFirstOut = 0;
  132263. char *aOut;
  132264. assert( nDist>0 );
  132265. if( bDescDoclist ){
  132266. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  132267. if( aOut==0 ) return SQLITE_NOMEM;
  132268. }else{
  132269. aOut = aRight;
  132270. }
  132271. p = aOut;
  132272. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  132273. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  132274. while( p1 && p2 ){
  132275. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  132276. if( iDiff==0 ){
  132277. char *pSave = p;
  132278. sqlite3_int64 iPrevSave = iPrev;
  132279. int bFirstOutSave = bFirstOut;
  132280. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  132281. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  132282. p = pSave;
  132283. iPrev = iPrevSave;
  132284. bFirstOut = bFirstOutSave;
  132285. }
  132286. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  132287. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  132288. }else if( iDiff<0 ){
  132289. fts3PoslistCopy(0, &p1);
  132290. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  132291. }else{
  132292. fts3PoslistCopy(0, &p2);
  132293. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  132294. }
  132295. }
  132296. *pnRight = (int)(p - aOut);
  132297. if( bDescDoclist ){
  132298. sqlite3_free(aRight);
  132299. *paRight = aOut;
  132300. }
  132301. return SQLITE_OK;
  132302. }
  132303. /*
  132304. ** Argument pList points to a position list nList bytes in size. This
  132305. ** function checks to see if the position list contains any entries for
  132306. ** a token in position 0 (of any column). If so, it writes argument iDelta
  132307. ** to the output buffer pOut, followed by a position list consisting only
  132308. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  132309. ** The value returned is the number of bytes written to pOut (if any).
  132310. */
  132311. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  132312. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  132313. char *pList, /* Position list (no 0x00 term) */
  132314. int nList, /* Size of pList in bytes */
  132315. char *pOut /* Write output here */
  132316. ){
  132317. int nOut = 0;
  132318. int bWritten = 0; /* True once iDelta has been written */
  132319. char *p = pList;
  132320. char *pEnd = &pList[nList];
  132321. if( *p!=0x01 ){
  132322. if( *p==0x02 ){
  132323. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  132324. pOut[nOut++] = 0x02;
  132325. bWritten = 1;
  132326. }
  132327. fts3ColumnlistCopy(0, &p);
  132328. }
  132329. while( p<pEnd && *p==0x01 ){
  132330. sqlite3_int64 iCol;
  132331. p++;
  132332. p += sqlite3Fts3GetVarint(p, &iCol);
  132333. if( *p==0x02 ){
  132334. if( bWritten==0 ){
  132335. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  132336. bWritten = 1;
  132337. }
  132338. pOut[nOut++] = 0x01;
  132339. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  132340. pOut[nOut++] = 0x02;
  132341. }
  132342. fts3ColumnlistCopy(0, &p);
  132343. }
  132344. if( bWritten ){
  132345. pOut[nOut++] = 0x00;
  132346. }
  132347. return nOut;
  132348. }
  132349. /*
  132350. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  132351. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  132352. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  132353. **
  132354. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  132355. ** the responsibility of the caller to free any doclists left in the
  132356. ** TermSelect.aaOutput[] array.
  132357. */
  132358. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  132359. char *aOut = 0;
  132360. int nOut = 0;
  132361. int i;
  132362. /* Loop through the doclists in the aaOutput[] array. Merge them all
  132363. ** into a single doclist.
  132364. */
  132365. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  132366. if( pTS->aaOutput[i] ){
  132367. if( !aOut ){
  132368. aOut = pTS->aaOutput[i];
  132369. nOut = pTS->anOutput[i];
  132370. pTS->aaOutput[i] = 0;
  132371. }else{
  132372. int nNew;
  132373. char *aNew;
  132374. int rc = fts3DoclistOrMerge(p->bDescIdx,
  132375. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  132376. );
  132377. if( rc!=SQLITE_OK ){
  132378. sqlite3_free(aOut);
  132379. return rc;
  132380. }
  132381. sqlite3_free(pTS->aaOutput[i]);
  132382. sqlite3_free(aOut);
  132383. pTS->aaOutput[i] = 0;
  132384. aOut = aNew;
  132385. nOut = nNew;
  132386. }
  132387. }
  132388. }
  132389. pTS->aaOutput[0] = aOut;
  132390. pTS->anOutput[0] = nOut;
  132391. return SQLITE_OK;
  132392. }
  132393. /*
  132394. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  132395. ** as the first argument. The merge is an "OR" merge (see function
  132396. ** fts3DoclistOrMerge() for details).
  132397. **
  132398. ** This function is called with the doclist for each term that matches
  132399. ** a queried prefix. It merges all these doclists into one, the doclist
  132400. ** for the specified prefix. Since there can be a very large number of
  132401. ** doclists to merge, the merging is done pair-wise using the TermSelect
  132402. ** object.
  132403. **
  132404. ** This function returns SQLITE_OK if the merge is successful, or an
  132405. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  132406. */
  132407. static int fts3TermSelectMerge(
  132408. Fts3Table *p, /* FTS table handle */
  132409. TermSelect *pTS, /* TermSelect object to merge into */
  132410. char *aDoclist, /* Pointer to doclist */
  132411. int nDoclist /* Size of aDoclist in bytes */
  132412. ){
  132413. if( pTS->aaOutput[0]==0 ){
  132414. /* If this is the first term selected, copy the doclist to the output
  132415. ** buffer using memcpy().
  132416. **
  132417. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  132418. ** allocation. This is so as to ensure that the buffer is big enough
  132419. ** to hold the current doclist AND'd with any other doclist. If the
  132420. ** doclists are stored in order=ASC order, this padding would not be
  132421. ** required (since the size of [doclistA AND doclistB] is always less
  132422. ** than or equal to the size of [doclistA] in that case). But this is
  132423. ** not true for order=DESC. For example, a doclist containing (1, -1)
  132424. ** may be smaller than (-1), as in the first example the -1 may be stored
  132425. ** as a single-byte delta, whereas in the second it must be stored as a
  132426. ** FTS3_VARINT_MAX byte varint.
  132427. **
  132428. ** Similar padding is added in the fts3DoclistOrMerge() function.
  132429. */
  132430. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  132431. pTS->anOutput[0] = nDoclist;
  132432. if( pTS->aaOutput[0] ){
  132433. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  132434. }else{
  132435. return SQLITE_NOMEM;
  132436. }
  132437. }else{
  132438. char *aMerge = aDoclist;
  132439. int nMerge = nDoclist;
  132440. int iOut;
  132441. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  132442. if( pTS->aaOutput[iOut]==0 ){
  132443. assert( iOut>0 );
  132444. pTS->aaOutput[iOut] = aMerge;
  132445. pTS->anOutput[iOut] = nMerge;
  132446. break;
  132447. }else{
  132448. char *aNew;
  132449. int nNew;
  132450. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  132451. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  132452. );
  132453. if( rc!=SQLITE_OK ){
  132454. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  132455. return rc;
  132456. }
  132457. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  132458. sqlite3_free(pTS->aaOutput[iOut]);
  132459. pTS->aaOutput[iOut] = 0;
  132460. aMerge = aNew;
  132461. nMerge = nNew;
  132462. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  132463. pTS->aaOutput[iOut] = aMerge;
  132464. pTS->anOutput[iOut] = nMerge;
  132465. }
  132466. }
  132467. }
  132468. }
  132469. return SQLITE_OK;
  132470. }
  132471. /*
  132472. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  132473. */
  132474. static int fts3SegReaderCursorAppend(
  132475. Fts3MultiSegReader *pCsr,
  132476. Fts3SegReader *pNew
  132477. ){
  132478. if( (pCsr->nSegment%16)==0 ){
  132479. Fts3SegReader **apNew;
  132480. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  132481. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  132482. if( !apNew ){
  132483. sqlite3Fts3SegReaderFree(pNew);
  132484. return SQLITE_NOMEM;
  132485. }
  132486. pCsr->apSegment = apNew;
  132487. }
  132488. pCsr->apSegment[pCsr->nSegment++] = pNew;
  132489. return SQLITE_OK;
  132490. }
  132491. /*
  132492. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  132493. ** 8th argument.
  132494. **
  132495. ** This function returns SQLITE_OK if successful, or an SQLite error code
  132496. ** otherwise.
  132497. */
  132498. static int fts3SegReaderCursor(
  132499. Fts3Table *p, /* FTS3 table handle */
  132500. int iLangid, /* Language id */
  132501. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  132502. int iLevel, /* Level of segments to scan */
  132503. const char *zTerm, /* Term to query for */
  132504. int nTerm, /* Size of zTerm in bytes */
  132505. int isPrefix, /* True for a prefix search */
  132506. int isScan, /* True to scan from zTerm to EOF */
  132507. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  132508. ){
  132509. int rc = SQLITE_OK; /* Error code */
  132510. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  132511. int rc2; /* Result of sqlite3_reset() */
  132512. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  132513. ** for the pending-terms. If this is a scan, then this call must be being
  132514. ** made by an fts4aux module, not an FTS table. In this case calling
  132515. ** Fts3SegReaderPending might segfault, as the data structures used by
  132516. ** fts4aux are not completely populated. So it's easiest to filter these
  132517. ** calls out here. */
  132518. if( iLevel<0 && p->aIndex ){
  132519. Fts3SegReader *pSeg = 0;
  132520. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  132521. if( rc==SQLITE_OK && pSeg ){
  132522. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  132523. }
  132524. }
  132525. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  132526. if( rc==SQLITE_OK ){
  132527. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  132528. }
  132529. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  132530. Fts3SegReader *pSeg = 0;
  132531. /* Read the values returned by the SELECT into local variables. */
  132532. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  132533. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  132534. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  132535. int nRoot = sqlite3_column_bytes(pStmt, 4);
  132536. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  132537. /* If zTerm is not NULL, and this segment is not stored entirely on its
  132538. ** root node, the range of leaves scanned can be reduced. Do this. */
  132539. if( iStartBlock && zTerm ){
  132540. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  132541. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  132542. if( rc!=SQLITE_OK ) goto finished;
  132543. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  132544. }
  132545. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  132546. (isPrefix==0 && isScan==0),
  132547. iStartBlock, iLeavesEndBlock,
  132548. iEndBlock, zRoot, nRoot, &pSeg
  132549. );
  132550. if( rc!=SQLITE_OK ) goto finished;
  132551. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  132552. }
  132553. }
  132554. finished:
  132555. rc2 = sqlite3_reset(pStmt);
  132556. if( rc==SQLITE_DONE ) rc = rc2;
  132557. return rc;
  132558. }
  132559. /*
  132560. ** Set up a cursor object for iterating through a full-text index or a
  132561. ** single level therein.
  132562. */
  132563. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  132564. Fts3Table *p, /* FTS3 table handle */
  132565. int iLangid, /* Language-id to search */
  132566. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  132567. int iLevel, /* Level of segments to scan */
  132568. const char *zTerm, /* Term to query for */
  132569. int nTerm, /* Size of zTerm in bytes */
  132570. int isPrefix, /* True for a prefix search */
  132571. int isScan, /* True to scan from zTerm to EOF */
  132572. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  132573. ){
  132574. assert( iIndex>=0 && iIndex<p->nIndex );
  132575. assert( iLevel==FTS3_SEGCURSOR_ALL
  132576. || iLevel==FTS3_SEGCURSOR_PENDING
  132577. || iLevel>=0
  132578. );
  132579. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  132580. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  132581. assert( isPrefix==0 || isScan==0 );
  132582. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  132583. return fts3SegReaderCursor(
  132584. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  132585. );
  132586. }
  132587. /*
  132588. ** In addition to its current configuration, have the Fts3MultiSegReader
  132589. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  132590. **
  132591. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  132592. */
  132593. static int fts3SegReaderCursorAddZero(
  132594. Fts3Table *p, /* FTS virtual table handle */
  132595. int iLangid,
  132596. const char *zTerm, /* Term to scan doclist of */
  132597. int nTerm, /* Number of bytes in zTerm */
  132598. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  132599. ){
  132600. return fts3SegReaderCursor(p,
  132601. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  132602. );
  132603. }
  132604. /*
  132605. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  132606. ** if isPrefix is true, to scan the doclist for all terms for which
  132607. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  132608. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  132609. ** an SQLite error code.
  132610. **
  132611. ** It is the responsibility of the caller to free this object by eventually
  132612. ** passing it to fts3SegReaderCursorFree()
  132613. **
  132614. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  132615. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  132616. */
  132617. static int fts3TermSegReaderCursor(
  132618. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  132619. const char *zTerm, /* Term to query for */
  132620. int nTerm, /* Size of zTerm in bytes */
  132621. int isPrefix, /* True for a prefix search */
  132622. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  132623. ){
  132624. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  132625. int rc = SQLITE_NOMEM; /* Return code */
  132626. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  132627. if( pSegcsr ){
  132628. int i;
  132629. int bFound = 0; /* True once an index has been found */
  132630. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  132631. if( isPrefix ){
  132632. for(i=1; bFound==0 && i<p->nIndex; i++){
  132633. if( p->aIndex[i].nPrefix==nTerm ){
  132634. bFound = 1;
  132635. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  132636. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  132637. );
  132638. pSegcsr->bLookup = 1;
  132639. }
  132640. }
  132641. for(i=1; bFound==0 && i<p->nIndex; i++){
  132642. if( p->aIndex[i].nPrefix==nTerm+1 ){
  132643. bFound = 1;
  132644. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  132645. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  132646. );
  132647. if( rc==SQLITE_OK ){
  132648. rc = fts3SegReaderCursorAddZero(
  132649. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  132650. );
  132651. }
  132652. }
  132653. }
  132654. }
  132655. if( bFound==0 ){
  132656. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  132657. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  132658. );
  132659. pSegcsr->bLookup = !isPrefix;
  132660. }
  132661. }
  132662. *ppSegcsr = pSegcsr;
  132663. return rc;
  132664. }
  132665. /*
  132666. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  132667. */
  132668. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  132669. sqlite3Fts3SegReaderFinish(pSegcsr);
  132670. sqlite3_free(pSegcsr);
  132671. }
  132672. /*
  132673. ** This function retrieves the doclist for the specified term (or term
  132674. ** prefix) from the database.
  132675. */
  132676. static int fts3TermSelect(
  132677. Fts3Table *p, /* Virtual table handle */
  132678. Fts3PhraseToken *pTok, /* Token to query for */
  132679. int iColumn, /* Column to query (or -ve for all columns) */
  132680. int *pnOut, /* OUT: Size of buffer at *ppOut */
  132681. char **ppOut /* OUT: Malloced result buffer */
  132682. ){
  132683. int rc; /* Return code */
  132684. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  132685. TermSelect tsc; /* Object for pair-wise doclist merging */
  132686. Fts3SegFilter filter; /* Segment term filter configuration */
  132687. pSegcsr = pTok->pSegcsr;
  132688. memset(&tsc, 0, sizeof(TermSelect));
  132689. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  132690. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  132691. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  132692. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  132693. filter.iCol = iColumn;
  132694. filter.zTerm = pTok->z;
  132695. filter.nTerm = pTok->n;
  132696. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  132697. while( SQLITE_OK==rc
  132698. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  132699. ){
  132700. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  132701. }
  132702. if( rc==SQLITE_OK ){
  132703. rc = fts3TermSelectFinishMerge(p, &tsc);
  132704. }
  132705. if( rc==SQLITE_OK ){
  132706. *ppOut = tsc.aaOutput[0];
  132707. *pnOut = tsc.anOutput[0];
  132708. }else{
  132709. int i;
  132710. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  132711. sqlite3_free(tsc.aaOutput[i]);
  132712. }
  132713. }
  132714. fts3SegReaderCursorFree(pSegcsr);
  132715. pTok->pSegcsr = 0;
  132716. return rc;
  132717. }
  132718. /*
  132719. ** This function counts the total number of docids in the doclist stored
  132720. ** in buffer aList[], size nList bytes.
  132721. **
  132722. ** If the isPoslist argument is true, then it is assumed that the doclist
  132723. ** contains a position-list following each docid. Otherwise, it is assumed
  132724. ** that the doclist is simply a list of docids stored as delta encoded
  132725. ** varints.
  132726. */
  132727. static int fts3DoclistCountDocids(char *aList, int nList){
  132728. int nDoc = 0; /* Return value */
  132729. if( aList ){
  132730. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  132731. char *p = aList; /* Cursor */
  132732. while( p<aEnd ){
  132733. nDoc++;
  132734. while( (*p++)&0x80 ); /* Skip docid varint */
  132735. fts3PoslistCopy(0, &p); /* Skip over position list */
  132736. }
  132737. }
  132738. return nDoc;
  132739. }
  132740. /*
  132741. ** Advance the cursor to the next row in the %_content table that
  132742. ** matches the search criteria. For a MATCH search, this will be
  132743. ** the next row that matches. For a full-table scan, this will be
  132744. ** simply the next row in the %_content table. For a docid lookup,
  132745. ** this routine simply sets the EOF flag.
  132746. **
  132747. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  132748. ** even if we reach end-of-file. The fts3EofMethod() will be called
  132749. ** subsequently to determine whether or not an EOF was hit.
  132750. */
  132751. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  132752. int rc;
  132753. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  132754. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  132755. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  132756. pCsr->isEof = 1;
  132757. rc = sqlite3_reset(pCsr->pStmt);
  132758. }else{
  132759. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  132760. rc = SQLITE_OK;
  132761. }
  132762. }else{
  132763. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  132764. }
  132765. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  132766. return rc;
  132767. }
  132768. /*
  132769. ** The following are copied from sqliteInt.h.
  132770. **
  132771. ** Constants for the largest and smallest possible 64-bit signed integers.
  132772. ** These macros are designed to work correctly on both 32-bit and 64-bit
  132773. ** compilers.
  132774. */
  132775. #ifndef SQLITE_AMALGAMATION
  132776. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  132777. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  132778. #endif
  132779. /*
  132780. ** If the numeric type of argument pVal is "integer", then return it
  132781. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  132782. ** the second parameter, iDefault.
  132783. */
  132784. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  132785. if( pVal ){
  132786. int eType = sqlite3_value_numeric_type(pVal);
  132787. if( eType==SQLITE_INTEGER ){
  132788. return sqlite3_value_int64(pVal);
  132789. }
  132790. }
  132791. return iDefault;
  132792. }
  132793. /*
  132794. ** This is the xFilter interface for the virtual table. See
  132795. ** the virtual table xFilter method documentation for additional
  132796. ** information.
  132797. **
  132798. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  132799. ** the %_content table.
  132800. **
  132801. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  132802. ** in the %_content table.
  132803. **
  132804. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  132805. ** column on the left-hand side of the MATCH operator is column
  132806. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  132807. ** side of the MATCH operator.
  132808. */
  132809. static int fts3FilterMethod(
  132810. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  132811. int idxNum, /* Strategy index */
  132812. const char *idxStr, /* Unused */
  132813. int nVal, /* Number of elements in apVal */
  132814. sqlite3_value **apVal /* Arguments for the indexing scheme */
  132815. ){
  132816. int rc = SQLITE_OK;
  132817. char *zSql; /* SQL statement used to access %_content */
  132818. int eSearch;
  132819. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  132820. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  132821. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  132822. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  132823. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  132824. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  132825. int iIdx;
  132826. UNUSED_PARAMETER(idxStr);
  132827. UNUSED_PARAMETER(nVal);
  132828. eSearch = (idxNum & 0x0000FFFF);
  132829. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  132830. assert( p->pSegments==0 );
  132831. /* Collect arguments into local variables */
  132832. iIdx = 0;
  132833. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  132834. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  132835. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  132836. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  132837. assert( iIdx==nVal );
  132838. /* In case the cursor has been used before, clear it now. */
  132839. sqlite3_finalize(pCsr->pStmt);
  132840. sqlite3_free(pCsr->aDoclist);
  132841. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  132842. sqlite3Fts3ExprFree(pCsr->pExpr);
  132843. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  132844. /* Set the lower and upper bounds on docids to return */
  132845. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  132846. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  132847. if( idxStr ){
  132848. pCsr->bDesc = (idxStr[0]=='D');
  132849. }else{
  132850. pCsr->bDesc = p->bDescIdx;
  132851. }
  132852. pCsr->eSearch = (i16)eSearch;
  132853. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  132854. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  132855. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  132856. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  132857. return SQLITE_NOMEM;
  132858. }
  132859. pCsr->iLangid = 0;
  132860. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  132861. assert( p->base.zErrMsg==0 );
  132862. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  132863. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  132864. &p->base.zErrMsg
  132865. );
  132866. if( rc!=SQLITE_OK ){
  132867. return rc;
  132868. }
  132869. rc = fts3EvalStart(pCsr);
  132870. sqlite3Fts3SegmentsClose(p);
  132871. if( rc!=SQLITE_OK ) return rc;
  132872. pCsr->pNextId = pCsr->aDoclist;
  132873. pCsr->iPrevId = 0;
  132874. }
  132875. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  132876. ** statement loops through all rows of the %_content table. For a
  132877. ** full-text query or docid lookup, the statement retrieves a single
  132878. ** row by docid.
  132879. */
  132880. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  132881. if( pDocidGe || pDocidLe ){
  132882. zSql = sqlite3_mprintf(
  132883. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  132884. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  132885. (pCsr->bDesc ? "DESC" : "ASC")
  132886. );
  132887. }else{
  132888. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  132889. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  132890. );
  132891. }
  132892. if( zSql ){
  132893. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  132894. sqlite3_free(zSql);
  132895. }else{
  132896. rc = SQLITE_NOMEM;
  132897. }
  132898. }else if( eSearch==FTS3_DOCID_SEARCH ){
  132899. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  132900. if( rc==SQLITE_OK ){
  132901. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  132902. }
  132903. }
  132904. if( rc!=SQLITE_OK ) return rc;
  132905. return fts3NextMethod(pCursor);
  132906. }
  132907. /*
  132908. ** This is the xEof method of the virtual table. SQLite calls this
  132909. ** routine to find out if it has reached the end of a result set.
  132910. */
  132911. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  132912. return ((Fts3Cursor *)pCursor)->isEof;
  132913. }
  132914. /*
  132915. ** This is the xRowid method. The SQLite core calls this routine to
  132916. ** retrieve the rowid for the current row of the result set. fts3
  132917. ** exposes %_content.docid as the rowid for the virtual table. The
  132918. ** rowid should be written to *pRowid.
  132919. */
  132920. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  132921. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  132922. *pRowid = pCsr->iPrevId;
  132923. return SQLITE_OK;
  132924. }
  132925. /*
  132926. ** This is the xColumn method, called by SQLite to request a value from
  132927. ** the row that the supplied cursor currently points to.
  132928. **
  132929. ** If:
  132930. **
  132931. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  132932. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  132933. ** (iCol == p->nColumn+1) -> Docid column
  132934. ** (iCol == p->nColumn+2) -> Langid column
  132935. */
  132936. static int fts3ColumnMethod(
  132937. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  132938. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  132939. int iCol /* Index of column to read value from */
  132940. ){
  132941. int rc = SQLITE_OK; /* Return Code */
  132942. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  132943. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  132944. /* The column value supplied by SQLite must be in range. */
  132945. assert( iCol>=0 && iCol<=p->nColumn+2 );
  132946. if( iCol==p->nColumn+1 ){
  132947. /* This call is a request for the "docid" column. Since "docid" is an
  132948. ** alias for "rowid", use the xRowid() method to obtain the value.
  132949. */
  132950. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  132951. }else if( iCol==p->nColumn ){
  132952. /* The extra column whose name is the same as the table.
  132953. ** Return a blob which is a pointer to the cursor. */
  132954. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  132955. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  132956. sqlite3_result_int64(pCtx, pCsr->iLangid);
  132957. }else{
  132958. /* The requested column is either a user column (one that contains
  132959. ** indexed data), or the language-id column. */
  132960. rc = fts3CursorSeek(0, pCsr);
  132961. if( rc==SQLITE_OK ){
  132962. if( iCol==p->nColumn+2 ){
  132963. int iLangid = 0;
  132964. if( p->zLanguageid ){
  132965. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  132966. }
  132967. sqlite3_result_int(pCtx, iLangid);
  132968. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  132969. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  132970. }
  132971. }
  132972. }
  132973. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  132974. return rc;
  132975. }
  132976. /*
  132977. ** This function is the implementation of the xUpdate callback used by
  132978. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  132979. ** inserted, updated or deleted.
  132980. */
  132981. static int fts3UpdateMethod(
  132982. sqlite3_vtab *pVtab, /* Virtual table handle */
  132983. int nArg, /* Size of argument array */
  132984. sqlite3_value **apVal, /* Array of arguments */
  132985. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  132986. ){
  132987. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  132988. }
  132989. /*
  132990. ** Implementation of xSync() method. Flush the contents of the pending-terms
  132991. ** hash-table to the database.
  132992. */
  132993. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  132994. /* Following an incremental-merge operation, assuming that the input
  132995. ** segments are not completely consumed (the usual case), they are updated
  132996. ** in place to remove the entries that have already been merged. This
  132997. ** involves updating the leaf block that contains the smallest unmerged
  132998. ** entry and each block (if any) between the leaf and the root node. So
  132999. ** if the height of the input segment b-trees is N, and input segments
  133000. ** are merged eight at a time, updating the input segments at the end
  133001. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  133002. ** small - often between 0 and 2. So the overhead of the incremental
  133003. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  133004. ** dwarfing the actual productive work accomplished, the incremental merge
  133005. ** is only attempted if it will write at least 64 leaf blocks. Hence
  133006. ** nMinMerge.
  133007. **
  133008. ** Of course, updating the input segments also involves deleting a bunch
  133009. ** of blocks from the segments table. But this is not considered overhead
  133010. ** as it would also be required by a crisis-merge that used the same input
  133011. ** segments.
  133012. */
  133013. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  133014. Fts3Table *p = (Fts3Table*)pVtab;
  133015. int rc = sqlite3Fts3PendingTermsFlush(p);
  133016. if( rc==SQLITE_OK
  133017. && p->nLeafAdd>(nMinMerge/16)
  133018. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  133019. ){
  133020. int mxLevel = 0; /* Maximum relative level value in db */
  133021. int A; /* Incr-merge parameter A */
  133022. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  133023. assert( rc==SQLITE_OK || mxLevel==0 );
  133024. A = p->nLeafAdd * mxLevel;
  133025. A += (A/2);
  133026. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  133027. }
  133028. sqlite3Fts3SegmentsClose(p);
  133029. return rc;
  133030. }
  133031. /*
  133032. ** If it is currently unknown whether or not the FTS table has an %_stat
  133033. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  133034. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  133035. ** if an error occurs.
  133036. */
  133037. static int fts3SetHasStat(Fts3Table *p){
  133038. int rc = SQLITE_OK;
  133039. if( p->bHasStat==2 ){
  133040. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  133041. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  133042. if( zSql ){
  133043. sqlite3_stmt *pStmt = 0;
  133044. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  133045. if( rc==SQLITE_OK ){
  133046. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  133047. rc = sqlite3_finalize(pStmt);
  133048. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  133049. }
  133050. sqlite3_free(zSql);
  133051. }else{
  133052. rc = SQLITE_NOMEM;
  133053. }
  133054. }
  133055. return rc;
  133056. }
  133057. /*
  133058. ** Implementation of xBegin() method.
  133059. */
  133060. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  133061. Fts3Table *p = (Fts3Table*)pVtab;
  133062. UNUSED_PARAMETER(pVtab);
  133063. assert( p->pSegments==0 );
  133064. assert( p->nPendingData==0 );
  133065. assert( p->inTransaction!=1 );
  133066. TESTONLY( p->inTransaction = 1 );
  133067. TESTONLY( p->mxSavepoint = -1; );
  133068. p->nLeafAdd = 0;
  133069. return fts3SetHasStat(p);
  133070. }
  133071. /*
  133072. ** Implementation of xCommit() method. This is a no-op. The contents of
  133073. ** the pending-terms hash-table have already been flushed into the database
  133074. ** by fts3SyncMethod().
  133075. */
  133076. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  133077. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  133078. UNUSED_PARAMETER(pVtab);
  133079. assert( p->nPendingData==0 );
  133080. assert( p->inTransaction!=0 );
  133081. assert( p->pSegments==0 );
  133082. TESTONLY( p->inTransaction = 0 );
  133083. TESTONLY( p->mxSavepoint = -1; );
  133084. return SQLITE_OK;
  133085. }
  133086. /*
  133087. ** Implementation of xRollback(). Discard the contents of the pending-terms
  133088. ** hash-table. Any changes made to the database are reverted by SQLite.
  133089. */
  133090. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  133091. Fts3Table *p = (Fts3Table*)pVtab;
  133092. sqlite3Fts3PendingTermsClear(p);
  133093. assert( p->inTransaction!=0 );
  133094. TESTONLY( p->inTransaction = 0 );
  133095. TESTONLY( p->mxSavepoint = -1; );
  133096. return SQLITE_OK;
  133097. }
  133098. /*
  133099. ** When called, *ppPoslist must point to the byte immediately following the
  133100. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  133101. ** moves *ppPoslist so that it instead points to the first byte of the
  133102. ** same position list.
  133103. */
  133104. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  133105. char *p = &(*ppPoslist)[-2];
  133106. char c = 0;
  133107. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  133108. while( p>pStart && (c=*p--)==0 );
  133109. /* Search backwards for a varint with value zero (the end of the previous
  133110. ** poslist). This is an 0x00 byte preceded by some byte that does not
  133111. ** have the 0x80 bit set. */
  133112. while( p>pStart && (*p & 0x80) | c ){
  133113. c = *p--;
  133114. }
  133115. assert( p==pStart || c==0 );
  133116. /* At this point p points to that preceding byte without the 0x80 bit
  133117. ** set. So to find the start of the poslist, skip forward 2 bytes then
  133118. ** over a varint.
  133119. **
  133120. ** Normally. The other case is that p==pStart and the poslist to return
  133121. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  133122. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  133123. ** is required for cases where the first byte of a doclist and the
  133124. ** doclist is empty. For example, if the first docid is 10, a doclist
  133125. ** that begins with:
  133126. **
  133127. ** 0x0A 0x00 <next docid delta varint>
  133128. */
  133129. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  133130. while( *p++&0x80 );
  133131. *ppPoslist = p;
  133132. }
  133133. /*
  133134. ** Helper function used by the implementation of the overloaded snippet(),
  133135. ** offsets() and optimize() SQL functions.
  133136. **
  133137. ** If the value passed as the third argument is a blob of size
  133138. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  133139. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  133140. ** message is written to context pContext and SQLITE_ERROR returned. The
  133141. ** string passed via zFunc is used as part of the error message.
  133142. */
  133143. static int fts3FunctionArg(
  133144. sqlite3_context *pContext, /* SQL function call context */
  133145. const char *zFunc, /* Function name */
  133146. sqlite3_value *pVal, /* argv[0] passed to function */
  133147. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  133148. ){
  133149. Fts3Cursor *pRet;
  133150. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  133151. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  133152. ){
  133153. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  133154. sqlite3_result_error(pContext, zErr, -1);
  133155. sqlite3_free(zErr);
  133156. return SQLITE_ERROR;
  133157. }
  133158. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  133159. *ppCsr = pRet;
  133160. return SQLITE_OK;
  133161. }
  133162. /*
  133163. ** Implementation of the snippet() function for FTS3
  133164. */
  133165. static void fts3SnippetFunc(
  133166. sqlite3_context *pContext, /* SQLite function call context */
  133167. int nVal, /* Size of apVal[] array */
  133168. sqlite3_value **apVal /* Array of arguments */
  133169. ){
  133170. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  133171. const char *zStart = "<b>";
  133172. const char *zEnd = "</b>";
  133173. const char *zEllipsis = "<b>...</b>";
  133174. int iCol = -1;
  133175. int nToken = 15; /* Default number of tokens in snippet */
  133176. /* There must be at least one argument passed to this function (otherwise
  133177. ** the non-overloaded version would have been called instead of this one).
  133178. */
  133179. assert( nVal>=1 );
  133180. if( nVal>6 ){
  133181. sqlite3_result_error(pContext,
  133182. "wrong number of arguments to function snippet()", -1);
  133183. return;
  133184. }
  133185. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  133186. switch( nVal ){
  133187. case 6: nToken = sqlite3_value_int(apVal[5]);
  133188. case 5: iCol = sqlite3_value_int(apVal[4]);
  133189. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  133190. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  133191. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  133192. }
  133193. if( !zEllipsis || !zEnd || !zStart ){
  133194. sqlite3_result_error_nomem(pContext);
  133195. }else if( nToken==0 ){
  133196. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  133197. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  133198. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  133199. }
  133200. }
  133201. /*
  133202. ** Implementation of the offsets() function for FTS3
  133203. */
  133204. static void fts3OffsetsFunc(
  133205. sqlite3_context *pContext, /* SQLite function call context */
  133206. int nVal, /* Size of argument array */
  133207. sqlite3_value **apVal /* Array of arguments */
  133208. ){
  133209. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  133210. UNUSED_PARAMETER(nVal);
  133211. assert( nVal==1 );
  133212. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  133213. assert( pCsr );
  133214. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  133215. sqlite3Fts3Offsets(pContext, pCsr);
  133216. }
  133217. }
  133218. /*
  133219. ** Implementation of the special optimize() function for FTS3. This
  133220. ** function merges all segments in the database to a single segment.
  133221. ** Example usage is:
  133222. **
  133223. ** SELECT optimize(t) FROM t LIMIT 1;
  133224. **
  133225. ** where 't' is the name of an FTS3 table.
  133226. */
  133227. static void fts3OptimizeFunc(
  133228. sqlite3_context *pContext, /* SQLite function call context */
  133229. int nVal, /* Size of argument array */
  133230. sqlite3_value **apVal /* Array of arguments */
  133231. ){
  133232. int rc; /* Return code */
  133233. Fts3Table *p; /* Virtual table handle */
  133234. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  133235. UNUSED_PARAMETER(nVal);
  133236. assert( nVal==1 );
  133237. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  133238. p = (Fts3Table *)pCursor->base.pVtab;
  133239. assert( p );
  133240. rc = sqlite3Fts3Optimize(p);
  133241. switch( rc ){
  133242. case SQLITE_OK:
  133243. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  133244. break;
  133245. case SQLITE_DONE:
  133246. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  133247. break;
  133248. default:
  133249. sqlite3_result_error_code(pContext, rc);
  133250. break;
  133251. }
  133252. }
  133253. /*
  133254. ** Implementation of the matchinfo() function for FTS3
  133255. */
  133256. static void fts3MatchinfoFunc(
  133257. sqlite3_context *pContext, /* SQLite function call context */
  133258. int nVal, /* Size of argument array */
  133259. sqlite3_value **apVal /* Array of arguments */
  133260. ){
  133261. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  133262. assert( nVal==1 || nVal==2 );
  133263. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  133264. const char *zArg = 0;
  133265. if( nVal>1 ){
  133266. zArg = (const char *)sqlite3_value_text(apVal[1]);
  133267. }
  133268. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  133269. }
  133270. }
  133271. /*
  133272. ** This routine implements the xFindFunction method for the FTS3
  133273. ** virtual table.
  133274. */
  133275. static int fts3FindFunctionMethod(
  133276. sqlite3_vtab *pVtab, /* Virtual table handle */
  133277. int nArg, /* Number of SQL function arguments */
  133278. const char *zName, /* Name of SQL function */
  133279. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  133280. void **ppArg /* Unused */
  133281. ){
  133282. struct Overloaded {
  133283. const char *zName;
  133284. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  133285. } aOverload[] = {
  133286. { "snippet", fts3SnippetFunc },
  133287. { "offsets", fts3OffsetsFunc },
  133288. { "optimize", fts3OptimizeFunc },
  133289. { "matchinfo", fts3MatchinfoFunc },
  133290. };
  133291. int i; /* Iterator variable */
  133292. UNUSED_PARAMETER(pVtab);
  133293. UNUSED_PARAMETER(nArg);
  133294. UNUSED_PARAMETER(ppArg);
  133295. for(i=0; i<SizeofArray(aOverload); i++){
  133296. if( strcmp(zName, aOverload[i].zName)==0 ){
  133297. *pxFunc = aOverload[i].xFunc;
  133298. return 1;
  133299. }
  133300. }
  133301. /* No function of the specified name was found. Return 0. */
  133302. return 0;
  133303. }
  133304. /*
  133305. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  133306. */
  133307. static int fts3RenameMethod(
  133308. sqlite3_vtab *pVtab, /* Virtual table handle */
  133309. const char *zName /* New name of table */
  133310. ){
  133311. Fts3Table *p = (Fts3Table *)pVtab;
  133312. sqlite3 *db = p->db; /* Database connection */
  133313. int rc; /* Return Code */
  133314. /* At this point it must be known if the %_stat table exists or not.
  133315. ** So bHasStat may not be 2. */
  133316. rc = fts3SetHasStat(p);
  133317. /* As it happens, the pending terms table is always empty here. This is
  133318. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  133319. ** always opens a savepoint transaction. And the xSavepoint() method
  133320. ** flushes the pending terms table. But leave the (no-op) call to
  133321. ** PendingTermsFlush() in in case that changes.
  133322. */
  133323. assert( p->nPendingData==0 );
  133324. if( rc==SQLITE_OK ){
  133325. rc = sqlite3Fts3PendingTermsFlush(p);
  133326. }
  133327. if( p->zContentTbl==0 ){
  133328. fts3DbExec(&rc, db,
  133329. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  133330. p->zDb, p->zName, zName
  133331. );
  133332. }
  133333. if( p->bHasDocsize ){
  133334. fts3DbExec(&rc, db,
  133335. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  133336. p->zDb, p->zName, zName
  133337. );
  133338. }
  133339. if( p->bHasStat ){
  133340. fts3DbExec(&rc, db,
  133341. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  133342. p->zDb, p->zName, zName
  133343. );
  133344. }
  133345. fts3DbExec(&rc, db,
  133346. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  133347. p->zDb, p->zName, zName
  133348. );
  133349. fts3DbExec(&rc, db,
  133350. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  133351. p->zDb, p->zName, zName
  133352. );
  133353. return rc;
  133354. }
  133355. /*
  133356. ** The xSavepoint() method.
  133357. **
  133358. ** Flush the contents of the pending-terms table to disk.
  133359. */
  133360. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  133361. int rc = SQLITE_OK;
  133362. UNUSED_PARAMETER(iSavepoint);
  133363. assert( ((Fts3Table *)pVtab)->inTransaction );
  133364. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  133365. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  133366. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  133367. rc = fts3SyncMethod(pVtab);
  133368. }
  133369. return rc;
  133370. }
  133371. /*
  133372. ** The xRelease() method.
  133373. **
  133374. ** This is a no-op.
  133375. */
  133376. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  133377. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  133378. UNUSED_PARAMETER(iSavepoint);
  133379. UNUSED_PARAMETER(pVtab);
  133380. assert( p->inTransaction );
  133381. assert( p->mxSavepoint >= iSavepoint );
  133382. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  133383. return SQLITE_OK;
  133384. }
  133385. /*
  133386. ** The xRollbackTo() method.
  133387. **
  133388. ** Discard the contents of the pending terms table.
  133389. */
  133390. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  133391. Fts3Table *p = (Fts3Table*)pVtab;
  133392. UNUSED_PARAMETER(iSavepoint);
  133393. assert( p->inTransaction );
  133394. assert( p->mxSavepoint >= iSavepoint );
  133395. TESTONLY( p->mxSavepoint = iSavepoint );
  133396. sqlite3Fts3PendingTermsClear(p);
  133397. return SQLITE_OK;
  133398. }
  133399. static const sqlite3_module fts3Module = {
  133400. /* iVersion */ 2,
  133401. /* xCreate */ fts3CreateMethod,
  133402. /* xConnect */ fts3ConnectMethod,
  133403. /* xBestIndex */ fts3BestIndexMethod,
  133404. /* xDisconnect */ fts3DisconnectMethod,
  133405. /* xDestroy */ fts3DestroyMethod,
  133406. /* xOpen */ fts3OpenMethod,
  133407. /* xClose */ fts3CloseMethod,
  133408. /* xFilter */ fts3FilterMethod,
  133409. /* xNext */ fts3NextMethod,
  133410. /* xEof */ fts3EofMethod,
  133411. /* xColumn */ fts3ColumnMethod,
  133412. /* xRowid */ fts3RowidMethod,
  133413. /* xUpdate */ fts3UpdateMethod,
  133414. /* xBegin */ fts3BeginMethod,
  133415. /* xSync */ fts3SyncMethod,
  133416. /* xCommit */ fts3CommitMethod,
  133417. /* xRollback */ fts3RollbackMethod,
  133418. /* xFindFunction */ fts3FindFunctionMethod,
  133419. /* xRename */ fts3RenameMethod,
  133420. /* xSavepoint */ fts3SavepointMethod,
  133421. /* xRelease */ fts3ReleaseMethod,
  133422. /* xRollbackTo */ fts3RollbackToMethod,
  133423. };
  133424. /*
  133425. ** This function is registered as the module destructor (called when an
  133426. ** FTS3 enabled database connection is closed). It frees the memory
  133427. ** allocated for the tokenizer hash table.
  133428. */
  133429. static void hashDestroy(void *p){
  133430. Fts3Hash *pHash = (Fts3Hash *)p;
  133431. sqlite3Fts3HashClear(pHash);
  133432. sqlite3_free(pHash);
  133433. }
  133434. /*
  133435. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  133436. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  133437. ** respectively. The following three forward declarations are for functions
  133438. ** declared in these files used to retrieve the respective implementations.
  133439. **
  133440. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  133441. ** to by the argument to point to the "simple" tokenizer implementation.
  133442. ** And so on.
  133443. */
  133444. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  133445. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  133446. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  133447. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  133448. #endif
  133449. #ifdef SQLITE_ENABLE_ICU
  133450. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  133451. #endif
  133452. /*
  133453. ** Initialize the fts3 extension. If this extension is built as part
  133454. ** of the sqlite library, then this function is called directly by
  133455. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  133456. ** function is called by the sqlite3_extension_init() entry point.
  133457. */
  133458. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  133459. int rc = SQLITE_OK;
  133460. Fts3Hash *pHash = 0;
  133461. const sqlite3_tokenizer_module *pSimple = 0;
  133462. const sqlite3_tokenizer_module *pPorter = 0;
  133463. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  133464. const sqlite3_tokenizer_module *pUnicode = 0;
  133465. #endif
  133466. #ifdef SQLITE_ENABLE_ICU
  133467. const sqlite3_tokenizer_module *pIcu = 0;
  133468. sqlite3Fts3IcuTokenizerModule(&pIcu);
  133469. #endif
  133470. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  133471. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  133472. #endif
  133473. #ifdef SQLITE_TEST
  133474. rc = sqlite3Fts3InitTerm(db);
  133475. if( rc!=SQLITE_OK ) return rc;
  133476. #endif
  133477. rc = sqlite3Fts3InitAux(db);
  133478. if( rc!=SQLITE_OK ) return rc;
  133479. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  133480. sqlite3Fts3PorterTokenizerModule(&pPorter);
  133481. /* Allocate and initialize the hash-table used to store tokenizers. */
  133482. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  133483. if( !pHash ){
  133484. rc = SQLITE_NOMEM;
  133485. }else{
  133486. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  133487. }
  133488. /* Load the built-in tokenizers into the hash table */
  133489. if( rc==SQLITE_OK ){
  133490. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  133491. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  133492. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  133493. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  133494. #endif
  133495. #ifdef SQLITE_ENABLE_ICU
  133496. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  133497. #endif
  133498. ){
  133499. rc = SQLITE_NOMEM;
  133500. }
  133501. }
  133502. #ifdef SQLITE_TEST
  133503. if( rc==SQLITE_OK ){
  133504. rc = sqlite3Fts3ExprInitTestInterface(db);
  133505. }
  133506. #endif
  133507. /* Create the virtual table wrapper around the hash-table and overload
  133508. ** the two scalar functions. If this is successful, register the
  133509. ** module with sqlite.
  133510. */
  133511. if( SQLITE_OK==rc
  133512. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  133513. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  133514. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  133515. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  133516. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  133517. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  133518. ){
  133519. rc = sqlite3_create_module_v2(
  133520. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  133521. );
  133522. if( rc==SQLITE_OK ){
  133523. rc = sqlite3_create_module_v2(
  133524. db, "fts4", &fts3Module, (void *)pHash, 0
  133525. );
  133526. }
  133527. if( rc==SQLITE_OK ){
  133528. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  133529. }
  133530. return rc;
  133531. }
  133532. /* An error has occurred. Delete the hash table and return the error code. */
  133533. assert( rc!=SQLITE_OK );
  133534. if( pHash ){
  133535. sqlite3Fts3HashClear(pHash);
  133536. sqlite3_free(pHash);
  133537. }
  133538. return rc;
  133539. }
  133540. /*
  133541. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  133542. ** by pExpr.
  133543. **
  133544. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  133545. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  133546. ** Fts3SegReader objects internally to provide an interface to seek or scan
  133547. ** within the union of all segments of a b-tree. Hence the name.
  133548. **
  133549. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  133550. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  133551. ** there exists prefix b-tree of the right length) then it may be traversed
  133552. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  133553. ** doclist and then traversed.
  133554. */
  133555. static void fts3EvalAllocateReaders(
  133556. Fts3Cursor *pCsr, /* FTS cursor handle */
  133557. Fts3Expr *pExpr, /* Allocate readers for this expression */
  133558. int *pnToken, /* OUT: Total number of tokens in phrase. */
  133559. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  133560. int *pRc /* IN/OUT: Error code */
  133561. ){
  133562. if( pExpr && SQLITE_OK==*pRc ){
  133563. if( pExpr->eType==FTSQUERY_PHRASE ){
  133564. int i;
  133565. int nToken = pExpr->pPhrase->nToken;
  133566. *pnToken += nToken;
  133567. for(i=0; i<nToken; i++){
  133568. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  133569. int rc = fts3TermSegReaderCursor(pCsr,
  133570. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  133571. );
  133572. if( rc!=SQLITE_OK ){
  133573. *pRc = rc;
  133574. return;
  133575. }
  133576. }
  133577. assert( pExpr->pPhrase->iDoclistToken==0 );
  133578. pExpr->pPhrase->iDoclistToken = -1;
  133579. }else{
  133580. *pnOr += (pExpr->eType==FTSQUERY_OR);
  133581. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  133582. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  133583. }
  133584. }
  133585. }
  133586. /*
  133587. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  133588. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  133589. **
  133590. ** This function assumes that pList points to a buffer allocated using
  133591. ** sqlite3_malloc(). This function takes responsibility for eventually
  133592. ** freeing the buffer.
  133593. **
  133594. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  133595. */
  133596. static int fts3EvalPhraseMergeToken(
  133597. Fts3Table *pTab, /* FTS Table pointer */
  133598. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  133599. int iToken, /* Token pList/nList corresponds to */
  133600. char *pList, /* Pointer to doclist */
  133601. int nList /* Number of bytes in pList */
  133602. ){
  133603. int rc = SQLITE_OK;
  133604. assert( iToken!=p->iDoclistToken );
  133605. if( pList==0 ){
  133606. sqlite3_free(p->doclist.aAll);
  133607. p->doclist.aAll = 0;
  133608. p->doclist.nAll = 0;
  133609. }
  133610. else if( p->iDoclistToken<0 ){
  133611. p->doclist.aAll = pList;
  133612. p->doclist.nAll = nList;
  133613. }
  133614. else if( p->doclist.aAll==0 ){
  133615. sqlite3_free(pList);
  133616. }
  133617. else {
  133618. char *pLeft;
  133619. char *pRight;
  133620. int nLeft;
  133621. int nRight;
  133622. int nDiff;
  133623. if( p->iDoclistToken<iToken ){
  133624. pLeft = p->doclist.aAll;
  133625. nLeft = p->doclist.nAll;
  133626. pRight = pList;
  133627. nRight = nList;
  133628. nDiff = iToken - p->iDoclistToken;
  133629. }else{
  133630. pRight = p->doclist.aAll;
  133631. nRight = p->doclist.nAll;
  133632. pLeft = pList;
  133633. nLeft = nList;
  133634. nDiff = p->iDoclistToken - iToken;
  133635. }
  133636. rc = fts3DoclistPhraseMerge(
  133637. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  133638. );
  133639. sqlite3_free(pLeft);
  133640. p->doclist.aAll = pRight;
  133641. p->doclist.nAll = nRight;
  133642. }
  133643. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  133644. return rc;
  133645. }
  133646. /*
  133647. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  133648. ** does not take deferred tokens into account.
  133649. **
  133650. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  133651. */
  133652. static int fts3EvalPhraseLoad(
  133653. Fts3Cursor *pCsr, /* FTS Cursor handle */
  133654. Fts3Phrase *p /* Phrase object */
  133655. ){
  133656. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  133657. int iToken;
  133658. int rc = SQLITE_OK;
  133659. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  133660. Fts3PhraseToken *pToken = &p->aToken[iToken];
  133661. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  133662. if( pToken->pSegcsr ){
  133663. int nThis = 0;
  133664. char *pThis = 0;
  133665. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  133666. if( rc==SQLITE_OK ){
  133667. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  133668. }
  133669. }
  133670. assert( pToken->pSegcsr==0 );
  133671. }
  133672. return rc;
  133673. }
  133674. /*
  133675. ** This function is called on each phrase after the position lists for
  133676. ** any deferred tokens have been loaded into memory. It updates the phrases
  133677. ** current position list to include only those positions that are really
  133678. ** instances of the phrase (after considering deferred tokens). If this
  133679. ** means that the phrase does not appear in the current row, doclist.pList
  133680. ** and doclist.nList are both zeroed.
  133681. **
  133682. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  133683. */
  133684. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  133685. int iToken; /* Used to iterate through phrase tokens */
  133686. char *aPoslist = 0; /* Position list for deferred tokens */
  133687. int nPoslist = 0; /* Number of bytes in aPoslist */
  133688. int iPrev = -1; /* Token number of previous deferred token */
  133689. assert( pPhrase->doclist.bFreeList==0 );
  133690. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  133691. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  133692. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  133693. if( pDeferred ){
  133694. char *pList;
  133695. int nList;
  133696. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  133697. if( rc!=SQLITE_OK ) return rc;
  133698. if( pList==0 ){
  133699. sqlite3_free(aPoslist);
  133700. pPhrase->doclist.pList = 0;
  133701. pPhrase->doclist.nList = 0;
  133702. return SQLITE_OK;
  133703. }else if( aPoslist==0 ){
  133704. aPoslist = pList;
  133705. nPoslist = nList;
  133706. }else{
  133707. char *aOut = pList;
  133708. char *p1 = aPoslist;
  133709. char *p2 = aOut;
  133710. assert( iPrev>=0 );
  133711. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  133712. sqlite3_free(aPoslist);
  133713. aPoslist = pList;
  133714. nPoslist = (int)(aOut - aPoslist);
  133715. if( nPoslist==0 ){
  133716. sqlite3_free(aPoslist);
  133717. pPhrase->doclist.pList = 0;
  133718. pPhrase->doclist.nList = 0;
  133719. return SQLITE_OK;
  133720. }
  133721. }
  133722. iPrev = iToken;
  133723. }
  133724. }
  133725. if( iPrev>=0 ){
  133726. int nMaxUndeferred = pPhrase->iDoclistToken;
  133727. if( nMaxUndeferred<0 ){
  133728. pPhrase->doclist.pList = aPoslist;
  133729. pPhrase->doclist.nList = nPoslist;
  133730. pPhrase->doclist.iDocid = pCsr->iPrevId;
  133731. pPhrase->doclist.bFreeList = 1;
  133732. }else{
  133733. int nDistance;
  133734. char *p1;
  133735. char *p2;
  133736. char *aOut;
  133737. if( nMaxUndeferred>iPrev ){
  133738. p1 = aPoslist;
  133739. p2 = pPhrase->doclist.pList;
  133740. nDistance = nMaxUndeferred - iPrev;
  133741. }else{
  133742. p1 = pPhrase->doclist.pList;
  133743. p2 = aPoslist;
  133744. nDistance = iPrev - nMaxUndeferred;
  133745. }
  133746. aOut = (char *)sqlite3_malloc(nPoslist+8);
  133747. if( !aOut ){
  133748. sqlite3_free(aPoslist);
  133749. return SQLITE_NOMEM;
  133750. }
  133751. pPhrase->doclist.pList = aOut;
  133752. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  133753. pPhrase->doclist.bFreeList = 1;
  133754. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  133755. }else{
  133756. sqlite3_free(aOut);
  133757. pPhrase->doclist.pList = 0;
  133758. pPhrase->doclist.nList = 0;
  133759. }
  133760. sqlite3_free(aPoslist);
  133761. }
  133762. }
  133763. return SQLITE_OK;
  133764. }
  133765. /*
  133766. ** Maximum number of tokens a phrase may have to be considered for the
  133767. ** incremental doclists strategy.
  133768. */
  133769. #define MAX_INCR_PHRASE_TOKENS 4
  133770. /*
  133771. ** This function is called for each Fts3Phrase in a full-text query
  133772. ** expression to initialize the mechanism for returning rows. Once this
  133773. ** function has been called successfully on an Fts3Phrase, it may be
  133774. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  133775. **
  133776. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  133777. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  133778. ** memory within this call.
  133779. **
  133780. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  133781. */
  133782. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  133783. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  133784. int rc = SQLITE_OK; /* Error code */
  133785. int i;
  133786. /* Determine if doclists may be loaded from disk incrementally. This is
  133787. ** possible if the bOptOk argument is true, the FTS doclists will be
  133788. ** scanned in forward order, and the phrase consists of
  133789. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  133790. ** tokens or prefix tokens that cannot use a prefix-index. */
  133791. int bHaveIncr = 0;
  133792. int bIncrOk = (bOptOk
  133793. && pCsr->bDesc==pTab->bDescIdx
  133794. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  133795. #ifdef SQLITE_TEST
  133796. && pTab->bNoIncrDoclist==0
  133797. #endif
  133798. );
  133799. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  133800. Fts3PhraseToken *pToken = &p->aToken[i];
  133801. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  133802. bIncrOk = 0;
  133803. }
  133804. if( pToken->pSegcsr ) bHaveIncr = 1;
  133805. }
  133806. if( bIncrOk && bHaveIncr ){
  133807. /* Use the incremental approach. */
  133808. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  133809. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  133810. Fts3PhraseToken *pToken = &p->aToken[i];
  133811. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  133812. if( pSegcsr ){
  133813. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  133814. }
  133815. }
  133816. p->bIncr = 1;
  133817. }else{
  133818. /* Load the full doclist for the phrase into memory. */
  133819. rc = fts3EvalPhraseLoad(pCsr, p);
  133820. p->bIncr = 0;
  133821. }
  133822. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  133823. return rc;
  133824. }
  133825. /*
  133826. ** This function is used to iterate backwards (from the end to start)
  133827. ** through doclists. It is used by this module to iterate through phrase
  133828. ** doclists in reverse and by the fts3_write.c module to iterate through
  133829. ** pending-terms lists when writing to databases with "order=desc".
  133830. **
  133831. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  133832. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  133833. ** function iterates from the end of the doclist to the beginning.
  133834. */
  133835. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  133836. int bDescIdx, /* True if the doclist is desc */
  133837. char *aDoclist, /* Pointer to entire doclist */
  133838. int nDoclist, /* Length of aDoclist in bytes */
  133839. char **ppIter, /* IN/OUT: Iterator pointer */
  133840. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  133841. int *pnList, /* OUT: List length pointer */
  133842. u8 *pbEof /* OUT: End-of-file flag */
  133843. ){
  133844. char *p = *ppIter;
  133845. assert( nDoclist>0 );
  133846. assert( *pbEof==0 );
  133847. assert( p || *piDocid==0 );
  133848. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  133849. if( p==0 ){
  133850. sqlite3_int64 iDocid = 0;
  133851. char *pNext = 0;
  133852. char *pDocid = aDoclist;
  133853. char *pEnd = &aDoclist[nDoclist];
  133854. int iMul = 1;
  133855. while( pDocid<pEnd ){
  133856. sqlite3_int64 iDelta;
  133857. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  133858. iDocid += (iMul * iDelta);
  133859. pNext = pDocid;
  133860. fts3PoslistCopy(0, &pDocid);
  133861. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  133862. iMul = (bDescIdx ? -1 : 1);
  133863. }
  133864. *pnList = (int)(pEnd - pNext);
  133865. *ppIter = pNext;
  133866. *piDocid = iDocid;
  133867. }else{
  133868. int iMul = (bDescIdx ? -1 : 1);
  133869. sqlite3_int64 iDelta;
  133870. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  133871. *piDocid -= (iMul * iDelta);
  133872. if( p==aDoclist ){
  133873. *pbEof = 1;
  133874. }else{
  133875. char *pSave = p;
  133876. fts3ReversePoslist(aDoclist, &p);
  133877. *pnList = (int)(pSave - p);
  133878. }
  133879. *ppIter = p;
  133880. }
  133881. }
  133882. /*
  133883. ** Iterate forwards through a doclist.
  133884. */
  133885. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  133886. int bDescIdx, /* True if the doclist is desc */
  133887. char *aDoclist, /* Pointer to entire doclist */
  133888. int nDoclist, /* Length of aDoclist in bytes */
  133889. char **ppIter, /* IN/OUT: Iterator pointer */
  133890. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  133891. u8 *pbEof /* OUT: End-of-file flag */
  133892. ){
  133893. char *p = *ppIter;
  133894. assert( nDoclist>0 );
  133895. assert( *pbEof==0 );
  133896. assert( p || *piDocid==0 );
  133897. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  133898. if( p==0 ){
  133899. p = aDoclist;
  133900. p += sqlite3Fts3GetVarint(p, piDocid);
  133901. }else{
  133902. fts3PoslistCopy(0, &p);
  133903. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  133904. if( p>=&aDoclist[nDoclist] ){
  133905. *pbEof = 1;
  133906. }else{
  133907. sqlite3_int64 iVar;
  133908. p += sqlite3Fts3GetVarint(p, &iVar);
  133909. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  133910. }
  133911. }
  133912. *ppIter = p;
  133913. }
  133914. /*
  133915. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  133916. ** to true if EOF is reached.
  133917. */
  133918. static void fts3EvalDlPhraseNext(
  133919. Fts3Table *pTab,
  133920. Fts3Doclist *pDL,
  133921. u8 *pbEof
  133922. ){
  133923. char *pIter; /* Used to iterate through aAll */
  133924. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  133925. if( pDL->pNextDocid ){
  133926. pIter = pDL->pNextDocid;
  133927. }else{
  133928. pIter = pDL->aAll;
  133929. }
  133930. if( pIter>=pEnd ){
  133931. /* We have already reached the end of this doclist. EOF. */
  133932. *pbEof = 1;
  133933. }else{
  133934. sqlite3_int64 iDelta;
  133935. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  133936. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  133937. pDL->iDocid += iDelta;
  133938. }else{
  133939. pDL->iDocid -= iDelta;
  133940. }
  133941. pDL->pList = pIter;
  133942. fts3PoslistCopy(0, &pIter);
  133943. pDL->nList = (int)(pIter - pDL->pList);
  133944. /* pIter now points just past the 0x00 that terminates the position-
  133945. ** list for document pDL->iDocid. However, if this position-list was
  133946. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  133947. ** point to the start of the next docid value. The following line deals
  133948. ** with this case by advancing pIter past the zero-padding added by
  133949. ** fts3EvalNearTrim(). */
  133950. while( pIter<pEnd && *pIter==0 ) pIter++;
  133951. pDL->pNextDocid = pIter;
  133952. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  133953. *pbEof = 0;
  133954. }
  133955. }
  133956. /*
  133957. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  133958. */
  133959. typedef struct TokenDoclist TokenDoclist;
  133960. struct TokenDoclist {
  133961. int bIgnore;
  133962. sqlite3_int64 iDocid;
  133963. char *pList;
  133964. int nList;
  133965. };
  133966. /*
  133967. ** Token pToken is an incrementally loaded token that is part of a
  133968. ** multi-token phrase. Advance it to the next matching document in the
  133969. ** database and populate output variable *p with the details of the new
  133970. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  133971. **
  133972. ** If an error occurs, return an SQLite error code. Otherwise, return
  133973. ** SQLITE_OK.
  133974. */
  133975. static int incrPhraseTokenNext(
  133976. Fts3Table *pTab, /* Virtual table handle */
  133977. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  133978. int iToken, /* Specific token to advance */
  133979. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  133980. u8 *pbEof /* OUT: True if iterator is at EOF */
  133981. ){
  133982. int rc = SQLITE_OK;
  133983. if( pPhrase->iDoclistToken==iToken ){
  133984. assert( p->bIgnore==0 );
  133985. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  133986. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  133987. p->pList = pPhrase->doclist.pList;
  133988. p->nList = pPhrase->doclist.nList;
  133989. p->iDocid = pPhrase->doclist.iDocid;
  133990. }else{
  133991. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  133992. assert( pToken->pDeferred==0 );
  133993. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  133994. if( pToken->pSegcsr ){
  133995. assert( p->bIgnore==0 );
  133996. rc = sqlite3Fts3MsrIncrNext(
  133997. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  133998. );
  133999. if( p->pList==0 ) *pbEof = 1;
  134000. }else{
  134001. p->bIgnore = 1;
  134002. }
  134003. }
  134004. return rc;
  134005. }
  134006. /*
  134007. ** The phrase iterator passed as the second argument:
  134008. **
  134009. ** * features at least one token that uses an incremental doclist, and
  134010. **
  134011. ** * does not contain any deferred tokens.
  134012. **
  134013. ** Advance it to the next matching documnent in the database and populate
  134014. ** the Fts3Doclist.pList and nList fields.
  134015. **
  134016. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  134017. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  134018. ** successfully advanced, *pbEof is set to 0.
  134019. **
  134020. ** If an error occurs, return an SQLite error code. Otherwise, return
  134021. ** SQLITE_OK.
  134022. */
  134023. static int fts3EvalIncrPhraseNext(
  134024. Fts3Cursor *pCsr, /* FTS Cursor handle */
  134025. Fts3Phrase *p, /* Phrase object to advance to next docid */
  134026. u8 *pbEof /* OUT: Set to 1 if EOF */
  134027. ){
  134028. int rc = SQLITE_OK;
  134029. Fts3Doclist *pDL = &p->doclist;
  134030. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  134031. u8 bEof = 0;
  134032. /* This is only called if it is guaranteed that the phrase has at least
  134033. ** one incremental token. In which case the bIncr flag is set. */
  134034. assert( p->bIncr==1 );
  134035. if( p->nToken==1 && p->bIncr ){
  134036. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  134037. &pDL->iDocid, &pDL->pList, &pDL->nList
  134038. );
  134039. if( pDL->pList==0 ) bEof = 1;
  134040. }else{
  134041. int bDescDoclist = pCsr->bDesc;
  134042. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  134043. memset(a, 0, sizeof(a));
  134044. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  134045. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  134046. while( bEof==0 ){
  134047. int bMaxSet = 0;
  134048. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  134049. int i; /* Used to iterate through tokens */
  134050. /* Advance the iterator for each token in the phrase once. */
  134051. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  134052. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  134053. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  134054. iMax = a[i].iDocid;
  134055. bMaxSet = 1;
  134056. }
  134057. }
  134058. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  134059. assert( rc!=SQLITE_OK || bMaxSet );
  134060. /* Keep advancing iterators until they all point to the same document */
  134061. for(i=0; i<p->nToken; i++){
  134062. while( rc==SQLITE_OK && bEof==0
  134063. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  134064. ){
  134065. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  134066. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  134067. iMax = a[i].iDocid;
  134068. i = 0;
  134069. }
  134070. }
  134071. }
  134072. /* Check if the current entries really are a phrase match */
  134073. if( bEof==0 ){
  134074. int nList = 0;
  134075. int nByte = a[p->nToken-1].nList;
  134076. char *aDoclist = sqlite3_malloc(nByte+1);
  134077. if( !aDoclist ) return SQLITE_NOMEM;
  134078. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  134079. for(i=0; i<(p->nToken-1); i++){
  134080. if( a[i].bIgnore==0 ){
  134081. char *pL = a[i].pList;
  134082. char *pR = aDoclist;
  134083. char *pOut = aDoclist;
  134084. int nDist = p->nToken-1-i;
  134085. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  134086. if( res==0 ) break;
  134087. nList = (int)(pOut - aDoclist);
  134088. }
  134089. }
  134090. if( i==(p->nToken-1) ){
  134091. pDL->iDocid = iMax;
  134092. pDL->pList = aDoclist;
  134093. pDL->nList = nList;
  134094. pDL->bFreeList = 1;
  134095. break;
  134096. }
  134097. sqlite3_free(aDoclist);
  134098. }
  134099. }
  134100. }
  134101. *pbEof = bEof;
  134102. return rc;
  134103. }
  134104. /*
  134105. ** Attempt to move the phrase iterator to point to the next matching docid.
  134106. ** If an error occurs, return an SQLite error code. Otherwise, return
  134107. ** SQLITE_OK.
  134108. **
  134109. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  134110. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  134111. ** successfully advanced, *pbEof is set to 0.
  134112. */
  134113. static int fts3EvalPhraseNext(
  134114. Fts3Cursor *pCsr, /* FTS Cursor handle */
  134115. Fts3Phrase *p, /* Phrase object to advance to next docid */
  134116. u8 *pbEof /* OUT: Set to 1 if EOF */
  134117. ){
  134118. int rc = SQLITE_OK;
  134119. Fts3Doclist *pDL = &p->doclist;
  134120. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  134121. if( p->bIncr ){
  134122. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  134123. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  134124. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  134125. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  134126. );
  134127. pDL->pList = pDL->pNextDocid;
  134128. }else{
  134129. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  134130. }
  134131. return rc;
  134132. }
  134133. /*
  134134. **
  134135. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  134136. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  134137. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  134138. ** expressions for which all descendent tokens are deferred.
  134139. **
  134140. ** If parameter bOptOk is zero, then it is guaranteed that the
  134141. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  134142. ** each phrase in the expression (subject to deferred token processing).
  134143. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  134144. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  134145. **
  134146. ** If an error occurs within this function, *pRc is set to an SQLite error
  134147. ** code before returning.
  134148. */
  134149. static void fts3EvalStartReaders(
  134150. Fts3Cursor *pCsr, /* FTS Cursor handle */
  134151. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  134152. int *pRc /* IN/OUT: Error code */
  134153. ){
  134154. if( pExpr && SQLITE_OK==*pRc ){
  134155. if( pExpr->eType==FTSQUERY_PHRASE ){
  134156. int nToken = pExpr->pPhrase->nToken;
  134157. if( nToken ){
  134158. int i;
  134159. for(i=0; i<nToken; i++){
  134160. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  134161. }
  134162. pExpr->bDeferred = (i==nToken);
  134163. }
  134164. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  134165. }else{
  134166. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  134167. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  134168. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  134169. }
  134170. }
  134171. }
  134172. /*
  134173. ** An array of the following structures is assembled as part of the process
  134174. ** of selecting tokens to defer before the query starts executing (as part
  134175. ** of the xFilter() method). There is one element in the array for each
  134176. ** token in the FTS expression.
  134177. **
  134178. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  134179. ** to phrases that are connected only by AND and NEAR operators (not OR or
  134180. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  134181. ** separately. The root of a tokens AND/NEAR cluster is stored in
  134182. ** Fts3TokenAndCost.pRoot.
  134183. */
  134184. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  134185. struct Fts3TokenAndCost {
  134186. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  134187. int iToken; /* Position of token in phrase */
  134188. Fts3PhraseToken *pToken; /* The token itself */
  134189. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  134190. int nOvfl; /* Number of overflow pages to load doclist */
  134191. int iCol; /* The column the token must match */
  134192. };
  134193. /*
  134194. ** This function is used to populate an allocated Fts3TokenAndCost array.
  134195. **
  134196. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  134197. ** Otherwise, if an error occurs during execution, *pRc is set to an
  134198. ** SQLite error code.
  134199. */
  134200. static void fts3EvalTokenCosts(
  134201. Fts3Cursor *pCsr, /* FTS Cursor handle */
  134202. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  134203. Fts3Expr *pExpr, /* Expression to consider */
  134204. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  134205. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  134206. int *pRc /* IN/OUT: Error code */
  134207. ){
  134208. if( *pRc==SQLITE_OK ){
  134209. if( pExpr->eType==FTSQUERY_PHRASE ){
  134210. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134211. int i;
  134212. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  134213. Fts3TokenAndCost *pTC = (*ppTC)++;
  134214. pTC->pPhrase = pPhrase;
  134215. pTC->iToken = i;
  134216. pTC->pRoot = pRoot;
  134217. pTC->pToken = &pPhrase->aToken[i];
  134218. pTC->iCol = pPhrase->iColumn;
  134219. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  134220. }
  134221. }else if( pExpr->eType!=FTSQUERY_NOT ){
  134222. assert( pExpr->eType==FTSQUERY_OR
  134223. || pExpr->eType==FTSQUERY_AND
  134224. || pExpr->eType==FTSQUERY_NEAR
  134225. );
  134226. assert( pExpr->pLeft && pExpr->pRight );
  134227. if( pExpr->eType==FTSQUERY_OR ){
  134228. pRoot = pExpr->pLeft;
  134229. **ppOr = pRoot;
  134230. (*ppOr)++;
  134231. }
  134232. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  134233. if( pExpr->eType==FTSQUERY_OR ){
  134234. pRoot = pExpr->pRight;
  134235. **ppOr = pRoot;
  134236. (*ppOr)++;
  134237. }
  134238. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  134239. }
  134240. }
  134241. }
  134242. /*
  134243. ** Determine the average document (row) size in pages. If successful,
  134244. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  134245. ** an SQLite error code.
  134246. **
  134247. ** The average document size in pages is calculated by first calculating
  134248. ** determining the average size in bytes, B. If B is less than the amount
  134249. ** of data that will fit on a single leaf page of an intkey table in
  134250. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  134251. ** the number of overflow pages consumed by a record B bytes in size.
  134252. */
  134253. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  134254. if( pCsr->nRowAvg==0 ){
  134255. /* The average document size, which is required to calculate the cost
  134256. ** of each doclist, has not yet been determined. Read the required
  134257. ** data from the %_stat table to calculate it.
  134258. **
  134259. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  134260. ** varints, where nCol is the number of columns in the FTS3 table.
  134261. ** The first varint is the number of documents currently stored in
  134262. ** the table. The following nCol varints contain the total amount of
  134263. ** data stored in all rows of each column of the table, from left
  134264. ** to right.
  134265. */
  134266. int rc;
  134267. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  134268. sqlite3_stmt *pStmt;
  134269. sqlite3_int64 nDoc = 0;
  134270. sqlite3_int64 nByte = 0;
  134271. const char *pEnd;
  134272. const char *a;
  134273. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  134274. if( rc!=SQLITE_OK ) return rc;
  134275. a = sqlite3_column_blob(pStmt, 0);
  134276. assert( a );
  134277. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  134278. a += sqlite3Fts3GetVarint(a, &nDoc);
  134279. while( a<pEnd ){
  134280. a += sqlite3Fts3GetVarint(a, &nByte);
  134281. }
  134282. if( nDoc==0 || nByte==0 ){
  134283. sqlite3_reset(pStmt);
  134284. return FTS_CORRUPT_VTAB;
  134285. }
  134286. pCsr->nDoc = nDoc;
  134287. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  134288. assert( pCsr->nRowAvg>0 );
  134289. rc = sqlite3_reset(pStmt);
  134290. if( rc!=SQLITE_OK ) return rc;
  134291. }
  134292. *pnPage = pCsr->nRowAvg;
  134293. return SQLITE_OK;
  134294. }
  134295. /*
  134296. ** This function is called to select the tokens (if any) that will be
  134297. ** deferred. The array aTC[] has already been populated when this is
  134298. ** called.
  134299. **
  134300. ** This function is called once for each AND/NEAR cluster in the
  134301. ** expression. Each invocation determines which tokens to defer within
  134302. ** the cluster with root node pRoot. See comments above the definition
  134303. ** of struct Fts3TokenAndCost for more details.
  134304. **
  134305. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  134306. ** called on each token to defer. Otherwise, an SQLite error code is
  134307. ** returned.
  134308. */
  134309. static int fts3EvalSelectDeferred(
  134310. Fts3Cursor *pCsr, /* FTS Cursor handle */
  134311. Fts3Expr *pRoot, /* Consider tokens with this root node */
  134312. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  134313. int nTC /* Number of entries in aTC[] */
  134314. ){
  134315. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  134316. int nDocSize = 0; /* Number of pages per doc loaded */
  134317. int rc = SQLITE_OK; /* Return code */
  134318. int ii; /* Iterator variable for various purposes */
  134319. int nOvfl = 0; /* Total overflow pages used by doclists */
  134320. int nToken = 0; /* Total number of tokens in cluster */
  134321. int nMinEst = 0; /* The minimum count for any phrase so far. */
  134322. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  134323. /* Tokens are never deferred for FTS tables created using the content=xxx
  134324. ** option. The reason being that it is not guaranteed that the content
  134325. ** table actually contains the same data as the index. To prevent this from
  134326. ** causing any problems, the deferred token optimization is completely
  134327. ** disabled for content=xxx tables. */
  134328. if( pTab->zContentTbl ){
  134329. return SQLITE_OK;
  134330. }
  134331. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  134332. ** associated with the tokens spill onto overflow pages, or if there is
  134333. ** only 1 token, exit early. No tokens to defer in this case. */
  134334. for(ii=0; ii<nTC; ii++){
  134335. if( aTC[ii].pRoot==pRoot ){
  134336. nOvfl += aTC[ii].nOvfl;
  134337. nToken++;
  134338. }
  134339. }
  134340. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  134341. /* Obtain the average docsize (in pages). */
  134342. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  134343. assert( rc!=SQLITE_OK || nDocSize>0 );
  134344. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  134345. ** of the number of overflow pages that will be loaded by the pager layer
  134346. ** to retrieve the entire doclist for the token from the full-text index.
  134347. ** Load the doclists for tokens that are either:
  134348. **
  134349. ** a. The cheapest token in the entire query (i.e. the one visited by the
  134350. ** first iteration of this loop), or
  134351. **
  134352. ** b. Part of a multi-token phrase.
  134353. **
  134354. ** After each token doclist is loaded, merge it with the others from the
  134355. ** same phrase and count the number of documents that the merged doclist
  134356. ** contains. Set variable "nMinEst" to the smallest number of documents in
  134357. ** any phrase doclist for which 1 or more token doclists have been loaded.
  134358. ** Let nOther be the number of other phrases for which it is certain that
  134359. ** one or more tokens will not be deferred.
  134360. **
  134361. ** Then, for each token, defer it if loading the doclist would result in
  134362. ** loading N or more overflow pages into memory, where N is computed as:
  134363. **
  134364. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  134365. */
  134366. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  134367. int iTC; /* Used to iterate through aTC[] array. */
  134368. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  134369. /* Set pTC to point to the cheapest remaining token. */
  134370. for(iTC=0; iTC<nTC; iTC++){
  134371. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  134372. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  134373. ){
  134374. pTC = &aTC[iTC];
  134375. }
  134376. }
  134377. assert( pTC );
  134378. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  134379. /* The number of overflow pages to load for this (and therefore all
  134380. ** subsequent) tokens is greater than the estimated number of pages
  134381. ** that will be loaded if all subsequent tokens are deferred.
  134382. */
  134383. Fts3PhraseToken *pToken = pTC->pToken;
  134384. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  134385. fts3SegReaderCursorFree(pToken->pSegcsr);
  134386. pToken->pSegcsr = 0;
  134387. }else{
  134388. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  134389. ** for-loop. Except, limit the value to 2^24 to prevent it from
  134390. ** overflowing the 32-bit integer it is stored in. */
  134391. if( ii<12 ) nLoad4 = nLoad4*4;
  134392. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  134393. /* Either this is the cheapest token in the entire query, or it is
  134394. ** part of a multi-token phrase. Either way, the entire doclist will
  134395. ** (eventually) be loaded into memory. It may as well be now. */
  134396. Fts3PhraseToken *pToken = pTC->pToken;
  134397. int nList = 0;
  134398. char *pList = 0;
  134399. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  134400. assert( rc==SQLITE_OK || pList==0 );
  134401. if( rc==SQLITE_OK ){
  134402. rc = fts3EvalPhraseMergeToken(
  134403. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  134404. );
  134405. }
  134406. if( rc==SQLITE_OK ){
  134407. int nCount;
  134408. nCount = fts3DoclistCountDocids(
  134409. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  134410. );
  134411. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  134412. }
  134413. }
  134414. }
  134415. pTC->pToken = 0;
  134416. }
  134417. return rc;
  134418. }
  134419. /*
  134420. ** This function is called from within the xFilter method. It initializes
  134421. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  134422. ** the results of a query, the caller does:
  134423. **
  134424. ** fts3EvalStart(pCsr);
  134425. ** while( 1 ){
  134426. ** fts3EvalNext(pCsr);
  134427. ** if( pCsr->bEof ) break;
  134428. ** ... return row pCsr->iPrevId to the caller ...
  134429. ** }
  134430. */
  134431. static int fts3EvalStart(Fts3Cursor *pCsr){
  134432. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  134433. int rc = SQLITE_OK;
  134434. int nToken = 0;
  134435. int nOr = 0;
  134436. /* Allocate a MultiSegReader for each token in the expression. */
  134437. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  134438. /* Determine which, if any, tokens in the expression should be deferred. */
  134439. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  134440. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  134441. Fts3TokenAndCost *aTC;
  134442. Fts3Expr **apOr;
  134443. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  134444. sizeof(Fts3TokenAndCost) * nToken
  134445. + sizeof(Fts3Expr *) * nOr * 2
  134446. );
  134447. apOr = (Fts3Expr **)&aTC[nToken];
  134448. if( !aTC ){
  134449. rc = SQLITE_NOMEM;
  134450. }else{
  134451. int ii;
  134452. Fts3TokenAndCost *pTC = aTC;
  134453. Fts3Expr **ppOr = apOr;
  134454. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  134455. nToken = (int)(pTC-aTC);
  134456. nOr = (int)(ppOr-apOr);
  134457. if( rc==SQLITE_OK ){
  134458. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  134459. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  134460. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  134461. }
  134462. }
  134463. sqlite3_free(aTC);
  134464. }
  134465. }
  134466. #endif
  134467. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  134468. return rc;
  134469. }
  134470. /*
  134471. ** Invalidate the current position list for phrase pPhrase.
  134472. */
  134473. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  134474. if( pPhrase->doclist.bFreeList ){
  134475. sqlite3_free(pPhrase->doclist.pList);
  134476. }
  134477. pPhrase->doclist.pList = 0;
  134478. pPhrase->doclist.nList = 0;
  134479. pPhrase->doclist.bFreeList = 0;
  134480. }
  134481. /*
  134482. ** This function is called to edit the position list associated with
  134483. ** the phrase object passed as the fifth argument according to a NEAR
  134484. ** condition. For example:
  134485. **
  134486. ** abc NEAR/5 "def ghi"
  134487. **
  134488. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  134489. ** the example above). When this function is called, *paPoslist points to
  134490. ** the position list, and *pnToken is the number of phrase tokens in, the
  134491. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  134492. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  134493. ** the position list associated with phrase "abc".
  134494. **
  134495. ** All positions in the pPhrase position list that are not sufficiently
  134496. ** close to a position in the *paPoslist position list are removed. If this
  134497. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  134498. **
  134499. ** Before returning, *paPoslist is set to point to the position lsit
  134500. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  134501. ** pPhrase.
  134502. */
  134503. static int fts3EvalNearTrim(
  134504. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  134505. char *aTmp, /* Temporary space to use */
  134506. char **paPoslist, /* IN/OUT: Position list */
  134507. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  134508. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  134509. ){
  134510. int nParam1 = nNear + pPhrase->nToken;
  134511. int nParam2 = nNear + *pnToken;
  134512. int nNew;
  134513. char *p2;
  134514. char *pOut;
  134515. int res;
  134516. assert( pPhrase->doclist.pList );
  134517. p2 = pOut = pPhrase->doclist.pList;
  134518. res = fts3PoslistNearMerge(
  134519. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  134520. );
  134521. if( res ){
  134522. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  134523. assert( pPhrase->doclist.pList[nNew]=='\0' );
  134524. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  134525. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  134526. pPhrase->doclist.nList = nNew;
  134527. *paPoslist = pPhrase->doclist.pList;
  134528. *pnToken = pPhrase->nToken;
  134529. }
  134530. return res;
  134531. }
  134532. /*
  134533. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  134534. ** Otherwise, it advances the expression passed as the second argument to
  134535. ** point to the next matching row in the database. Expressions iterate through
  134536. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  134537. ** or descending if it is non-zero.
  134538. **
  134539. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  134540. ** successful, the following variables in pExpr are set:
  134541. **
  134542. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  134543. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  134544. **
  134545. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  134546. ** at EOF, then the following variables are populated with the position list
  134547. ** for the phrase for the visited row:
  134548. **
  134549. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  134550. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  134551. **
  134552. ** It says above that this function advances the expression to the next
  134553. ** matching row. This is usually true, but there are the following exceptions:
  134554. **
  134555. ** 1. Deferred tokens are not taken into account. If a phrase consists
  134556. ** entirely of deferred tokens, it is assumed to match every row in
  134557. ** the db. In this case the position-list is not populated at all.
  134558. **
  134559. ** Or, if a phrase contains one or more deferred tokens and one or
  134560. ** more non-deferred tokens, then the expression is advanced to the
  134561. ** next possible match, considering only non-deferred tokens. In other
  134562. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  134563. ** is advanced to the next row that contains an instance of "A * C",
  134564. ** where "*" may match any single token. The position list in this case
  134565. ** is populated as for "A * C" before returning.
  134566. **
  134567. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  134568. ** advanced to point to the next row that matches "x AND y".
  134569. **
  134570. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  134571. ** really a match, taking into account deferred tokens and NEAR operators.
  134572. */
  134573. static void fts3EvalNextRow(
  134574. Fts3Cursor *pCsr, /* FTS Cursor handle */
  134575. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  134576. int *pRc /* IN/OUT: Error code */
  134577. ){
  134578. if( *pRc==SQLITE_OK ){
  134579. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  134580. assert( pExpr->bEof==0 );
  134581. pExpr->bStart = 1;
  134582. switch( pExpr->eType ){
  134583. case FTSQUERY_NEAR:
  134584. case FTSQUERY_AND: {
  134585. Fts3Expr *pLeft = pExpr->pLeft;
  134586. Fts3Expr *pRight = pExpr->pRight;
  134587. assert( !pLeft->bDeferred || !pRight->bDeferred );
  134588. if( pLeft->bDeferred ){
  134589. /* LHS is entirely deferred. So we assume it matches every row.
  134590. ** Advance the RHS iterator to find the next row visited. */
  134591. fts3EvalNextRow(pCsr, pRight, pRc);
  134592. pExpr->iDocid = pRight->iDocid;
  134593. pExpr->bEof = pRight->bEof;
  134594. }else if( pRight->bDeferred ){
  134595. /* RHS is entirely deferred. So we assume it matches every row.
  134596. ** Advance the LHS iterator to find the next row visited. */
  134597. fts3EvalNextRow(pCsr, pLeft, pRc);
  134598. pExpr->iDocid = pLeft->iDocid;
  134599. pExpr->bEof = pLeft->bEof;
  134600. }else{
  134601. /* Neither the RHS or LHS are deferred. */
  134602. fts3EvalNextRow(pCsr, pLeft, pRc);
  134603. fts3EvalNextRow(pCsr, pRight, pRc);
  134604. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  134605. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  134606. if( iDiff==0 ) break;
  134607. if( iDiff<0 ){
  134608. fts3EvalNextRow(pCsr, pLeft, pRc);
  134609. }else{
  134610. fts3EvalNextRow(pCsr, pRight, pRc);
  134611. }
  134612. }
  134613. pExpr->iDocid = pLeft->iDocid;
  134614. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  134615. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  134616. if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
  134617. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  134618. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  134619. memset(pDl->pList, 0, pDl->nList);
  134620. fts3EvalNextRow(pCsr, pRight, pRc);
  134621. }
  134622. }
  134623. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  134624. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  134625. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  134626. memset(pDl->pList, 0, pDl->nList);
  134627. fts3EvalNextRow(pCsr, pLeft, pRc);
  134628. }
  134629. }
  134630. }
  134631. }
  134632. break;
  134633. }
  134634. case FTSQUERY_OR: {
  134635. Fts3Expr *pLeft = pExpr->pLeft;
  134636. Fts3Expr *pRight = pExpr->pRight;
  134637. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  134638. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  134639. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  134640. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  134641. fts3EvalNextRow(pCsr, pLeft, pRc);
  134642. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  134643. fts3EvalNextRow(pCsr, pRight, pRc);
  134644. }else{
  134645. fts3EvalNextRow(pCsr, pLeft, pRc);
  134646. fts3EvalNextRow(pCsr, pRight, pRc);
  134647. }
  134648. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  134649. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  134650. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  134651. pExpr->iDocid = pLeft->iDocid;
  134652. }else{
  134653. pExpr->iDocid = pRight->iDocid;
  134654. }
  134655. break;
  134656. }
  134657. case FTSQUERY_NOT: {
  134658. Fts3Expr *pLeft = pExpr->pLeft;
  134659. Fts3Expr *pRight = pExpr->pRight;
  134660. if( pRight->bStart==0 ){
  134661. fts3EvalNextRow(pCsr, pRight, pRc);
  134662. assert( *pRc!=SQLITE_OK || pRight->bStart );
  134663. }
  134664. fts3EvalNextRow(pCsr, pLeft, pRc);
  134665. if( pLeft->bEof==0 ){
  134666. while( !*pRc
  134667. && !pRight->bEof
  134668. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  134669. ){
  134670. fts3EvalNextRow(pCsr, pRight, pRc);
  134671. }
  134672. }
  134673. pExpr->iDocid = pLeft->iDocid;
  134674. pExpr->bEof = pLeft->bEof;
  134675. break;
  134676. }
  134677. default: {
  134678. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134679. fts3EvalInvalidatePoslist(pPhrase);
  134680. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  134681. pExpr->iDocid = pPhrase->doclist.iDocid;
  134682. break;
  134683. }
  134684. }
  134685. }
  134686. }
  134687. /*
  134688. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  134689. ** cluster, then this function returns 1 immediately.
  134690. **
  134691. ** Otherwise, it checks if the current row really does match the NEAR
  134692. ** expression, using the data currently stored in the position lists
  134693. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  134694. **
  134695. ** If the current row is a match, the position list associated with each
  134696. ** phrase in the NEAR expression is edited in place to contain only those
  134697. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  134698. ** constraints. In this case it returns 1. If the NEAR expression does not
  134699. ** match the current row, 0 is returned. The position lists may or may not
  134700. ** be edited if 0 is returned.
  134701. */
  134702. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  134703. int res = 1;
  134704. /* The following block runs if pExpr is the root of a NEAR query.
  134705. ** For example, the query:
  134706. **
  134707. ** "w" NEAR "x" NEAR "y" NEAR "z"
  134708. **
  134709. ** which is represented in tree form as:
  134710. **
  134711. ** |
  134712. ** +--NEAR--+ <-- root of NEAR query
  134713. ** | |
  134714. ** +--NEAR--+ "z"
  134715. ** | |
  134716. ** +--NEAR--+ "y"
  134717. ** | |
  134718. ** "w" "x"
  134719. **
  134720. ** The right-hand child of a NEAR node is always a phrase. The
  134721. ** left-hand child may be either a phrase or a NEAR node. There are
  134722. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  134723. */
  134724. if( *pRc==SQLITE_OK
  134725. && pExpr->eType==FTSQUERY_NEAR
  134726. && pExpr->bEof==0
  134727. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  134728. ){
  134729. Fts3Expr *p;
  134730. int nTmp = 0; /* Bytes of temp space */
  134731. char *aTmp; /* Temp space for PoslistNearMerge() */
  134732. /* Allocate temporary working space. */
  134733. for(p=pExpr; p->pLeft; p=p->pLeft){
  134734. nTmp += p->pRight->pPhrase->doclist.nList;
  134735. }
  134736. nTmp += p->pPhrase->doclist.nList;
  134737. if( nTmp==0 ){
  134738. res = 0;
  134739. }else{
  134740. aTmp = sqlite3_malloc(nTmp*2);
  134741. if( !aTmp ){
  134742. *pRc = SQLITE_NOMEM;
  134743. res = 0;
  134744. }else{
  134745. char *aPoslist = p->pPhrase->doclist.pList;
  134746. int nToken = p->pPhrase->nToken;
  134747. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  134748. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  134749. int nNear = p->nNear;
  134750. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  134751. }
  134752. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  134753. nToken = pExpr->pRight->pPhrase->nToken;
  134754. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  134755. int nNear;
  134756. Fts3Phrase *pPhrase;
  134757. assert( p->pParent && p->pParent->pLeft==p );
  134758. nNear = p->pParent->nNear;
  134759. pPhrase = (
  134760. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  134761. );
  134762. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  134763. }
  134764. }
  134765. sqlite3_free(aTmp);
  134766. }
  134767. }
  134768. return res;
  134769. }
  134770. /*
  134771. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  134772. ** Assuming no error occurs or has occurred, It returns non-zero if the
  134773. ** expression passed as the second argument matches the row that pCsr
  134774. ** currently points to, or zero if it does not.
  134775. **
  134776. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  134777. ** If an error occurs during execution of this function, *pRc is set to
  134778. ** the appropriate SQLite error code. In this case the returned value is
  134779. ** undefined.
  134780. */
  134781. static int fts3EvalTestExpr(
  134782. Fts3Cursor *pCsr, /* FTS cursor handle */
  134783. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  134784. int *pRc /* IN/OUT: Error code */
  134785. ){
  134786. int bHit = 1; /* Return value */
  134787. if( *pRc==SQLITE_OK ){
  134788. switch( pExpr->eType ){
  134789. case FTSQUERY_NEAR:
  134790. case FTSQUERY_AND:
  134791. bHit = (
  134792. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  134793. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  134794. && fts3EvalNearTest(pExpr, pRc)
  134795. );
  134796. /* If the NEAR expression does not match any rows, zero the doclist for
  134797. ** all phrases involved in the NEAR. This is because the snippet(),
  134798. ** offsets() and matchinfo() functions are not supposed to recognize
  134799. ** any instances of phrases that are part of unmatched NEAR queries.
  134800. ** For example if this expression:
  134801. **
  134802. ** ... MATCH 'a OR (b NEAR c)'
  134803. **
  134804. ** is matched against a row containing:
  134805. **
  134806. ** 'a b d e'
  134807. **
  134808. ** then any snippet() should ony highlight the "a" term, not the "b"
  134809. ** (as "b" is part of a non-matching NEAR clause).
  134810. */
  134811. if( bHit==0
  134812. && pExpr->eType==FTSQUERY_NEAR
  134813. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  134814. ){
  134815. Fts3Expr *p;
  134816. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  134817. if( p->pRight->iDocid==pCsr->iPrevId ){
  134818. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  134819. }
  134820. }
  134821. if( p->iDocid==pCsr->iPrevId ){
  134822. fts3EvalInvalidatePoslist(p->pPhrase);
  134823. }
  134824. }
  134825. break;
  134826. case FTSQUERY_OR: {
  134827. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  134828. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  134829. bHit = bHit1 || bHit2;
  134830. break;
  134831. }
  134832. case FTSQUERY_NOT:
  134833. bHit = (
  134834. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  134835. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  134836. );
  134837. break;
  134838. default: {
  134839. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  134840. if( pCsr->pDeferred
  134841. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  134842. ){
  134843. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134844. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  134845. if( pExpr->bDeferred ){
  134846. fts3EvalInvalidatePoslist(pPhrase);
  134847. }
  134848. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  134849. bHit = (pPhrase->doclist.pList!=0);
  134850. pExpr->iDocid = pCsr->iPrevId;
  134851. }else
  134852. #endif
  134853. {
  134854. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  134855. }
  134856. break;
  134857. }
  134858. }
  134859. }
  134860. return bHit;
  134861. }
  134862. /*
  134863. ** This function is called as the second part of each xNext operation when
  134864. ** iterating through the results of a full-text query. At this point the
  134865. ** cursor points to a row that matches the query expression, with the
  134866. ** following caveats:
  134867. **
  134868. ** * Up until this point, "NEAR" operators in the expression have been
  134869. ** treated as "AND".
  134870. **
  134871. ** * Deferred tokens have not yet been considered.
  134872. **
  134873. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  134874. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  134875. ** operators and deferred tokens the current row is still a match for the
  134876. ** expression. It returns 1 if both of the following are true:
  134877. **
  134878. ** 1. *pRc is SQLITE_OK when this function returns, and
  134879. **
  134880. ** 2. After scanning the current FTS table row for the deferred tokens,
  134881. ** it is determined that the row does *not* match the query.
  134882. **
  134883. ** Or, if no error occurs and it seems the current row does match the FTS
  134884. ** query, return 0.
  134885. */
  134886. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  134887. int rc = *pRc;
  134888. int bMiss = 0;
  134889. if( rc==SQLITE_OK ){
  134890. /* If there are one or more deferred tokens, load the current row into
  134891. ** memory and scan it to determine the position list for each deferred
  134892. ** token. Then, see if this row is really a match, considering deferred
  134893. ** tokens and NEAR operators (neither of which were taken into account
  134894. ** earlier, by fts3EvalNextRow()).
  134895. */
  134896. if( pCsr->pDeferred ){
  134897. rc = fts3CursorSeek(0, pCsr);
  134898. if( rc==SQLITE_OK ){
  134899. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  134900. }
  134901. }
  134902. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  134903. /* Free the position-lists accumulated for each deferred token above. */
  134904. sqlite3Fts3FreeDeferredDoclists(pCsr);
  134905. *pRc = rc;
  134906. }
  134907. return (rc==SQLITE_OK && bMiss);
  134908. }
  134909. /*
  134910. ** Advance to the next document that matches the FTS expression in
  134911. ** Fts3Cursor.pExpr.
  134912. */
  134913. static int fts3EvalNext(Fts3Cursor *pCsr){
  134914. int rc = SQLITE_OK; /* Return Code */
  134915. Fts3Expr *pExpr = pCsr->pExpr;
  134916. assert( pCsr->isEof==0 );
  134917. if( pExpr==0 ){
  134918. pCsr->isEof = 1;
  134919. }else{
  134920. do {
  134921. if( pCsr->isRequireSeek==0 ){
  134922. sqlite3_reset(pCsr->pStmt);
  134923. }
  134924. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  134925. fts3EvalNextRow(pCsr, pExpr, &rc);
  134926. pCsr->isEof = pExpr->bEof;
  134927. pCsr->isRequireSeek = 1;
  134928. pCsr->isMatchinfoNeeded = 1;
  134929. pCsr->iPrevId = pExpr->iDocid;
  134930. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  134931. }
  134932. /* Check if the cursor is past the end of the docid range specified
  134933. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  134934. if( rc==SQLITE_OK && (
  134935. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  134936. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  134937. )){
  134938. pCsr->isEof = 1;
  134939. }
  134940. return rc;
  134941. }
  134942. /*
  134943. ** Restart interation for expression pExpr so that the next call to
  134944. ** fts3EvalNext() visits the first row. Do not allow incremental
  134945. ** loading or merging of phrase doclists for this iteration.
  134946. **
  134947. ** If *pRc is other than SQLITE_OK when this function is called, it is
  134948. ** a no-op. If an error occurs within this function, *pRc is set to an
  134949. ** SQLite error code before returning.
  134950. */
  134951. static void fts3EvalRestart(
  134952. Fts3Cursor *pCsr,
  134953. Fts3Expr *pExpr,
  134954. int *pRc
  134955. ){
  134956. if( pExpr && *pRc==SQLITE_OK ){
  134957. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134958. if( pPhrase ){
  134959. fts3EvalInvalidatePoslist(pPhrase);
  134960. if( pPhrase->bIncr ){
  134961. int i;
  134962. for(i=0; i<pPhrase->nToken; i++){
  134963. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  134964. assert( pToken->pDeferred==0 );
  134965. if( pToken->pSegcsr ){
  134966. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  134967. }
  134968. }
  134969. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  134970. }
  134971. pPhrase->doclist.pNextDocid = 0;
  134972. pPhrase->doclist.iDocid = 0;
  134973. pPhrase->pOrPoslist = 0;
  134974. }
  134975. pExpr->iDocid = 0;
  134976. pExpr->bEof = 0;
  134977. pExpr->bStart = 0;
  134978. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  134979. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  134980. }
  134981. }
  134982. /*
  134983. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  134984. ** expression rooted at pExpr, the cursor iterates through all rows matched
  134985. ** by pExpr, calling this function for each row. This function increments
  134986. ** the values in Fts3Expr.aMI[] according to the position-list currently
  134987. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  134988. ** expression nodes.
  134989. */
  134990. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  134991. if( pExpr ){
  134992. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134993. if( pPhrase && pPhrase->doclist.pList ){
  134994. int iCol = 0;
  134995. char *p = pPhrase->doclist.pList;
  134996. assert( *p );
  134997. while( 1 ){
  134998. u8 c = 0;
  134999. int iCnt = 0;
  135000. while( 0xFE & (*p | c) ){
  135001. if( (c&0x80)==0 ) iCnt++;
  135002. c = *p++ & 0x80;
  135003. }
  135004. /* aMI[iCol*3 + 1] = Number of occurrences
  135005. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  135006. */
  135007. pExpr->aMI[iCol*3 + 1] += iCnt;
  135008. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  135009. if( *p==0x00 ) break;
  135010. p++;
  135011. p += fts3GetVarint32(p, &iCol);
  135012. }
  135013. }
  135014. fts3EvalUpdateCounts(pExpr->pLeft);
  135015. fts3EvalUpdateCounts(pExpr->pRight);
  135016. }
  135017. }
  135018. /*
  135019. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  135020. **
  135021. ** If it is not already allocated and populated, this function allocates and
  135022. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  135023. ** of a NEAR expression, then it also allocates and populates the same array
  135024. ** for all other phrases that are part of the NEAR expression.
  135025. **
  135026. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  135027. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  135028. */
  135029. static int fts3EvalGatherStats(
  135030. Fts3Cursor *pCsr, /* Cursor object */
  135031. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  135032. ){
  135033. int rc = SQLITE_OK; /* Return code */
  135034. assert( pExpr->eType==FTSQUERY_PHRASE );
  135035. if( pExpr->aMI==0 ){
  135036. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  135037. Fts3Expr *pRoot; /* Root of NEAR expression */
  135038. Fts3Expr *p; /* Iterator used for several purposes */
  135039. sqlite3_int64 iPrevId = pCsr->iPrevId;
  135040. sqlite3_int64 iDocid;
  135041. u8 bEof;
  135042. /* Find the root of the NEAR expression */
  135043. pRoot = pExpr;
  135044. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  135045. pRoot = pRoot->pParent;
  135046. }
  135047. iDocid = pRoot->iDocid;
  135048. bEof = pRoot->bEof;
  135049. assert( pRoot->bStart );
  135050. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  135051. for(p=pRoot; p; p=p->pLeft){
  135052. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  135053. assert( pE->aMI==0 );
  135054. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  135055. if( !pE->aMI ) return SQLITE_NOMEM;
  135056. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  135057. }
  135058. fts3EvalRestart(pCsr, pRoot, &rc);
  135059. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  135060. do {
  135061. /* Ensure the %_content statement is reset. */
  135062. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  135063. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  135064. /* Advance to the next document */
  135065. fts3EvalNextRow(pCsr, pRoot, &rc);
  135066. pCsr->isEof = pRoot->bEof;
  135067. pCsr->isRequireSeek = 1;
  135068. pCsr->isMatchinfoNeeded = 1;
  135069. pCsr->iPrevId = pRoot->iDocid;
  135070. }while( pCsr->isEof==0
  135071. && pRoot->eType==FTSQUERY_NEAR
  135072. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  135073. );
  135074. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  135075. fts3EvalUpdateCounts(pRoot);
  135076. }
  135077. }
  135078. pCsr->isEof = 0;
  135079. pCsr->iPrevId = iPrevId;
  135080. if( bEof ){
  135081. pRoot->bEof = bEof;
  135082. }else{
  135083. /* Caution: pRoot may iterate through docids in ascending or descending
  135084. ** order. For this reason, even though it seems more defensive, the
  135085. ** do loop can not be written:
  135086. **
  135087. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  135088. */
  135089. fts3EvalRestart(pCsr, pRoot, &rc);
  135090. do {
  135091. fts3EvalNextRow(pCsr, pRoot, &rc);
  135092. assert( pRoot->bEof==0 );
  135093. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  135094. }
  135095. }
  135096. return rc;
  135097. }
  135098. /*
  135099. ** This function is used by the matchinfo() module to query a phrase
  135100. ** expression node for the following information:
  135101. **
  135102. ** 1. The total number of occurrences of the phrase in each column of
  135103. ** the FTS table (considering all rows), and
  135104. **
  135105. ** 2. For each column, the number of rows in the table for which the
  135106. ** column contains at least one instance of the phrase.
  135107. **
  135108. ** If no error occurs, SQLITE_OK is returned and the values for each column
  135109. ** written into the array aiOut as follows:
  135110. **
  135111. ** aiOut[iCol*3 + 1] = Number of occurrences
  135112. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  135113. **
  135114. ** Caveats:
  135115. **
  135116. ** * If a phrase consists entirely of deferred tokens, then all output
  135117. ** values are set to the number of documents in the table. In other
  135118. ** words we assume that very common tokens occur exactly once in each
  135119. ** column of each row of the table.
  135120. **
  135121. ** * If a phrase contains some deferred tokens (and some non-deferred
  135122. ** tokens), count the potential occurrence identified by considering
  135123. ** the non-deferred tokens instead of actual phrase occurrences.
  135124. **
  135125. ** * If the phrase is part of a NEAR expression, then only phrase instances
  135126. ** that meet the NEAR constraint are included in the counts.
  135127. */
  135128. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  135129. Fts3Cursor *pCsr, /* FTS cursor handle */
  135130. Fts3Expr *pExpr, /* Phrase expression */
  135131. u32 *aiOut /* Array to write results into (see above) */
  135132. ){
  135133. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  135134. int rc = SQLITE_OK;
  135135. int iCol;
  135136. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  135137. assert( pCsr->nDoc>0 );
  135138. for(iCol=0; iCol<pTab->nColumn; iCol++){
  135139. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  135140. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  135141. }
  135142. }else{
  135143. rc = fts3EvalGatherStats(pCsr, pExpr);
  135144. if( rc==SQLITE_OK ){
  135145. assert( pExpr->aMI );
  135146. for(iCol=0; iCol<pTab->nColumn; iCol++){
  135147. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  135148. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  135149. }
  135150. }
  135151. }
  135152. return rc;
  135153. }
  135154. /*
  135155. ** The expression pExpr passed as the second argument to this function
  135156. ** must be of type FTSQUERY_PHRASE.
  135157. **
  135158. ** The returned value is either NULL or a pointer to a buffer containing
  135159. ** a position-list indicating the occurrences of the phrase in column iCol
  135160. ** of the current row.
  135161. **
  135162. ** More specifically, the returned buffer contains 1 varint for each
  135163. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  135164. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  135165. ** if the requested column contains "a b X c d X X" and the position-list
  135166. ** for 'X' is requested, the buffer returned may contain:
  135167. **
  135168. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  135169. **
  135170. ** This function works regardless of whether or not the phrase is deferred,
  135171. ** incremental, or neither.
  135172. */
  135173. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  135174. Fts3Cursor *pCsr, /* FTS3 cursor object */
  135175. Fts3Expr *pExpr, /* Phrase to return doclist for */
  135176. int iCol, /* Column to return position list for */
  135177. char **ppOut /* OUT: Pointer to position list */
  135178. ){
  135179. Fts3Phrase *pPhrase = pExpr->pPhrase;
  135180. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  135181. char *pIter;
  135182. int iThis;
  135183. sqlite3_int64 iDocid;
  135184. /* If this phrase is applies specifically to some column other than
  135185. ** column iCol, return a NULL pointer. */
  135186. *ppOut = 0;
  135187. assert( iCol>=0 && iCol<pTab->nColumn );
  135188. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  135189. return SQLITE_OK;
  135190. }
  135191. iDocid = pExpr->iDocid;
  135192. pIter = pPhrase->doclist.pList;
  135193. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  135194. int rc = SQLITE_OK;
  135195. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  135196. int bOr = 0;
  135197. u8 bTreeEof = 0;
  135198. Fts3Expr *p; /* Used to iterate from pExpr to root */
  135199. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  135200. int bMatch;
  135201. /* Check if this phrase descends from an OR expression node. If not,
  135202. ** return NULL. Otherwise, the entry that corresponds to docid
  135203. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  135204. ** tree that the node is part of has been marked as EOF, but the node
  135205. ** itself is not EOF, then it may point to an earlier entry. */
  135206. pNear = pExpr;
  135207. for(p=pExpr->pParent; p; p=p->pParent){
  135208. if( p->eType==FTSQUERY_OR ) bOr = 1;
  135209. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  135210. if( p->bEof ) bTreeEof = 1;
  135211. }
  135212. if( bOr==0 ) return SQLITE_OK;
  135213. /* This is the descendent of an OR node. In this case we cannot use
  135214. ** an incremental phrase. Load the entire doclist for the phrase
  135215. ** into memory in this case. */
  135216. if( pPhrase->bIncr ){
  135217. int bEofSave = pNear->bEof;
  135218. fts3EvalRestart(pCsr, pNear, &rc);
  135219. while( rc==SQLITE_OK && !pNear->bEof ){
  135220. fts3EvalNextRow(pCsr, pNear, &rc);
  135221. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  135222. }
  135223. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  135224. }
  135225. if( bTreeEof ){
  135226. while( rc==SQLITE_OK && !pNear->bEof ){
  135227. fts3EvalNextRow(pCsr, pNear, &rc);
  135228. }
  135229. }
  135230. if( rc!=SQLITE_OK ) return rc;
  135231. bMatch = 1;
  135232. for(p=pNear; p; p=p->pLeft){
  135233. u8 bEof = 0;
  135234. Fts3Expr *pTest = p;
  135235. Fts3Phrase *pPh;
  135236. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  135237. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  135238. assert( pTest->eType==FTSQUERY_PHRASE );
  135239. pPh = pTest->pPhrase;
  135240. pIter = pPh->pOrPoslist;
  135241. iDocid = pPh->iOrDocid;
  135242. if( pCsr->bDesc==bDescDoclist ){
  135243. bEof = !pPh->doclist.nAll ||
  135244. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  135245. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  135246. sqlite3Fts3DoclistNext(
  135247. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  135248. &pIter, &iDocid, &bEof
  135249. );
  135250. }
  135251. }else{
  135252. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  135253. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  135254. int dummy;
  135255. sqlite3Fts3DoclistPrev(
  135256. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  135257. &pIter, &iDocid, &dummy, &bEof
  135258. );
  135259. }
  135260. }
  135261. pPh->pOrPoslist = pIter;
  135262. pPh->iOrDocid = iDocid;
  135263. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  135264. }
  135265. if( bMatch ){
  135266. pIter = pPhrase->pOrPoslist;
  135267. }else{
  135268. pIter = 0;
  135269. }
  135270. }
  135271. if( pIter==0 ) return SQLITE_OK;
  135272. if( *pIter==0x01 ){
  135273. pIter++;
  135274. pIter += fts3GetVarint32(pIter, &iThis);
  135275. }else{
  135276. iThis = 0;
  135277. }
  135278. while( iThis<iCol ){
  135279. fts3ColumnlistCopy(0, &pIter);
  135280. if( *pIter==0x00 ) return SQLITE_OK;
  135281. pIter++;
  135282. pIter += fts3GetVarint32(pIter, &iThis);
  135283. }
  135284. if( *pIter==0x00 ){
  135285. pIter = 0;
  135286. }
  135287. *ppOut = ((iCol==iThis)?pIter:0);
  135288. return SQLITE_OK;
  135289. }
  135290. /*
  135291. ** Free all components of the Fts3Phrase structure that were allocated by
  135292. ** the eval module. Specifically, this means to free:
  135293. **
  135294. ** * the contents of pPhrase->doclist, and
  135295. ** * any Fts3MultiSegReader objects held by phrase tokens.
  135296. */
  135297. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  135298. if( pPhrase ){
  135299. int i;
  135300. sqlite3_free(pPhrase->doclist.aAll);
  135301. fts3EvalInvalidatePoslist(pPhrase);
  135302. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  135303. for(i=0; i<pPhrase->nToken; i++){
  135304. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  135305. pPhrase->aToken[i].pSegcsr = 0;
  135306. }
  135307. }
  135308. }
  135309. /*
  135310. ** Return SQLITE_CORRUPT_VTAB.
  135311. */
  135312. #ifdef SQLITE_DEBUG
  135313. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  135314. return SQLITE_CORRUPT_VTAB;
  135315. }
  135316. #endif
  135317. #if !SQLITE_CORE
  135318. /*
  135319. ** Initialize API pointer table, if required.
  135320. */
  135321. #ifdef _WIN32
  135322. __declspec(dllexport)
  135323. #endif
  135324. SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
  135325. sqlite3 *db,
  135326. char **pzErrMsg,
  135327. const sqlite3_api_routines *pApi
  135328. ){
  135329. SQLITE_EXTENSION_INIT2(pApi)
  135330. return sqlite3Fts3Init(db);
  135331. }
  135332. #endif
  135333. #endif
  135334. /************** End of fts3.c ************************************************/
  135335. /************** Begin file fts3_aux.c ****************************************/
  135336. /*
  135337. ** 2011 Jan 27
  135338. **
  135339. ** The author disclaims copyright to this source code. In place of
  135340. ** a legal notice, here is a blessing:
  135341. **
  135342. ** May you do good and not evil.
  135343. ** May you find forgiveness for yourself and forgive others.
  135344. ** May you share freely, never taking more than you give.
  135345. **
  135346. ******************************************************************************
  135347. **
  135348. */
  135349. /* #include "fts3Int.h" */
  135350. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135351. /* #include <string.h> */
  135352. /* #include <assert.h> */
  135353. typedef struct Fts3auxTable Fts3auxTable;
  135354. typedef struct Fts3auxCursor Fts3auxCursor;
  135355. struct Fts3auxTable {
  135356. sqlite3_vtab base; /* Base class used by SQLite core */
  135357. Fts3Table *pFts3Tab;
  135358. };
  135359. struct Fts3auxCursor {
  135360. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  135361. Fts3MultiSegReader csr; /* Must be right after "base" */
  135362. Fts3SegFilter filter;
  135363. char *zStop;
  135364. int nStop; /* Byte-length of string zStop */
  135365. int iLangid; /* Language id to query */
  135366. int isEof; /* True if cursor is at EOF */
  135367. sqlite3_int64 iRowid; /* Current rowid */
  135368. int iCol; /* Current value of 'col' column */
  135369. int nStat; /* Size of aStat[] array */
  135370. struct Fts3auxColstats {
  135371. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  135372. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  135373. } *aStat;
  135374. };
  135375. /*
  135376. ** Schema of the terms table.
  135377. */
  135378. #define FTS3_AUX_SCHEMA \
  135379. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  135380. /*
  135381. ** This function does all the work for both the xConnect and xCreate methods.
  135382. ** These tables have no persistent representation of their own, so xConnect
  135383. ** and xCreate are identical operations.
  135384. */
  135385. static int fts3auxConnectMethod(
  135386. sqlite3 *db, /* Database connection */
  135387. void *pUnused, /* Unused */
  135388. int argc, /* Number of elements in argv array */
  135389. const char * const *argv, /* xCreate/xConnect argument array */
  135390. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  135391. char **pzErr /* OUT: sqlite3_malloc'd error message */
  135392. ){
  135393. char const *zDb; /* Name of database (e.g. "main") */
  135394. char const *zFts3; /* Name of fts3 table */
  135395. int nDb; /* Result of strlen(zDb) */
  135396. int nFts3; /* Result of strlen(zFts3) */
  135397. int nByte; /* Bytes of space to allocate here */
  135398. int rc; /* value returned by declare_vtab() */
  135399. Fts3auxTable *p; /* Virtual table object to return */
  135400. UNUSED_PARAMETER(pUnused);
  135401. /* The user should invoke this in one of two forms:
  135402. **
  135403. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  135404. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  135405. */
  135406. if( argc!=4 && argc!=5 ) goto bad_args;
  135407. zDb = argv[1];
  135408. nDb = (int)strlen(zDb);
  135409. if( argc==5 ){
  135410. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  135411. zDb = argv[3];
  135412. nDb = (int)strlen(zDb);
  135413. zFts3 = argv[4];
  135414. }else{
  135415. goto bad_args;
  135416. }
  135417. }else{
  135418. zFts3 = argv[3];
  135419. }
  135420. nFts3 = (int)strlen(zFts3);
  135421. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  135422. if( rc!=SQLITE_OK ) return rc;
  135423. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  135424. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  135425. if( !p ) return SQLITE_NOMEM;
  135426. memset(p, 0, nByte);
  135427. p->pFts3Tab = (Fts3Table *)&p[1];
  135428. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  135429. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  135430. p->pFts3Tab->db = db;
  135431. p->pFts3Tab->nIndex = 1;
  135432. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  135433. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  135434. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  135435. *ppVtab = (sqlite3_vtab *)p;
  135436. return SQLITE_OK;
  135437. bad_args:
  135438. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  135439. return SQLITE_ERROR;
  135440. }
  135441. /*
  135442. ** This function does the work for both the xDisconnect and xDestroy methods.
  135443. ** These tables have no persistent representation of their own, so xDisconnect
  135444. ** and xDestroy are identical operations.
  135445. */
  135446. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  135447. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  135448. Fts3Table *pFts3 = p->pFts3Tab;
  135449. int i;
  135450. /* Free any prepared statements held */
  135451. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  135452. sqlite3_finalize(pFts3->aStmt[i]);
  135453. }
  135454. sqlite3_free(pFts3->zSegmentsTbl);
  135455. sqlite3_free(p);
  135456. return SQLITE_OK;
  135457. }
  135458. #define FTS4AUX_EQ_CONSTRAINT 1
  135459. #define FTS4AUX_GE_CONSTRAINT 2
  135460. #define FTS4AUX_LE_CONSTRAINT 4
  135461. /*
  135462. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  135463. */
  135464. static int fts3auxBestIndexMethod(
  135465. sqlite3_vtab *pVTab,
  135466. sqlite3_index_info *pInfo
  135467. ){
  135468. int i;
  135469. int iEq = -1;
  135470. int iGe = -1;
  135471. int iLe = -1;
  135472. int iLangid = -1;
  135473. int iNext = 1; /* Next free argvIndex value */
  135474. UNUSED_PARAMETER(pVTab);
  135475. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  135476. if( pInfo->nOrderBy==1
  135477. && pInfo->aOrderBy[0].iColumn==0
  135478. && pInfo->aOrderBy[0].desc==0
  135479. ){
  135480. pInfo->orderByConsumed = 1;
  135481. }
  135482. /* Search for equality and range constraints on the "term" column.
  135483. ** And equality constraints on the hidden "languageid" column. */
  135484. for(i=0; i<pInfo->nConstraint; i++){
  135485. if( pInfo->aConstraint[i].usable ){
  135486. int op = pInfo->aConstraint[i].op;
  135487. int iCol = pInfo->aConstraint[i].iColumn;
  135488. if( iCol==0 ){
  135489. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  135490. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  135491. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  135492. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  135493. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  135494. }
  135495. if( iCol==4 ){
  135496. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  135497. }
  135498. }
  135499. }
  135500. if( iEq>=0 ){
  135501. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  135502. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  135503. pInfo->estimatedCost = 5;
  135504. }else{
  135505. pInfo->idxNum = 0;
  135506. pInfo->estimatedCost = 20000;
  135507. if( iGe>=0 ){
  135508. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  135509. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  135510. pInfo->estimatedCost /= 2;
  135511. }
  135512. if( iLe>=0 ){
  135513. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  135514. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  135515. pInfo->estimatedCost /= 2;
  135516. }
  135517. }
  135518. if( iLangid>=0 ){
  135519. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  135520. pInfo->estimatedCost--;
  135521. }
  135522. return SQLITE_OK;
  135523. }
  135524. /*
  135525. ** xOpen - Open a cursor.
  135526. */
  135527. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  135528. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  135529. UNUSED_PARAMETER(pVTab);
  135530. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  135531. if( !pCsr ) return SQLITE_NOMEM;
  135532. memset(pCsr, 0, sizeof(Fts3auxCursor));
  135533. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  135534. return SQLITE_OK;
  135535. }
  135536. /*
  135537. ** xClose - Close a cursor.
  135538. */
  135539. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  135540. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  135541. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  135542. sqlite3Fts3SegmentsClose(pFts3);
  135543. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  135544. sqlite3_free((void *)pCsr->filter.zTerm);
  135545. sqlite3_free(pCsr->zStop);
  135546. sqlite3_free(pCsr->aStat);
  135547. sqlite3_free(pCsr);
  135548. return SQLITE_OK;
  135549. }
  135550. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  135551. if( nSize>pCsr->nStat ){
  135552. struct Fts3auxColstats *aNew;
  135553. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  135554. sizeof(struct Fts3auxColstats) * nSize
  135555. );
  135556. if( aNew==0 ) return SQLITE_NOMEM;
  135557. memset(&aNew[pCsr->nStat], 0,
  135558. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  135559. );
  135560. pCsr->aStat = aNew;
  135561. pCsr->nStat = nSize;
  135562. }
  135563. return SQLITE_OK;
  135564. }
  135565. /*
  135566. ** xNext - Advance the cursor to the next row, if any.
  135567. */
  135568. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  135569. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  135570. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  135571. int rc;
  135572. /* Increment our pretend rowid value. */
  135573. pCsr->iRowid++;
  135574. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  135575. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  135576. }
  135577. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  135578. if( rc==SQLITE_ROW ){
  135579. int i = 0;
  135580. int nDoclist = pCsr->csr.nDoclist;
  135581. char *aDoclist = pCsr->csr.aDoclist;
  135582. int iCol;
  135583. int eState = 0;
  135584. if( pCsr->zStop ){
  135585. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  135586. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  135587. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  135588. pCsr->isEof = 1;
  135589. return SQLITE_OK;
  135590. }
  135591. }
  135592. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  135593. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  135594. iCol = 0;
  135595. while( i<nDoclist ){
  135596. sqlite3_int64 v = 0;
  135597. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  135598. switch( eState ){
  135599. /* State 0. In this state the integer just read was a docid. */
  135600. case 0:
  135601. pCsr->aStat[0].nDoc++;
  135602. eState = 1;
  135603. iCol = 0;
  135604. break;
  135605. /* State 1. In this state we are expecting either a 1, indicating
  135606. ** that the following integer will be a column number, or the
  135607. ** start of a position list for column 0.
  135608. **
  135609. ** The only difference between state 1 and state 2 is that if the
  135610. ** integer encountered in state 1 is not 0 or 1, then we need to
  135611. ** increment the column 0 "nDoc" count for this term.
  135612. */
  135613. case 1:
  135614. assert( iCol==0 );
  135615. if( v>1 ){
  135616. pCsr->aStat[1].nDoc++;
  135617. }
  135618. eState = 2;
  135619. /* fall through */
  135620. case 2:
  135621. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  135622. eState = 0;
  135623. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  135624. eState = 3;
  135625. }else{ /* 2 or greater. A position. */
  135626. pCsr->aStat[iCol+1].nOcc++;
  135627. pCsr->aStat[0].nOcc++;
  135628. }
  135629. break;
  135630. /* State 3. The integer just read is a column number. */
  135631. default: assert( eState==3 );
  135632. iCol = (int)v;
  135633. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  135634. pCsr->aStat[iCol+1].nDoc++;
  135635. eState = 2;
  135636. break;
  135637. }
  135638. }
  135639. pCsr->iCol = 0;
  135640. rc = SQLITE_OK;
  135641. }else{
  135642. pCsr->isEof = 1;
  135643. }
  135644. return rc;
  135645. }
  135646. /*
  135647. ** xFilter - Initialize a cursor to point at the start of its data.
  135648. */
  135649. static int fts3auxFilterMethod(
  135650. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  135651. int idxNum, /* Strategy index */
  135652. const char *idxStr, /* Unused */
  135653. int nVal, /* Number of elements in apVal */
  135654. sqlite3_value **apVal /* Arguments for the indexing scheme */
  135655. ){
  135656. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  135657. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  135658. int rc;
  135659. int isScan = 0;
  135660. int iLangVal = 0; /* Language id to query */
  135661. int iEq = -1; /* Index of term=? value in apVal */
  135662. int iGe = -1; /* Index of term>=? value in apVal */
  135663. int iLe = -1; /* Index of term<=? value in apVal */
  135664. int iLangid = -1; /* Index of languageid=? value in apVal */
  135665. int iNext = 0;
  135666. UNUSED_PARAMETER(nVal);
  135667. UNUSED_PARAMETER(idxStr);
  135668. assert( idxStr==0 );
  135669. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  135670. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  135671. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  135672. );
  135673. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  135674. iEq = iNext++;
  135675. }else{
  135676. isScan = 1;
  135677. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  135678. iGe = iNext++;
  135679. }
  135680. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  135681. iLe = iNext++;
  135682. }
  135683. }
  135684. if( iNext<nVal ){
  135685. iLangid = iNext++;
  135686. }
  135687. /* In case this cursor is being reused, close and zero it. */
  135688. testcase(pCsr->filter.zTerm);
  135689. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  135690. sqlite3_free((void *)pCsr->filter.zTerm);
  135691. sqlite3_free(pCsr->aStat);
  135692. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  135693. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  135694. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  135695. if( iEq>=0 || iGe>=0 ){
  135696. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  135697. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  135698. if( zStr ){
  135699. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  135700. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  135701. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  135702. }
  135703. }
  135704. if( iLe>=0 ){
  135705. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  135706. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  135707. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  135708. }
  135709. if( iLangid>=0 ){
  135710. iLangVal = sqlite3_value_int(apVal[iLangid]);
  135711. /* If the user specified a negative value for the languageid, use zero
  135712. ** instead. This works, as the "languageid=?" constraint will also
  135713. ** be tested by the VDBE layer. The test will always be false (since
  135714. ** this module will not return a row with a negative languageid), and
  135715. ** so the overall query will return zero rows. */
  135716. if( iLangVal<0 ) iLangVal = 0;
  135717. }
  135718. pCsr->iLangid = iLangVal;
  135719. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  135720. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  135721. );
  135722. if( rc==SQLITE_OK ){
  135723. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  135724. }
  135725. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  135726. return rc;
  135727. }
  135728. /*
  135729. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  135730. */
  135731. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  135732. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  135733. return pCsr->isEof;
  135734. }
  135735. /*
  135736. ** xColumn - Return a column value.
  135737. */
  135738. static int fts3auxColumnMethod(
  135739. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  135740. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  135741. int iCol /* Index of column to read value from */
  135742. ){
  135743. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  135744. assert( p->isEof==0 );
  135745. switch( iCol ){
  135746. case 0: /* term */
  135747. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  135748. break;
  135749. case 1: /* col */
  135750. if( p->iCol ){
  135751. sqlite3_result_int(pCtx, p->iCol-1);
  135752. }else{
  135753. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  135754. }
  135755. break;
  135756. case 2: /* documents */
  135757. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  135758. break;
  135759. case 3: /* occurrences */
  135760. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  135761. break;
  135762. default: /* languageid */
  135763. assert( iCol==4 );
  135764. sqlite3_result_int(pCtx, p->iLangid);
  135765. break;
  135766. }
  135767. return SQLITE_OK;
  135768. }
  135769. /*
  135770. ** xRowid - Return the current rowid for the cursor.
  135771. */
  135772. static int fts3auxRowidMethod(
  135773. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  135774. sqlite_int64 *pRowid /* OUT: Rowid value */
  135775. ){
  135776. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  135777. *pRowid = pCsr->iRowid;
  135778. return SQLITE_OK;
  135779. }
  135780. /*
  135781. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  135782. ** if successful or an error code if sqlite3_create_module() fails.
  135783. */
  135784. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  135785. static const sqlite3_module fts3aux_module = {
  135786. 0, /* iVersion */
  135787. fts3auxConnectMethod, /* xCreate */
  135788. fts3auxConnectMethod, /* xConnect */
  135789. fts3auxBestIndexMethod, /* xBestIndex */
  135790. fts3auxDisconnectMethod, /* xDisconnect */
  135791. fts3auxDisconnectMethod, /* xDestroy */
  135792. fts3auxOpenMethod, /* xOpen */
  135793. fts3auxCloseMethod, /* xClose */
  135794. fts3auxFilterMethod, /* xFilter */
  135795. fts3auxNextMethod, /* xNext */
  135796. fts3auxEofMethod, /* xEof */
  135797. fts3auxColumnMethod, /* xColumn */
  135798. fts3auxRowidMethod, /* xRowid */
  135799. 0, /* xUpdate */
  135800. 0, /* xBegin */
  135801. 0, /* xSync */
  135802. 0, /* xCommit */
  135803. 0, /* xRollback */
  135804. 0, /* xFindFunction */
  135805. 0, /* xRename */
  135806. 0, /* xSavepoint */
  135807. 0, /* xRelease */
  135808. 0 /* xRollbackTo */
  135809. };
  135810. int rc; /* Return code */
  135811. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  135812. return rc;
  135813. }
  135814. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  135815. /************** End of fts3_aux.c ********************************************/
  135816. /************** Begin file fts3_expr.c ***************************************/
  135817. /*
  135818. ** 2008 Nov 28
  135819. **
  135820. ** The author disclaims copyright to this source code. In place of
  135821. ** a legal notice, here is a blessing:
  135822. **
  135823. ** May you do good and not evil.
  135824. ** May you find forgiveness for yourself and forgive others.
  135825. ** May you share freely, never taking more than you give.
  135826. **
  135827. ******************************************************************************
  135828. **
  135829. ** This module contains code that implements a parser for fts3 query strings
  135830. ** (the right-hand argument to the MATCH operator). Because the supported
  135831. ** syntax is relatively simple, the whole tokenizer/parser system is
  135832. ** hand-coded.
  135833. */
  135834. /* #include "fts3Int.h" */
  135835. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135836. /*
  135837. ** By default, this module parses the legacy syntax that has been
  135838. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  135839. ** is defined, then it uses the new syntax. The differences between
  135840. ** the new and the old syntaxes are:
  135841. **
  135842. ** a) The new syntax supports parenthesis. The old does not.
  135843. **
  135844. ** b) The new syntax supports the AND and NOT operators. The old does not.
  135845. **
  135846. ** c) The old syntax supports the "-" token qualifier. This is not
  135847. ** supported by the new syntax (it is replaced by the NOT operator).
  135848. **
  135849. ** d) When using the old syntax, the OR operator has a greater precedence
  135850. ** than an implicit AND. When using the new, both implicity and explicit
  135851. ** AND operators have a higher precedence than OR.
  135852. **
  135853. ** If compiled with SQLITE_TEST defined, then this module exports the
  135854. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  135855. ** to zero causes the module to use the old syntax. If it is set to
  135856. ** non-zero the new syntax is activated. This is so both syntaxes can
  135857. ** be tested using a single build of testfixture.
  135858. **
  135859. ** The following describes the syntax supported by the fts3 MATCH
  135860. ** operator in a similar format to that used by the lemon parser
  135861. ** generator. This module does not use actually lemon, it uses a
  135862. ** custom parser.
  135863. **
  135864. ** query ::= andexpr (OR andexpr)*.
  135865. **
  135866. ** andexpr ::= notexpr (AND? notexpr)*.
  135867. **
  135868. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  135869. ** notexpr ::= LP query RP.
  135870. **
  135871. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  135872. **
  135873. ** distance_opt ::= .
  135874. ** distance_opt ::= / INTEGER.
  135875. **
  135876. ** phrase ::= TOKEN.
  135877. ** phrase ::= COLUMN:TOKEN.
  135878. ** phrase ::= "TOKEN TOKEN TOKEN...".
  135879. */
  135880. #ifdef SQLITE_TEST
  135881. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  135882. #else
  135883. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  135884. # define sqlite3_fts3_enable_parentheses 1
  135885. # else
  135886. # define sqlite3_fts3_enable_parentheses 0
  135887. # endif
  135888. #endif
  135889. /*
  135890. ** Default span for NEAR operators.
  135891. */
  135892. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  135893. /* #include <string.h> */
  135894. /* #include <assert.h> */
  135895. /*
  135896. ** isNot:
  135897. ** This variable is used by function getNextNode(). When getNextNode() is
  135898. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  135899. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  135900. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  135901. ** zero.
  135902. */
  135903. typedef struct ParseContext ParseContext;
  135904. struct ParseContext {
  135905. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  135906. int iLangid; /* Language id used with tokenizer */
  135907. const char **azCol; /* Array of column names for fts3 table */
  135908. int bFts4; /* True to allow FTS4-only syntax */
  135909. int nCol; /* Number of entries in azCol[] */
  135910. int iDefaultCol; /* Default column to query */
  135911. int isNot; /* True if getNextNode() sees a unary - */
  135912. sqlite3_context *pCtx; /* Write error message here */
  135913. int nNest; /* Number of nested brackets */
  135914. };
  135915. /*
  135916. ** This function is equivalent to the standard isspace() function.
  135917. **
  135918. ** The standard isspace() can be awkward to use safely, because although it
  135919. ** is defined to accept an argument of type int, its behavior when passed
  135920. ** an integer that falls outside of the range of the unsigned char type
  135921. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  135922. ** is defined to accept an argument of type char, and always returns 0 for
  135923. ** any values that fall outside of the range of the unsigned char type (i.e.
  135924. ** negative values).
  135925. */
  135926. static int fts3isspace(char c){
  135927. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  135928. }
  135929. /*
  135930. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  135931. ** zero the memory before returning a pointer to it. If unsuccessful,
  135932. ** return NULL.
  135933. */
  135934. static void *fts3MallocZero(int nByte){
  135935. void *pRet = sqlite3_malloc(nByte);
  135936. if( pRet ) memset(pRet, 0, nByte);
  135937. return pRet;
  135938. }
  135939. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  135940. sqlite3_tokenizer *pTokenizer,
  135941. int iLangid,
  135942. const char *z,
  135943. int n,
  135944. sqlite3_tokenizer_cursor **ppCsr
  135945. ){
  135946. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  135947. sqlite3_tokenizer_cursor *pCsr = 0;
  135948. int rc;
  135949. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  135950. assert( rc==SQLITE_OK || pCsr==0 );
  135951. if( rc==SQLITE_OK ){
  135952. pCsr->pTokenizer = pTokenizer;
  135953. if( pModule->iVersion>=1 ){
  135954. rc = pModule->xLanguageid(pCsr, iLangid);
  135955. if( rc!=SQLITE_OK ){
  135956. pModule->xClose(pCsr);
  135957. pCsr = 0;
  135958. }
  135959. }
  135960. }
  135961. *ppCsr = pCsr;
  135962. return rc;
  135963. }
  135964. /*
  135965. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  135966. ** call fts3ExprParse(). So this forward declaration is required.
  135967. */
  135968. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  135969. /*
  135970. ** Extract the next token from buffer z (length n) using the tokenizer
  135971. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  135972. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  135973. ** single token and set *ppExpr to point to it. If the end of the buffer is
  135974. ** reached before a token is found, set *ppExpr to zero. It is the
  135975. ** responsibility of the caller to eventually deallocate the allocated
  135976. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  135977. **
  135978. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  135979. ** fails.
  135980. */
  135981. static int getNextToken(
  135982. ParseContext *pParse, /* fts3 query parse context */
  135983. int iCol, /* Value for Fts3Phrase.iColumn */
  135984. const char *z, int n, /* Input string */
  135985. Fts3Expr **ppExpr, /* OUT: expression */
  135986. int *pnConsumed /* OUT: Number of bytes consumed */
  135987. ){
  135988. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  135989. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  135990. int rc;
  135991. sqlite3_tokenizer_cursor *pCursor;
  135992. Fts3Expr *pRet = 0;
  135993. int i = 0;
  135994. /* Set variable i to the maximum number of bytes of input to tokenize. */
  135995. for(i=0; i<n; i++){
  135996. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  135997. if( z[i]=='"' ) break;
  135998. }
  135999. *pnConsumed = i;
  136000. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  136001. if( rc==SQLITE_OK ){
  136002. const char *zToken;
  136003. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  136004. int nByte; /* total space to allocate */
  136005. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  136006. if( rc==SQLITE_OK ){
  136007. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  136008. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  136009. if( !pRet ){
  136010. rc = SQLITE_NOMEM;
  136011. }else{
  136012. pRet->eType = FTSQUERY_PHRASE;
  136013. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  136014. pRet->pPhrase->nToken = 1;
  136015. pRet->pPhrase->iColumn = iCol;
  136016. pRet->pPhrase->aToken[0].n = nToken;
  136017. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  136018. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  136019. if( iEnd<n && z[iEnd]=='*' ){
  136020. pRet->pPhrase->aToken[0].isPrefix = 1;
  136021. iEnd++;
  136022. }
  136023. while( 1 ){
  136024. if( !sqlite3_fts3_enable_parentheses
  136025. && iStart>0 && z[iStart-1]=='-'
  136026. ){
  136027. pParse->isNot = 1;
  136028. iStart--;
  136029. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  136030. pRet->pPhrase->aToken[0].bFirst = 1;
  136031. iStart--;
  136032. }else{
  136033. break;
  136034. }
  136035. }
  136036. }
  136037. *pnConsumed = iEnd;
  136038. }else if( i && rc==SQLITE_DONE ){
  136039. rc = SQLITE_OK;
  136040. }
  136041. pModule->xClose(pCursor);
  136042. }
  136043. *ppExpr = pRet;
  136044. return rc;
  136045. }
  136046. /*
  136047. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  136048. ** then free the old allocation.
  136049. */
  136050. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  136051. void *pRet = sqlite3_realloc(pOrig, nNew);
  136052. if( !pRet ){
  136053. sqlite3_free(pOrig);
  136054. }
  136055. return pRet;
  136056. }
  136057. /*
  136058. ** Buffer zInput, length nInput, contains the contents of a quoted string
  136059. ** that appeared as part of an fts3 query expression. Neither quote character
  136060. ** is included in the buffer. This function attempts to tokenize the entire
  136061. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  136062. ** containing the results.
  136063. **
  136064. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  136065. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  136066. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  136067. ** to 0.
  136068. */
  136069. static int getNextString(
  136070. ParseContext *pParse, /* fts3 query parse context */
  136071. const char *zInput, int nInput, /* Input string */
  136072. Fts3Expr **ppExpr /* OUT: expression */
  136073. ){
  136074. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  136075. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  136076. int rc;
  136077. Fts3Expr *p = 0;
  136078. sqlite3_tokenizer_cursor *pCursor = 0;
  136079. char *zTemp = 0;
  136080. int nTemp = 0;
  136081. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  136082. int nToken = 0;
  136083. /* The final Fts3Expr data structure, including the Fts3Phrase,
  136084. ** Fts3PhraseToken structures token buffers are all stored as a single
  136085. ** allocation so that the expression can be freed with a single call to
  136086. ** sqlite3_free(). Setting this up requires a two pass approach.
  136087. **
  136088. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  136089. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  136090. ** to assemble data in two dynamic buffers:
  136091. **
  136092. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  136093. ** structure, followed by the array of Fts3PhraseToken
  136094. ** structures. This pass only populates the Fts3PhraseToken array.
  136095. **
  136096. ** Buffer zTemp: Contains copies of all tokens.
  136097. **
  136098. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  136099. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  136100. ** structures.
  136101. */
  136102. rc = sqlite3Fts3OpenTokenizer(
  136103. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  136104. if( rc==SQLITE_OK ){
  136105. int ii;
  136106. for(ii=0; rc==SQLITE_OK; ii++){
  136107. const char *zByte;
  136108. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  136109. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  136110. if( rc==SQLITE_OK ){
  136111. Fts3PhraseToken *pToken;
  136112. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  136113. if( !p ) goto no_mem;
  136114. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  136115. if( !zTemp ) goto no_mem;
  136116. assert( nToken==ii );
  136117. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  136118. memset(pToken, 0, sizeof(Fts3PhraseToken));
  136119. memcpy(&zTemp[nTemp], zByte, nByte);
  136120. nTemp += nByte;
  136121. pToken->n = nByte;
  136122. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  136123. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  136124. nToken = ii+1;
  136125. }
  136126. }
  136127. pModule->xClose(pCursor);
  136128. pCursor = 0;
  136129. }
  136130. if( rc==SQLITE_DONE ){
  136131. int jj;
  136132. char *zBuf = 0;
  136133. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  136134. if( !p ) goto no_mem;
  136135. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  136136. p->eType = FTSQUERY_PHRASE;
  136137. p->pPhrase = (Fts3Phrase *)&p[1];
  136138. p->pPhrase->iColumn = pParse->iDefaultCol;
  136139. p->pPhrase->nToken = nToken;
  136140. zBuf = (char *)&p->pPhrase->aToken[nToken];
  136141. if( zTemp ){
  136142. memcpy(zBuf, zTemp, nTemp);
  136143. sqlite3_free(zTemp);
  136144. }else{
  136145. assert( nTemp==0 );
  136146. }
  136147. for(jj=0; jj<p->pPhrase->nToken; jj++){
  136148. p->pPhrase->aToken[jj].z = zBuf;
  136149. zBuf += p->pPhrase->aToken[jj].n;
  136150. }
  136151. rc = SQLITE_OK;
  136152. }
  136153. *ppExpr = p;
  136154. return rc;
  136155. no_mem:
  136156. if( pCursor ){
  136157. pModule->xClose(pCursor);
  136158. }
  136159. sqlite3_free(zTemp);
  136160. sqlite3_free(p);
  136161. *ppExpr = 0;
  136162. return SQLITE_NOMEM;
  136163. }
  136164. /*
  136165. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  136166. ** structure, or set to 0 if the end of the input buffer is reached.
  136167. **
  136168. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  136169. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  136170. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  136171. */
  136172. static int getNextNode(
  136173. ParseContext *pParse, /* fts3 query parse context */
  136174. const char *z, int n, /* Input string */
  136175. Fts3Expr **ppExpr, /* OUT: expression */
  136176. int *pnConsumed /* OUT: Number of bytes consumed */
  136177. ){
  136178. static const struct Fts3Keyword {
  136179. char *z; /* Keyword text */
  136180. unsigned char n; /* Length of the keyword */
  136181. unsigned char parenOnly; /* Only valid in paren mode */
  136182. unsigned char eType; /* Keyword code */
  136183. } aKeyword[] = {
  136184. { "OR" , 2, 0, FTSQUERY_OR },
  136185. { "AND", 3, 1, FTSQUERY_AND },
  136186. { "NOT", 3, 1, FTSQUERY_NOT },
  136187. { "NEAR", 4, 0, FTSQUERY_NEAR }
  136188. };
  136189. int ii;
  136190. int iCol;
  136191. int iColLen;
  136192. int rc;
  136193. Fts3Expr *pRet = 0;
  136194. const char *zInput = z;
  136195. int nInput = n;
  136196. pParse->isNot = 0;
  136197. /* Skip over any whitespace before checking for a keyword, an open or
  136198. ** close bracket, or a quoted string.
  136199. */
  136200. while( nInput>0 && fts3isspace(*zInput) ){
  136201. nInput--;
  136202. zInput++;
  136203. }
  136204. if( nInput==0 ){
  136205. return SQLITE_DONE;
  136206. }
  136207. /* See if we are dealing with a keyword. */
  136208. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  136209. const struct Fts3Keyword *pKey = &aKeyword[ii];
  136210. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  136211. continue;
  136212. }
  136213. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  136214. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  136215. int nKey = pKey->n;
  136216. char cNext;
  136217. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  136218. if( pKey->eType==FTSQUERY_NEAR ){
  136219. assert( nKey==4 );
  136220. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  136221. nNear = 0;
  136222. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  136223. nNear = nNear * 10 + (zInput[nKey] - '0');
  136224. }
  136225. }
  136226. }
  136227. /* At this point this is probably a keyword. But for that to be true,
  136228. ** the next byte must contain either whitespace, an open or close
  136229. ** parenthesis, a quote character, or EOF.
  136230. */
  136231. cNext = zInput[nKey];
  136232. if( fts3isspace(cNext)
  136233. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  136234. ){
  136235. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  136236. if( !pRet ){
  136237. return SQLITE_NOMEM;
  136238. }
  136239. pRet->eType = pKey->eType;
  136240. pRet->nNear = nNear;
  136241. *ppExpr = pRet;
  136242. *pnConsumed = (int)((zInput - z) + nKey);
  136243. return SQLITE_OK;
  136244. }
  136245. /* Turns out that wasn't a keyword after all. This happens if the
  136246. ** user has supplied a token such as "ORacle". Continue.
  136247. */
  136248. }
  136249. }
  136250. /* See if we are dealing with a quoted phrase. If this is the case, then
  136251. ** search for the closing quote and pass the whole string to getNextString()
  136252. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  136253. ** a quote character embedded in a string.
  136254. */
  136255. if( *zInput=='"' ){
  136256. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  136257. *pnConsumed = (int)((zInput - z) + ii + 1);
  136258. if( ii==nInput ){
  136259. return SQLITE_ERROR;
  136260. }
  136261. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  136262. }
  136263. if( sqlite3_fts3_enable_parentheses ){
  136264. if( *zInput=='(' ){
  136265. int nConsumed = 0;
  136266. pParse->nNest++;
  136267. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  136268. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  136269. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  136270. return rc;
  136271. }else if( *zInput==')' ){
  136272. pParse->nNest--;
  136273. *pnConsumed = (int)((zInput - z) + 1);
  136274. *ppExpr = 0;
  136275. return SQLITE_DONE;
  136276. }
  136277. }
  136278. /* If control flows to this point, this must be a regular token, or
  136279. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  136280. ** interface. Before doing so, figure out if there is an explicit
  136281. ** column specifier for the token.
  136282. **
  136283. ** TODO: Strangely, it is not possible to associate a column specifier
  136284. ** with a quoted phrase, only with a single token. Not sure if this was
  136285. ** an implementation artifact or an intentional decision when fts3 was
  136286. ** first implemented. Whichever it was, this module duplicates the
  136287. ** limitation.
  136288. */
  136289. iCol = pParse->iDefaultCol;
  136290. iColLen = 0;
  136291. for(ii=0; ii<pParse->nCol; ii++){
  136292. const char *zStr = pParse->azCol[ii];
  136293. int nStr = (int)strlen(zStr);
  136294. if( nInput>nStr && zInput[nStr]==':'
  136295. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  136296. ){
  136297. iCol = ii;
  136298. iColLen = (int)((zInput - z) + nStr + 1);
  136299. break;
  136300. }
  136301. }
  136302. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  136303. *pnConsumed += iColLen;
  136304. return rc;
  136305. }
  136306. /*
  136307. ** The argument is an Fts3Expr structure for a binary operator (any type
  136308. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  136309. ** precedence of the operator. Lower values have a higher precedence (i.e.
  136310. ** group more tightly). For example, in the C language, the == operator
  136311. ** groups more tightly than ||, and would therefore have a higher precedence.
  136312. **
  136313. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  136314. ** is defined), the order of the operators in precedence from highest to
  136315. ** lowest is:
  136316. **
  136317. ** NEAR
  136318. ** NOT
  136319. ** AND (including implicit ANDs)
  136320. ** OR
  136321. **
  136322. ** Note that when using the old query syntax, the OR operator has a higher
  136323. ** precedence than the AND operator.
  136324. */
  136325. static int opPrecedence(Fts3Expr *p){
  136326. assert( p->eType!=FTSQUERY_PHRASE );
  136327. if( sqlite3_fts3_enable_parentheses ){
  136328. return p->eType;
  136329. }else if( p->eType==FTSQUERY_NEAR ){
  136330. return 1;
  136331. }else if( p->eType==FTSQUERY_OR ){
  136332. return 2;
  136333. }
  136334. assert( p->eType==FTSQUERY_AND );
  136335. return 3;
  136336. }
  136337. /*
  136338. ** Argument ppHead contains a pointer to the current head of a query
  136339. ** expression tree being parsed. pPrev is the expression node most recently
  136340. ** inserted into the tree. This function adds pNew, which is always a binary
  136341. ** operator node, into the expression tree based on the relative precedence
  136342. ** of pNew and the existing nodes of the tree. This may result in the head
  136343. ** of the tree changing, in which case *ppHead is set to the new root node.
  136344. */
  136345. static void insertBinaryOperator(
  136346. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  136347. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  136348. Fts3Expr *pNew /* New binary node to insert into expression tree */
  136349. ){
  136350. Fts3Expr *pSplit = pPrev;
  136351. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  136352. pSplit = pSplit->pParent;
  136353. }
  136354. if( pSplit->pParent ){
  136355. assert( pSplit->pParent->pRight==pSplit );
  136356. pSplit->pParent->pRight = pNew;
  136357. pNew->pParent = pSplit->pParent;
  136358. }else{
  136359. *ppHead = pNew;
  136360. }
  136361. pNew->pLeft = pSplit;
  136362. pSplit->pParent = pNew;
  136363. }
  136364. /*
  136365. ** Parse the fts3 query expression found in buffer z, length n. This function
  136366. ** returns either when the end of the buffer is reached or an unmatched
  136367. ** closing bracket - ')' - is encountered.
  136368. **
  136369. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  136370. ** parsed form of the expression and *pnConsumed is set to the number of
  136371. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  136372. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  136373. */
  136374. static int fts3ExprParse(
  136375. ParseContext *pParse, /* fts3 query parse context */
  136376. const char *z, int n, /* Text of MATCH query */
  136377. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  136378. int *pnConsumed /* OUT: Number of bytes consumed */
  136379. ){
  136380. Fts3Expr *pRet = 0;
  136381. Fts3Expr *pPrev = 0;
  136382. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  136383. int nIn = n;
  136384. const char *zIn = z;
  136385. int rc = SQLITE_OK;
  136386. int isRequirePhrase = 1;
  136387. while( rc==SQLITE_OK ){
  136388. Fts3Expr *p = 0;
  136389. int nByte = 0;
  136390. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  136391. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  136392. if( rc==SQLITE_OK ){
  136393. if( p ){
  136394. int isPhrase;
  136395. if( !sqlite3_fts3_enable_parentheses
  136396. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  136397. ){
  136398. /* Create an implicit NOT operator. */
  136399. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  136400. if( !pNot ){
  136401. sqlite3Fts3ExprFree(p);
  136402. rc = SQLITE_NOMEM;
  136403. goto exprparse_out;
  136404. }
  136405. pNot->eType = FTSQUERY_NOT;
  136406. pNot->pRight = p;
  136407. p->pParent = pNot;
  136408. if( pNotBranch ){
  136409. pNot->pLeft = pNotBranch;
  136410. pNotBranch->pParent = pNot;
  136411. }
  136412. pNotBranch = pNot;
  136413. p = pPrev;
  136414. }else{
  136415. int eType = p->eType;
  136416. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  136417. /* The isRequirePhrase variable is set to true if a phrase or
  136418. ** an expression contained in parenthesis is required. If a
  136419. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  136420. ** isRequirePhrase is set, this is a syntax error.
  136421. */
  136422. if( !isPhrase && isRequirePhrase ){
  136423. sqlite3Fts3ExprFree(p);
  136424. rc = SQLITE_ERROR;
  136425. goto exprparse_out;
  136426. }
  136427. if( isPhrase && !isRequirePhrase ){
  136428. /* Insert an implicit AND operator. */
  136429. Fts3Expr *pAnd;
  136430. assert( pRet && pPrev );
  136431. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  136432. if( !pAnd ){
  136433. sqlite3Fts3ExprFree(p);
  136434. rc = SQLITE_NOMEM;
  136435. goto exprparse_out;
  136436. }
  136437. pAnd->eType = FTSQUERY_AND;
  136438. insertBinaryOperator(&pRet, pPrev, pAnd);
  136439. pPrev = pAnd;
  136440. }
  136441. /* This test catches attempts to make either operand of a NEAR
  136442. ** operator something other than a phrase. For example, either of
  136443. ** the following:
  136444. **
  136445. ** (bracketed expression) NEAR phrase
  136446. ** phrase NEAR (bracketed expression)
  136447. **
  136448. ** Return an error in either case.
  136449. */
  136450. if( pPrev && (
  136451. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  136452. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  136453. )){
  136454. sqlite3Fts3ExprFree(p);
  136455. rc = SQLITE_ERROR;
  136456. goto exprparse_out;
  136457. }
  136458. if( isPhrase ){
  136459. if( pRet ){
  136460. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  136461. pPrev->pRight = p;
  136462. p->pParent = pPrev;
  136463. }else{
  136464. pRet = p;
  136465. }
  136466. }else{
  136467. insertBinaryOperator(&pRet, pPrev, p);
  136468. }
  136469. isRequirePhrase = !isPhrase;
  136470. }
  136471. pPrev = p;
  136472. }
  136473. assert( nByte>0 );
  136474. }
  136475. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  136476. nIn -= nByte;
  136477. zIn += nByte;
  136478. }
  136479. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  136480. rc = SQLITE_ERROR;
  136481. }
  136482. if( rc==SQLITE_DONE ){
  136483. rc = SQLITE_OK;
  136484. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  136485. if( !pRet ){
  136486. rc = SQLITE_ERROR;
  136487. }else{
  136488. Fts3Expr *pIter = pNotBranch;
  136489. while( pIter->pLeft ){
  136490. pIter = pIter->pLeft;
  136491. }
  136492. pIter->pLeft = pRet;
  136493. pRet->pParent = pIter;
  136494. pRet = pNotBranch;
  136495. }
  136496. }
  136497. }
  136498. *pnConsumed = n - nIn;
  136499. exprparse_out:
  136500. if( rc!=SQLITE_OK ){
  136501. sqlite3Fts3ExprFree(pRet);
  136502. sqlite3Fts3ExprFree(pNotBranch);
  136503. pRet = 0;
  136504. }
  136505. *ppExpr = pRet;
  136506. return rc;
  136507. }
  136508. /*
  136509. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  136510. ** as the only argument is more than nMaxDepth.
  136511. */
  136512. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  136513. int rc = SQLITE_OK;
  136514. if( p ){
  136515. if( nMaxDepth<0 ){
  136516. rc = SQLITE_TOOBIG;
  136517. }else{
  136518. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  136519. if( rc==SQLITE_OK ){
  136520. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  136521. }
  136522. }
  136523. }
  136524. return rc;
  136525. }
  136526. /*
  136527. ** This function attempts to transform the expression tree at (*pp) to
  136528. ** an equivalent but more balanced form. The tree is modified in place.
  136529. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  136530. ** new root expression node.
  136531. **
  136532. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  136533. **
  136534. ** Otherwise, if an error occurs, an SQLite error code is returned and
  136535. ** expression (*pp) freed.
  136536. */
  136537. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  136538. int rc = SQLITE_OK; /* Return code */
  136539. Fts3Expr *pRoot = *pp; /* Initial root node */
  136540. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  136541. int eType = pRoot->eType; /* Type of node in this tree */
  136542. if( nMaxDepth==0 ){
  136543. rc = SQLITE_ERROR;
  136544. }
  136545. if( rc==SQLITE_OK ){
  136546. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  136547. Fts3Expr **apLeaf;
  136548. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  136549. if( 0==apLeaf ){
  136550. rc = SQLITE_NOMEM;
  136551. }else{
  136552. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  136553. }
  136554. if( rc==SQLITE_OK ){
  136555. int i;
  136556. Fts3Expr *p;
  136557. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  136558. for(p=pRoot; p->eType==eType; p=p->pLeft){
  136559. assert( p->pParent==0 || p->pParent->pLeft==p );
  136560. assert( p->pLeft && p->pRight );
  136561. }
  136562. /* This loop runs once for each leaf in the tree of eType nodes. */
  136563. while( 1 ){
  136564. int iLvl;
  136565. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  136566. assert( pParent==0 || pParent->pLeft==p );
  136567. p->pParent = 0;
  136568. if( pParent ){
  136569. pParent->pLeft = 0;
  136570. }else{
  136571. pRoot = 0;
  136572. }
  136573. rc = fts3ExprBalance(&p, nMaxDepth-1);
  136574. if( rc!=SQLITE_OK ) break;
  136575. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  136576. if( apLeaf[iLvl]==0 ){
  136577. apLeaf[iLvl] = p;
  136578. p = 0;
  136579. }else{
  136580. assert( pFree );
  136581. pFree->pLeft = apLeaf[iLvl];
  136582. pFree->pRight = p;
  136583. pFree->pLeft->pParent = pFree;
  136584. pFree->pRight->pParent = pFree;
  136585. p = pFree;
  136586. pFree = pFree->pParent;
  136587. p->pParent = 0;
  136588. apLeaf[iLvl] = 0;
  136589. }
  136590. }
  136591. if( p ){
  136592. sqlite3Fts3ExprFree(p);
  136593. rc = SQLITE_TOOBIG;
  136594. break;
  136595. }
  136596. /* If that was the last leaf node, break out of the loop */
  136597. if( pParent==0 ) break;
  136598. /* Set $p to point to the next leaf in the tree of eType nodes */
  136599. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  136600. /* Remove pParent from the original tree. */
  136601. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  136602. pParent->pRight->pParent = pParent->pParent;
  136603. if( pParent->pParent ){
  136604. pParent->pParent->pLeft = pParent->pRight;
  136605. }else{
  136606. assert( pParent==pRoot );
  136607. pRoot = pParent->pRight;
  136608. }
  136609. /* Link pParent into the free node list. It will be used as an
  136610. ** internal node of the new tree. */
  136611. pParent->pParent = pFree;
  136612. pFree = pParent;
  136613. }
  136614. if( rc==SQLITE_OK ){
  136615. p = 0;
  136616. for(i=0; i<nMaxDepth; i++){
  136617. if( apLeaf[i] ){
  136618. if( p==0 ){
  136619. p = apLeaf[i];
  136620. p->pParent = 0;
  136621. }else{
  136622. assert( pFree!=0 );
  136623. pFree->pRight = p;
  136624. pFree->pLeft = apLeaf[i];
  136625. pFree->pLeft->pParent = pFree;
  136626. pFree->pRight->pParent = pFree;
  136627. p = pFree;
  136628. pFree = pFree->pParent;
  136629. p->pParent = 0;
  136630. }
  136631. }
  136632. }
  136633. pRoot = p;
  136634. }else{
  136635. /* An error occurred. Delete the contents of the apLeaf[] array
  136636. ** and pFree list. Everything else is cleaned up by the call to
  136637. ** sqlite3Fts3ExprFree(pRoot) below. */
  136638. Fts3Expr *pDel;
  136639. for(i=0; i<nMaxDepth; i++){
  136640. sqlite3Fts3ExprFree(apLeaf[i]);
  136641. }
  136642. while( (pDel=pFree)!=0 ){
  136643. pFree = pDel->pParent;
  136644. sqlite3_free(pDel);
  136645. }
  136646. }
  136647. assert( pFree==0 );
  136648. sqlite3_free( apLeaf );
  136649. }
  136650. }else if( eType==FTSQUERY_NOT ){
  136651. Fts3Expr *pLeft = pRoot->pLeft;
  136652. Fts3Expr *pRight = pRoot->pRight;
  136653. pRoot->pLeft = 0;
  136654. pRoot->pRight = 0;
  136655. pLeft->pParent = 0;
  136656. pRight->pParent = 0;
  136657. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  136658. if( rc==SQLITE_OK ){
  136659. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  136660. }
  136661. if( rc!=SQLITE_OK ){
  136662. sqlite3Fts3ExprFree(pRight);
  136663. sqlite3Fts3ExprFree(pLeft);
  136664. }else{
  136665. assert( pLeft && pRight );
  136666. pRoot->pLeft = pLeft;
  136667. pLeft->pParent = pRoot;
  136668. pRoot->pRight = pRight;
  136669. pRight->pParent = pRoot;
  136670. }
  136671. }
  136672. }
  136673. if( rc!=SQLITE_OK ){
  136674. sqlite3Fts3ExprFree(pRoot);
  136675. pRoot = 0;
  136676. }
  136677. *pp = pRoot;
  136678. return rc;
  136679. }
  136680. /*
  136681. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  136682. ** differences:
  136683. **
  136684. ** 1. It does not do expression rebalancing.
  136685. ** 2. It does not check that the expression does not exceed the
  136686. ** maximum allowable depth.
  136687. ** 3. Even if it fails, *ppExpr may still be set to point to an
  136688. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  136689. ** in this case.
  136690. */
  136691. static int fts3ExprParseUnbalanced(
  136692. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  136693. int iLangid, /* Language id for tokenizer */
  136694. char **azCol, /* Array of column names for fts3 table */
  136695. int bFts4, /* True to allow FTS4-only syntax */
  136696. int nCol, /* Number of entries in azCol[] */
  136697. int iDefaultCol, /* Default column to query */
  136698. const char *z, int n, /* Text of MATCH query */
  136699. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  136700. ){
  136701. int nParsed;
  136702. int rc;
  136703. ParseContext sParse;
  136704. memset(&sParse, 0, sizeof(ParseContext));
  136705. sParse.pTokenizer = pTokenizer;
  136706. sParse.iLangid = iLangid;
  136707. sParse.azCol = (const char **)azCol;
  136708. sParse.nCol = nCol;
  136709. sParse.iDefaultCol = iDefaultCol;
  136710. sParse.bFts4 = bFts4;
  136711. if( z==0 ){
  136712. *ppExpr = 0;
  136713. return SQLITE_OK;
  136714. }
  136715. if( n<0 ){
  136716. n = (int)strlen(z);
  136717. }
  136718. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  136719. assert( rc==SQLITE_OK || *ppExpr==0 );
  136720. /* Check for mismatched parenthesis */
  136721. if( rc==SQLITE_OK && sParse.nNest ){
  136722. rc = SQLITE_ERROR;
  136723. }
  136724. return rc;
  136725. }
  136726. /*
  136727. ** Parameters z and n contain a pointer to and length of a buffer containing
  136728. ** an fts3 query expression, respectively. This function attempts to parse the
  136729. ** query expression and create a tree of Fts3Expr structures representing the
  136730. ** parsed expression. If successful, *ppExpr is set to point to the head
  136731. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  136732. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  136733. ** error) is returned and *ppExpr is set to 0.
  136734. **
  136735. ** If parameter n is a negative number, then z is assumed to point to a
  136736. ** nul-terminated string and the length is determined using strlen().
  136737. **
  136738. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  136739. ** use to normalize query tokens while parsing the expression. The azCol[]
  136740. ** array, which is assumed to contain nCol entries, should contain the names
  136741. ** of each column in the target fts3 table, in order from left to right.
  136742. ** Column names must be nul-terminated strings.
  136743. **
  136744. ** The iDefaultCol parameter should be passed the index of the table column
  136745. ** that appears on the left-hand-side of the MATCH operator (the default
  136746. ** column to match against for tokens for which a column name is not explicitly
  136747. ** specified as part of the query string), or -1 if tokens may by default
  136748. ** match any table column.
  136749. */
  136750. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  136751. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  136752. int iLangid, /* Language id for tokenizer */
  136753. char **azCol, /* Array of column names for fts3 table */
  136754. int bFts4, /* True to allow FTS4-only syntax */
  136755. int nCol, /* Number of entries in azCol[] */
  136756. int iDefaultCol, /* Default column to query */
  136757. const char *z, int n, /* Text of MATCH query */
  136758. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  136759. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  136760. ){
  136761. int rc = fts3ExprParseUnbalanced(
  136762. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  136763. );
  136764. /* Rebalance the expression. And check that its depth does not exceed
  136765. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  136766. if( rc==SQLITE_OK && *ppExpr ){
  136767. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  136768. if( rc==SQLITE_OK ){
  136769. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  136770. }
  136771. }
  136772. if( rc!=SQLITE_OK ){
  136773. sqlite3Fts3ExprFree(*ppExpr);
  136774. *ppExpr = 0;
  136775. if( rc==SQLITE_TOOBIG ){
  136776. sqlite3Fts3ErrMsg(pzErr,
  136777. "FTS expression tree is too large (maximum depth %d)",
  136778. SQLITE_FTS3_MAX_EXPR_DEPTH
  136779. );
  136780. rc = SQLITE_ERROR;
  136781. }else if( rc==SQLITE_ERROR ){
  136782. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  136783. }
  136784. }
  136785. return rc;
  136786. }
  136787. /*
  136788. ** Free a single node of an expression tree.
  136789. */
  136790. static void fts3FreeExprNode(Fts3Expr *p){
  136791. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  136792. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  136793. sqlite3_free(p->aMI);
  136794. sqlite3_free(p);
  136795. }
  136796. /*
  136797. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  136798. **
  136799. ** This function would be simpler if it recursively called itself. But
  136800. ** that would mean passing a sufficiently large expression to ExprParse()
  136801. ** could cause a stack overflow.
  136802. */
  136803. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  136804. Fts3Expr *p;
  136805. assert( pDel==0 || pDel->pParent==0 );
  136806. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  136807. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  136808. }
  136809. while( p ){
  136810. Fts3Expr *pParent = p->pParent;
  136811. fts3FreeExprNode(p);
  136812. if( pParent && p==pParent->pLeft && pParent->pRight ){
  136813. p = pParent->pRight;
  136814. while( p && (p->pLeft || p->pRight) ){
  136815. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  136816. p = (p->pLeft ? p->pLeft : p->pRight);
  136817. }
  136818. }else{
  136819. p = pParent;
  136820. }
  136821. }
  136822. }
  136823. /****************************************************************************
  136824. *****************************************************************************
  136825. ** Everything after this point is just test code.
  136826. */
  136827. #ifdef SQLITE_TEST
  136828. /* #include <stdio.h> */
  136829. /*
  136830. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  136831. */
  136832. static int queryTestTokenizer(
  136833. sqlite3 *db,
  136834. const char *zName,
  136835. const sqlite3_tokenizer_module **pp
  136836. ){
  136837. int rc;
  136838. sqlite3_stmt *pStmt;
  136839. const char zSql[] = "SELECT fts3_tokenizer(?)";
  136840. *pp = 0;
  136841. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  136842. if( rc!=SQLITE_OK ){
  136843. return rc;
  136844. }
  136845. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  136846. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  136847. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  136848. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  136849. }
  136850. }
  136851. return sqlite3_finalize(pStmt);
  136852. }
  136853. /*
  136854. ** Return a pointer to a buffer containing a text representation of the
  136855. ** expression passed as the first argument. The buffer is obtained from
  136856. ** sqlite3_malloc(). It is the responsibility of the caller to use
  136857. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  136858. ** NULL is returned.
  136859. **
  136860. ** If the second argument is not NULL, then its contents are prepended to
  136861. ** the returned expression text and then freed using sqlite3_free().
  136862. */
  136863. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  136864. if( pExpr==0 ){
  136865. return sqlite3_mprintf("");
  136866. }
  136867. switch( pExpr->eType ){
  136868. case FTSQUERY_PHRASE: {
  136869. Fts3Phrase *pPhrase = pExpr->pPhrase;
  136870. int i;
  136871. zBuf = sqlite3_mprintf(
  136872. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  136873. for(i=0; zBuf && i<pPhrase->nToken; i++){
  136874. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  136875. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  136876. (pPhrase->aToken[i].isPrefix?"+":"")
  136877. );
  136878. }
  136879. return zBuf;
  136880. }
  136881. case FTSQUERY_NEAR:
  136882. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  136883. break;
  136884. case FTSQUERY_NOT:
  136885. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  136886. break;
  136887. case FTSQUERY_AND:
  136888. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  136889. break;
  136890. case FTSQUERY_OR:
  136891. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  136892. break;
  136893. }
  136894. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  136895. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  136896. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  136897. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  136898. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  136899. return zBuf;
  136900. }
  136901. /*
  136902. ** This is the implementation of a scalar SQL function used to test the
  136903. ** expression parser. It should be called as follows:
  136904. **
  136905. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  136906. **
  136907. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  136908. ** to parse the query expression (see README.tokenizers). The second argument
  136909. ** is the query expression to parse. Each subsequent argument is the name
  136910. ** of a column of the fts3 table that the query expression may refer to.
  136911. ** For example:
  136912. **
  136913. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  136914. */
  136915. static void fts3ExprTest(
  136916. sqlite3_context *context,
  136917. int argc,
  136918. sqlite3_value **argv
  136919. ){
  136920. sqlite3_tokenizer_module const *pModule = 0;
  136921. sqlite3_tokenizer *pTokenizer = 0;
  136922. int rc;
  136923. char **azCol = 0;
  136924. const char *zExpr;
  136925. int nExpr;
  136926. int nCol;
  136927. int ii;
  136928. Fts3Expr *pExpr;
  136929. char *zBuf = 0;
  136930. sqlite3 *db = sqlite3_context_db_handle(context);
  136931. if( argc<3 ){
  136932. sqlite3_result_error(context,
  136933. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  136934. );
  136935. return;
  136936. }
  136937. rc = queryTestTokenizer(db,
  136938. (const char *)sqlite3_value_text(argv[0]), &pModule);
  136939. if( rc==SQLITE_NOMEM ){
  136940. sqlite3_result_error_nomem(context);
  136941. goto exprtest_out;
  136942. }else if( !pModule ){
  136943. sqlite3_result_error(context, "No such tokenizer module", -1);
  136944. goto exprtest_out;
  136945. }
  136946. rc = pModule->xCreate(0, 0, &pTokenizer);
  136947. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  136948. if( rc==SQLITE_NOMEM ){
  136949. sqlite3_result_error_nomem(context);
  136950. goto exprtest_out;
  136951. }
  136952. pTokenizer->pModule = pModule;
  136953. zExpr = (const char *)sqlite3_value_text(argv[1]);
  136954. nExpr = sqlite3_value_bytes(argv[1]);
  136955. nCol = argc-2;
  136956. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  136957. if( !azCol ){
  136958. sqlite3_result_error_nomem(context);
  136959. goto exprtest_out;
  136960. }
  136961. for(ii=0; ii<nCol; ii++){
  136962. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  136963. }
  136964. if( sqlite3_user_data(context) ){
  136965. char *zDummy = 0;
  136966. rc = sqlite3Fts3ExprParse(
  136967. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  136968. );
  136969. assert( rc==SQLITE_OK || pExpr==0 );
  136970. sqlite3_free(zDummy);
  136971. }else{
  136972. rc = fts3ExprParseUnbalanced(
  136973. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  136974. );
  136975. }
  136976. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  136977. sqlite3Fts3ExprFree(pExpr);
  136978. sqlite3_result_error(context, "Error parsing expression", -1);
  136979. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  136980. sqlite3_result_error_nomem(context);
  136981. }else{
  136982. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  136983. sqlite3_free(zBuf);
  136984. }
  136985. sqlite3Fts3ExprFree(pExpr);
  136986. exprtest_out:
  136987. if( pModule && pTokenizer ){
  136988. rc = pModule->xDestroy(pTokenizer);
  136989. }
  136990. sqlite3_free(azCol);
  136991. }
  136992. /*
  136993. ** Register the query expression parser test function fts3_exprtest()
  136994. ** with database connection db.
  136995. */
  136996. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  136997. int rc = sqlite3_create_function(
  136998. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  136999. );
  137000. if( rc==SQLITE_OK ){
  137001. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  137002. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  137003. );
  137004. }
  137005. return rc;
  137006. }
  137007. #endif
  137008. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137009. /************** End of fts3_expr.c *******************************************/
  137010. /************** Begin file fts3_hash.c ***************************************/
  137011. /*
  137012. ** 2001 September 22
  137013. **
  137014. ** The author disclaims copyright to this source code. In place of
  137015. ** a legal notice, here is a blessing:
  137016. **
  137017. ** May you do good and not evil.
  137018. ** May you find forgiveness for yourself and forgive others.
  137019. ** May you share freely, never taking more than you give.
  137020. **
  137021. *************************************************************************
  137022. ** This is the implementation of generic hash-tables used in SQLite.
  137023. ** We've modified it slightly to serve as a standalone hash table
  137024. ** implementation for the full-text indexing module.
  137025. */
  137026. /*
  137027. ** The code in this file is only compiled if:
  137028. **
  137029. ** * The FTS3 module is being built as an extension
  137030. ** (in which case SQLITE_CORE is not defined), or
  137031. **
  137032. ** * The FTS3 module is being built into the core of
  137033. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  137034. */
  137035. /* #include "fts3Int.h" */
  137036. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137037. /* #include <assert.h> */
  137038. /* #include <stdlib.h> */
  137039. /* #include <string.h> */
  137040. /* #include "fts3_hash.h" */
  137041. /*
  137042. ** Malloc and Free functions
  137043. */
  137044. static void *fts3HashMalloc(int n){
  137045. void *p = sqlite3_malloc(n);
  137046. if( p ){
  137047. memset(p, 0, n);
  137048. }
  137049. return p;
  137050. }
  137051. static void fts3HashFree(void *p){
  137052. sqlite3_free(p);
  137053. }
  137054. /* Turn bulk memory into a hash table object by initializing the
  137055. ** fields of the Hash structure.
  137056. **
  137057. ** "pNew" is a pointer to the hash table that is to be initialized.
  137058. ** keyClass is one of the constants
  137059. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  137060. ** determines what kind of key the hash table will use. "copyKey" is
  137061. ** true if the hash table should make its own private copy of keys and
  137062. ** false if it should just use the supplied pointer.
  137063. */
  137064. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  137065. assert( pNew!=0 );
  137066. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  137067. pNew->keyClass = keyClass;
  137068. pNew->copyKey = copyKey;
  137069. pNew->first = 0;
  137070. pNew->count = 0;
  137071. pNew->htsize = 0;
  137072. pNew->ht = 0;
  137073. }
  137074. /* Remove all entries from a hash table. Reclaim all memory.
  137075. ** Call this routine to delete a hash table or to reset a hash table
  137076. ** to the empty state.
  137077. */
  137078. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  137079. Fts3HashElem *elem; /* For looping over all elements of the table */
  137080. assert( pH!=0 );
  137081. elem = pH->first;
  137082. pH->first = 0;
  137083. fts3HashFree(pH->ht);
  137084. pH->ht = 0;
  137085. pH->htsize = 0;
  137086. while( elem ){
  137087. Fts3HashElem *next_elem = elem->next;
  137088. if( pH->copyKey && elem->pKey ){
  137089. fts3HashFree(elem->pKey);
  137090. }
  137091. fts3HashFree(elem);
  137092. elem = next_elem;
  137093. }
  137094. pH->count = 0;
  137095. }
  137096. /*
  137097. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  137098. */
  137099. static int fts3StrHash(const void *pKey, int nKey){
  137100. const char *z = (const char *)pKey;
  137101. unsigned h = 0;
  137102. if( nKey<=0 ) nKey = (int) strlen(z);
  137103. while( nKey > 0 ){
  137104. h = (h<<3) ^ h ^ *z++;
  137105. nKey--;
  137106. }
  137107. return (int)(h & 0x7fffffff);
  137108. }
  137109. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  137110. if( n1!=n2 ) return 1;
  137111. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  137112. }
  137113. /*
  137114. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  137115. */
  137116. static int fts3BinHash(const void *pKey, int nKey){
  137117. int h = 0;
  137118. const char *z = (const char *)pKey;
  137119. while( nKey-- > 0 ){
  137120. h = (h<<3) ^ h ^ *(z++);
  137121. }
  137122. return h & 0x7fffffff;
  137123. }
  137124. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  137125. if( n1!=n2 ) return 1;
  137126. return memcmp(pKey1,pKey2,n1);
  137127. }
  137128. /*
  137129. ** Return a pointer to the appropriate hash function given the key class.
  137130. **
  137131. ** The C syntax in this function definition may be unfamilar to some
  137132. ** programmers, so we provide the following additional explanation:
  137133. **
  137134. ** The name of the function is "ftsHashFunction". The function takes a
  137135. ** single parameter "keyClass". The return value of ftsHashFunction()
  137136. ** is a pointer to another function. Specifically, the return value
  137137. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  137138. ** with types "const void*" and "int" and returns an "int".
  137139. */
  137140. static int (*ftsHashFunction(int keyClass))(const void*,int){
  137141. if( keyClass==FTS3_HASH_STRING ){
  137142. return &fts3StrHash;
  137143. }else{
  137144. assert( keyClass==FTS3_HASH_BINARY );
  137145. return &fts3BinHash;
  137146. }
  137147. }
  137148. /*
  137149. ** Return a pointer to the appropriate hash function given the key class.
  137150. **
  137151. ** For help in interpreted the obscure C code in the function definition,
  137152. ** see the header comment on the previous function.
  137153. */
  137154. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  137155. if( keyClass==FTS3_HASH_STRING ){
  137156. return &fts3StrCompare;
  137157. }else{
  137158. assert( keyClass==FTS3_HASH_BINARY );
  137159. return &fts3BinCompare;
  137160. }
  137161. }
  137162. /* Link an element into the hash table
  137163. */
  137164. static void fts3HashInsertElement(
  137165. Fts3Hash *pH, /* The complete hash table */
  137166. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  137167. Fts3HashElem *pNew /* The element to be inserted */
  137168. ){
  137169. Fts3HashElem *pHead; /* First element already in pEntry */
  137170. pHead = pEntry->chain;
  137171. if( pHead ){
  137172. pNew->next = pHead;
  137173. pNew->prev = pHead->prev;
  137174. if( pHead->prev ){ pHead->prev->next = pNew; }
  137175. else { pH->first = pNew; }
  137176. pHead->prev = pNew;
  137177. }else{
  137178. pNew->next = pH->first;
  137179. if( pH->first ){ pH->first->prev = pNew; }
  137180. pNew->prev = 0;
  137181. pH->first = pNew;
  137182. }
  137183. pEntry->count++;
  137184. pEntry->chain = pNew;
  137185. }
  137186. /* Resize the hash table so that it cantains "new_size" buckets.
  137187. ** "new_size" must be a power of 2. The hash table might fail
  137188. ** to resize if sqliteMalloc() fails.
  137189. **
  137190. ** Return non-zero if a memory allocation error occurs.
  137191. */
  137192. static int fts3Rehash(Fts3Hash *pH, int new_size){
  137193. struct _fts3ht *new_ht; /* The new hash table */
  137194. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  137195. int (*xHash)(const void*,int); /* The hash function */
  137196. assert( (new_size & (new_size-1))==0 );
  137197. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  137198. if( new_ht==0 ) return 1;
  137199. fts3HashFree(pH->ht);
  137200. pH->ht = new_ht;
  137201. pH->htsize = new_size;
  137202. xHash = ftsHashFunction(pH->keyClass);
  137203. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  137204. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  137205. next_elem = elem->next;
  137206. fts3HashInsertElement(pH, &new_ht[h], elem);
  137207. }
  137208. return 0;
  137209. }
  137210. /* This function (for internal use only) locates an element in an
  137211. ** hash table that matches the given key. The hash for this key has
  137212. ** already been computed and is passed as the 4th parameter.
  137213. */
  137214. static Fts3HashElem *fts3FindElementByHash(
  137215. const Fts3Hash *pH, /* The pH to be searched */
  137216. const void *pKey, /* The key we are searching for */
  137217. int nKey,
  137218. int h /* The hash for this key. */
  137219. ){
  137220. Fts3HashElem *elem; /* Used to loop thru the element list */
  137221. int count; /* Number of elements left to test */
  137222. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  137223. if( pH->ht ){
  137224. struct _fts3ht *pEntry = &pH->ht[h];
  137225. elem = pEntry->chain;
  137226. count = pEntry->count;
  137227. xCompare = ftsCompareFunction(pH->keyClass);
  137228. while( count-- && elem ){
  137229. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  137230. return elem;
  137231. }
  137232. elem = elem->next;
  137233. }
  137234. }
  137235. return 0;
  137236. }
  137237. /* Remove a single entry from the hash table given a pointer to that
  137238. ** element and a hash on the element's key.
  137239. */
  137240. static void fts3RemoveElementByHash(
  137241. Fts3Hash *pH, /* The pH containing "elem" */
  137242. Fts3HashElem* elem, /* The element to be removed from the pH */
  137243. int h /* Hash value for the element */
  137244. ){
  137245. struct _fts3ht *pEntry;
  137246. if( elem->prev ){
  137247. elem->prev->next = elem->next;
  137248. }else{
  137249. pH->first = elem->next;
  137250. }
  137251. if( elem->next ){
  137252. elem->next->prev = elem->prev;
  137253. }
  137254. pEntry = &pH->ht[h];
  137255. if( pEntry->chain==elem ){
  137256. pEntry->chain = elem->next;
  137257. }
  137258. pEntry->count--;
  137259. if( pEntry->count<=0 ){
  137260. pEntry->chain = 0;
  137261. }
  137262. if( pH->copyKey && elem->pKey ){
  137263. fts3HashFree(elem->pKey);
  137264. }
  137265. fts3HashFree( elem );
  137266. pH->count--;
  137267. if( pH->count<=0 ){
  137268. assert( pH->first==0 );
  137269. assert( pH->count==0 );
  137270. fts3HashClear(pH);
  137271. }
  137272. }
  137273. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  137274. const Fts3Hash *pH,
  137275. const void *pKey,
  137276. int nKey
  137277. ){
  137278. int h; /* A hash on key */
  137279. int (*xHash)(const void*,int); /* The hash function */
  137280. if( pH==0 || pH->ht==0 ) return 0;
  137281. xHash = ftsHashFunction(pH->keyClass);
  137282. assert( xHash!=0 );
  137283. h = (*xHash)(pKey,nKey);
  137284. assert( (pH->htsize & (pH->htsize-1))==0 );
  137285. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  137286. }
  137287. /*
  137288. ** Attempt to locate an element of the hash table pH with a key
  137289. ** that matches pKey,nKey. Return the data for this element if it is
  137290. ** found, or NULL if there is no match.
  137291. */
  137292. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  137293. Fts3HashElem *pElem; /* The element that matches key (if any) */
  137294. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  137295. return pElem ? pElem->data : 0;
  137296. }
  137297. /* Insert an element into the hash table pH. The key is pKey,nKey
  137298. ** and the data is "data".
  137299. **
  137300. ** If no element exists with a matching key, then a new
  137301. ** element is created. A copy of the key is made if the copyKey
  137302. ** flag is set. NULL is returned.
  137303. **
  137304. ** If another element already exists with the same key, then the
  137305. ** new data replaces the old data and the old data is returned.
  137306. ** The key is not copied in this instance. If a malloc fails, then
  137307. ** the new data is returned and the hash table is unchanged.
  137308. **
  137309. ** If the "data" parameter to this function is NULL, then the
  137310. ** element corresponding to "key" is removed from the hash table.
  137311. */
  137312. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  137313. Fts3Hash *pH, /* The hash table to insert into */
  137314. const void *pKey, /* The key */
  137315. int nKey, /* Number of bytes in the key */
  137316. void *data /* The data */
  137317. ){
  137318. int hraw; /* Raw hash value of the key */
  137319. int h; /* the hash of the key modulo hash table size */
  137320. Fts3HashElem *elem; /* Used to loop thru the element list */
  137321. Fts3HashElem *new_elem; /* New element added to the pH */
  137322. int (*xHash)(const void*,int); /* The hash function */
  137323. assert( pH!=0 );
  137324. xHash = ftsHashFunction(pH->keyClass);
  137325. assert( xHash!=0 );
  137326. hraw = (*xHash)(pKey, nKey);
  137327. assert( (pH->htsize & (pH->htsize-1))==0 );
  137328. h = hraw & (pH->htsize-1);
  137329. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  137330. if( elem ){
  137331. void *old_data = elem->data;
  137332. if( data==0 ){
  137333. fts3RemoveElementByHash(pH,elem,h);
  137334. }else{
  137335. elem->data = data;
  137336. }
  137337. return old_data;
  137338. }
  137339. if( data==0 ) return 0;
  137340. if( (pH->htsize==0 && fts3Rehash(pH,8))
  137341. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  137342. ){
  137343. pH->count = 0;
  137344. return data;
  137345. }
  137346. assert( pH->htsize>0 );
  137347. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  137348. if( new_elem==0 ) return data;
  137349. if( pH->copyKey && pKey!=0 ){
  137350. new_elem->pKey = fts3HashMalloc( nKey );
  137351. if( new_elem->pKey==0 ){
  137352. fts3HashFree(new_elem);
  137353. return data;
  137354. }
  137355. memcpy((void*)new_elem->pKey, pKey, nKey);
  137356. }else{
  137357. new_elem->pKey = (void*)pKey;
  137358. }
  137359. new_elem->nKey = nKey;
  137360. pH->count++;
  137361. assert( pH->htsize>0 );
  137362. assert( (pH->htsize & (pH->htsize-1))==0 );
  137363. h = hraw & (pH->htsize-1);
  137364. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  137365. new_elem->data = data;
  137366. return 0;
  137367. }
  137368. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137369. /************** End of fts3_hash.c *******************************************/
  137370. /************** Begin file fts3_porter.c *************************************/
  137371. /*
  137372. ** 2006 September 30
  137373. **
  137374. ** The author disclaims copyright to this source code. In place of
  137375. ** a legal notice, here is a blessing:
  137376. **
  137377. ** May you do good and not evil.
  137378. ** May you find forgiveness for yourself and forgive others.
  137379. ** May you share freely, never taking more than you give.
  137380. **
  137381. *************************************************************************
  137382. ** Implementation of the full-text-search tokenizer that implements
  137383. ** a Porter stemmer.
  137384. */
  137385. /*
  137386. ** The code in this file is only compiled if:
  137387. **
  137388. ** * The FTS3 module is being built as an extension
  137389. ** (in which case SQLITE_CORE is not defined), or
  137390. **
  137391. ** * The FTS3 module is being built into the core of
  137392. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  137393. */
  137394. /* #include "fts3Int.h" */
  137395. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137396. /* #include <assert.h> */
  137397. /* #include <stdlib.h> */
  137398. /* #include <stdio.h> */
  137399. /* #include <string.h> */
  137400. /* #include "fts3_tokenizer.h" */
  137401. /*
  137402. ** Class derived from sqlite3_tokenizer
  137403. */
  137404. typedef struct porter_tokenizer {
  137405. sqlite3_tokenizer base; /* Base class */
  137406. } porter_tokenizer;
  137407. /*
  137408. ** Class derived from sqlite3_tokenizer_cursor
  137409. */
  137410. typedef struct porter_tokenizer_cursor {
  137411. sqlite3_tokenizer_cursor base;
  137412. const char *zInput; /* input we are tokenizing */
  137413. int nInput; /* size of the input */
  137414. int iOffset; /* current position in zInput */
  137415. int iToken; /* index of next token to be returned */
  137416. char *zToken; /* storage for current token */
  137417. int nAllocated; /* space allocated to zToken buffer */
  137418. } porter_tokenizer_cursor;
  137419. /*
  137420. ** Create a new tokenizer instance.
  137421. */
  137422. static int porterCreate(
  137423. int argc, const char * const *argv,
  137424. sqlite3_tokenizer **ppTokenizer
  137425. ){
  137426. porter_tokenizer *t;
  137427. UNUSED_PARAMETER(argc);
  137428. UNUSED_PARAMETER(argv);
  137429. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  137430. if( t==NULL ) return SQLITE_NOMEM;
  137431. memset(t, 0, sizeof(*t));
  137432. *ppTokenizer = &t->base;
  137433. return SQLITE_OK;
  137434. }
  137435. /*
  137436. ** Destroy a tokenizer
  137437. */
  137438. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  137439. sqlite3_free(pTokenizer);
  137440. return SQLITE_OK;
  137441. }
  137442. /*
  137443. ** Prepare to begin tokenizing a particular string. The input
  137444. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  137445. ** used to incrementally tokenize this string is returned in
  137446. ** *ppCursor.
  137447. */
  137448. static int porterOpen(
  137449. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  137450. const char *zInput, int nInput, /* String to be tokenized */
  137451. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  137452. ){
  137453. porter_tokenizer_cursor *c;
  137454. UNUSED_PARAMETER(pTokenizer);
  137455. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  137456. if( c==NULL ) return SQLITE_NOMEM;
  137457. c->zInput = zInput;
  137458. if( zInput==0 ){
  137459. c->nInput = 0;
  137460. }else if( nInput<0 ){
  137461. c->nInput = (int)strlen(zInput);
  137462. }else{
  137463. c->nInput = nInput;
  137464. }
  137465. c->iOffset = 0; /* start tokenizing at the beginning */
  137466. c->iToken = 0;
  137467. c->zToken = NULL; /* no space allocated, yet. */
  137468. c->nAllocated = 0;
  137469. *ppCursor = &c->base;
  137470. return SQLITE_OK;
  137471. }
  137472. /*
  137473. ** Close a tokenization cursor previously opened by a call to
  137474. ** porterOpen() above.
  137475. */
  137476. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  137477. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  137478. sqlite3_free(c->zToken);
  137479. sqlite3_free(c);
  137480. return SQLITE_OK;
  137481. }
  137482. /*
  137483. ** Vowel or consonant
  137484. */
  137485. static const char cType[] = {
  137486. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  137487. 1, 1, 1, 2, 1
  137488. };
  137489. /*
  137490. ** isConsonant() and isVowel() determine if their first character in
  137491. ** the string they point to is a consonant or a vowel, according
  137492. ** to Porter ruls.
  137493. **
  137494. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  137495. ** 'Y' is a consonant unless it follows another consonant,
  137496. ** in which case it is a vowel.
  137497. **
  137498. ** In these routine, the letters are in reverse order. So the 'y' rule
  137499. ** is that 'y' is a consonant unless it is followed by another
  137500. ** consonent.
  137501. */
  137502. static int isVowel(const char*);
  137503. static int isConsonant(const char *z){
  137504. int j;
  137505. char x = *z;
  137506. if( x==0 ) return 0;
  137507. assert( x>='a' && x<='z' );
  137508. j = cType[x-'a'];
  137509. if( j<2 ) return j;
  137510. return z[1]==0 || isVowel(z + 1);
  137511. }
  137512. static int isVowel(const char *z){
  137513. int j;
  137514. char x = *z;
  137515. if( x==0 ) return 0;
  137516. assert( x>='a' && x<='z' );
  137517. j = cType[x-'a'];
  137518. if( j<2 ) return 1-j;
  137519. return isConsonant(z + 1);
  137520. }
  137521. /*
  137522. ** Let any sequence of one or more vowels be represented by V and let
  137523. ** C be sequence of one or more consonants. Then every word can be
  137524. ** represented as:
  137525. **
  137526. ** [C] (VC){m} [V]
  137527. **
  137528. ** In prose: A word is an optional consonant followed by zero or
  137529. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  137530. ** number of vowel consonant pairs. This routine computes the value
  137531. ** of m for the first i bytes of a word.
  137532. **
  137533. ** Return true if the m-value for z is 1 or more. In other words,
  137534. ** return true if z contains at least one vowel that is followed
  137535. ** by a consonant.
  137536. **
  137537. ** In this routine z[] is in reverse order. So we are really looking
  137538. ** for an instance of a consonant followed by a vowel.
  137539. */
  137540. static int m_gt_0(const char *z){
  137541. while( isVowel(z) ){ z++; }
  137542. if( *z==0 ) return 0;
  137543. while( isConsonant(z) ){ z++; }
  137544. return *z!=0;
  137545. }
  137546. /* Like mgt0 above except we are looking for a value of m which is
  137547. ** exactly 1
  137548. */
  137549. static int m_eq_1(const char *z){
  137550. while( isVowel(z) ){ z++; }
  137551. if( *z==0 ) return 0;
  137552. while( isConsonant(z) ){ z++; }
  137553. if( *z==0 ) return 0;
  137554. while( isVowel(z) ){ z++; }
  137555. if( *z==0 ) return 1;
  137556. while( isConsonant(z) ){ z++; }
  137557. return *z==0;
  137558. }
  137559. /* Like mgt0 above except we are looking for a value of m>1 instead
  137560. ** or m>0
  137561. */
  137562. static int m_gt_1(const char *z){
  137563. while( isVowel(z) ){ z++; }
  137564. if( *z==0 ) return 0;
  137565. while( isConsonant(z) ){ z++; }
  137566. if( *z==0 ) return 0;
  137567. while( isVowel(z) ){ z++; }
  137568. if( *z==0 ) return 0;
  137569. while( isConsonant(z) ){ z++; }
  137570. return *z!=0;
  137571. }
  137572. /*
  137573. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  137574. */
  137575. static int hasVowel(const char *z){
  137576. while( isConsonant(z) ){ z++; }
  137577. return *z!=0;
  137578. }
  137579. /*
  137580. ** Return TRUE if the word ends in a double consonant.
  137581. **
  137582. ** The text is reversed here. So we are really looking at
  137583. ** the first two characters of z[].
  137584. */
  137585. static int doubleConsonant(const char *z){
  137586. return isConsonant(z) && z[0]==z[1];
  137587. }
  137588. /*
  137589. ** Return TRUE if the word ends with three letters which
  137590. ** are consonant-vowel-consonent and where the final consonant
  137591. ** is not 'w', 'x', or 'y'.
  137592. **
  137593. ** The word is reversed here. So we are really checking the
  137594. ** first three letters and the first one cannot be in [wxy].
  137595. */
  137596. static int star_oh(const char *z){
  137597. return
  137598. isConsonant(z) &&
  137599. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  137600. isVowel(z+1) &&
  137601. isConsonant(z+2);
  137602. }
  137603. /*
  137604. ** If the word ends with zFrom and xCond() is true for the stem
  137605. ** of the word that preceeds the zFrom ending, then change the
  137606. ** ending to zTo.
  137607. **
  137608. ** The input word *pz and zFrom are both in reverse order. zTo
  137609. ** is in normal order.
  137610. **
  137611. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  137612. ** match. Not that TRUE is returned even if xCond() fails and
  137613. ** no substitution occurs.
  137614. */
  137615. static int stem(
  137616. char **pz, /* The word being stemmed (Reversed) */
  137617. const char *zFrom, /* If the ending matches this... (Reversed) */
  137618. const char *zTo, /* ... change the ending to this (not reversed) */
  137619. int (*xCond)(const char*) /* Condition that must be true */
  137620. ){
  137621. char *z = *pz;
  137622. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  137623. if( *zFrom!=0 ) return 0;
  137624. if( xCond && !xCond(z) ) return 1;
  137625. while( *zTo ){
  137626. *(--z) = *(zTo++);
  137627. }
  137628. *pz = z;
  137629. return 1;
  137630. }
  137631. /*
  137632. ** This is the fallback stemmer used when the porter stemmer is
  137633. ** inappropriate. The input word is copied into the output with
  137634. ** US-ASCII case folding. If the input word is too long (more
  137635. ** than 20 bytes if it contains no digits or more than 6 bytes if
  137636. ** it contains digits) then word is truncated to 20 or 6 bytes
  137637. ** by taking 10 or 3 bytes from the beginning and end.
  137638. */
  137639. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  137640. int i, mx, j;
  137641. int hasDigit = 0;
  137642. for(i=0; i<nIn; i++){
  137643. char c = zIn[i];
  137644. if( c>='A' && c<='Z' ){
  137645. zOut[i] = c - 'A' + 'a';
  137646. }else{
  137647. if( c>='0' && c<='9' ) hasDigit = 1;
  137648. zOut[i] = c;
  137649. }
  137650. }
  137651. mx = hasDigit ? 3 : 10;
  137652. if( nIn>mx*2 ){
  137653. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  137654. zOut[j] = zOut[i];
  137655. }
  137656. i = j;
  137657. }
  137658. zOut[i] = 0;
  137659. *pnOut = i;
  137660. }
  137661. /*
  137662. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  137663. ** zOut is at least big enough to hold nIn bytes. Write the actual
  137664. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  137665. **
  137666. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  137667. ** are converted to lower case. Upper-case UTF characters are
  137668. ** unchanged.
  137669. **
  137670. ** Words that are longer than about 20 bytes are stemmed by retaining
  137671. ** a few bytes from the beginning and the end of the word. If the
  137672. ** word contains digits, 3 bytes are taken from the beginning and
  137673. ** 3 bytes from the end. For long words without digits, 10 bytes
  137674. ** are taken from each end. US-ASCII case folding still applies.
  137675. **
  137676. ** If the input word contains not digits but does characters not
  137677. ** in [a-zA-Z] then no stemming is attempted and this routine just
  137678. ** copies the input into the input into the output with US-ASCII
  137679. ** case folding.
  137680. **
  137681. ** Stemming never increases the length of the word. So there is
  137682. ** no chance of overflowing the zOut buffer.
  137683. */
  137684. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  137685. int i, j;
  137686. char zReverse[28];
  137687. char *z, *z2;
  137688. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  137689. /* The word is too big or too small for the porter stemmer.
  137690. ** Fallback to the copy stemmer */
  137691. copy_stemmer(zIn, nIn, zOut, pnOut);
  137692. return;
  137693. }
  137694. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  137695. char c = zIn[i];
  137696. if( c>='A' && c<='Z' ){
  137697. zReverse[j] = c + 'a' - 'A';
  137698. }else if( c>='a' && c<='z' ){
  137699. zReverse[j] = c;
  137700. }else{
  137701. /* The use of a character not in [a-zA-Z] means that we fallback
  137702. ** to the copy stemmer */
  137703. copy_stemmer(zIn, nIn, zOut, pnOut);
  137704. return;
  137705. }
  137706. }
  137707. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  137708. z = &zReverse[j+1];
  137709. /* Step 1a */
  137710. if( z[0]=='s' ){
  137711. if(
  137712. !stem(&z, "sess", "ss", 0) &&
  137713. !stem(&z, "sei", "i", 0) &&
  137714. !stem(&z, "ss", "ss", 0)
  137715. ){
  137716. z++;
  137717. }
  137718. }
  137719. /* Step 1b */
  137720. z2 = z;
  137721. if( stem(&z, "dee", "ee", m_gt_0) ){
  137722. /* Do nothing. The work was all in the test */
  137723. }else if(
  137724. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  137725. && z!=z2
  137726. ){
  137727. if( stem(&z, "ta", "ate", 0) ||
  137728. stem(&z, "lb", "ble", 0) ||
  137729. stem(&z, "zi", "ize", 0) ){
  137730. /* Do nothing. The work was all in the test */
  137731. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  137732. z++;
  137733. }else if( m_eq_1(z) && star_oh(z) ){
  137734. *(--z) = 'e';
  137735. }
  137736. }
  137737. /* Step 1c */
  137738. if( z[0]=='y' && hasVowel(z+1) ){
  137739. z[0] = 'i';
  137740. }
  137741. /* Step 2 */
  137742. switch( z[1] ){
  137743. case 'a':
  137744. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  137745. stem(&z, "lanoit", "tion", m_gt_0);
  137746. }
  137747. break;
  137748. case 'c':
  137749. if( !stem(&z, "icne", "ence", m_gt_0) ){
  137750. stem(&z, "icna", "ance", m_gt_0);
  137751. }
  137752. break;
  137753. case 'e':
  137754. stem(&z, "rezi", "ize", m_gt_0);
  137755. break;
  137756. case 'g':
  137757. stem(&z, "igol", "log", m_gt_0);
  137758. break;
  137759. case 'l':
  137760. if( !stem(&z, "ilb", "ble", m_gt_0)
  137761. && !stem(&z, "illa", "al", m_gt_0)
  137762. && !stem(&z, "iltne", "ent", m_gt_0)
  137763. && !stem(&z, "ile", "e", m_gt_0)
  137764. ){
  137765. stem(&z, "ilsuo", "ous", m_gt_0);
  137766. }
  137767. break;
  137768. case 'o':
  137769. if( !stem(&z, "noitazi", "ize", m_gt_0)
  137770. && !stem(&z, "noita", "ate", m_gt_0)
  137771. ){
  137772. stem(&z, "rota", "ate", m_gt_0);
  137773. }
  137774. break;
  137775. case 's':
  137776. if( !stem(&z, "msila", "al", m_gt_0)
  137777. && !stem(&z, "ssenevi", "ive", m_gt_0)
  137778. && !stem(&z, "ssenluf", "ful", m_gt_0)
  137779. ){
  137780. stem(&z, "ssensuo", "ous", m_gt_0);
  137781. }
  137782. break;
  137783. case 't':
  137784. if( !stem(&z, "itila", "al", m_gt_0)
  137785. && !stem(&z, "itivi", "ive", m_gt_0)
  137786. ){
  137787. stem(&z, "itilib", "ble", m_gt_0);
  137788. }
  137789. break;
  137790. }
  137791. /* Step 3 */
  137792. switch( z[0] ){
  137793. case 'e':
  137794. if( !stem(&z, "etaci", "ic", m_gt_0)
  137795. && !stem(&z, "evita", "", m_gt_0)
  137796. ){
  137797. stem(&z, "ezila", "al", m_gt_0);
  137798. }
  137799. break;
  137800. case 'i':
  137801. stem(&z, "itici", "ic", m_gt_0);
  137802. break;
  137803. case 'l':
  137804. if( !stem(&z, "laci", "ic", m_gt_0) ){
  137805. stem(&z, "luf", "", m_gt_0);
  137806. }
  137807. break;
  137808. case 's':
  137809. stem(&z, "ssen", "", m_gt_0);
  137810. break;
  137811. }
  137812. /* Step 4 */
  137813. switch( z[1] ){
  137814. case 'a':
  137815. if( z[0]=='l' && m_gt_1(z+2) ){
  137816. z += 2;
  137817. }
  137818. break;
  137819. case 'c':
  137820. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  137821. z += 4;
  137822. }
  137823. break;
  137824. case 'e':
  137825. if( z[0]=='r' && m_gt_1(z+2) ){
  137826. z += 2;
  137827. }
  137828. break;
  137829. case 'i':
  137830. if( z[0]=='c' && m_gt_1(z+2) ){
  137831. z += 2;
  137832. }
  137833. break;
  137834. case 'l':
  137835. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  137836. z += 4;
  137837. }
  137838. break;
  137839. case 'n':
  137840. if( z[0]=='t' ){
  137841. if( z[2]=='a' ){
  137842. if( m_gt_1(z+3) ){
  137843. z += 3;
  137844. }
  137845. }else if( z[2]=='e' ){
  137846. if( !stem(&z, "tneme", "", m_gt_1)
  137847. && !stem(&z, "tnem", "", m_gt_1)
  137848. ){
  137849. stem(&z, "tne", "", m_gt_1);
  137850. }
  137851. }
  137852. }
  137853. break;
  137854. case 'o':
  137855. if( z[0]=='u' ){
  137856. if( m_gt_1(z+2) ){
  137857. z += 2;
  137858. }
  137859. }else if( z[3]=='s' || z[3]=='t' ){
  137860. stem(&z, "noi", "", m_gt_1);
  137861. }
  137862. break;
  137863. case 's':
  137864. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  137865. z += 3;
  137866. }
  137867. break;
  137868. case 't':
  137869. if( !stem(&z, "eta", "", m_gt_1) ){
  137870. stem(&z, "iti", "", m_gt_1);
  137871. }
  137872. break;
  137873. case 'u':
  137874. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  137875. z += 3;
  137876. }
  137877. break;
  137878. case 'v':
  137879. case 'z':
  137880. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  137881. z += 3;
  137882. }
  137883. break;
  137884. }
  137885. /* Step 5a */
  137886. if( z[0]=='e' ){
  137887. if( m_gt_1(z+1) ){
  137888. z++;
  137889. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  137890. z++;
  137891. }
  137892. }
  137893. /* Step 5b */
  137894. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  137895. z++;
  137896. }
  137897. /* z[] is now the stemmed word in reverse order. Flip it back
  137898. ** around into forward order and return.
  137899. */
  137900. *pnOut = i = (int)strlen(z);
  137901. zOut[i] = 0;
  137902. while( *z ){
  137903. zOut[--i] = *(z++);
  137904. }
  137905. }
  137906. /*
  137907. ** Characters that can be part of a token. We assume any character
  137908. ** whose value is greater than 0x80 (any UTF character) can be
  137909. ** part of a token. In other words, delimiters all must have
  137910. ** values of 0x7f or lower.
  137911. */
  137912. static const char porterIdChar[] = {
  137913. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  137914. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  137915. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  137916. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  137917. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  137918. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  137919. };
  137920. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  137921. /*
  137922. ** Extract the next token from a tokenization cursor. The cursor must
  137923. ** have been opened by a prior call to porterOpen().
  137924. */
  137925. static int porterNext(
  137926. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  137927. const char **pzToken, /* OUT: *pzToken is the token text */
  137928. int *pnBytes, /* OUT: Number of bytes in token */
  137929. int *piStartOffset, /* OUT: Starting offset of token */
  137930. int *piEndOffset, /* OUT: Ending offset of token */
  137931. int *piPosition /* OUT: Position integer of token */
  137932. ){
  137933. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  137934. const char *z = c->zInput;
  137935. while( c->iOffset<c->nInput ){
  137936. int iStartOffset, ch;
  137937. /* Scan past delimiter characters */
  137938. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  137939. c->iOffset++;
  137940. }
  137941. /* Count non-delimiter characters. */
  137942. iStartOffset = c->iOffset;
  137943. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  137944. c->iOffset++;
  137945. }
  137946. if( c->iOffset>iStartOffset ){
  137947. int n = c->iOffset-iStartOffset;
  137948. if( n>c->nAllocated ){
  137949. char *pNew;
  137950. c->nAllocated = n+20;
  137951. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  137952. if( !pNew ) return SQLITE_NOMEM;
  137953. c->zToken = pNew;
  137954. }
  137955. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  137956. *pzToken = c->zToken;
  137957. *piStartOffset = iStartOffset;
  137958. *piEndOffset = c->iOffset;
  137959. *piPosition = c->iToken++;
  137960. return SQLITE_OK;
  137961. }
  137962. }
  137963. return SQLITE_DONE;
  137964. }
  137965. /*
  137966. ** The set of routines that implement the porter-stemmer tokenizer
  137967. */
  137968. static const sqlite3_tokenizer_module porterTokenizerModule = {
  137969. 0,
  137970. porterCreate,
  137971. porterDestroy,
  137972. porterOpen,
  137973. porterClose,
  137974. porterNext,
  137975. 0
  137976. };
  137977. /*
  137978. ** Allocate a new porter tokenizer. Return a pointer to the new
  137979. ** tokenizer in *ppModule
  137980. */
  137981. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  137982. sqlite3_tokenizer_module const**ppModule
  137983. ){
  137984. *ppModule = &porterTokenizerModule;
  137985. }
  137986. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137987. /************** End of fts3_porter.c *****************************************/
  137988. /************** Begin file fts3_tokenizer.c **********************************/
  137989. /*
  137990. ** 2007 June 22
  137991. **
  137992. ** The author disclaims copyright to this source code. In place of
  137993. ** a legal notice, here is a blessing:
  137994. **
  137995. ** May you do good and not evil.
  137996. ** May you find forgiveness for yourself and forgive others.
  137997. ** May you share freely, never taking more than you give.
  137998. **
  137999. ******************************************************************************
  138000. **
  138001. ** This is part of an SQLite module implementing full-text search.
  138002. ** This particular file implements the generic tokenizer interface.
  138003. */
  138004. /*
  138005. ** The code in this file is only compiled if:
  138006. **
  138007. ** * The FTS3 module is being built as an extension
  138008. ** (in which case SQLITE_CORE is not defined), or
  138009. **
  138010. ** * The FTS3 module is being built into the core of
  138011. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  138012. */
  138013. /* #include "fts3Int.h" */
  138014. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  138015. /* #include <assert.h> */
  138016. /* #include <string.h> */
  138017. /*
  138018. ** Return true if the two-argument version of fts3_tokenizer()
  138019. ** has been activated via a prior call to sqlite3_db_config(db,
  138020. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  138021. */
  138022. static int fts3TokenizerEnabled(sqlite3_context *context){
  138023. sqlite3 *db = sqlite3_context_db_handle(context);
  138024. int isEnabled = 0;
  138025. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  138026. return isEnabled;
  138027. }
  138028. /*
  138029. ** Implementation of the SQL scalar function for accessing the underlying
  138030. ** hash table. This function may be called as follows:
  138031. **
  138032. ** SELECT <function-name>(<key-name>);
  138033. ** SELECT <function-name>(<key-name>, <pointer>);
  138034. **
  138035. ** where <function-name> is the name passed as the second argument
  138036. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  138037. **
  138038. ** If the <pointer> argument is specified, it must be a blob value
  138039. ** containing a pointer to be stored as the hash data corresponding
  138040. ** to the string <key-name>. If <pointer> is not specified, then
  138041. ** the string <key-name> must already exist in the has table. Otherwise,
  138042. ** an error is returned.
  138043. **
  138044. ** Whether or not the <pointer> argument is specified, the value returned
  138045. ** is a blob containing the pointer stored as the hash data corresponding
  138046. ** to string <key-name> (after the hash-table is updated, if applicable).
  138047. */
  138048. static void fts3TokenizerFunc(
  138049. sqlite3_context *context,
  138050. int argc,
  138051. sqlite3_value **argv
  138052. ){
  138053. Fts3Hash *pHash;
  138054. void *pPtr = 0;
  138055. const unsigned char *zName;
  138056. int nName;
  138057. assert( argc==1 || argc==2 );
  138058. pHash = (Fts3Hash *)sqlite3_user_data(context);
  138059. zName = sqlite3_value_text(argv[0]);
  138060. nName = sqlite3_value_bytes(argv[0])+1;
  138061. if( argc==2 ){
  138062. if( fts3TokenizerEnabled(context) ){
  138063. void *pOld;
  138064. int n = sqlite3_value_bytes(argv[1]);
  138065. if( zName==0 || n!=sizeof(pPtr) ){
  138066. sqlite3_result_error(context, "argument type mismatch", -1);
  138067. return;
  138068. }
  138069. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  138070. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  138071. if( pOld==pPtr ){
  138072. sqlite3_result_error(context, "out of memory", -1);
  138073. }
  138074. }else{
  138075. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  138076. return;
  138077. }
  138078. }else{
  138079. if( zName ){
  138080. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  138081. }
  138082. if( !pPtr ){
  138083. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  138084. sqlite3_result_error(context, zErr, -1);
  138085. sqlite3_free(zErr);
  138086. return;
  138087. }
  138088. }
  138089. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  138090. }
  138091. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  138092. static const char isFtsIdChar[] = {
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  138095. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  138096. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  138097. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  138098. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  138099. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  138100. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  138101. };
  138102. return (c&0x80 || isFtsIdChar[(int)(c)]);
  138103. }
  138104. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  138105. const char *z1;
  138106. const char *z2 = 0;
  138107. /* Find the start of the next token. */
  138108. z1 = zStr;
  138109. while( z2==0 ){
  138110. char c = *z1;
  138111. switch( c ){
  138112. case '\0': return 0; /* No more tokens here */
  138113. case '\'':
  138114. case '"':
  138115. case '`': {
  138116. z2 = z1;
  138117. while( *++z2 && (*z2!=c || *++z2==c) );
  138118. break;
  138119. }
  138120. case '[':
  138121. z2 = &z1[1];
  138122. while( *z2 && z2[0]!=']' ) z2++;
  138123. if( *z2 ) z2++;
  138124. break;
  138125. default:
  138126. if( sqlite3Fts3IsIdChar(*z1) ){
  138127. z2 = &z1[1];
  138128. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  138129. }else{
  138130. z1++;
  138131. }
  138132. }
  138133. }
  138134. *pn = (int)(z2-z1);
  138135. return z1;
  138136. }
  138137. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  138138. Fts3Hash *pHash, /* Tokenizer hash table */
  138139. const char *zArg, /* Tokenizer name */
  138140. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  138141. char **pzErr /* OUT: Set to malloced error message */
  138142. ){
  138143. int rc;
  138144. char *z = (char *)zArg;
  138145. int n = 0;
  138146. char *zCopy;
  138147. char *zEnd; /* Pointer to nul-term of zCopy */
  138148. sqlite3_tokenizer_module *m;
  138149. zCopy = sqlite3_mprintf("%s", zArg);
  138150. if( !zCopy ) return SQLITE_NOMEM;
  138151. zEnd = &zCopy[strlen(zCopy)];
  138152. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  138153. if( z==0 ){
  138154. assert( n==0 );
  138155. z = zCopy;
  138156. }
  138157. z[n] = '\0';
  138158. sqlite3Fts3Dequote(z);
  138159. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  138160. if( !m ){
  138161. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  138162. rc = SQLITE_ERROR;
  138163. }else{
  138164. char const **aArg = 0;
  138165. int iArg = 0;
  138166. z = &z[n+1];
  138167. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  138168. int nNew = sizeof(char *)*(iArg+1);
  138169. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  138170. if( !aNew ){
  138171. sqlite3_free(zCopy);
  138172. sqlite3_free((void *)aArg);
  138173. return SQLITE_NOMEM;
  138174. }
  138175. aArg = aNew;
  138176. aArg[iArg++] = z;
  138177. z[n] = '\0';
  138178. sqlite3Fts3Dequote(z);
  138179. z = &z[n+1];
  138180. }
  138181. rc = m->xCreate(iArg, aArg, ppTok);
  138182. assert( rc!=SQLITE_OK || *ppTok );
  138183. if( rc!=SQLITE_OK ){
  138184. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  138185. }else{
  138186. (*ppTok)->pModule = m;
  138187. }
  138188. sqlite3_free((void *)aArg);
  138189. }
  138190. sqlite3_free(zCopy);
  138191. return rc;
  138192. }
  138193. #ifdef SQLITE_TEST
  138194. #include <tcl.h>
  138195. /* #include <string.h> */
  138196. /*
  138197. ** Implementation of a special SQL scalar function for testing tokenizers
  138198. ** designed to be used in concert with the Tcl testing framework. This
  138199. ** function must be called with two or more arguments:
  138200. **
  138201. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  138202. **
  138203. ** where <function-name> is the name passed as the second argument
  138204. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  138205. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  138206. **
  138207. ** The return value is a string that may be interpreted as a Tcl
  138208. ** list. For each token in the <input-string>, three elements are
  138209. ** added to the returned list. The first is the token position, the
  138210. ** second is the token text (folded, stemmed, etc.) and the third is the
  138211. ** substring of <input-string> associated with the token. For example,
  138212. ** using the built-in "simple" tokenizer:
  138213. **
  138214. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  138215. **
  138216. ** will return the string:
  138217. **
  138218. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  138219. **
  138220. */
  138221. static void testFunc(
  138222. sqlite3_context *context,
  138223. int argc,
  138224. sqlite3_value **argv
  138225. ){
  138226. Fts3Hash *pHash;
  138227. sqlite3_tokenizer_module *p;
  138228. sqlite3_tokenizer *pTokenizer = 0;
  138229. sqlite3_tokenizer_cursor *pCsr = 0;
  138230. const char *zErr = 0;
  138231. const char *zName;
  138232. int nName;
  138233. const char *zInput;
  138234. int nInput;
  138235. const char *azArg[64];
  138236. const char *zToken;
  138237. int nToken = 0;
  138238. int iStart = 0;
  138239. int iEnd = 0;
  138240. int iPos = 0;
  138241. int i;
  138242. Tcl_Obj *pRet;
  138243. if( argc<2 ){
  138244. sqlite3_result_error(context, "insufficient arguments", -1);
  138245. return;
  138246. }
  138247. nName = sqlite3_value_bytes(argv[0]);
  138248. zName = (const char *)sqlite3_value_text(argv[0]);
  138249. nInput = sqlite3_value_bytes(argv[argc-1]);
  138250. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  138251. pHash = (Fts3Hash *)sqlite3_user_data(context);
  138252. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  138253. if( !p ){
  138254. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  138255. sqlite3_result_error(context, zErr2, -1);
  138256. sqlite3_free(zErr2);
  138257. return;
  138258. }
  138259. pRet = Tcl_NewObj();
  138260. Tcl_IncrRefCount(pRet);
  138261. for(i=1; i<argc-1; i++){
  138262. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  138263. }
  138264. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  138265. zErr = "error in xCreate()";
  138266. goto finish;
  138267. }
  138268. pTokenizer->pModule = p;
  138269. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  138270. zErr = "error in xOpen()";
  138271. goto finish;
  138272. }
  138273. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  138274. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  138275. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  138276. zToken = &zInput[iStart];
  138277. nToken = iEnd-iStart;
  138278. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  138279. }
  138280. if( SQLITE_OK!=p->xClose(pCsr) ){
  138281. zErr = "error in xClose()";
  138282. goto finish;
  138283. }
  138284. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  138285. zErr = "error in xDestroy()";
  138286. goto finish;
  138287. }
  138288. finish:
  138289. if( zErr ){
  138290. sqlite3_result_error(context, zErr, -1);
  138291. }else{
  138292. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  138293. }
  138294. Tcl_DecrRefCount(pRet);
  138295. }
  138296. static
  138297. int registerTokenizer(
  138298. sqlite3 *db,
  138299. char *zName,
  138300. const sqlite3_tokenizer_module *p
  138301. ){
  138302. int rc;
  138303. sqlite3_stmt *pStmt;
  138304. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  138305. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  138306. if( rc!=SQLITE_OK ){
  138307. return rc;
  138308. }
  138309. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  138310. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  138311. sqlite3_step(pStmt);
  138312. return sqlite3_finalize(pStmt);
  138313. }
  138314. static
  138315. int queryTokenizer(
  138316. sqlite3 *db,
  138317. char *zName,
  138318. const sqlite3_tokenizer_module **pp
  138319. ){
  138320. int rc;
  138321. sqlite3_stmt *pStmt;
  138322. const char zSql[] = "SELECT fts3_tokenizer(?)";
  138323. *pp = 0;
  138324. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  138325. if( rc!=SQLITE_OK ){
  138326. return rc;
  138327. }
  138328. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  138329. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  138330. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  138331. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  138332. }
  138333. }
  138334. return sqlite3_finalize(pStmt);
  138335. }
  138336. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  138337. /*
  138338. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  138339. ** This function is used for testing only, it is not included in the
  138340. ** build unless SQLITE_TEST is defined.
  138341. **
  138342. ** The purpose of this is to test that the fts3_tokenizer() function
  138343. ** can be used as designed by the C-code in the queryTokenizer and
  138344. ** registerTokenizer() functions above. These two functions are repeated
  138345. ** in the README.tokenizer file as an example, so it is important to
  138346. ** test them.
  138347. **
  138348. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  138349. ** function with no arguments. An assert() will fail if a problem is
  138350. ** detected. i.e.:
  138351. **
  138352. ** SELECT fts3_tokenizer_internal_test();
  138353. **
  138354. */
  138355. static void intTestFunc(
  138356. sqlite3_context *context,
  138357. int argc,
  138358. sqlite3_value **argv
  138359. ){
  138360. int rc;
  138361. const sqlite3_tokenizer_module *p1;
  138362. const sqlite3_tokenizer_module *p2;
  138363. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  138364. UNUSED_PARAMETER(argc);
  138365. UNUSED_PARAMETER(argv);
  138366. /* Test the query function */
  138367. sqlite3Fts3SimpleTokenizerModule(&p1);
  138368. rc = queryTokenizer(db, "simple", &p2);
  138369. assert( rc==SQLITE_OK );
  138370. assert( p1==p2 );
  138371. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  138372. assert( rc==SQLITE_ERROR );
  138373. assert( p2==0 );
  138374. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  138375. /* Test the storage function */
  138376. if( fts3TokenizerEnabled(context) ){
  138377. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  138378. assert( rc==SQLITE_OK );
  138379. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  138380. assert( rc==SQLITE_OK );
  138381. assert( p2==p1 );
  138382. }
  138383. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  138384. }
  138385. #endif
  138386. /*
  138387. ** Set up SQL objects in database db used to access the contents of
  138388. ** the hash table pointed to by argument pHash. The hash table must
  138389. ** been initialized to use string keys, and to take a private copy
  138390. ** of the key when a value is inserted. i.e. by a call similar to:
  138391. **
  138392. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  138393. **
  138394. ** This function adds a scalar function (see header comment above
  138395. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  138396. ** defined at compilation time, a temporary virtual table (see header
  138397. ** comment above struct HashTableVtab) to the database schema. Both
  138398. ** provide read/write access to the contents of *pHash.
  138399. **
  138400. ** The third argument to this function, zName, is used as the name
  138401. ** of both the scalar and, if created, the virtual table.
  138402. */
  138403. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  138404. sqlite3 *db,
  138405. Fts3Hash *pHash,
  138406. const char *zName
  138407. ){
  138408. int rc = SQLITE_OK;
  138409. void *p = (void *)pHash;
  138410. const int any = SQLITE_ANY;
  138411. #ifdef SQLITE_TEST
  138412. char *zTest = 0;
  138413. char *zTest2 = 0;
  138414. void *pdb = (void *)db;
  138415. zTest = sqlite3_mprintf("%s_test", zName);
  138416. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  138417. if( !zTest || !zTest2 ){
  138418. rc = SQLITE_NOMEM;
  138419. }
  138420. #endif
  138421. if( SQLITE_OK==rc ){
  138422. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  138423. }
  138424. if( SQLITE_OK==rc ){
  138425. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  138426. }
  138427. #ifdef SQLITE_TEST
  138428. if( SQLITE_OK==rc ){
  138429. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  138430. }
  138431. if( SQLITE_OK==rc ){
  138432. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  138433. }
  138434. #endif
  138435. #ifdef SQLITE_TEST
  138436. sqlite3_free(zTest);
  138437. sqlite3_free(zTest2);
  138438. #endif
  138439. return rc;
  138440. }
  138441. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  138442. /************** End of fts3_tokenizer.c **************************************/
  138443. /************** Begin file fts3_tokenizer1.c *********************************/
  138444. /*
  138445. ** 2006 Oct 10
  138446. **
  138447. ** The author disclaims copyright to this source code. In place of
  138448. ** a legal notice, here is a blessing:
  138449. **
  138450. ** May you do good and not evil.
  138451. ** May you find forgiveness for yourself and forgive others.
  138452. ** May you share freely, never taking more than you give.
  138453. **
  138454. ******************************************************************************
  138455. **
  138456. ** Implementation of the "simple" full-text-search tokenizer.
  138457. */
  138458. /*
  138459. ** The code in this file is only compiled if:
  138460. **
  138461. ** * The FTS3 module is being built as an extension
  138462. ** (in which case SQLITE_CORE is not defined), or
  138463. **
  138464. ** * The FTS3 module is being built into the core of
  138465. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  138466. */
  138467. /* #include "fts3Int.h" */
  138468. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  138469. /* #include <assert.h> */
  138470. /* #include <stdlib.h> */
  138471. /* #include <stdio.h> */
  138472. /* #include <string.h> */
  138473. /* #include "fts3_tokenizer.h" */
  138474. typedef struct simple_tokenizer {
  138475. sqlite3_tokenizer base;
  138476. char delim[128]; /* flag ASCII delimiters */
  138477. } simple_tokenizer;
  138478. typedef struct simple_tokenizer_cursor {
  138479. sqlite3_tokenizer_cursor base;
  138480. const char *pInput; /* input we are tokenizing */
  138481. int nBytes; /* size of the input */
  138482. int iOffset; /* current position in pInput */
  138483. int iToken; /* index of next token to be returned */
  138484. char *pToken; /* storage for current token */
  138485. int nTokenAllocated; /* space allocated to zToken buffer */
  138486. } simple_tokenizer_cursor;
  138487. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  138488. return c<0x80 && t->delim[c];
  138489. }
  138490. static int fts3_isalnum(int x){
  138491. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  138492. }
  138493. /*
  138494. ** Create a new tokenizer instance.
  138495. */
  138496. static int simpleCreate(
  138497. int argc, const char * const *argv,
  138498. sqlite3_tokenizer **ppTokenizer
  138499. ){
  138500. simple_tokenizer *t;
  138501. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  138502. if( t==NULL ) return SQLITE_NOMEM;
  138503. memset(t, 0, sizeof(*t));
  138504. /* TODO(shess) Delimiters need to remain the same from run to run,
  138505. ** else we need to reindex. One solution would be a meta-table to
  138506. ** track such information in the database, then we'd only want this
  138507. ** information on the initial create.
  138508. */
  138509. if( argc>1 ){
  138510. int i, n = (int)strlen(argv[1]);
  138511. for(i=0; i<n; i++){
  138512. unsigned char ch = argv[1][i];
  138513. /* We explicitly don't support UTF-8 delimiters for now. */
  138514. if( ch>=0x80 ){
  138515. sqlite3_free(t);
  138516. return SQLITE_ERROR;
  138517. }
  138518. t->delim[ch] = 1;
  138519. }
  138520. } else {
  138521. /* Mark non-alphanumeric ASCII characters as delimiters */
  138522. int i;
  138523. for(i=1; i<0x80; i++){
  138524. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  138525. }
  138526. }
  138527. *ppTokenizer = &t->base;
  138528. return SQLITE_OK;
  138529. }
  138530. /*
  138531. ** Destroy a tokenizer
  138532. */
  138533. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  138534. sqlite3_free(pTokenizer);
  138535. return SQLITE_OK;
  138536. }
  138537. /*
  138538. ** Prepare to begin tokenizing a particular string. The input
  138539. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  138540. ** used to incrementally tokenize this string is returned in
  138541. ** *ppCursor.
  138542. */
  138543. static int simpleOpen(
  138544. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  138545. const char *pInput, int nBytes, /* String to be tokenized */
  138546. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  138547. ){
  138548. simple_tokenizer_cursor *c;
  138549. UNUSED_PARAMETER(pTokenizer);
  138550. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  138551. if( c==NULL ) return SQLITE_NOMEM;
  138552. c->pInput = pInput;
  138553. if( pInput==0 ){
  138554. c->nBytes = 0;
  138555. }else if( nBytes<0 ){
  138556. c->nBytes = (int)strlen(pInput);
  138557. }else{
  138558. c->nBytes = nBytes;
  138559. }
  138560. c->iOffset = 0; /* start tokenizing at the beginning */
  138561. c->iToken = 0;
  138562. c->pToken = NULL; /* no space allocated, yet. */
  138563. c->nTokenAllocated = 0;
  138564. *ppCursor = &c->base;
  138565. return SQLITE_OK;
  138566. }
  138567. /*
  138568. ** Close a tokenization cursor previously opened by a call to
  138569. ** simpleOpen() above.
  138570. */
  138571. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  138572. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  138573. sqlite3_free(c->pToken);
  138574. sqlite3_free(c);
  138575. return SQLITE_OK;
  138576. }
  138577. /*
  138578. ** Extract the next token from a tokenization cursor. The cursor must
  138579. ** have been opened by a prior call to simpleOpen().
  138580. */
  138581. static int simpleNext(
  138582. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  138583. const char **ppToken, /* OUT: *ppToken is the token text */
  138584. int *pnBytes, /* OUT: Number of bytes in token */
  138585. int *piStartOffset, /* OUT: Starting offset of token */
  138586. int *piEndOffset, /* OUT: Ending offset of token */
  138587. int *piPosition /* OUT: Position integer of token */
  138588. ){
  138589. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  138590. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  138591. unsigned char *p = (unsigned char *)c->pInput;
  138592. while( c->iOffset<c->nBytes ){
  138593. int iStartOffset;
  138594. /* Scan past delimiter characters */
  138595. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  138596. c->iOffset++;
  138597. }
  138598. /* Count non-delimiter characters. */
  138599. iStartOffset = c->iOffset;
  138600. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  138601. c->iOffset++;
  138602. }
  138603. if( c->iOffset>iStartOffset ){
  138604. int i, n = c->iOffset-iStartOffset;
  138605. if( n>c->nTokenAllocated ){
  138606. char *pNew;
  138607. c->nTokenAllocated = n+20;
  138608. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  138609. if( !pNew ) return SQLITE_NOMEM;
  138610. c->pToken = pNew;
  138611. }
  138612. for(i=0; i<n; i++){
  138613. /* TODO(shess) This needs expansion to handle UTF-8
  138614. ** case-insensitivity.
  138615. */
  138616. unsigned char ch = p[iStartOffset+i];
  138617. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  138618. }
  138619. *ppToken = c->pToken;
  138620. *pnBytes = n;
  138621. *piStartOffset = iStartOffset;
  138622. *piEndOffset = c->iOffset;
  138623. *piPosition = c->iToken++;
  138624. return SQLITE_OK;
  138625. }
  138626. }
  138627. return SQLITE_DONE;
  138628. }
  138629. /*
  138630. ** The set of routines that implement the simple tokenizer
  138631. */
  138632. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  138633. 0,
  138634. simpleCreate,
  138635. simpleDestroy,
  138636. simpleOpen,
  138637. simpleClose,
  138638. simpleNext,
  138639. 0,
  138640. };
  138641. /*
  138642. ** Allocate a new simple tokenizer. Return a pointer to the new
  138643. ** tokenizer in *ppModule
  138644. */
  138645. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  138646. sqlite3_tokenizer_module const**ppModule
  138647. ){
  138648. *ppModule = &simpleTokenizerModule;
  138649. }
  138650. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  138651. /************** End of fts3_tokenizer1.c *************************************/
  138652. /************** Begin file fts3_tokenize_vtab.c ******************************/
  138653. /*
  138654. ** 2013 Apr 22
  138655. **
  138656. ** The author disclaims copyright to this source code. In place of
  138657. ** a legal notice, here is a blessing:
  138658. **
  138659. ** May you do good and not evil.
  138660. ** May you find forgiveness for yourself and forgive others.
  138661. ** May you share freely, never taking more than you give.
  138662. **
  138663. ******************************************************************************
  138664. **
  138665. ** This file contains code for the "fts3tokenize" virtual table module.
  138666. ** An fts3tokenize virtual table is created as follows:
  138667. **
  138668. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  138669. ** <tokenizer-name>, <arg-1>, ...
  138670. ** );
  138671. **
  138672. ** The table created has the following schema:
  138673. **
  138674. ** CREATE TABLE <tbl>(input, token, start, end, position)
  138675. **
  138676. ** When queried, the query must include a WHERE clause of type:
  138677. **
  138678. ** input = <string>
  138679. **
  138680. ** The virtual table module tokenizes this <string>, using the FTS3
  138681. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  138682. ** statement and returns one row for each token in the result. With
  138683. ** fields set as follows:
  138684. **
  138685. ** input: Always set to a copy of <string>
  138686. ** token: A token from the input.
  138687. ** start: Byte offset of the token within the input <string>.
  138688. ** end: Byte offset of the byte immediately following the end of the
  138689. ** token within the input string.
  138690. ** pos: Token offset of token within input.
  138691. **
  138692. */
  138693. /* #include "fts3Int.h" */
  138694. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  138695. /* #include <string.h> */
  138696. /* #include <assert.h> */
  138697. typedef struct Fts3tokTable Fts3tokTable;
  138698. typedef struct Fts3tokCursor Fts3tokCursor;
  138699. /*
  138700. ** Virtual table structure.
  138701. */
  138702. struct Fts3tokTable {
  138703. sqlite3_vtab base; /* Base class used by SQLite core */
  138704. const sqlite3_tokenizer_module *pMod;
  138705. sqlite3_tokenizer *pTok;
  138706. };
  138707. /*
  138708. ** Virtual table cursor structure.
  138709. */
  138710. struct Fts3tokCursor {
  138711. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  138712. char *zInput; /* Input string */
  138713. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  138714. int iRowid; /* Current 'rowid' value */
  138715. const char *zToken; /* Current 'token' value */
  138716. int nToken; /* Size of zToken in bytes */
  138717. int iStart; /* Current 'start' value */
  138718. int iEnd; /* Current 'end' value */
  138719. int iPos; /* Current 'pos' value */
  138720. };
  138721. /*
  138722. ** Query FTS for the tokenizer implementation named zName.
  138723. */
  138724. static int fts3tokQueryTokenizer(
  138725. Fts3Hash *pHash,
  138726. const char *zName,
  138727. const sqlite3_tokenizer_module **pp,
  138728. char **pzErr
  138729. ){
  138730. sqlite3_tokenizer_module *p;
  138731. int nName = (int)strlen(zName);
  138732. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  138733. if( !p ){
  138734. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  138735. return SQLITE_ERROR;
  138736. }
  138737. *pp = p;
  138738. return SQLITE_OK;
  138739. }
  138740. /*
  138741. ** The second argument, argv[], is an array of pointers to nul-terminated
  138742. ** strings. This function makes a copy of the array and strings into a
  138743. ** single block of memory. It then dequotes any of the strings that appear
  138744. ** to be quoted.
  138745. **
  138746. ** If successful, output parameter *pazDequote is set to point at the
  138747. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  138748. ** responsible for eventually calling sqlite3_free() to free the array
  138749. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  138750. ** The final value of *pazDequote is undefined in this case.
  138751. */
  138752. static int fts3tokDequoteArray(
  138753. int argc, /* Number of elements in argv[] */
  138754. const char * const *argv, /* Input array */
  138755. char ***pazDequote /* Output array */
  138756. ){
  138757. int rc = SQLITE_OK; /* Return code */
  138758. if( argc==0 ){
  138759. *pazDequote = 0;
  138760. }else{
  138761. int i;
  138762. int nByte = 0;
  138763. char **azDequote;
  138764. for(i=0; i<argc; i++){
  138765. nByte += (int)(strlen(argv[i]) + 1);
  138766. }
  138767. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  138768. if( azDequote==0 ){
  138769. rc = SQLITE_NOMEM;
  138770. }else{
  138771. char *pSpace = (char *)&azDequote[argc];
  138772. for(i=0; i<argc; i++){
  138773. int n = (int)strlen(argv[i]);
  138774. azDequote[i] = pSpace;
  138775. memcpy(pSpace, argv[i], n+1);
  138776. sqlite3Fts3Dequote(pSpace);
  138777. pSpace += (n+1);
  138778. }
  138779. }
  138780. }
  138781. return rc;
  138782. }
  138783. /*
  138784. ** Schema of the tokenizer table.
  138785. */
  138786. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  138787. /*
  138788. ** This function does all the work for both the xConnect and xCreate methods.
  138789. ** These tables have no persistent representation of their own, so xConnect
  138790. ** and xCreate are identical operations.
  138791. **
  138792. ** argv[0]: module name
  138793. ** argv[1]: database name
  138794. ** argv[2]: table name
  138795. ** argv[3]: first argument (tokenizer name)
  138796. */
  138797. static int fts3tokConnectMethod(
  138798. sqlite3 *db, /* Database connection */
  138799. void *pHash, /* Hash table of tokenizers */
  138800. int argc, /* Number of elements in argv array */
  138801. const char * const *argv, /* xCreate/xConnect argument array */
  138802. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  138803. char **pzErr /* OUT: sqlite3_malloc'd error message */
  138804. ){
  138805. Fts3tokTable *pTab = 0;
  138806. const sqlite3_tokenizer_module *pMod = 0;
  138807. sqlite3_tokenizer *pTok = 0;
  138808. int rc;
  138809. char **azDequote = 0;
  138810. int nDequote;
  138811. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  138812. if( rc!=SQLITE_OK ) return rc;
  138813. nDequote = argc-3;
  138814. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  138815. if( rc==SQLITE_OK ){
  138816. const char *zModule;
  138817. if( nDequote<1 ){
  138818. zModule = "simple";
  138819. }else{
  138820. zModule = azDequote[0];
  138821. }
  138822. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  138823. }
  138824. assert( (rc==SQLITE_OK)==(pMod!=0) );
  138825. if( rc==SQLITE_OK ){
  138826. const char * const *azArg = (const char * const *)&azDequote[1];
  138827. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  138828. }
  138829. if( rc==SQLITE_OK ){
  138830. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  138831. if( pTab==0 ){
  138832. rc = SQLITE_NOMEM;
  138833. }
  138834. }
  138835. if( rc==SQLITE_OK ){
  138836. memset(pTab, 0, sizeof(Fts3tokTable));
  138837. pTab->pMod = pMod;
  138838. pTab->pTok = pTok;
  138839. *ppVtab = &pTab->base;
  138840. }else{
  138841. if( pTok ){
  138842. pMod->xDestroy(pTok);
  138843. }
  138844. }
  138845. sqlite3_free(azDequote);
  138846. return rc;
  138847. }
  138848. /*
  138849. ** This function does the work for both the xDisconnect and xDestroy methods.
  138850. ** These tables have no persistent representation of their own, so xDisconnect
  138851. ** and xDestroy are identical operations.
  138852. */
  138853. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  138854. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  138855. pTab->pMod->xDestroy(pTab->pTok);
  138856. sqlite3_free(pTab);
  138857. return SQLITE_OK;
  138858. }
  138859. /*
  138860. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  138861. */
  138862. static int fts3tokBestIndexMethod(
  138863. sqlite3_vtab *pVTab,
  138864. sqlite3_index_info *pInfo
  138865. ){
  138866. int i;
  138867. UNUSED_PARAMETER(pVTab);
  138868. for(i=0; i<pInfo->nConstraint; i++){
  138869. if( pInfo->aConstraint[i].usable
  138870. && pInfo->aConstraint[i].iColumn==0
  138871. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  138872. ){
  138873. pInfo->idxNum = 1;
  138874. pInfo->aConstraintUsage[i].argvIndex = 1;
  138875. pInfo->aConstraintUsage[i].omit = 1;
  138876. pInfo->estimatedCost = 1;
  138877. return SQLITE_OK;
  138878. }
  138879. }
  138880. pInfo->idxNum = 0;
  138881. assert( pInfo->estimatedCost>1000000.0 );
  138882. return SQLITE_OK;
  138883. }
  138884. /*
  138885. ** xOpen - Open a cursor.
  138886. */
  138887. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  138888. Fts3tokCursor *pCsr;
  138889. UNUSED_PARAMETER(pVTab);
  138890. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  138891. if( pCsr==0 ){
  138892. return SQLITE_NOMEM;
  138893. }
  138894. memset(pCsr, 0, sizeof(Fts3tokCursor));
  138895. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  138896. return SQLITE_OK;
  138897. }
  138898. /*
  138899. ** Reset the tokenizer cursor passed as the only argument. As if it had
  138900. ** just been returned by fts3tokOpenMethod().
  138901. */
  138902. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  138903. if( pCsr->pCsr ){
  138904. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  138905. pTab->pMod->xClose(pCsr->pCsr);
  138906. pCsr->pCsr = 0;
  138907. }
  138908. sqlite3_free(pCsr->zInput);
  138909. pCsr->zInput = 0;
  138910. pCsr->zToken = 0;
  138911. pCsr->nToken = 0;
  138912. pCsr->iStart = 0;
  138913. pCsr->iEnd = 0;
  138914. pCsr->iPos = 0;
  138915. pCsr->iRowid = 0;
  138916. }
  138917. /*
  138918. ** xClose - Close a cursor.
  138919. */
  138920. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  138921. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  138922. fts3tokResetCursor(pCsr);
  138923. sqlite3_free(pCsr);
  138924. return SQLITE_OK;
  138925. }
  138926. /*
  138927. ** xNext - Advance the cursor to the next row, if any.
  138928. */
  138929. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  138930. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  138931. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  138932. int rc; /* Return code */
  138933. pCsr->iRowid++;
  138934. rc = pTab->pMod->xNext(pCsr->pCsr,
  138935. &pCsr->zToken, &pCsr->nToken,
  138936. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  138937. );
  138938. if( rc!=SQLITE_OK ){
  138939. fts3tokResetCursor(pCsr);
  138940. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  138941. }
  138942. return rc;
  138943. }
  138944. /*
  138945. ** xFilter - Initialize a cursor to point at the start of its data.
  138946. */
  138947. static int fts3tokFilterMethod(
  138948. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  138949. int idxNum, /* Strategy index */
  138950. const char *idxStr, /* Unused */
  138951. int nVal, /* Number of elements in apVal */
  138952. sqlite3_value **apVal /* Arguments for the indexing scheme */
  138953. ){
  138954. int rc = SQLITE_ERROR;
  138955. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  138956. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  138957. UNUSED_PARAMETER(idxStr);
  138958. UNUSED_PARAMETER(nVal);
  138959. fts3tokResetCursor(pCsr);
  138960. if( idxNum==1 ){
  138961. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  138962. int nByte = sqlite3_value_bytes(apVal[0]);
  138963. pCsr->zInput = sqlite3_malloc(nByte+1);
  138964. if( pCsr->zInput==0 ){
  138965. rc = SQLITE_NOMEM;
  138966. }else{
  138967. memcpy(pCsr->zInput, zByte, nByte);
  138968. pCsr->zInput[nByte] = 0;
  138969. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  138970. if( rc==SQLITE_OK ){
  138971. pCsr->pCsr->pTokenizer = pTab->pTok;
  138972. }
  138973. }
  138974. }
  138975. if( rc!=SQLITE_OK ) return rc;
  138976. return fts3tokNextMethod(pCursor);
  138977. }
  138978. /*
  138979. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  138980. */
  138981. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  138982. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  138983. return (pCsr->zToken==0);
  138984. }
  138985. /*
  138986. ** xColumn - Return a column value.
  138987. */
  138988. static int fts3tokColumnMethod(
  138989. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  138990. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  138991. int iCol /* Index of column to read value from */
  138992. ){
  138993. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  138994. /* CREATE TABLE x(input, token, start, end, position) */
  138995. switch( iCol ){
  138996. case 0:
  138997. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  138998. break;
  138999. case 1:
  139000. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  139001. break;
  139002. case 2:
  139003. sqlite3_result_int(pCtx, pCsr->iStart);
  139004. break;
  139005. case 3:
  139006. sqlite3_result_int(pCtx, pCsr->iEnd);
  139007. break;
  139008. default:
  139009. assert( iCol==4 );
  139010. sqlite3_result_int(pCtx, pCsr->iPos);
  139011. break;
  139012. }
  139013. return SQLITE_OK;
  139014. }
  139015. /*
  139016. ** xRowid - Return the current rowid for the cursor.
  139017. */
  139018. static int fts3tokRowidMethod(
  139019. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  139020. sqlite_int64 *pRowid /* OUT: Rowid value */
  139021. ){
  139022. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  139023. *pRowid = (sqlite3_int64)pCsr->iRowid;
  139024. return SQLITE_OK;
  139025. }
  139026. /*
  139027. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  139028. ** if successful or an error code if sqlite3_create_module() fails.
  139029. */
  139030. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  139031. static const sqlite3_module fts3tok_module = {
  139032. 0, /* iVersion */
  139033. fts3tokConnectMethod, /* xCreate */
  139034. fts3tokConnectMethod, /* xConnect */
  139035. fts3tokBestIndexMethod, /* xBestIndex */
  139036. fts3tokDisconnectMethod, /* xDisconnect */
  139037. fts3tokDisconnectMethod, /* xDestroy */
  139038. fts3tokOpenMethod, /* xOpen */
  139039. fts3tokCloseMethod, /* xClose */
  139040. fts3tokFilterMethod, /* xFilter */
  139041. fts3tokNextMethod, /* xNext */
  139042. fts3tokEofMethod, /* xEof */
  139043. fts3tokColumnMethod, /* xColumn */
  139044. fts3tokRowidMethod, /* xRowid */
  139045. 0, /* xUpdate */
  139046. 0, /* xBegin */
  139047. 0, /* xSync */
  139048. 0, /* xCommit */
  139049. 0, /* xRollback */
  139050. 0, /* xFindFunction */
  139051. 0, /* xRename */
  139052. 0, /* xSavepoint */
  139053. 0, /* xRelease */
  139054. 0 /* xRollbackTo */
  139055. };
  139056. int rc; /* Return code */
  139057. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  139058. return rc;
  139059. }
  139060. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  139061. /************** End of fts3_tokenize_vtab.c **********************************/
  139062. /************** Begin file fts3_write.c **************************************/
  139063. /*
  139064. ** 2009 Oct 23
  139065. **
  139066. ** The author disclaims copyright to this source code. In place of
  139067. ** a legal notice, here is a blessing:
  139068. **
  139069. ** May you do good and not evil.
  139070. ** May you find forgiveness for yourself and forgive others.
  139071. ** May you share freely, never taking more than you give.
  139072. **
  139073. ******************************************************************************
  139074. **
  139075. ** This file is part of the SQLite FTS3 extension module. Specifically,
  139076. ** this file contains code to insert, update and delete rows from FTS3
  139077. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  139078. ** of the sub-routines used to merge segments are also used by the query
  139079. ** code in fts3.c.
  139080. */
  139081. /* #include "fts3Int.h" */
  139082. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  139083. /* #include <string.h> */
  139084. /* #include <assert.h> */
  139085. /* #include <stdlib.h> */
  139086. #define FTS_MAX_APPENDABLE_HEIGHT 16
  139087. /*
  139088. ** When full-text index nodes are loaded from disk, the buffer that they
  139089. ** are loaded into has the following number of bytes of padding at the end
  139090. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  139091. ** of 920 bytes is allocated for it.
  139092. **
  139093. ** This means that if we have a pointer into a buffer containing node data,
  139094. ** it is always safe to read up to two varints from it without risking an
  139095. ** overread, even if the node data is corrupted.
  139096. */
  139097. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  139098. /*
  139099. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  139100. ** memory incrementally instead of all at once. This can be a big performance
  139101. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  139102. ** method before retrieving all query results (as may happen, for example,
  139103. ** if a query has a LIMIT clause).
  139104. **
  139105. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  139106. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  139107. ** The code is written so that the hard lower-limit for each of these values
  139108. ** is 1. Clearly such small values would be inefficient, but can be useful
  139109. ** for testing purposes.
  139110. **
  139111. ** If this module is built with SQLITE_TEST defined, these constants may
  139112. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  139113. ** a Tcl interface to read and write the values.
  139114. */
  139115. #ifdef SQLITE_TEST
  139116. int test_fts3_node_chunksize = (4*1024);
  139117. int test_fts3_node_chunk_threshold = (4*1024)*4;
  139118. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  139119. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  139120. #else
  139121. # define FTS3_NODE_CHUNKSIZE (4*1024)
  139122. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  139123. #endif
  139124. /*
  139125. ** The two values that may be meaningfully bound to the :1 parameter in
  139126. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  139127. */
  139128. #define FTS_STAT_DOCTOTAL 0
  139129. #define FTS_STAT_INCRMERGEHINT 1
  139130. #define FTS_STAT_AUTOINCRMERGE 2
  139131. /*
  139132. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  139133. ** and incremental merge operation that takes place. This is used for
  139134. ** debugging FTS only, it should not usually be turned on in production
  139135. ** systems.
  139136. */
  139137. #ifdef FTS3_LOG_MERGES
  139138. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  139139. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  139140. }
  139141. #else
  139142. #define fts3LogMerge(x, y)
  139143. #endif
  139144. typedef struct PendingList PendingList;
  139145. typedef struct SegmentNode SegmentNode;
  139146. typedef struct SegmentWriter SegmentWriter;
  139147. /*
  139148. ** An instance of the following data structure is used to build doclists
  139149. ** incrementally. See function fts3PendingListAppend() for details.
  139150. */
  139151. struct PendingList {
  139152. int nData;
  139153. char *aData;
  139154. int nSpace;
  139155. sqlite3_int64 iLastDocid;
  139156. sqlite3_int64 iLastCol;
  139157. sqlite3_int64 iLastPos;
  139158. };
  139159. /*
  139160. ** Each cursor has a (possibly empty) linked list of the following objects.
  139161. */
  139162. struct Fts3DeferredToken {
  139163. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  139164. int iCol; /* Column token must occur in */
  139165. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  139166. PendingList *pList; /* Doclist is assembled here */
  139167. };
  139168. /*
  139169. ** An instance of this structure is used to iterate through the terms on
  139170. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  139171. ** this structure are only manipulated by code in this file, opaque handles
  139172. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  139173. ** terms when querying the full-text index. See functions:
  139174. **
  139175. ** sqlite3Fts3SegReaderNew()
  139176. ** sqlite3Fts3SegReaderFree()
  139177. ** sqlite3Fts3SegReaderIterate()
  139178. **
  139179. ** Methods used to manipulate Fts3SegReader structures:
  139180. **
  139181. ** fts3SegReaderNext()
  139182. ** fts3SegReaderFirstDocid()
  139183. ** fts3SegReaderNextDocid()
  139184. */
  139185. struct Fts3SegReader {
  139186. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  139187. u8 bLookup; /* True for a lookup only */
  139188. u8 rootOnly; /* True for a root-only reader */
  139189. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  139190. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  139191. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  139192. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  139193. char *aNode; /* Pointer to node data (or NULL) */
  139194. int nNode; /* Size of buffer at aNode (or 0) */
  139195. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  139196. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  139197. Fts3HashElem **ppNextElem;
  139198. /* Variables set by fts3SegReaderNext(). These may be read directly
  139199. ** by the caller. They are valid from the time SegmentReaderNew() returns
  139200. ** until SegmentReaderNext() returns something other than SQLITE_OK
  139201. ** (i.e. SQLITE_DONE).
  139202. */
  139203. int nTerm; /* Number of bytes in current term */
  139204. char *zTerm; /* Pointer to current term */
  139205. int nTermAlloc; /* Allocated size of zTerm buffer */
  139206. char *aDoclist; /* Pointer to doclist of current entry */
  139207. int nDoclist; /* Size of doclist in current entry */
  139208. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  139209. ** through the current doclist (aDoclist/nDoclist).
  139210. */
  139211. char *pOffsetList;
  139212. int nOffsetList; /* For descending pending seg-readers only */
  139213. sqlite3_int64 iDocid;
  139214. };
  139215. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  139216. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  139217. /*
  139218. ** An instance of this structure is used to create a segment b-tree in the
  139219. ** database. The internal details of this type are only accessed by the
  139220. ** following functions:
  139221. **
  139222. ** fts3SegWriterAdd()
  139223. ** fts3SegWriterFlush()
  139224. ** fts3SegWriterFree()
  139225. */
  139226. struct SegmentWriter {
  139227. SegmentNode *pTree; /* Pointer to interior tree structure */
  139228. sqlite3_int64 iFirst; /* First slot in %_segments written */
  139229. sqlite3_int64 iFree; /* Next free slot in %_segments */
  139230. char *zTerm; /* Pointer to previous term buffer */
  139231. int nTerm; /* Number of bytes in zTerm */
  139232. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  139233. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  139234. int nSize; /* Size of allocation at aData */
  139235. int nData; /* Bytes of data in aData */
  139236. char *aData; /* Pointer to block from malloc() */
  139237. i64 nLeafData; /* Number of bytes of leaf data written */
  139238. };
  139239. /*
  139240. ** Type SegmentNode is used by the following three functions to create
  139241. ** the interior part of the segment b+-tree structures (everything except
  139242. ** the leaf nodes). These functions and type are only ever used by code
  139243. ** within the fts3SegWriterXXX() family of functions described above.
  139244. **
  139245. ** fts3NodeAddTerm()
  139246. ** fts3NodeWrite()
  139247. ** fts3NodeFree()
  139248. **
  139249. ** When a b+tree is written to the database (either as a result of a merge
  139250. ** or the pending-terms table being flushed), leaves are written into the
  139251. ** database file as soon as they are completely populated. The interior of
  139252. ** the tree is assembled in memory and written out only once all leaves have
  139253. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  139254. ** very large, meaning that the interior of the tree consumes relatively
  139255. ** little memory.
  139256. */
  139257. struct SegmentNode {
  139258. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  139259. SegmentNode *pRight; /* Pointer to right-sibling */
  139260. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  139261. int nEntry; /* Number of terms written to node so far */
  139262. char *zTerm; /* Pointer to previous term buffer */
  139263. int nTerm; /* Number of bytes in zTerm */
  139264. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  139265. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  139266. int nData; /* Bytes of valid data so far */
  139267. char *aData; /* Node data */
  139268. };
  139269. /*
  139270. ** Valid values for the second argument to fts3SqlStmt().
  139271. */
  139272. #define SQL_DELETE_CONTENT 0
  139273. #define SQL_IS_EMPTY 1
  139274. #define SQL_DELETE_ALL_CONTENT 2
  139275. #define SQL_DELETE_ALL_SEGMENTS 3
  139276. #define SQL_DELETE_ALL_SEGDIR 4
  139277. #define SQL_DELETE_ALL_DOCSIZE 5
  139278. #define SQL_DELETE_ALL_STAT 6
  139279. #define SQL_SELECT_CONTENT_BY_ROWID 7
  139280. #define SQL_NEXT_SEGMENT_INDEX 8
  139281. #define SQL_INSERT_SEGMENTS 9
  139282. #define SQL_NEXT_SEGMENTS_ID 10
  139283. #define SQL_INSERT_SEGDIR 11
  139284. #define SQL_SELECT_LEVEL 12
  139285. #define SQL_SELECT_LEVEL_RANGE 13
  139286. #define SQL_SELECT_LEVEL_COUNT 14
  139287. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  139288. #define SQL_DELETE_SEGDIR_LEVEL 16
  139289. #define SQL_DELETE_SEGMENTS_RANGE 17
  139290. #define SQL_CONTENT_INSERT 18
  139291. #define SQL_DELETE_DOCSIZE 19
  139292. #define SQL_REPLACE_DOCSIZE 20
  139293. #define SQL_SELECT_DOCSIZE 21
  139294. #define SQL_SELECT_STAT 22
  139295. #define SQL_REPLACE_STAT 23
  139296. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  139297. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  139298. #define SQL_DELETE_SEGDIR_RANGE 26
  139299. #define SQL_SELECT_ALL_LANGID 27
  139300. #define SQL_FIND_MERGE_LEVEL 28
  139301. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  139302. #define SQL_DELETE_SEGDIR_ENTRY 30
  139303. #define SQL_SHIFT_SEGDIR_ENTRY 31
  139304. #define SQL_SELECT_SEGDIR 32
  139305. #define SQL_CHOMP_SEGDIR 33
  139306. #define SQL_SEGMENT_IS_APPENDABLE 34
  139307. #define SQL_SELECT_INDEXES 35
  139308. #define SQL_SELECT_MXLEVEL 36
  139309. #define SQL_SELECT_LEVEL_RANGE2 37
  139310. #define SQL_UPDATE_LEVEL_IDX 38
  139311. #define SQL_UPDATE_LEVEL 39
  139312. /*
  139313. ** This function is used to obtain an SQLite prepared statement handle
  139314. ** for the statement identified by the second argument. If successful,
  139315. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  139316. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  139317. **
  139318. ** If argument apVal is not NULL, then it must point to an array with
  139319. ** at least as many entries as the requested statement has bound
  139320. ** parameters. The values are bound to the statements parameters before
  139321. ** returning.
  139322. */
  139323. static int fts3SqlStmt(
  139324. Fts3Table *p, /* Virtual table handle */
  139325. int eStmt, /* One of the SQL_XXX constants above */
  139326. sqlite3_stmt **pp, /* OUT: Statement handle */
  139327. sqlite3_value **apVal /* Values to bind to statement */
  139328. ){
  139329. const char *azSql[] = {
  139330. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  139331. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  139332. /* 2 */ "DELETE FROM %Q.'%q_content'",
  139333. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  139334. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  139335. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  139336. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  139337. /* 7 */ "SELECT %s WHERE rowid=?",
  139338. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  139339. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  139340. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  139341. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  139342. /* Return segments in order from oldest to newest.*/
  139343. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  139344. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  139345. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  139346. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  139347. "ORDER BY level DESC, idx ASC",
  139348. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  139349. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  139350. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  139351. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  139352. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  139353. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  139354. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  139355. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  139356. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  139357. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  139358. /* 24 */ "",
  139359. /* 25 */ "",
  139360. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  139361. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  139362. /* This statement is used to determine which level to read the input from
  139363. ** when performing an incremental merge. It returns the absolute level number
  139364. ** of the oldest level in the db that contains at least ? segments. Or,
  139365. ** if no level in the FTS index contains more than ? segments, the statement
  139366. ** returns zero rows. */
  139367. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  139368. " GROUP BY level HAVING cnt>=?"
  139369. " ORDER BY (level %% 1024) ASC LIMIT 1",
  139370. /* Estimate the upper limit on the number of leaf nodes in a new segment
  139371. ** created by merging the oldest :2 segments from absolute level :1. See
  139372. ** function sqlite3Fts3Incrmerge() for details. */
  139373. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  139374. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  139375. /* SQL_DELETE_SEGDIR_ENTRY
  139376. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  139377. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  139378. /* SQL_SHIFT_SEGDIR_ENTRY
  139379. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  139380. ** to :1. */
  139381. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  139382. /* SQL_SELECT_SEGDIR
  139383. ** Read a single entry from the %_segdir table. The entry from absolute
  139384. ** level :1 with index value :2. */
  139385. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  139386. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  139387. /* SQL_CHOMP_SEGDIR
  139388. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  139389. ** entry located on absolute level :3 with index :4. */
  139390. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  139391. "WHERE level = ? AND idx = ?",
  139392. /* SQL_SEGMENT_IS_APPENDABLE
  139393. ** Return a single row if the segment with end_block=? is appendable. Or
  139394. ** no rows otherwise. */
  139395. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  139396. /* SQL_SELECT_INDEXES
  139397. ** Return the list of valid segment indexes for absolute level ? */
  139398. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  139399. /* SQL_SELECT_MXLEVEL
  139400. ** Return the largest relative level in the FTS index or indexes. */
  139401. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  139402. /* Return segments in order from oldest to newest.*/
  139403. /* 37 */ "SELECT level, idx, end_block "
  139404. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  139405. "ORDER BY level DESC, idx ASC",
  139406. /* Update statements used while promoting segments */
  139407. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  139408. "WHERE level=? AND idx=?",
  139409. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  139410. };
  139411. int rc = SQLITE_OK;
  139412. sqlite3_stmt *pStmt;
  139413. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  139414. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  139415. pStmt = p->aStmt[eStmt];
  139416. if( !pStmt ){
  139417. char *zSql;
  139418. if( eStmt==SQL_CONTENT_INSERT ){
  139419. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  139420. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  139421. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  139422. }else{
  139423. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  139424. }
  139425. if( !zSql ){
  139426. rc = SQLITE_NOMEM;
  139427. }else{
  139428. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  139429. sqlite3_free(zSql);
  139430. assert( rc==SQLITE_OK || pStmt==0 );
  139431. p->aStmt[eStmt] = pStmt;
  139432. }
  139433. }
  139434. if( apVal ){
  139435. int i;
  139436. int nParam = sqlite3_bind_parameter_count(pStmt);
  139437. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  139438. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  139439. }
  139440. }
  139441. *pp = pStmt;
  139442. return rc;
  139443. }
  139444. static int fts3SelectDocsize(
  139445. Fts3Table *pTab, /* FTS3 table handle */
  139446. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  139447. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  139448. ){
  139449. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  139450. int rc; /* Return code */
  139451. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  139452. if( rc==SQLITE_OK ){
  139453. sqlite3_bind_int64(pStmt, 1, iDocid);
  139454. rc = sqlite3_step(pStmt);
  139455. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  139456. rc = sqlite3_reset(pStmt);
  139457. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  139458. pStmt = 0;
  139459. }else{
  139460. rc = SQLITE_OK;
  139461. }
  139462. }
  139463. *ppStmt = pStmt;
  139464. return rc;
  139465. }
  139466. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  139467. Fts3Table *pTab, /* Fts3 table handle */
  139468. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  139469. ){
  139470. sqlite3_stmt *pStmt = 0;
  139471. int rc;
  139472. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  139473. if( rc==SQLITE_OK ){
  139474. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  139475. if( sqlite3_step(pStmt)!=SQLITE_ROW
  139476. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  139477. ){
  139478. rc = sqlite3_reset(pStmt);
  139479. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  139480. pStmt = 0;
  139481. }
  139482. }
  139483. *ppStmt = pStmt;
  139484. return rc;
  139485. }
  139486. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  139487. Fts3Table *pTab, /* Fts3 table handle */
  139488. sqlite3_int64 iDocid, /* Docid to read size data for */
  139489. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  139490. ){
  139491. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  139492. }
  139493. /*
  139494. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  139495. ** array apVal[] to the SQL statement identified by eStmt, the statement
  139496. ** is executed.
  139497. **
  139498. ** Returns SQLITE_OK if the statement is successfully executed, or an
  139499. ** SQLite error code otherwise.
  139500. */
  139501. static void fts3SqlExec(
  139502. int *pRC, /* Result code */
  139503. Fts3Table *p, /* The FTS3 table */
  139504. int eStmt, /* Index of statement to evaluate */
  139505. sqlite3_value **apVal /* Parameters to bind */
  139506. ){
  139507. sqlite3_stmt *pStmt;
  139508. int rc;
  139509. if( *pRC ) return;
  139510. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  139511. if( rc==SQLITE_OK ){
  139512. sqlite3_step(pStmt);
  139513. rc = sqlite3_reset(pStmt);
  139514. }
  139515. *pRC = rc;
  139516. }
  139517. /*
  139518. ** This function ensures that the caller has obtained an exclusive
  139519. ** shared-cache table-lock on the %_segdir table. This is required before
  139520. ** writing data to the fts3 table. If this lock is not acquired first, then
  139521. ** the caller may end up attempting to take this lock as part of committing
  139522. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  139523. ** LOCKED_SHAREDCACHEto a COMMIT command.
  139524. **
  139525. ** It is best to avoid this because if FTS3 returns any error when
  139526. ** committing a transaction, the whole transaction will be rolled back.
  139527. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  139528. ** It can still happen if the user locks the underlying tables directly
  139529. ** instead of accessing them via FTS.
  139530. */
  139531. static int fts3Writelock(Fts3Table *p){
  139532. int rc = SQLITE_OK;
  139533. if( p->nPendingData==0 ){
  139534. sqlite3_stmt *pStmt;
  139535. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  139536. if( rc==SQLITE_OK ){
  139537. sqlite3_bind_null(pStmt, 1);
  139538. sqlite3_step(pStmt);
  139539. rc = sqlite3_reset(pStmt);
  139540. }
  139541. }
  139542. return rc;
  139543. }
  139544. /*
  139545. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  139546. ** Within each language id, a separate index is maintained to store the
  139547. ** document terms, and each configured prefix size (configured the FTS
  139548. ** "prefix=" option). And each index consists of multiple levels ("relative
  139549. ** levels").
  139550. **
  139551. ** All three of these values (the language id, the specific index and the
  139552. ** level within the index) are encoded in 64-bit integer values stored
  139553. ** in the %_segdir table on disk. This function is used to convert three
  139554. ** separate component values into the single 64-bit integer value that
  139555. ** can be used to query the %_segdir table.
  139556. **
  139557. ** Specifically, each language-id/index combination is allocated 1024
  139558. ** 64-bit integer level values ("absolute levels"). The main terms index
  139559. ** for language-id 0 is allocate values 0-1023. The first prefix index
  139560. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  139561. ** Language 1 indexes are allocated immediately following language 0.
  139562. **
  139563. ** So, for a system with nPrefix prefix indexes configured, the block of
  139564. ** absolute levels that corresponds to language-id iLangid and index
  139565. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  139566. */
  139567. static sqlite3_int64 getAbsoluteLevel(
  139568. Fts3Table *p, /* FTS3 table handle */
  139569. int iLangid, /* Language id */
  139570. int iIndex, /* Index in p->aIndex[] */
  139571. int iLevel /* Level of segments */
  139572. ){
  139573. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  139574. assert( iLangid>=0 );
  139575. assert( p->nIndex>0 );
  139576. assert( iIndex>=0 && iIndex<p->nIndex );
  139577. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  139578. return iBase + iLevel;
  139579. }
  139580. /*
  139581. ** Set *ppStmt to a statement handle that may be used to iterate through
  139582. ** all rows in the %_segdir table, from oldest to newest. If successful,
  139583. ** return SQLITE_OK. If an error occurs while preparing the statement,
  139584. ** return an SQLite error code.
  139585. **
  139586. ** There is only ever one instance of this SQL statement compiled for
  139587. ** each FTS3 table.
  139588. **
  139589. ** The statement returns the following columns from the %_segdir table:
  139590. **
  139591. ** 0: idx
  139592. ** 1: start_block
  139593. ** 2: leaves_end_block
  139594. ** 3: end_block
  139595. ** 4: root
  139596. */
  139597. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  139598. Fts3Table *p, /* FTS3 table */
  139599. int iLangid, /* Language being queried */
  139600. int iIndex, /* Index for p->aIndex[] */
  139601. int iLevel, /* Level to select (relative level) */
  139602. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  139603. ){
  139604. int rc;
  139605. sqlite3_stmt *pStmt = 0;
  139606. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  139607. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  139608. assert( iIndex>=0 && iIndex<p->nIndex );
  139609. if( iLevel<0 ){
  139610. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  139611. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  139612. if( rc==SQLITE_OK ){
  139613. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  139614. sqlite3_bind_int64(pStmt, 2,
  139615. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  139616. );
  139617. }
  139618. }else{
  139619. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  139620. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  139621. if( rc==SQLITE_OK ){
  139622. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  139623. }
  139624. }
  139625. *ppStmt = pStmt;
  139626. return rc;
  139627. }
  139628. /*
  139629. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  139630. ** if successful, or an SQLite error code otherwise.
  139631. **
  139632. ** This function also serves to allocate the PendingList structure itself.
  139633. ** For example, to create a new PendingList structure containing two
  139634. ** varints:
  139635. **
  139636. ** PendingList *p = 0;
  139637. ** fts3PendingListAppendVarint(&p, 1);
  139638. ** fts3PendingListAppendVarint(&p, 2);
  139639. */
  139640. static int fts3PendingListAppendVarint(
  139641. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  139642. sqlite3_int64 i /* Value to append to data */
  139643. ){
  139644. PendingList *p = *pp;
  139645. /* Allocate or grow the PendingList as required. */
  139646. if( !p ){
  139647. p = sqlite3_malloc(sizeof(*p) + 100);
  139648. if( !p ){
  139649. return SQLITE_NOMEM;
  139650. }
  139651. p->nSpace = 100;
  139652. p->aData = (char *)&p[1];
  139653. p->nData = 0;
  139654. }
  139655. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  139656. int nNew = p->nSpace * 2;
  139657. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  139658. if( !p ){
  139659. sqlite3_free(*pp);
  139660. *pp = 0;
  139661. return SQLITE_NOMEM;
  139662. }
  139663. p->nSpace = nNew;
  139664. p->aData = (char *)&p[1];
  139665. }
  139666. /* Append the new serialized varint to the end of the list. */
  139667. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  139668. p->aData[p->nData] = '\0';
  139669. *pp = p;
  139670. return SQLITE_OK;
  139671. }
  139672. /*
  139673. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  139674. ** is returned if the structure is sqlite3_realloced as part of adding
  139675. ** the entry. Otherwise, zero.
  139676. **
  139677. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  139678. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  139679. ** it is set to SQLITE_OK.
  139680. */
  139681. static int fts3PendingListAppend(
  139682. PendingList **pp, /* IN/OUT: PendingList structure */
  139683. sqlite3_int64 iDocid, /* Docid for entry to add */
  139684. sqlite3_int64 iCol, /* Column for entry to add */
  139685. sqlite3_int64 iPos, /* Position of term for entry to add */
  139686. int *pRc /* OUT: Return code */
  139687. ){
  139688. PendingList *p = *pp;
  139689. int rc = SQLITE_OK;
  139690. assert( !p || p->iLastDocid<=iDocid );
  139691. if( !p || p->iLastDocid!=iDocid ){
  139692. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  139693. if( p ){
  139694. assert( p->nData<p->nSpace );
  139695. assert( p->aData[p->nData]==0 );
  139696. p->nData++;
  139697. }
  139698. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  139699. goto pendinglistappend_out;
  139700. }
  139701. p->iLastCol = -1;
  139702. p->iLastPos = 0;
  139703. p->iLastDocid = iDocid;
  139704. }
  139705. if( iCol>0 && p->iLastCol!=iCol ){
  139706. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  139707. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  139708. ){
  139709. goto pendinglistappend_out;
  139710. }
  139711. p->iLastCol = iCol;
  139712. p->iLastPos = 0;
  139713. }
  139714. if( iCol>=0 ){
  139715. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  139716. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  139717. if( rc==SQLITE_OK ){
  139718. p->iLastPos = iPos;
  139719. }
  139720. }
  139721. pendinglistappend_out:
  139722. *pRc = rc;
  139723. if( p!=*pp ){
  139724. *pp = p;
  139725. return 1;
  139726. }
  139727. return 0;
  139728. }
  139729. /*
  139730. ** Free a PendingList object allocated by fts3PendingListAppend().
  139731. */
  139732. static void fts3PendingListDelete(PendingList *pList){
  139733. sqlite3_free(pList);
  139734. }
  139735. /*
  139736. ** Add an entry to one of the pending-terms hash tables.
  139737. */
  139738. static int fts3PendingTermsAddOne(
  139739. Fts3Table *p,
  139740. int iCol,
  139741. int iPos,
  139742. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  139743. const char *zToken,
  139744. int nToken
  139745. ){
  139746. PendingList *pList;
  139747. int rc = SQLITE_OK;
  139748. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  139749. if( pList ){
  139750. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  139751. }
  139752. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  139753. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  139754. /* Malloc failed while inserting the new entry. This can only
  139755. ** happen if there was no previous entry for this token.
  139756. */
  139757. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  139758. sqlite3_free(pList);
  139759. rc = SQLITE_NOMEM;
  139760. }
  139761. }
  139762. if( rc==SQLITE_OK ){
  139763. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  139764. }
  139765. return rc;
  139766. }
  139767. /*
  139768. ** Tokenize the nul-terminated string zText and add all tokens to the
  139769. ** pending-terms hash-table. The docid used is that currently stored in
  139770. ** p->iPrevDocid, and the column is specified by argument iCol.
  139771. **
  139772. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  139773. */
  139774. static int fts3PendingTermsAdd(
  139775. Fts3Table *p, /* Table into which text will be inserted */
  139776. int iLangid, /* Language id to use */
  139777. const char *zText, /* Text of document to be inserted */
  139778. int iCol, /* Column into which text is being inserted */
  139779. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  139780. ){
  139781. int rc;
  139782. int iStart = 0;
  139783. int iEnd = 0;
  139784. int iPos = 0;
  139785. int nWord = 0;
  139786. char const *zToken;
  139787. int nToken = 0;
  139788. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  139789. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  139790. sqlite3_tokenizer_cursor *pCsr;
  139791. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  139792. const char**,int*,int*,int*,int*);
  139793. assert( pTokenizer && pModule );
  139794. /* If the user has inserted a NULL value, this function may be called with
  139795. ** zText==0. In this case, add zero token entries to the hash table and
  139796. ** return early. */
  139797. if( zText==0 ){
  139798. *pnWord = 0;
  139799. return SQLITE_OK;
  139800. }
  139801. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  139802. if( rc!=SQLITE_OK ){
  139803. return rc;
  139804. }
  139805. xNext = pModule->xNext;
  139806. while( SQLITE_OK==rc
  139807. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  139808. ){
  139809. int i;
  139810. if( iPos>=nWord ) nWord = iPos+1;
  139811. /* Positions cannot be negative; we use -1 as a terminator internally.
  139812. ** Tokens must have a non-zero length.
  139813. */
  139814. if( iPos<0 || !zToken || nToken<=0 ){
  139815. rc = SQLITE_ERROR;
  139816. break;
  139817. }
  139818. /* Add the term to the terms index */
  139819. rc = fts3PendingTermsAddOne(
  139820. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  139821. );
  139822. /* Add the term to each of the prefix indexes that it is not too
  139823. ** short for. */
  139824. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  139825. struct Fts3Index *pIndex = &p->aIndex[i];
  139826. if( nToken<pIndex->nPrefix ) continue;
  139827. rc = fts3PendingTermsAddOne(
  139828. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  139829. );
  139830. }
  139831. }
  139832. pModule->xClose(pCsr);
  139833. *pnWord += nWord;
  139834. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  139835. }
  139836. /*
  139837. ** Calling this function indicates that subsequent calls to
  139838. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  139839. ** contents of the document with docid iDocid.
  139840. */
  139841. static int fts3PendingTermsDocid(
  139842. Fts3Table *p, /* Full-text table handle */
  139843. int bDelete, /* True if this op is a delete */
  139844. int iLangid, /* Language id of row being written */
  139845. sqlite_int64 iDocid /* Docid of row being written */
  139846. ){
  139847. assert( iLangid>=0 );
  139848. assert( bDelete==1 || bDelete==0 );
  139849. /* TODO(shess) Explore whether partially flushing the buffer on
  139850. ** forced-flush would provide better performance. I suspect that if
  139851. ** we ordered the doclists by size and flushed the largest until the
  139852. ** buffer was half empty, that would let the less frequent terms
  139853. ** generate longer doclists.
  139854. */
  139855. if( iDocid<p->iPrevDocid
  139856. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  139857. || p->iPrevLangid!=iLangid
  139858. || p->nPendingData>p->nMaxPendingData
  139859. ){
  139860. int rc = sqlite3Fts3PendingTermsFlush(p);
  139861. if( rc!=SQLITE_OK ) return rc;
  139862. }
  139863. p->iPrevDocid = iDocid;
  139864. p->iPrevLangid = iLangid;
  139865. p->bPrevDelete = bDelete;
  139866. return SQLITE_OK;
  139867. }
  139868. /*
  139869. ** Discard the contents of the pending-terms hash tables.
  139870. */
  139871. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  139872. int i;
  139873. for(i=0; i<p->nIndex; i++){
  139874. Fts3HashElem *pElem;
  139875. Fts3Hash *pHash = &p->aIndex[i].hPending;
  139876. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  139877. PendingList *pList = (PendingList *)fts3HashData(pElem);
  139878. fts3PendingListDelete(pList);
  139879. }
  139880. fts3HashClear(pHash);
  139881. }
  139882. p->nPendingData = 0;
  139883. }
  139884. /*
  139885. ** This function is called by the xUpdate() method as part of an INSERT
  139886. ** operation. It adds entries for each term in the new record to the
  139887. ** pendingTerms hash table.
  139888. **
  139889. ** Argument apVal is the same as the similarly named argument passed to
  139890. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  139891. */
  139892. static int fts3InsertTerms(
  139893. Fts3Table *p,
  139894. int iLangid,
  139895. sqlite3_value **apVal,
  139896. u32 *aSz
  139897. ){
  139898. int i; /* Iterator variable */
  139899. for(i=2; i<p->nColumn+2; i++){
  139900. int iCol = i-2;
  139901. if( p->abNotindexed[iCol]==0 ){
  139902. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  139903. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  139904. if( rc!=SQLITE_OK ){
  139905. return rc;
  139906. }
  139907. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  139908. }
  139909. }
  139910. return SQLITE_OK;
  139911. }
  139912. /*
  139913. ** This function is called by the xUpdate() method for an INSERT operation.
  139914. ** The apVal parameter is passed a copy of the apVal argument passed by
  139915. ** SQLite to the xUpdate() method. i.e:
  139916. **
  139917. ** apVal[0] Not used for INSERT.
  139918. ** apVal[1] rowid
  139919. ** apVal[2] Left-most user-defined column
  139920. ** ...
  139921. ** apVal[p->nColumn+1] Right-most user-defined column
  139922. ** apVal[p->nColumn+2] Hidden column with same name as table
  139923. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  139924. ** apVal[p->nColumn+4] Hidden languageid column
  139925. */
  139926. static int fts3InsertData(
  139927. Fts3Table *p, /* Full-text table */
  139928. sqlite3_value **apVal, /* Array of values to insert */
  139929. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  139930. ){
  139931. int rc; /* Return code */
  139932. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  139933. if( p->zContentTbl ){
  139934. sqlite3_value *pRowid = apVal[p->nColumn+3];
  139935. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  139936. pRowid = apVal[1];
  139937. }
  139938. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  139939. return SQLITE_CONSTRAINT;
  139940. }
  139941. *piDocid = sqlite3_value_int64(pRowid);
  139942. return SQLITE_OK;
  139943. }
  139944. /* Locate the statement handle used to insert data into the %_content
  139945. ** table. The SQL for this statement is:
  139946. **
  139947. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  139948. **
  139949. ** The statement features N '?' variables, where N is the number of user
  139950. ** defined columns in the FTS3 table, plus one for the docid field.
  139951. */
  139952. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  139953. if( rc==SQLITE_OK && p->zLanguageid ){
  139954. rc = sqlite3_bind_int(
  139955. pContentInsert, p->nColumn+2,
  139956. sqlite3_value_int(apVal[p->nColumn+4])
  139957. );
  139958. }
  139959. if( rc!=SQLITE_OK ) return rc;
  139960. /* There is a quirk here. The users INSERT statement may have specified
  139961. ** a value for the "rowid" field, for the "docid" field, or for both.
  139962. ** Which is a problem, since "rowid" and "docid" are aliases for the
  139963. ** same value. For example:
  139964. **
  139965. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  139966. **
  139967. ** In FTS3, this is an error. It is an error to specify non-NULL values
  139968. ** for both docid and some other rowid alias.
  139969. */
  139970. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  139971. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  139972. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  139973. ){
  139974. /* A rowid/docid conflict. */
  139975. return SQLITE_ERROR;
  139976. }
  139977. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  139978. if( rc!=SQLITE_OK ) return rc;
  139979. }
  139980. /* Execute the statement to insert the record. Set *piDocid to the
  139981. ** new docid value.
  139982. */
  139983. sqlite3_step(pContentInsert);
  139984. rc = sqlite3_reset(pContentInsert);
  139985. *piDocid = sqlite3_last_insert_rowid(p->db);
  139986. return rc;
  139987. }
  139988. /*
  139989. ** Remove all data from the FTS3 table. Clear the hash table containing
  139990. ** pending terms.
  139991. */
  139992. static int fts3DeleteAll(Fts3Table *p, int bContent){
  139993. int rc = SQLITE_OK; /* Return code */
  139994. /* Discard the contents of the pending-terms hash table. */
  139995. sqlite3Fts3PendingTermsClear(p);
  139996. /* Delete everything from the shadow tables. Except, leave %_content as
  139997. ** is if bContent is false. */
  139998. assert( p->zContentTbl==0 || bContent==0 );
  139999. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  140000. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  140001. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  140002. if( p->bHasDocsize ){
  140003. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  140004. }
  140005. if( p->bHasStat ){
  140006. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  140007. }
  140008. return rc;
  140009. }
  140010. /*
  140011. **
  140012. */
  140013. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  140014. int iLangid = 0;
  140015. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  140016. return iLangid;
  140017. }
  140018. /*
  140019. ** The first element in the apVal[] array is assumed to contain the docid
  140020. ** (an integer) of a row about to be deleted. Remove all terms from the
  140021. ** full-text index.
  140022. */
  140023. static void fts3DeleteTerms(
  140024. int *pRC, /* Result code */
  140025. Fts3Table *p, /* The FTS table to delete from */
  140026. sqlite3_value *pRowid, /* The docid to be deleted */
  140027. u32 *aSz, /* Sizes of deleted document written here */
  140028. int *pbFound /* OUT: Set to true if row really does exist */
  140029. ){
  140030. int rc;
  140031. sqlite3_stmt *pSelect;
  140032. assert( *pbFound==0 );
  140033. if( *pRC ) return;
  140034. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  140035. if( rc==SQLITE_OK ){
  140036. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  140037. int i;
  140038. int iLangid = langidFromSelect(p, pSelect);
  140039. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  140040. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  140041. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  140042. int iCol = i-1;
  140043. if( p->abNotindexed[iCol]==0 ){
  140044. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  140045. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  140046. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  140047. }
  140048. }
  140049. if( rc!=SQLITE_OK ){
  140050. sqlite3_reset(pSelect);
  140051. *pRC = rc;
  140052. return;
  140053. }
  140054. *pbFound = 1;
  140055. }
  140056. rc = sqlite3_reset(pSelect);
  140057. }else{
  140058. sqlite3_reset(pSelect);
  140059. }
  140060. *pRC = rc;
  140061. }
  140062. /*
  140063. ** Forward declaration to account for the circular dependency between
  140064. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  140065. */
  140066. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  140067. /*
  140068. ** This function allocates a new level iLevel index in the segdir table.
  140069. ** Usually, indexes are allocated within a level sequentially starting
  140070. ** with 0, so the allocated index is one greater than the value returned
  140071. ** by:
  140072. **
  140073. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  140074. **
  140075. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  140076. ** level, they are merged into a single level (iLevel+1) segment and the
  140077. ** allocated index is 0.
  140078. **
  140079. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  140080. ** returned. Otherwise, an SQLite error code is returned.
  140081. */
  140082. static int fts3AllocateSegdirIdx(
  140083. Fts3Table *p,
  140084. int iLangid, /* Language id */
  140085. int iIndex, /* Index for p->aIndex */
  140086. int iLevel,
  140087. int *piIdx
  140088. ){
  140089. int rc; /* Return Code */
  140090. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  140091. int iNext = 0; /* Result of query pNextIdx */
  140092. assert( iLangid>=0 );
  140093. assert( p->nIndex>=1 );
  140094. /* Set variable iNext to the next available segdir index at level iLevel. */
  140095. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  140096. if( rc==SQLITE_OK ){
  140097. sqlite3_bind_int64(
  140098. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  140099. );
  140100. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  140101. iNext = sqlite3_column_int(pNextIdx, 0);
  140102. }
  140103. rc = sqlite3_reset(pNextIdx);
  140104. }
  140105. if( rc==SQLITE_OK ){
  140106. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  140107. ** full, merge all segments in level iLevel into a single iLevel+1
  140108. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  140109. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  140110. */
  140111. if( iNext>=FTS3_MERGE_COUNT ){
  140112. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  140113. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  140114. *piIdx = 0;
  140115. }else{
  140116. *piIdx = iNext;
  140117. }
  140118. }
  140119. return rc;
  140120. }
  140121. /*
  140122. ** The %_segments table is declared as follows:
  140123. **
  140124. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  140125. **
  140126. ** This function reads data from a single row of the %_segments table. The
  140127. ** specific row is identified by the iBlockid parameter. If paBlob is not
  140128. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  140129. ** with the contents of the blob stored in the "block" column of the
  140130. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  140131. ** to the size of the blob in bytes before returning.
  140132. **
  140133. ** If an error occurs, or the table does not contain the specified row,
  140134. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  140135. ** paBlob is non-NULL, then it is the responsibility of the caller to
  140136. ** eventually free the returned buffer.
  140137. **
  140138. ** This function may leave an open sqlite3_blob* handle in the
  140139. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  140140. ** to this function. The handle may be closed by calling the
  140141. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  140142. ** performance improvement, but the blob handle should always be closed
  140143. ** before control is returned to the user (to prevent a lock being held
  140144. ** on the database file for longer than necessary). Thus, any virtual table
  140145. ** method (xFilter etc.) that may directly or indirectly call this function
  140146. ** must call sqlite3Fts3SegmentsClose() before returning.
  140147. */
  140148. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  140149. Fts3Table *p, /* FTS3 table handle */
  140150. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  140151. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  140152. int *pnBlob, /* OUT: Size of blob data */
  140153. int *pnLoad /* OUT: Bytes actually loaded */
  140154. ){
  140155. int rc; /* Return code */
  140156. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  140157. assert( pnBlob );
  140158. if( p->pSegments ){
  140159. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  140160. }else{
  140161. if( 0==p->zSegmentsTbl ){
  140162. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  140163. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  140164. }
  140165. rc = sqlite3_blob_open(
  140166. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  140167. );
  140168. }
  140169. if( rc==SQLITE_OK ){
  140170. int nByte = sqlite3_blob_bytes(p->pSegments);
  140171. *pnBlob = nByte;
  140172. if( paBlob ){
  140173. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  140174. if( !aByte ){
  140175. rc = SQLITE_NOMEM;
  140176. }else{
  140177. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  140178. nByte = FTS3_NODE_CHUNKSIZE;
  140179. *pnLoad = nByte;
  140180. }
  140181. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  140182. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  140183. if( rc!=SQLITE_OK ){
  140184. sqlite3_free(aByte);
  140185. aByte = 0;
  140186. }
  140187. }
  140188. *paBlob = aByte;
  140189. }
  140190. }
  140191. return rc;
  140192. }
  140193. /*
  140194. ** Close the blob handle at p->pSegments, if it is open. See comments above
  140195. ** the sqlite3Fts3ReadBlock() function for details.
  140196. */
  140197. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  140198. sqlite3_blob_close(p->pSegments);
  140199. p->pSegments = 0;
  140200. }
  140201. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  140202. int nRead; /* Number of bytes to read */
  140203. int rc; /* Return code */
  140204. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  140205. rc = sqlite3_blob_read(
  140206. pReader->pBlob,
  140207. &pReader->aNode[pReader->nPopulate],
  140208. nRead,
  140209. pReader->nPopulate
  140210. );
  140211. if( rc==SQLITE_OK ){
  140212. pReader->nPopulate += nRead;
  140213. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  140214. if( pReader->nPopulate==pReader->nNode ){
  140215. sqlite3_blob_close(pReader->pBlob);
  140216. pReader->pBlob = 0;
  140217. pReader->nPopulate = 0;
  140218. }
  140219. }
  140220. return rc;
  140221. }
  140222. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  140223. int rc = SQLITE_OK;
  140224. assert( !pReader->pBlob
  140225. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  140226. );
  140227. while( pReader->pBlob && rc==SQLITE_OK
  140228. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  140229. ){
  140230. rc = fts3SegReaderIncrRead(pReader);
  140231. }
  140232. return rc;
  140233. }
  140234. /*
  140235. ** Set an Fts3SegReader cursor to point at EOF.
  140236. */
  140237. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  140238. if( !fts3SegReaderIsRootOnly(pSeg) ){
  140239. sqlite3_free(pSeg->aNode);
  140240. sqlite3_blob_close(pSeg->pBlob);
  140241. pSeg->pBlob = 0;
  140242. }
  140243. pSeg->aNode = 0;
  140244. }
  140245. /*
  140246. ** Move the iterator passed as the first argument to the next term in the
  140247. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  140248. ** SQLITE_DONE. Otherwise, an SQLite error code.
  140249. */
  140250. static int fts3SegReaderNext(
  140251. Fts3Table *p,
  140252. Fts3SegReader *pReader,
  140253. int bIncr
  140254. ){
  140255. int rc; /* Return code of various sub-routines */
  140256. char *pNext; /* Cursor variable */
  140257. int nPrefix; /* Number of bytes in term prefix */
  140258. int nSuffix; /* Number of bytes in term suffix */
  140259. if( !pReader->aDoclist ){
  140260. pNext = pReader->aNode;
  140261. }else{
  140262. pNext = &pReader->aDoclist[pReader->nDoclist];
  140263. }
  140264. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  140265. if( fts3SegReaderIsPending(pReader) ){
  140266. Fts3HashElem *pElem = *(pReader->ppNextElem);
  140267. sqlite3_free(pReader->aNode);
  140268. pReader->aNode = 0;
  140269. if( pElem ){
  140270. char *aCopy;
  140271. PendingList *pList = (PendingList *)fts3HashData(pElem);
  140272. int nCopy = pList->nData+1;
  140273. pReader->zTerm = (char *)fts3HashKey(pElem);
  140274. pReader->nTerm = fts3HashKeysize(pElem);
  140275. aCopy = (char*)sqlite3_malloc(nCopy);
  140276. if( !aCopy ) return SQLITE_NOMEM;
  140277. memcpy(aCopy, pList->aData, nCopy);
  140278. pReader->nNode = pReader->nDoclist = nCopy;
  140279. pReader->aNode = pReader->aDoclist = aCopy;
  140280. pReader->ppNextElem++;
  140281. assert( pReader->aNode );
  140282. }
  140283. return SQLITE_OK;
  140284. }
  140285. fts3SegReaderSetEof(pReader);
  140286. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  140287. ** blocks have already been traversed. */
  140288. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  140289. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  140290. return SQLITE_OK;
  140291. }
  140292. rc = sqlite3Fts3ReadBlock(
  140293. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  140294. (bIncr ? &pReader->nPopulate : 0)
  140295. );
  140296. if( rc!=SQLITE_OK ) return rc;
  140297. assert( pReader->pBlob==0 );
  140298. if( bIncr && pReader->nPopulate<pReader->nNode ){
  140299. pReader->pBlob = p->pSegments;
  140300. p->pSegments = 0;
  140301. }
  140302. pNext = pReader->aNode;
  140303. }
  140304. assert( !fts3SegReaderIsPending(pReader) );
  140305. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  140306. if( rc!=SQLITE_OK ) return rc;
  140307. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  140308. ** safe (no risk of overread) even if the node data is corrupted. */
  140309. pNext += fts3GetVarint32(pNext, &nPrefix);
  140310. pNext += fts3GetVarint32(pNext, &nSuffix);
  140311. if( nPrefix<0 || nSuffix<=0
  140312. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  140313. ){
  140314. return FTS_CORRUPT_VTAB;
  140315. }
  140316. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  140317. int nNew = (nPrefix+nSuffix)*2;
  140318. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  140319. if( !zNew ){
  140320. return SQLITE_NOMEM;
  140321. }
  140322. pReader->zTerm = zNew;
  140323. pReader->nTermAlloc = nNew;
  140324. }
  140325. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  140326. if( rc!=SQLITE_OK ) return rc;
  140327. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  140328. pReader->nTerm = nPrefix+nSuffix;
  140329. pNext += nSuffix;
  140330. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  140331. pReader->aDoclist = pNext;
  140332. pReader->pOffsetList = 0;
  140333. /* Check that the doclist does not appear to extend past the end of the
  140334. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  140335. ** of these statements is untrue, then the data structure is corrupt.
  140336. */
  140337. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  140338. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  140339. ){
  140340. return FTS_CORRUPT_VTAB;
  140341. }
  140342. return SQLITE_OK;
  140343. }
  140344. /*
  140345. ** Set the SegReader to point to the first docid in the doclist associated
  140346. ** with the current term.
  140347. */
  140348. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  140349. int rc = SQLITE_OK;
  140350. assert( pReader->aDoclist );
  140351. assert( !pReader->pOffsetList );
  140352. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  140353. u8 bEof = 0;
  140354. pReader->iDocid = 0;
  140355. pReader->nOffsetList = 0;
  140356. sqlite3Fts3DoclistPrev(0,
  140357. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  140358. &pReader->iDocid, &pReader->nOffsetList, &bEof
  140359. );
  140360. }else{
  140361. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  140362. if( rc==SQLITE_OK ){
  140363. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  140364. pReader->pOffsetList = &pReader->aDoclist[n];
  140365. }
  140366. }
  140367. return rc;
  140368. }
  140369. /*
  140370. ** Advance the SegReader to point to the next docid in the doclist
  140371. ** associated with the current term.
  140372. **
  140373. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  140374. ** *ppOffsetList is set to point to the first column-offset list
  140375. ** in the doclist entry (i.e. immediately past the docid varint).
  140376. ** *pnOffsetList is set to the length of the set of column-offset
  140377. ** lists, not including the nul-terminator byte. For example:
  140378. */
  140379. static int fts3SegReaderNextDocid(
  140380. Fts3Table *pTab,
  140381. Fts3SegReader *pReader, /* Reader to advance to next docid */
  140382. char **ppOffsetList, /* OUT: Pointer to current position-list */
  140383. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  140384. ){
  140385. int rc = SQLITE_OK;
  140386. char *p = pReader->pOffsetList;
  140387. char c = 0;
  140388. assert( p );
  140389. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  140390. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  140391. ** Pending-terms doclists are always built up in ascending order, so
  140392. ** we have to iterate through them backwards here. */
  140393. u8 bEof = 0;
  140394. if( ppOffsetList ){
  140395. *ppOffsetList = pReader->pOffsetList;
  140396. *pnOffsetList = pReader->nOffsetList - 1;
  140397. }
  140398. sqlite3Fts3DoclistPrev(0,
  140399. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  140400. &pReader->nOffsetList, &bEof
  140401. );
  140402. if( bEof ){
  140403. pReader->pOffsetList = 0;
  140404. }else{
  140405. pReader->pOffsetList = p;
  140406. }
  140407. }else{
  140408. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  140409. /* Pointer p currently points at the first byte of an offset list. The
  140410. ** following block advances it to point one byte past the end of
  140411. ** the same offset list. */
  140412. while( 1 ){
  140413. /* The following line of code (and the "p++" below the while() loop) is
  140414. ** normally all that is required to move pointer p to the desired
  140415. ** position. The exception is if this node is being loaded from disk
  140416. ** incrementally and pointer "p" now points to the first byte past
  140417. ** the populated part of pReader->aNode[].
  140418. */
  140419. while( *p | c ) c = *p++ & 0x80;
  140420. assert( *p==0 );
  140421. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  140422. rc = fts3SegReaderIncrRead(pReader);
  140423. if( rc!=SQLITE_OK ) return rc;
  140424. }
  140425. p++;
  140426. /* If required, populate the output variables with a pointer to and the
  140427. ** size of the previous offset-list.
  140428. */
  140429. if( ppOffsetList ){
  140430. *ppOffsetList = pReader->pOffsetList;
  140431. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  140432. }
  140433. /* List may have been edited in place by fts3EvalNearTrim() */
  140434. while( p<pEnd && *p==0 ) p++;
  140435. /* If there are no more entries in the doclist, set pOffsetList to
  140436. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  140437. ** Fts3SegReader.pOffsetList to point to the next offset list before
  140438. ** returning.
  140439. */
  140440. if( p>=pEnd ){
  140441. pReader->pOffsetList = 0;
  140442. }else{
  140443. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  140444. if( rc==SQLITE_OK ){
  140445. sqlite3_int64 iDelta;
  140446. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  140447. if( pTab->bDescIdx ){
  140448. pReader->iDocid -= iDelta;
  140449. }else{
  140450. pReader->iDocid += iDelta;
  140451. }
  140452. }
  140453. }
  140454. }
  140455. return SQLITE_OK;
  140456. }
  140457. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  140458. Fts3Cursor *pCsr,
  140459. Fts3MultiSegReader *pMsr,
  140460. int *pnOvfl
  140461. ){
  140462. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  140463. int nOvfl = 0;
  140464. int ii;
  140465. int rc = SQLITE_OK;
  140466. int pgsz = p->nPgsz;
  140467. assert( p->bFts4 );
  140468. assert( pgsz>0 );
  140469. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  140470. Fts3SegReader *pReader = pMsr->apSegment[ii];
  140471. if( !fts3SegReaderIsPending(pReader)
  140472. && !fts3SegReaderIsRootOnly(pReader)
  140473. ){
  140474. sqlite3_int64 jj;
  140475. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  140476. int nBlob;
  140477. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  140478. if( rc!=SQLITE_OK ) break;
  140479. if( (nBlob+35)>pgsz ){
  140480. nOvfl += (nBlob + 34)/pgsz;
  140481. }
  140482. }
  140483. }
  140484. }
  140485. *pnOvfl = nOvfl;
  140486. return rc;
  140487. }
  140488. /*
  140489. ** Free all allocations associated with the iterator passed as the
  140490. ** second argument.
  140491. */
  140492. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  140493. if( pReader ){
  140494. if( !fts3SegReaderIsPending(pReader) ){
  140495. sqlite3_free(pReader->zTerm);
  140496. }
  140497. if( !fts3SegReaderIsRootOnly(pReader) ){
  140498. sqlite3_free(pReader->aNode);
  140499. }
  140500. sqlite3_blob_close(pReader->pBlob);
  140501. }
  140502. sqlite3_free(pReader);
  140503. }
  140504. /*
  140505. ** Allocate a new SegReader object.
  140506. */
  140507. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  140508. int iAge, /* Segment "age". */
  140509. int bLookup, /* True for a lookup only */
  140510. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  140511. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  140512. sqlite3_int64 iEndBlock, /* Final block of segment */
  140513. const char *zRoot, /* Buffer containing root node */
  140514. int nRoot, /* Size of buffer containing root node */
  140515. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  140516. ){
  140517. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  140518. int nExtra = 0; /* Bytes to allocate segment root node */
  140519. assert( iStartLeaf<=iEndLeaf );
  140520. if( iStartLeaf==0 ){
  140521. nExtra = nRoot + FTS3_NODE_PADDING;
  140522. }
  140523. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  140524. if( !pReader ){
  140525. return SQLITE_NOMEM;
  140526. }
  140527. memset(pReader, 0, sizeof(Fts3SegReader));
  140528. pReader->iIdx = iAge;
  140529. pReader->bLookup = bLookup!=0;
  140530. pReader->iStartBlock = iStartLeaf;
  140531. pReader->iLeafEndBlock = iEndLeaf;
  140532. pReader->iEndBlock = iEndBlock;
  140533. if( nExtra ){
  140534. /* The entire segment is stored in the root node. */
  140535. pReader->aNode = (char *)&pReader[1];
  140536. pReader->rootOnly = 1;
  140537. pReader->nNode = nRoot;
  140538. memcpy(pReader->aNode, zRoot, nRoot);
  140539. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  140540. }else{
  140541. pReader->iCurrentBlock = iStartLeaf-1;
  140542. }
  140543. *ppReader = pReader;
  140544. return SQLITE_OK;
  140545. }
  140546. /*
  140547. ** This is a comparison function used as a qsort() callback when sorting
  140548. ** an array of pending terms by term. This occurs as part of flushing
  140549. ** the contents of the pending-terms hash table to the database.
  140550. */
  140551. static int SQLITE_CDECL fts3CompareElemByTerm(
  140552. const void *lhs,
  140553. const void *rhs
  140554. ){
  140555. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  140556. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  140557. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  140558. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  140559. int n = (n1<n2 ? n1 : n2);
  140560. int c = memcmp(z1, z2, n);
  140561. if( c==0 ){
  140562. c = n1 - n2;
  140563. }
  140564. return c;
  140565. }
  140566. /*
  140567. ** This function is used to allocate an Fts3SegReader that iterates through
  140568. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  140569. **
  140570. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  140571. ** through each term in the pending-terms table. Or, if isPrefixIter is
  140572. ** non-zero, it iterates through each term and its prefixes. For example, if
  140573. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  140574. ** "firebird", then the iterator visits the following 'terms' (in the order
  140575. ** shown):
  140576. **
  140577. ** f fi fir fire fireb firebi firebir firebird
  140578. ** m my mys mysq mysql
  140579. ** s sq sql sqli sqlit sqlite
  140580. **
  140581. ** Whereas if isPrefixIter is zero, the terms visited are:
  140582. **
  140583. ** firebird mysql sqlite
  140584. */
  140585. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  140586. Fts3Table *p, /* Virtual table handle */
  140587. int iIndex, /* Index for p->aIndex */
  140588. const char *zTerm, /* Term to search for */
  140589. int nTerm, /* Size of buffer zTerm */
  140590. int bPrefix, /* True for a prefix iterator */
  140591. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  140592. ){
  140593. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  140594. Fts3HashElem *pE; /* Iterator variable */
  140595. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  140596. int nElem = 0; /* Size of array at aElem */
  140597. int rc = SQLITE_OK; /* Return Code */
  140598. Fts3Hash *pHash;
  140599. pHash = &p->aIndex[iIndex].hPending;
  140600. if( bPrefix ){
  140601. int nAlloc = 0; /* Size of allocated array at aElem */
  140602. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  140603. char *zKey = (char *)fts3HashKey(pE);
  140604. int nKey = fts3HashKeysize(pE);
  140605. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  140606. if( nElem==nAlloc ){
  140607. Fts3HashElem **aElem2;
  140608. nAlloc += 16;
  140609. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  140610. aElem, nAlloc*sizeof(Fts3HashElem *)
  140611. );
  140612. if( !aElem2 ){
  140613. rc = SQLITE_NOMEM;
  140614. nElem = 0;
  140615. break;
  140616. }
  140617. aElem = aElem2;
  140618. }
  140619. aElem[nElem++] = pE;
  140620. }
  140621. }
  140622. /* If more than one term matches the prefix, sort the Fts3HashElem
  140623. ** objects in term order using qsort(). This uses the same comparison
  140624. ** callback as is used when flushing terms to disk.
  140625. */
  140626. if( nElem>1 ){
  140627. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  140628. }
  140629. }else{
  140630. /* The query is a simple term lookup that matches at most one term in
  140631. ** the index. All that is required is a straight hash-lookup.
  140632. **
  140633. ** Because the stack address of pE may be accessed via the aElem pointer
  140634. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  140635. ** within this entire function, not just this "else{...}" block.
  140636. */
  140637. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  140638. if( pE ){
  140639. aElem = &pE;
  140640. nElem = 1;
  140641. }
  140642. }
  140643. if( nElem>0 ){
  140644. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  140645. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  140646. if( !pReader ){
  140647. rc = SQLITE_NOMEM;
  140648. }else{
  140649. memset(pReader, 0, nByte);
  140650. pReader->iIdx = 0x7FFFFFFF;
  140651. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  140652. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  140653. }
  140654. }
  140655. if( bPrefix ){
  140656. sqlite3_free(aElem);
  140657. }
  140658. *ppReader = pReader;
  140659. return rc;
  140660. }
  140661. /*
  140662. ** Compare the entries pointed to by two Fts3SegReader structures.
  140663. ** Comparison is as follows:
  140664. **
  140665. ** 1) EOF is greater than not EOF.
  140666. **
  140667. ** 2) The current terms (if any) are compared using memcmp(). If one
  140668. ** term is a prefix of another, the longer term is considered the
  140669. ** larger.
  140670. **
  140671. ** 3) By segment age. An older segment is considered larger.
  140672. */
  140673. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  140674. int rc;
  140675. if( pLhs->aNode && pRhs->aNode ){
  140676. int rc2 = pLhs->nTerm - pRhs->nTerm;
  140677. if( rc2<0 ){
  140678. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  140679. }else{
  140680. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  140681. }
  140682. if( rc==0 ){
  140683. rc = rc2;
  140684. }
  140685. }else{
  140686. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  140687. }
  140688. if( rc==0 ){
  140689. rc = pRhs->iIdx - pLhs->iIdx;
  140690. }
  140691. assert( rc!=0 );
  140692. return rc;
  140693. }
  140694. /*
  140695. ** A different comparison function for SegReader structures. In this
  140696. ** version, it is assumed that each SegReader points to an entry in
  140697. ** a doclist for identical terms. Comparison is made as follows:
  140698. **
  140699. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  140700. **
  140701. ** 2) By current docid.
  140702. **
  140703. ** 3) By segment age. An older segment is considered larger.
  140704. */
  140705. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  140706. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  140707. if( rc==0 ){
  140708. if( pLhs->iDocid==pRhs->iDocid ){
  140709. rc = pRhs->iIdx - pLhs->iIdx;
  140710. }else{
  140711. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  140712. }
  140713. }
  140714. assert( pLhs->aNode && pRhs->aNode );
  140715. return rc;
  140716. }
  140717. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  140718. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  140719. if( rc==0 ){
  140720. if( pLhs->iDocid==pRhs->iDocid ){
  140721. rc = pRhs->iIdx - pLhs->iIdx;
  140722. }else{
  140723. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  140724. }
  140725. }
  140726. assert( pLhs->aNode && pRhs->aNode );
  140727. return rc;
  140728. }
  140729. /*
  140730. ** Compare the term that the Fts3SegReader object passed as the first argument
  140731. ** points to with the term specified by arguments zTerm and nTerm.
  140732. **
  140733. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  140734. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  140735. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  140736. */
  140737. static int fts3SegReaderTermCmp(
  140738. Fts3SegReader *pSeg, /* Segment reader object */
  140739. const char *zTerm, /* Term to compare to */
  140740. int nTerm /* Size of term zTerm in bytes */
  140741. ){
  140742. int res = 0;
  140743. if( pSeg->aNode ){
  140744. if( pSeg->nTerm>nTerm ){
  140745. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  140746. }else{
  140747. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  140748. }
  140749. if( res==0 ){
  140750. res = pSeg->nTerm-nTerm;
  140751. }
  140752. }
  140753. return res;
  140754. }
  140755. /*
  140756. ** Argument apSegment is an array of nSegment elements. It is known that
  140757. ** the final (nSegment-nSuspect) members are already in sorted order
  140758. ** (according to the comparison function provided). This function shuffles
  140759. ** the array around until all entries are in sorted order.
  140760. */
  140761. static void fts3SegReaderSort(
  140762. Fts3SegReader **apSegment, /* Array to sort entries of */
  140763. int nSegment, /* Size of apSegment array */
  140764. int nSuspect, /* Unsorted entry count */
  140765. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  140766. ){
  140767. int i; /* Iterator variable */
  140768. assert( nSuspect<=nSegment );
  140769. if( nSuspect==nSegment ) nSuspect--;
  140770. for(i=nSuspect-1; i>=0; i--){
  140771. int j;
  140772. for(j=i; j<(nSegment-1); j++){
  140773. Fts3SegReader *pTmp;
  140774. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  140775. pTmp = apSegment[j+1];
  140776. apSegment[j+1] = apSegment[j];
  140777. apSegment[j] = pTmp;
  140778. }
  140779. }
  140780. #ifndef NDEBUG
  140781. /* Check that the list really is sorted now. */
  140782. for(i=0; i<(nSuspect-1); i++){
  140783. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  140784. }
  140785. #endif
  140786. }
  140787. /*
  140788. ** Insert a record into the %_segments table.
  140789. */
  140790. static int fts3WriteSegment(
  140791. Fts3Table *p, /* Virtual table handle */
  140792. sqlite3_int64 iBlock, /* Block id for new block */
  140793. char *z, /* Pointer to buffer containing block data */
  140794. int n /* Size of buffer z in bytes */
  140795. ){
  140796. sqlite3_stmt *pStmt;
  140797. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  140798. if( rc==SQLITE_OK ){
  140799. sqlite3_bind_int64(pStmt, 1, iBlock);
  140800. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  140801. sqlite3_step(pStmt);
  140802. rc = sqlite3_reset(pStmt);
  140803. }
  140804. return rc;
  140805. }
  140806. /*
  140807. ** Find the largest relative level number in the table. If successful, set
  140808. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  140809. ** set *pnMax to zero and return an SQLite error code.
  140810. */
  140811. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  140812. int rc;
  140813. int mxLevel = 0;
  140814. sqlite3_stmt *pStmt = 0;
  140815. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  140816. if( rc==SQLITE_OK ){
  140817. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  140818. mxLevel = sqlite3_column_int(pStmt, 0);
  140819. }
  140820. rc = sqlite3_reset(pStmt);
  140821. }
  140822. *pnMax = mxLevel;
  140823. return rc;
  140824. }
  140825. /*
  140826. ** Insert a record into the %_segdir table.
  140827. */
  140828. static int fts3WriteSegdir(
  140829. Fts3Table *p, /* Virtual table handle */
  140830. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  140831. int iIdx, /* Value for "idx" field */
  140832. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  140833. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  140834. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  140835. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  140836. char *zRoot, /* Blob value for "root" field */
  140837. int nRoot /* Number of bytes in buffer zRoot */
  140838. ){
  140839. sqlite3_stmt *pStmt;
  140840. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  140841. if( rc==SQLITE_OK ){
  140842. sqlite3_bind_int64(pStmt, 1, iLevel);
  140843. sqlite3_bind_int(pStmt, 2, iIdx);
  140844. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  140845. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  140846. if( nLeafData==0 ){
  140847. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  140848. }else{
  140849. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  140850. if( !zEnd ) return SQLITE_NOMEM;
  140851. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  140852. }
  140853. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  140854. sqlite3_step(pStmt);
  140855. rc = sqlite3_reset(pStmt);
  140856. }
  140857. return rc;
  140858. }
  140859. /*
  140860. ** Return the size of the common prefix (if any) shared by zPrev and
  140861. ** zNext, in bytes. For example,
  140862. **
  140863. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  140864. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  140865. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  140866. */
  140867. static int fts3PrefixCompress(
  140868. const char *zPrev, /* Buffer containing previous term */
  140869. int nPrev, /* Size of buffer zPrev in bytes */
  140870. const char *zNext, /* Buffer containing next term */
  140871. int nNext /* Size of buffer zNext in bytes */
  140872. ){
  140873. int n;
  140874. UNUSED_PARAMETER(nNext);
  140875. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  140876. return n;
  140877. }
  140878. /*
  140879. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  140880. ** (according to memcmp) than the previous term.
  140881. */
  140882. static int fts3NodeAddTerm(
  140883. Fts3Table *p, /* Virtual table handle */
  140884. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  140885. int isCopyTerm, /* True if zTerm/nTerm is transient */
  140886. const char *zTerm, /* Pointer to buffer containing term */
  140887. int nTerm /* Size of term in bytes */
  140888. ){
  140889. SegmentNode *pTree = *ppTree;
  140890. int rc;
  140891. SegmentNode *pNew;
  140892. /* First try to append the term to the current node. Return early if
  140893. ** this is possible.
  140894. */
  140895. if( pTree ){
  140896. int nData = pTree->nData; /* Current size of node in bytes */
  140897. int nReq = nData; /* Required space after adding zTerm */
  140898. int nPrefix; /* Number of bytes of prefix compression */
  140899. int nSuffix; /* Suffix length */
  140900. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  140901. nSuffix = nTerm-nPrefix;
  140902. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  140903. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  140904. if( nReq>p->nNodeSize ){
  140905. /* An unusual case: this is the first term to be added to the node
  140906. ** and the static node buffer (p->nNodeSize bytes) is not large
  140907. ** enough. Use a separately malloced buffer instead This wastes
  140908. ** p->nNodeSize bytes, but since this scenario only comes about when
  140909. ** the database contain two terms that share a prefix of almost 2KB,
  140910. ** this is not expected to be a serious problem.
  140911. */
  140912. assert( pTree->aData==(char *)&pTree[1] );
  140913. pTree->aData = (char *)sqlite3_malloc(nReq);
  140914. if( !pTree->aData ){
  140915. return SQLITE_NOMEM;
  140916. }
  140917. }
  140918. if( pTree->zTerm ){
  140919. /* There is no prefix-length field for first term in a node */
  140920. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  140921. }
  140922. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  140923. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  140924. pTree->nData = nData + nSuffix;
  140925. pTree->nEntry++;
  140926. if( isCopyTerm ){
  140927. if( pTree->nMalloc<nTerm ){
  140928. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  140929. if( !zNew ){
  140930. return SQLITE_NOMEM;
  140931. }
  140932. pTree->nMalloc = nTerm*2;
  140933. pTree->zMalloc = zNew;
  140934. }
  140935. pTree->zTerm = pTree->zMalloc;
  140936. memcpy(pTree->zTerm, zTerm, nTerm);
  140937. pTree->nTerm = nTerm;
  140938. }else{
  140939. pTree->zTerm = (char *)zTerm;
  140940. pTree->nTerm = nTerm;
  140941. }
  140942. return SQLITE_OK;
  140943. }
  140944. }
  140945. /* If control flows to here, it was not possible to append zTerm to the
  140946. ** current node. Create a new node (a right-sibling of the current node).
  140947. ** If this is the first node in the tree, the term is added to it.
  140948. **
  140949. ** Otherwise, the term is not added to the new node, it is left empty for
  140950. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  140951. ** has no parent, one is created here.
  140952. */
  140953. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  140954. if( !pNew ){
  140955. return SQLITE_NOMEM;
  140956. }
  140957. memset(pNew, 0, sizeof(SegmentNode));
  140958. pNew->nData = 1 + FTS3_VARINT_MAX;
  140959. pNew->aData = (char *)&pNew[1];
  140960. if( pTree ){
  140961. SegmentNode *pParent = pTree->pParent;
  140962. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  140963. if( pTree->pParent==0 ){
  140964. pTree->pParent = pParent;
  140965. }
  140966. pTree->pRight = pNew;
  140967. pNew->pLeftmost = pTree->pLeftmost;
  140968. pNew->pParent = pParent;
  140969. pNew->zMalloc = pTree->zMalloc;
  140970. pNew->nMalloc = pTree->nMalloc;
  140971. pTree->zMalloc = 0;
  140972. }else{
  140973. pNew->pLeftmost = pNew;
  140974. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  140975. }
  140976. *ppTree = pNew;
  140977. return rc;
  140978. }
  140979. /*
  140980. ** Helper function for fts3NodeWrite().
  140981. */
  140982. static int fts3TreeFinishNode(
  140983. SegmentNode *pTree,
  140984. int iHeight,
  140985. sqlite3_int64 iLeftChild
  140986. ){
  140987. int nStart;
  140988. assert( iHeight>=1 && iHeight<128 );
  140989. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  140990. pTree->aData[nStart] = (char)iHeight;
  140991. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  140992. return nStart;
  140993. }
  140994. /*
  140995. ** Write the buffer for the segment node pTree and all of its peers to the
  140996. ** database. Then call this function recursively to write the parent of
  140997. ** pTree and its peers to the database.
  140998. **
  140999. ** Except, if pTree is a root node, do not write it to the database. Instead,
  141000. ** set output variables *paRoot and *pnRoot to contain the root node.
  141001. **
  141002. ** If successful, SQLITE_OK is returned and output variable *piLast is
  141003. ** set to the largest blockid written to the database (or zero if no
  141004. ** blocks were written to the db). Otherwise, an SQLite error code is
  141005. ** returned.
  141006. */
  141007. static int fts3NodeWrite(
  141008. Fts3Table *p, /* Virtual table handle */
  141009. SegmentNode *pTree, /* SegmentNode handle */
  141010. int iHeight, /* Height of this node in tree */
  141011. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  141012. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  141013. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  141014. char **paRoot, /* OUT: Data for root node */
  141015. int *pnRoot /* OUT: Size of root node in bytes */
  141016. ){
  141017. int rc = SQLITE_OK;
  141018. if( !pTree->pParent ){
  141019. /* Root node of the tree. */
  141020. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  141021. *piLast = iFree-1;
  141022. *pnRoot = pTree->nData - nStart;
  141023. *paRoot = &pTree->aData[nStart];
  141024. }else{
  141025. SegmentNode *pIter;
  141026. sqlite3_int64 iNextFree = iFree;
  141027. sqlite3_int64 iNextLeaf = iLeaf;
  141028. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  141029. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  141030. int nWrite = pIter->nData - nStart;
  141031. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  141032. iNextFree++;
  141033. iNextLeaf += (pIter->nEntry+1);
  141034. }
  141035. if( rc==SQLITE_OK ){
  141036. assert( iNextLeaf==iFree );
  141037. rc = fts3NodeWrite(
  141038. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  141039. );
  141040. }
  141041. }
  141042. return rc;
  141043. }
  141044. /*
  141045. ** Free all memory allocations associated with the tree pTree.
  141046. */
  141047. static void fts3NodeFree(SegmentNode *pTree){
  141048. if( pTree ){
  141049. SegmentNode *p = pTree->pLeftmost;
  141050. fts3NodeFree(p->pParent);
  141051. while( p ){
  141052. SegmentNode *pRight = p->pRight;
  141053. if( p->aData!=(char *)&p[1] ){
  141054. sqlite3_free(p->aData);
  141055. }
  141056. assert( pRight==0 || p->zMalloc==0 );
  141057. sqlite3_free(p->zMalloc);
  141058. sqlite3_free(p);
  141059. p = pRight;
  141060. }
  141061. }
  141062. }
  141063. /*
  141064. ** Add a term to the segment being constructed by the SegmentWriter object
  141065. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  141066. ** be passed NULL. This function will allocate a new SegmentWriter object
  141067. ** and return it via the input/output variable *ppWriter in this case.
  141068. **
  141069. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  141070. */
  141071. static int fts3SegWriterAdd(
  141072. Fts3Table *p, /* Virtual table handle */
  141073. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  141074. int isCopyTerm, /* True if buffer zTerm must be copied */
  141075. const char *zTerm, /* Pointer to buffer containing term */
  141076. int nTerm, /* Size of term in bytes */
  141077. const char *aDoclist, /* Pointer to buffer containing doclist */
  141078. int nDoclist /* Size of doclist in bytes */
  141079. ){
  141080. int nPrefix; /* Size of term prefix in bytes */
  141081. int nSuffix; /* Size of term suffix in bytes */
  141082. int nReq; /* Number of bytes required on leaf page */
  141083. int nData;
  141084. SegmentWriter *pWriter = *ppWriter;
  141085. if( !pWriter ){
  141086. int rc;
  141087. sqlite3_stmt *pStmt;
  141088. /* Allocate the SegmentWriter structure */
  141089. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  141090. if( !pWriter ) return SQLITE_NOMEM;
  141091. memset(pWriter, 0, sizeof(SegmentWriter));
  141092. *ppWriter = pWriter;
  141093. /* Allocate a buffer in which to accumulate data */
  141094. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  141095. if( !pWriter->aData ) return SQLITE_NOMEM;
  141096. pWriter->nSize = p->nNodeSize;
  141097. /* Find the next free blockid in the %_segments table */
  141098. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  141099. if( rc!=SQLITE_OK ) return rc;
  141100. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  141101. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  141102. pWriter->iFirst = pWriter->iFree;
  141103. }
  141104. rc = sqlite3_reset(pStmt);
  141105. if( rc!=SQLITE_OK ) return rc;
  141106. }
  141107. nData = pWriter->nData;
  141108. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  141109. nSuffix = nTerm-nPrefix;
  141110. /* Figure out how many bytes are required by this new entry */
  141111. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  141112. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  141113. nSuffix + /* Term suffix */
  141114. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  141115. nDoclist; /* Doclist data */
  141116. if( nData>0 && nData+nReq>p->nNodeSize ){
  141117. int rc;
  141118. /* The current leaf node is full. Write it out to the database. */
  141119. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  141120. if( rc!=SQLITE_OK ) return rc;
  141121. p->nLeafAdd++;
  141122. /* Add the current term to the interior node tree. The term added to
  141123. ** the interior tree must:
  141124. **
  141125. ** a) be greater than the largest term on the leaf node just written
  141126. ** to the database (still available in pWriter->zTerm), and
  141127. **
  141128. ** b) be less than or equal to the term about to be added to the new
  141129. ** leaf node (zTerm/nTerm).
  141130. **
  141131. ** In other words, it must be the prefix of zTerm 1 byte longer than
  141132. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  141133. */
  141134. assert( nPrefix<nTerm );
  141135. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  141136. if( rc!=SQLITE_OK ) return rc;
  141137. nData = 0;
  141138. pWriter->nTerm = 0;
  141139. nPrefix = 0;
  141140. nSuffix = nTerm;
  141141. nReq = 1 + /* varint containing prefix size */
  141142. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  141143. nTerm + /* Term suffix */
  141144. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  141145. nDoclist; /* Doclist data */
  141146. }
  141147. /* Increase the total number of bytes written to account for the new entry. */
  141148. pWriter->nLeafData += nReq;
  141149. /* If the buffer currently allocated is too small for this entry, realloc
  141150. ** the buffer to make it large enough.
  141151. */
  141152. if( nReq>pWriter->nSize ){
  141153. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  141154. if( !aNew ) return SQLITE_NOMEM;
  141155. pWriter->aData = aNew;
  141156. pWriter->nSize = nReq;
  141157. }
  141158. assert( nData+nReq<=pWriter->nSize );
  141159. /* Append the prefix-compressed term and doclist to the buffer. */
  141160. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  141161. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  141162. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  141163. nData += nSuffix;
  141164. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  141165. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  141166. pWriter->nData = nData + nDoclist;
  141167. /* Save the current term so that it can be used to prefix-compress the next.
  141168. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  141169. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  141170. ** store a copy of the pointer.
  141171. */
  141172. if( isCopyTerm ){
  141173. if( nTerm>pWriter->nMalloc ){
  141174. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  141175. if( !zNew ){
  141176. return SQLITE_NOMEM;
  141177. }
  141178. pWriter->nMalloc = nTerm*2;
  141179. pWriter->zMalloc = zNew;
  141180. pWriter->zTerm = zNew;
  141181. }
  141182. assert( pWriter->zTerm==pWriter->zMalloc );
  141183. memcpy(pWriter->zTerm, zTerm, nTerm);
  141184. }else{
  141185. pWriter->zTerm = (char *)zTerm;
  141186. }
  141187. pWriter->nTerm = nTerm;
  141188. return SQLITE_OK;
  141189. }
  141190. /*
  141191. ** Flush all data associated with the SegmentWriter object pWriter to the
  141192. ** database. This function must be called after all terms have been added
  141193. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  141194. ** returned. Otherwise, an SQLite error code.
  141195. */
  141196. static int fts3SegWriterFlush(
  141197. Fts3Table *p, /* Virtual table handle */
  141198. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  141199. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  141200. int iIdx /* Value for 'idx' column of %_segdir */
  141201. ){
  141202. int rc; /* Return code */
  141203. if( pWriter->pTree ){
  141204. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  141205. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  141206. char *zRoot = NULL; /* Pointer to buffer containing root node */
  141207. int nRoot = 0; /* Size of buffer zRoot */
  141208. iLastLeaf = pWriter->iFree;
  141209. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  141210. if( rc==SQLITE_OK ){
  141211. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  141212. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  141213. }
  141214. if( rc==SQLITE_OK ){
  141215. rc = fts3WriteSegdir(p, iLevel, iIdx,
  141216. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  141217. }
  141218. }else{
  141219. /* The entire tree fits on the root node. Write it to the segdir table. */
  141220. rc = fts3WriteSegdir(p, iLevel, iIdx,
  141221. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  141222. }
  141223. p->nLeafAdd++;
  141224. return rc;
  141225. }
  141226. /*
  141227. ** Release all memory held by the SegmentWriter object passed as the
  141228. ** first argument.
  141229. */
  141230. static void fts3SegWriterFree(SegmentWriter *pWriter){
  141231. if( pWriter ){
  141232. sqlite3_free(pWriter->aData);
  141233. sqlite3_free(pWriter->zMalloc);
  141234. fts3NodeFree(pWriter->pTree);
  141235. sqlite3_free(pWriter);
  141236. }
  141237. }
  141238. /*
  141239. ** The first value in the apVal[] array is assumed to contain an integer.
  141240. ** This function tests if there exist any documents with docid values that
  141241. ** are different from that integer. i.e. if deleting the document with docid
  141242. ** pRowid would mean the FTS3 table were empty.
  141243. **
  141244. ** If successful, *pisEmpty is set to true if the table is empty except for
  141245. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  141246. ** error occurs, an SQLite error code is returned.
  141247. */
  141248. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  141249. sqlite3_stmt *pStmt;
  141250. int rc;
  141251. if( p->zContentTbl ){
  141252. /* If using the content=xxx option, assume the table is never empty */
  141253. *pisEmpty = 0;
  141254. rc = SQLITE_OK;
  141255. }else{
  141256. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  141257. if( rc==SQLITE_OK ){
  141258. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  141259. *pisEmpty = sqlite3_column_int(pStmt, 0);
  141260. }
  141261. rc = sqlite3_reset(pStmt);
  141262. }
  141263. }
  141264. return rc;
  141265. }
  141266. /*
  141267. ** Set *pnMax to the largest segment level in the database for the index
  141268. ** iIndex.
  141269. **
  141270. ** Segment levels are stored in the 'level' column of the %_segdir table.
  141271. **
  141272. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  141273. */
  141274. static int fts3SegmentMaxLevel(
  141275. Fts3Table *p,
  141276. int iLangid,
  141277. int iIndex,
  141278. sqlite3_int64 *pnMax
  141279. ){
  141280. sqlite3_stmt *pStmt;
  141281. int rc;
  141282. assert( iIndex>=0 && iIndex<p->nIndex );
  141283. /* Set pStmt to the compiled version of:
  141284. **
  141285. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  141286. **
  141287. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  141288. */
  141289. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  141290. if( rc!=SQLITE_OK ) return rc;
  141291. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  141292. sqlite3_bind_int64(pStmt, 2,
  141293. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  141294. );
  141295. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  141296. *pnMax = sqlite3_column_int64(pStmt, 0);
  141297. }
  141298. return sqlite3_reset(pStmt);
  141299. }
  141300. /*
  141301. ** iAbsLevel is an absolute level that may be assumed to exist within
  141302. ** the database. This function checks if it is the largest level number
  141303. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  141304. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  141305. ** is returned. If an error occurs, an error code is returned and the
  141306. ** final value of *pbMax is undefined.
  141307. */
  141308. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  141309. /* Set pStmt to the compiled version of:
  141310. **
  141311. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  141312. **
  141313. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  141314. */
  141315. sqlite3_stmt *pStmt;
  141316. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  141317. if( rc!=SQLITE_OK ) return rc;
  141318. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  141319. sqlite3_bind_int64(pStmt, 2,
  141320. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  141321. );
  141322. *pbMax = 0;
  141323. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  141324. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  141325. }
  141326. return sqlite3_reset(pStmt);
  141327. }
  141328. /*
  141329. ** Delete all entries in the %_segments table associated with the segment
  141330. ** opened with seg-reader pSeg. This function does not affect the contents
  141331. ** of the %_segdir table.
  141332. */
  141333. static int fts3DeleteSegment(
  141334. Fts3Table *p, /* FTS table handle */
  141335. Fts3SegReader *pSeg /* Segment to delete */
  141336. ){
  141337. int rc = SQLITE_OK; /* Return code */
  141338. if( pSeg->iStartBlock ){
  141339. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  141340. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  141341. if( rc==SQLITE_OK ){
  141342. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  141343. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  141344. sqlite3_step(pDelete);
  141345. rc = sqlite3_reset(pDelete);
  141346. }
  141347. }
  141348. return rc;
  141349. }
  141350. /*
  141351. ** This function is used after merging multiple segments into a single large
  141352. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  141353. ** it:
  141354. **
  141355. ** 1) Deletes all %_segments entries for the segments associated with
  141356. ** each of the SegReader objects in the array passed as the third
  141357. ** argument, and
  141358. **
  141359. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  141360. ** entries regardless of level if (iLevel<0).
  141361. **
  141362. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  141363. */
  141364. static int fts3DeleteSegdir(
  141365. Fts3Table *p, /* Virtual table handle */
  141366. int iLangid, /* Language id */
  141367. int iIndex, /* Index for p->aIndex */
  141368. int iLevel, /* Level of %_segdir entries to delete */
  141369. Fts3SegReader **apSegment, /* Array of SegReader objects */
  141370. int nReader /* Size of array apSegment */
  141371. ){
  141372. int rc = SQLITE_OK; /* Return Code */
  141373. int i; /* Iterator variable */
  141374. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  141375. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  141376. rc = fts3DeleteSegment(p, apSegment[i]);
  141377. }
  141378. if( rc!=SQLITE_OK ){
  141379. return rc;
  141380. }
  141381. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  141382. if( iLevel==FTS3_SEGCURSOR_ALL ){
  141383. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  141384. if( rc==SQLITE_OK ){
  141385. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  141386. sqlite3_bind_int64(pDelete, 2,
  141387. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  141388. );
  141389. }
  141390. }else{
  141391. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  141392. if( rc==SQLITE_OK ){
  141393. sqlite3_bind_int64(
  141394. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  141395. );
  141396. }
  141397. }
  141398. if( rc==SQLITE_OK ){
  141399. sqlite3_step(pDelete);
  141400. rc = sqlite3_reset(pDelete);
  141401. }
  141402. return rc;
  141403. }
  141404. /*
  141405. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  141406. ** a position list that may (or may not) feature multiple columns. This
  141407. ** function adjusts the pointer *ppList and the length *pnList so that they
  141408. ** identify the subset of the position list that corresponds to column iCol.
  141409. **
  141410. ** If there are no entries in the input position list for column iCol, then
  141411. ** *pnList is set to zero before returning.
  141412. **
  141413. ** If parameter bZero is non-zero, then any part of the input list following
  141414. ** the end of the output list is zeroed before returning.
  141415. */
  141416. static void fts3ColumnFilter(
  141417. int iCol, /* Column to filter on */
  141418. int bZero, /* Zero out anything following *ppList */
  141419. char **ppList, /* IN/OUT: Pointer to position list */
  141420. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  141421. ){
  141422. char *pList = *ppList;
  141423. int nList = *pnList;
  141424. char *pEnd = &pList[nList];
  141425. int iCurrent = 0;
  141426. char *p = pList;
  141427. assert( iCol>=0 );
  141428. while( 1 ){
  141429. char c = 0;
  141430. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  141431. if( iCol==iCurrent ){
  141432. nList = (int)(p - pList);
  141433. break;
  141434. }
  141435. nList -= (int)(p - pList);
  141436. pList = p;
  141437. if( nList==0 ){
  141438. break;
  141439. }
  141440. p = &pList[1];
  141441. p += fts3GetVarint32(p, &iCurrent);
  141442. }
  141443. if( bZero && &pList[nList]!=pEnd ){
  141444. memset(&pList[nList], 0, pEnd - &pList[nList]);
  141445. }
  141446. *ppList = pList;
  141447. *pnList = nList;
  141448. }
  141449. /*
  141450. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  141451. ** existing data). Grow the buffer if required.
  141452. **
  141453. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  141454. ** trying to resize the buffer, return SQLITE_NOMEM.
  141455. */
  141456. static int fts3MsrBufferData(
  141457. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  141458. char *pList,
  141459. int nList
  141460. ){
  141461. if( nList>pMsr->nBuffer ){
  141462. char *pNew;
  141463. pMsr->nBuffer = nList*2;
  141464. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  141465. if( !pNew ) return SQLITE_NOMEM;
  141466. pMsr->aBuffer = pNew;
  141467. }
  141468. memcpy(pMsr->aBuffer, pList, nList);
  141469. return SQLITE_OK;
  141470. }
  141471. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  141472. Fts3Table *p, /* Virtual table handle */
  141473. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  141474. sqlite3_int64 *piDocid, /* OUT: Docid value */
  141475. char **paPoslist, /* OUT: Pointer to position list */
  141476. int *pnPoslist /* OUT: Size of position list in bytes */
  141477. ){
  141478. int nMerge = pMsr->nAdvance;
  141479. Fts3SegReader **apSegment = pMsr->apSegment;
  141480. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  141481. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  141482. );
  141483. if( nMerge==0 ){
  141484. *paPoslist = 0;
  141485. return SQLITE_OK;
  141486. }
  141487. while( 1 ){
  141488. Fts3SegReader *pSeg;
  141489. pSeg = pMsr->apSegment[0];
  141490. if( pSeg->pOffsetList==0 ){
  141491. *paPoslist = 0;
  141492. break;
  141493. }else{
  141494. int rc;
  141495. char *pList;
  141496. int nList;
  141497. int j;
  141498. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  141499. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  141500. j = 1;
  141501. while( rc==SQLITE_OK
  141502. && j<nMerge
  141503. && apSegment[j]->pOffsetList
  141504. && apSegment[j]->iDocid==iDocid
  141505. ){
  141506. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  141507. j++;
  141508. }
  141509. if( rc!=SQLITE_OK ) return rc;
  141510. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  141511. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  141512. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  141513. if( rc!=SQLITE_OK ) return rc;
  141514. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  141515. pList = pMsr->aBuffer;
  141516. }
  141517. if( pMsr->iColFilter>=0 ){
  141518. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  141519. }
  141520. if( nList>0 ){
  141521. *paPoslist = pList;
  141522. *piDocid = iDocid;
  141523. *pnPoslist = nList;
  141524. break;
  141525. }
  141526. }
  141527. }
  141528. return SQLITE_OK;
  141529. }
  141530. static int fts3SegReaderStart(
  141531. Fts3Table *p, /* Virtual table handle */
  141532. Fts3MultiSegReader *pCsr, /* Cursor object */
  141533. const char *zTerm, /* Term searched for (or NULL) */
  141534. int nTerm /* Length of zTerm in bytes */
  141535. ){
  141536. int i;
  141537. int nSeg = pCsr->nSegment;
  141538. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  141539. ** for, then advance each segment iterator until it points to a term of
  141540. ** equal or greater value than the specified term. This prevents many
  141541. ** unnecessary merge/sort operations for the case where single segment
  141542. ** b-tree leaf nodes contain more than one term.
  141543. */
  141544. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  141545. int res = 0;
  141546. Fts3SegReader *pSeg = pCsr->apSegment[i];
  141547. do {
  141548. int rc = fts3SegReaderNext(p, pSeg, 0);
  141549. if( rc!=SQLITE_OK ) return rc;
  141550. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  141551. if( pSeg->bLookup && res!=0 ){
  141552. fts3SegReaderSetEof(pSeg);
  141553. }
  141554. }
  141555. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  141556. return SQLITE_OK;
  141557. }
  141558. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  141559. Fts3Table *p, /* Virtual table handle */
  141560. Fts3MultiSegReader *pCsr, /* Cursor object */
  141561. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  141562. ){
  141563. pCsr->pFilter = pFilter;
  141564. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  141565. }
  141566. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  141567. Fts3Table *p, /* Virtual table handle */
  141568. Fts3MultiSegReader *pCsr, /* Cursor object */
  141569. int iCol, /* Column to match on. */
  141570. const char *zTerm, /* Term to iterate through a doclist for */
  141571. int nTerm /* Number of bytes in zTerm */
  141572. ){
  141573. int i;
  141574. int rc;
  141575. int nSegment = pCsr->nSegment;
  141576. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  141577. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  141578. );
  141579. assert( pCsr->pFilter==0 );
  141580. assert( zTerm && nTerm>0 );
  141581. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  141582. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  141583. if( rc!=SQLITE_OK ) return rc;
  141584. /* Determine how many of the segments actually point to zTerm/nTerm. */
  141585. for(i=0; i<nSegment; i++){
  141586. Fts3SegReader *pSeg = pCsr->apSegment[i];
  141587. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  141588. break;
  141589. }
  141590. }
  141591. pCsr->nAdvance = i;
  141592. /* Advance each of the segments to point to the first docid. */
  141593. for(i=0; i<pCsr->nAdvance; i++){
  141594. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  141595. if( rc!=SQLITE_OK ) return rc;
  141596. }
  141597. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  141598. assert( iCol<0 || iCol<p->nColumn );
  141599. pCsr->iColFilter = iCol;
  141600. return SQLITE_OK;
  141601. }
  141602. /*
  141603. ** This function is called on a MultiSegReader that has been started using
  141604. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  141605. ** have been made. Calling this function puts the MultiSegReader in such
  141606. ** a state that if the next two calls are:
  141607. **
  141608. ** sqlite3Fts3SegReaderStart()
  141609. ** sqlite3Fts3SegReaderStep()
  141610. **
  141611. ** then the entire doclist for the term is available in
  141612. ** MultiSegReader.aDoclist/nDoclist.
  141613. */
  141614. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  141615. int i; /* Used to iterate through segment-readers */
  141616. assert( pCsr->zTerm==0 );
  141617. assert( pCsr->nTerm==0 );
  141618. assert( pCsr->aDoclist==0 );
  141619. assert( pCsr->nDoclist==0 );
  141620. pCsr->nAdvance = 0;
  141621. pCsr->bRestart = 1;
  141622. for(i=0; i<pCsr->nSegment; i++){
  141623. pCsr->apSegment[i]->pOffsetList = 0;
  141624. pCsr->apSegment[i]->nOffsetList = 0;
  141625. pCsr->apSegment[i]->iDocid = 0;
  141626. }
  141627. return SQLITE_OK;
  141628. }
  141629. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  141630. Fts3Table *p, /* Virtual table handle */
  141631. Fts3MultiSegReader *pCsr /* Cursor object */
  141632. ){
  141633. int rc = SQLITE_OK;
  141634. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  141635. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  141636. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  141637. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  141638. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  141639. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  141640. Fts3SegReader **apSegment = pCsr->apSegment;
  141641. int nSegment = pCsr->nSegment;
  141642. Fts3SegFilter *pFilter = pCsr->pFilter;
  141643. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  141644. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  141645. );
  141646. if( pCsr->nSegment==0 ) return SQLITE_OK;
  141647. do {
  141648. int nMerge;
  141649. int i;
  141650. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  141651. ** forward. Then sort the list in order of current term again.
  141652. */
  141653. for(i=0; i<pCsr->nAdvance; i++){
  141654. Fts3SegReader *pSeg = apSegment[i];
  141655. if( pSeg->bLookup ){
  141656. fts3SegReaderSetEof(pSeg);
  141657. }else{
  141658. rc = fts3SegReaderNext(p, pSeg, 0);
  141659. }
  141660. if( rc!=SQLITE_OK ) return rc;
  141661. }
  141662. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  141663. pCsr->nAdvance = 0;
  141664. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  141665. assert( rc==SQLITE_OK );
  141666. if( apSegment[0]->aNode==0 ) break;
  141667. pCsr->nTerm = apSegment[0]->nTerm;
  141668. pCsr->zTerm = apSegment[0]->zTerm;
  141669. /* If this is a prefix-search, and if the term that apSegment[0] points
  141670. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  141671. ** required callbacks have been made. In this case exit early.
  141672. **
  141673. ** Similarly, if this is a search for an exact match, and the first term
  141674. ** of segment apSegment[0] is not a match, exit early.
  141675. */
  141676. if( pFilter->zTerm && !isScan ){
  141677. if( pCsr->nTerm<pFilter->nTerm
  141678. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  141679. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  141680. ){
  141681. break;
  141682. }
  141683. }
  141684. nMerge = 1;
  141685. while( nMerge<nSegment
  141686. && apSegment[nMerge]->aNode
  141687. && apSegment[nMerge]->nTerm==pCsr->nTerm
  141688. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  141689. ){
  141690. nMerge++;
  141691. }
  141692. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  141693. if( nMerge==1
  141694. && !isIgnoreEmpty
  141695. && !isFirst
  141696. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  141697. ){
  141698. pCsr->nDoclist = apSegment[0]->nDoclist;
  141699. if( fts3SegReaderIsPending(apSegment[0]) ){
  141700. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  141701. pCsr->aDoclist = pCsr->aBuffer;
  141702. }else{
  141703. pCsr->aDoclist = apSegment[0]->aDoclist;
  141704. }
  141705. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  141706. }else{
  141707. int nDoclist = 0; /* Size of doclist */
  141708. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  141709. /* The current term of the first nMerge entries in the array
  141710. ** of Fts3SegReader objects is the same. The doclists must be merged
  141711. ** and a single term returned with the merged doclist.
  141712. */
  141713. for(i=0; i<nMerge; i++){
  141714. fts3SegReaderFirstDocid(p, apSegment[i]);
  141715. }
  141716. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  141717. while( apSegment[0]->pOffsetList ){
  141718. int j; /* Number of segments that share a docid */
  141719. char *pList = 0;
  141720. int nList = 0;
  141721. int nByte;
  141722. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  141723. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  141724. j = 1;
  141725. while( j<nMerge
  141726. && apSegment[j]->pOffsetList
  141727. && apSegment[j]->iDocid==iDocid
  141728. ){
  141729. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  141730. j++;
  141731. }
  141732. if( isColFilter ){
  141733. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  141734. }
  141735. if( !isIgnoreEmpty || nList>0 ){
  141736. /* Calculate the 'docid' delta value to write into the merged
  141737. ** doclist. */
  141738. sqlite3_int64 iDelta;
  141739. if( p->bDescIdx && nDoclist>0 ){
  141740. iDelta = iPrev - iDocid;
  141741. }else{
  141742. iDelta = iDocid - iPrev;
  141743. }
  141744. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  141745. assert( nDoclist>0 || iDelta==iDocid );
  141746. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  141747. if( nDoclist+nByte>pCsr->nBuffer ){
  141748. char *aNew;
  141749. pCsr->nBuffer = (nDoclist+nByte)*2;
  141750. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  141751. if( !aNew ){
  141752. return SQLITE_NOMEM;
  141753. }
  141754. pCsr->aBuffer = aNew;
  141755. }
  141756. if( isFirst ){
  141757. char *a = &pCsr->aBuffer[nDoclist];
  141758. int nWrite;
  141759. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  141760. if( nWrite ){
  141761. iPrev = iDocid;
  141762. nDoclist += nWrite;
  141763. }
  141764. }else{
  141765. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  141766. iPrev = iDocid;
  141767. if( isRequirePos ){
  141768. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  141769. nDoclist += nList;
  141770. pCsr->aBuffer[nDoclist++] = '\0';
  141771. }
  141772. }
  141773. }
  141774. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  141775. }
  141776. if( nDoclist>0 ){
  141777. pCsr->aDoclist = pCsr->aBuffer;
  141778. pCsr->nDoclist = nDoclist;
  141779. rc = SQLITE_ROW;
  141780. }
  141781. }
  141782. pCsr->nAdvance = nMerge;
  141783. }while( rc==SQLITE_OK );
  141784. return rc;
  141785. }
  141786. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  141787. Fts3MultiSegReader *pCsr /* Cursor object */
  141788. ){
  141789. if( pCsr ){
  141790. int i;
  141791. for(i=0; i<pCsr->nSegment; i++){
  141792. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  141793. }
  141794. sqlite3_free(pCsr->apSegment);
  141795. sqlite3_free(pCsr->aBuffer);
  141796. pCsr->nSegment = 0;
  141797. pCsr->apSegment = 0;
  141798. pCsr->aBuffer = 0;
  141799. }
  141800. }
  141801. /*
  141802. ** Decode the "end_block" field, selected by column iCol of the SELECT
  141803. ** statement passed as the first argument.
  141804. **
  141805. ** The "end_block" field may contain either an integer, or a text field
  141806. ** containing the text representation of two non-negative integers separated
  141807. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  141808. ** to the integer value and *pnByte to zero before returning. In the second,
  141809. ** set *piEndBlock to the first value and *pnByte to the second.
  141810. */
  141811. static void fts3ReadEndBlockField(
  141812. sqlite3_stmt *pStmt,
  141813. int iCol,
  141814. i64 *piEndBlock,
  141815. i64 *pnByte
  141816. ){
  141817. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  141818. if( zText ){
  141819. int i;
  141820. int iMul = 1;
  141821. i64 iVal = 0;
  141822. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  141823. iVal = iVal*10 + (zText[i] - '0');
  141824. }
  141825. *piEndBlock = iVal;
  141826. while( zText[i]==' ' ) i++;
  141827. iVal = 0;
  141828. if( zText[i]=='-' ){
  141829. i++;
  141830. iMul = -1;
  141831. }
  141832. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  141833. iVal = iVal*10 + (zText[i] - '0');
  141834. }
  141835. *pnByte = (iVal * (i64)iMul);
  141836. }
  141837. }
  141838. /*
  141839. ** A segment of size nByte bytes has just been written to absolute level
  141840. ** iAbsLevel. Promote any segments that should be promoted as a result.
  141841. */
  141842. static int fts3PromoteSegments(
  141843. Fts3Table *p, /* FTS table handle */
  141844. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  141845. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  141846. ){
  141847. int rc = SQLITE_OK;
  141848. sqlite3_stmt *pRange;
  141849. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  141850. if( rc==SQLITE_OK ){
  141851. int bOk = 0;
  141852. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  141853. i64 nLimit = (nByte*3)/2;
  141854. /* Loop through all entries in the %_segdir table corresponding to
  141855. ** segments in this index on levels greater than iAbsLevel. If there is
  141856. ** at least one such segment, and it is possible to determine that all
  141857. ** such segments are smaller than nLimit bytes in size, they will be
  141858. ** promoted to level iAbsLevel. */
  141859. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  141860. sqlite3_bind_int64(pRange, 2, iLast);
  141861. while( SQLITE_ROW==sqlite3_step(pRange) ){
  141862. i64 nSize = 0, dummy;
  141863. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  141864. if( nSize<=0 || nSize>nLimit ){
  141865. /* If nSize==0, then the %_segdir.end_block field does not not
  141866. ** contain a size value. This happens if it was written by an
  141867. ** old version of FTS. In this case it is not possible to determine
  141868. ** the size of the segment, and so segment promotion does not
  141869. ** take place. */
  141870. bOk = 0;
  141871. break;
  141872. }
  141873. bOk = 1;
  141874. }
  141875. rc = sqlite3_reset(pRange);
  141876. if( bOk ){
  141877. int iIdx = 0;
  141878. sqlite3_stmt *pUpdate1 = 0;
  141879. sqlite3_stmt *pUpdate2 = 0;
  141880. if( rc==SQLITE_OK ){
  141881. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  141882. }
  141883. if( rc==SQLITE_OK ){
  141884. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  141885. }
  141886. if( rc==SQLITE_OK ){
  141887. /* Loop through all %_segdir entries for segments in this index with
  141888. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  141889. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  141890. ** oldest segment in the range, 1 for the next oldest, and so on.
  141891. **
  141892. ** In other words, move all segments being promoted to level -1,
  141893. ** setting the "idx" fields as appropriate to keep them in the same
  141894. ** order. The contents of level -1 (which is never used, except
  141895. ** transiently here), will be moved back to level iAbsLevel below. */
  141896. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  141897. while( SQLITE_ROW==sqlite3_step(pRange) ){
  141898. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  141899. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  141900. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  141901. sqlite3_step(pUpdate1);
  141902. rc = sqlite3_reset(pUpdate1);
  141903. if( rc!=SQLITE_OK ){
  141904. sqlite3_reset(pRange);
  141905. break;
  141906. }
  141907. }
  141908. }
  141909. if( rc==SQLITE_OK ){
  141910. rc = sqlite3_reset(pRange);
  141911. }
  141912. /* Move level -1 to level iAbsLevel */
  141913. if( rc==SQLITE_OK ){
  141914. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  141915. sqlite3_step(pUpdate2);
  141916. rc = sqlite3_reset(pUpdate2);
  141917. }
  141918. }
  141919. }
  141920. return rc;
  141921. }
  141922. /*
  141923. ** Merge all level iLevel segments in the database into a single
  141924. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  141925. ** single segment with a level equal to the numerically largest level
  141926. ** currently present in the database.
  141927. **
  141928. ** If this function is called with iLevel<0, but there is only one
  141929. ** segment in the database, SQLITE_DONE is returned immediately.
  141930. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  141931. ** an SQLite error code is returned.
  141932. */
  141933. static int fts3SegmentMerge(
  141934. Fts3Table *p,
  141935. int iLangid, /* Language id to merge */
  141936. int iIndex, /* Index in p->aIndex[] to merge */
  141937. int iLevel /* Level to merge */
  141938. ){
  141939. int rc; /* Return code */
  141940. int iIdx = 0; /* Index of new segment */
  141941. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  141942. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  141943. Fts3SegFilter filter; /* Segment term filter condition */
  141944. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  141945. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  141946. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  141947. assert( iLevel==FTS3_SEGCURSOR_ALL
  141948. || iLevel==FTS3_SEGCURSOR_PENDING
  141949. || iLevel>=0
  141950. );
  141951. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  141952. assert( iIndex>=0 && iIndex<p->nIndex );
  141953. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  141954. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  141955. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  141956. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  141957. if( rc!=SQLITE_OK ) goto finished;
  141958. }
  141959. if( iLevel==FTS3_SEGCURSOR_ALL ){
  141960. /* This call is to merge all segments in the database to a single
  141961. ** segment. The level of the new segment is equal to the numerically
  141962. ** greatest segment level currently present in the database for this
  141963. ** index. The idx of the new segment is always 0. */
  141964. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  141965. rc = SQLITE_DONE;
  141966. goto finished;
  141967. }
  141968. iNewLevel = iMaxLevel;
  141969. bIgnoreEmpty = 1;
  141970. }else{
  141971. /* This call is to merge all segments at level iLevel. find the next
  141972. ** available segment index at level iLevel+1. The call to
  141973. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  141974. ** a single iLevel+2 segment if necessary. */
  141975. assert( FTS3_SEGCURSOR_PENDING==-1 );
  141976. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  141977. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  141978. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  141979. }
  141980. if( rc!=SQLITE_OK ) goto finished;
  141981. assert( csr.nSegment>0 );
  141982. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  141983. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  141984. memset(&filter, 0, sizeof(Fts3SegFilter));
  141985. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  141986. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  141987. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  141988. while( SQLITE_OK==rc ){
  141989. rc = sqlite3Fts3SegReaderStep(p, &csr);
  141990. if( rc!=SQLITE_ROW ) break;
  141991. rc = fts3SegWriterAdd(p, &pWriter, 1,
  141992. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  141993. }
  141994. if( rc!=SQLITE_OK ) goto finished;
  141995. assert( pWriter || bIgnoreEmpty );
  141996. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  141997. rc = fts3DeleteSegdir(
  141998. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  141999. );
  142000. if( rc!=SQLITE_OK ) goto finished;
  142001. }
  142002. if( pWriter ){
  142003. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  142004. if( rc==SQLITE_OK ){
  142005. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  142006. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  142007. }
  142008. }
  142009. }
  142010. finished:
  142011. fts3SegWriterFree(pWriter);
  142012. sqlite3Fts3SegReaderFinish(&csr);
  142013. return rc;
  142014. }
  142015. /*
  142016. ** Flush the contents of pendingTerms to level 0 segments.
  142017. */
  142018. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  142019. int rc = SQLITE_OK;
  142020. int i;
  142021. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  142022. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  142023. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  142024. }
  142025. sqlite3Fts3PendingTermsClear(p);
  142026. /* Determine the auto-incr-merge setting if unknown. If enabled,
  142027. ** estimate the number of leaf blocks of content to be written
  142028. */
  142029. if( rc==SQLITE_OK && p->bHasStat
  142030. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  142031. ){
  142032. sqlite3_stmt *pStmt = 0;
  142033. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  142034. if( rc==SQLITE_OK ){
  142035. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  142036. rc = sqlite3_step(pStmt);
  142037. if( rc==SQLITE_ROW ){
  142038. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  142039. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  142040. }else if( rc==SQLITE_DONE ){
  142041. p->nAutoincrmerge = 0;
  142042. }
  142043. rc = sqlite3_reset(pStmt);
  142044. }
  142045. }
  142046. return rc;
  142047. }
  142048. /*
  142049. ** Encode N integers as varints into a blob.
  142050. */
  142051. static void fts3EncodeIntArray(
  142052. int N, /* The number of integers to encode */
  142053. u32 *a, /* The integer values */
  142054. char *zBuf, /* Write the BLOB here */
  142055. int *pNBuf /* Write number of bytes if zBuf[] used here */
  142056. ){
  142057. int i, j;
  142058. for(i=j=0; i<N; i++){
  142059. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  142060. }
  142061. *pNBuf = j;
  142062. }
  142063. /*
  142064. ** Decode a blob of varints into N integers
  142065. */
  142066. static void fts3DecodeIntArray(
  142067. int N, /* The number of integers to decode */
  142068. u32 *a, /* Write the integer values */
  142069. const char *zBuf, /* The BLOB containing the varints */
  142070. int nBuf /* size of the BLOB */
  142071. ){
  142072. int i, j;
  142073. UNUSED_PARAMETER(nBuf);
  142074. for(i=j=0; i<N; i++){
  142075. sqlite3_int64 x;
  142076. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  142077. assert(j<=nBuf);
  142078. a[i] = (u32)(x & 0xffffffff);
  142079. }
  142080. }
  142081. /*
  142082. ** Insert the sizes (in tokens) for each column of the document
  142083. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  142084. ** a blob of varints.
  142085. */
  142086. static void fts3InsertDocsize(
  142087. int *pRC, /* Result code */
  142088. Fts3Table *p, /* Table into which to insert */
  142089. u32 *aSz /* Sizes of each column, in tokens */
  142090. ){
  142091. char *pBlob; /* The BLOB encoding of the document size */
  142092. int nBlob; /* Number of bytes in the BLOB */
  142093. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  142094. int rc; /* Result code from subfunctions */
  142095. if( *pRC ) return;
  142096. pBlob = sqlite3_malloc( 10*p->nColumn );
  142097. if( pBlob==0 ){
  142098. *pRC = SQLITE_NOMEM;
  142099. return;
  142100. }
  142101. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  142102. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  142103. if( rc ){
  142104. sqlite3_free(pBlob);
  142105. *pRC = rc;
  142106. return;
  142107. }
  142108. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  142109. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  142110. sqlite3_step(pStmt);
  142111. *pRC = sqlite3_reset(pStmt);
  142112. }
  142113. /*
  142114. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  142115. ** where N is the number of user defined columns in the fts3 table plus
  142116. ** two. If nCol is the number of user defined columns, then values of the
  142117. ** varints are set as follows:
  142118. **
  142119. ** Varint 0: Total number of rows in the table.
  142120. **
  142121. ** Varint 1..nCol: For each column, the total number of tokens stored in
  142122. ** the column for all rows of the table.
  142123. **
  142124. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  142125. ** columns of all rows of the table.
  142126. **
  142127. */
  142128. static void fts3UpdateDocTotals(
  142129. int *pRC, /* The result code */
  142130. Fts3Table *p, /* Table being updated */
  142131. u32 *aSzIns, /* Size increases */
  142132. u32 *aSzDel, /* Size decreases */
  142133. int nChng /* Change in the number of documents */
  142134. ){
  142135. char *pBlob; /* Storage for BLOB written into %_stat */
  142136. int nBlob; /* Size of BLOB written into %_stat */
  142137. u32 *a; /* Array of integers that becomes the BLOB */
  142138. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  142139. int i; /* Loop counter */
  142140. int rc; /* Result code from subfunctions */
  142141. const int nStat = p->nColumn+2;
  142142. if( *pRC ) return;
  142143. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  142144. if( a==0 ){
  142145. *pRC = SQLITE_NOMEM;
  142146. return;
  142147. }
  142148. pBlob = (char*)&a[nStat];
  142149. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  142150. if( rc ){
  142151. sqlite3_free(a);
  142152. *pRC = rc;
  142153. return;
  142154. }
  142155. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  142156. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  142157. fts3DecodeIntArray(nStat, a,
  142158. sqlite3_column_blob(pStmt, 0),
  142159. sqlite3_column_bytes(pStmt, 0));
  142160. }else{
  142161. memset(a, 0, sizeof(u32)*(nStat) );
  142162. }
  142163. rc = sqlite3_reset(pStmt);
  142164. if( rc!=SQLITE_OK ){
  142165. sqlite3_free(a);
  142166. *pRC = rc;
  142167. return;
  142168. }
  142169. if( nChng<0 && a[0]<(u32)(-nChng) ){
  142170. a[0] = 0;
  142171. }else{
  142172. a[0] += nChng;
  142173. }
  142174. for(i=0; i<p->nColumn+1; i++){
  142175. u32 x = a[i+1];
  142176. if( x+aSzIns[i] < aSzDel[i] ){
  142177. x = 0;
  142178. }else{
  142179. x = x + aSzIns[i] - aSzDel[i];
  142180. }
  142181. a[i+1] = x;
  142182. }
  142183. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  142184. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  142185. if( rc ){
  142186. sqlite3_free(a);
  142187. *pRC = rc;
  142188. return;
  142189. }
  142190. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  142191. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  142192. sqlite3_step(pStmt);
  142193. *pRC = sqlite3_reset(pStmt);
  142194. sqlite3_free(a);
  142195. }
  142196. /*
  142197. ** Merge the entire database so that there is one segment for each
  142198. ** iIndex/iLangid combination.
  142199. */
  142200. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  142201. int bSeenDone = 0;
  142202. int rc;
  142203. sqlite3_stmt *pAllLangid = 0;
  142204. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  142205. if( rc==SQLITE_OK ){
  142206. int rc2;
  142207. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  142208. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  142209. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  142210. int i;
  142211. int iLangid = sqlite3_column_int(pAllLangid, 0);
  142212. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  142213. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  142214. if( rc==SQLITE_DONE ){
  142215. bSeenDone = 1;
  142216. rc = SQLITE_OK;
  142217. }
  142218. }
  142219. }
  142220. rc2 = sqlite3_reset(pAllLangid);
  142221. if( rc==SQLITE_OK ) rc = rc2;
  142222. }
  142223. sqlite3Fts3SegmentsClose(p);
  142224. sqlite3Fts3PendingTermsClear(p);
  142225. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  142226. }
  142227. /*
  142228. ** This function is called when the user executes the following statement:
  142229. **
  142230. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  142231. **
  142232. ** The entire FTS index is discarded and rebuilt. If the table is one
  142233. ** created using the content=xxx option, then the new index is based on
  142234. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  142235. ** on the contents of the %_content table.
  142236. */
  142237. static int fts3DoRebuild(Fts3Table *p){
  142238. int rc; /* Return Code */
  142239. rc = fts3DeleteAll(p, 0);
  142240. if( rc==SQLITE_OK ){
  142241. u32 *aSz = 0;
  142242. u32 *aSzIns = 0;
  142243. u32 *aSzDel = 0;
  142244. sqlite3_stmt *pStmt = 0;
  142245. int nEntry = 0;
  142246. /* Compose and prepare an SQL statement to loop through the content table */
  142247. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  142248. if( !zSql ){
  142249. rc = SQLITE_NOMEM;
  142250. }else{
  142251. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  142252. sqlite3_free(zSql);
  142253. }
  142254. if( rc==SQLITE_OK ){
  142255. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  142256. aSz = (u32 *)sqlite3_malloc(nByte);
  142257. if( aSz==0 ){
  142258. rc = SQLITE_NOMEM;
  142259. }else{
  142260. memset(aSz, 0, nByte);
  142261. aSzIns = &aSz[p->nColumn+1];
  142262. aSzDel = &aSzIns[p->nColumn+1];
  142263. }
  142264. }
  142265. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  142266. int iCol;
  142267. int iLangid = langidFromSelect(p, pStmt);
  142268. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  142269. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  142270. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  142271. if( p->abNotindexed[iCol]==0 ){
  142272. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  142273. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  142274. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  142275. }
  142276. }
  142277. if( p->bHasDocsize ){
  142278. fts3InsertDocsize(&rc, p, aSz);
  142279. }
  142280. if( rc!=SQLITE_OK ){
  142281. sqlite3_finalize(pStmt);
  142282. pStmt = 0;
  142283. }else{
  142284. nEntry++;
  142285. for(iCol=0; iCol<=p->nColumn; iCol++){
  142286. aSzIns[iCol] += aSz[iCol];
  142287. }
  142288. }
  142289. }
  142290. if( p->bFts4 ){
  142291. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  142292. }
  142293. sqlite3_free(aSz);
  142294. if( pStmt ){
  142295. int rc2 = sqlite3_finalize(pStmt);
  142296. if( rc==SQLITE_OK ){
  142297. rc = rc2;
  142298. }
  142299. }
  142300. }
  142301. return rc;
  142302. }
  142303. /*
  142304. ** This function opens a cursor used to read the input data for an
  142305. ** incremental merge operation. Specifically, it opens a cursor to scan
  142306. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  142307. ** level iAbsLevel.
  142308. */
  142309. static int fts3IncrmergeCsr(
  142310. Fts3Table *p, /* FTS3 table handle */
  142311. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  142312. int nSeg, /* Number of segments to merge */
  142313. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  142314. ){
  142315. int rc; /* Return Code */
  142316. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  142317. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  142318. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  142319. memset(pCsr, 0, sizeof(*pCsr));
  142320. nByte = sizeof(Fts3SegReader *) * nSeg;
  142321. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  142322. if( pCsr->apSegment==0 ){
  142323. rc = SQLITE_NOMEM;
  142324. }else{
  142325. memset(pCsr->apSegment, 0, nByte);
  142326. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  142327. }
  142328. if( rc==SQLITE_OK ){
  142329. int i;
  142330. int rc2;
  142331. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  142332. assert( pCsr->nSegment==0 );
  142333. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  142334. rc = sqlite3Fts3SegReaderNew(i, 0,
  142335. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  142336. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  142337. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  142338. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  142339. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  142340. &pCsr->apSegment[i]
  142341. );
  142342. pCsr->nSegment++;
  142343. }
  142344. rc2 = sqlite3_reset(pStmt);
  142345. if( rc==SQLITE_OK ) rc = rc2;
  142346. }
  142347. return rc;
  142348. }
  142349. typedef struct IncrmergeWriter IncrmergeWriter;
  142350. typedef struct NodeWriter NodeWriter;
  142351. typedef struct Blob Blob;
  142352. typedef struct NodeReader NodeReader;
  142353. /*
  142354. ** An instance of the following structure is used as a dynamic buffer
  142355. ** to build up nodes or other blobs of data in.
  142356. **
  142357. ** The function blobGrowBuffer() is used to extend the allocation.
  142358. */
  142359. struct Blob {
  142360. char *a; /* Pointer to allocation */
  142361. int n; /* Number of valid bytes of data in a[] */
  142362. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  142363. };
  142364. /*
  142365. ** This structure is used to build up buffers containing segment b-tree
  142366. ** nodes (blocks).
  142367. */
  142368. struct NodeWriter {
  142369. sqlite3_int64 iBlock; /* Current block id */
  142370. Blob key; /* Last key written to the current block */
  142371. Blob block; /* Current block image */
  142372. };
  142373. /*
  142374. ** An object of this type contains the state required to create or append
  142375. ** to an appendable b-tree segment.
  142376. */
  142377. struct IncrmergeWriter {
  142378. int nLeafEst; /* Space allocated for leaf blocks */
  142379. int nWork; /* Number of leaf pages flushed */
  142380. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  142381. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  142382. sqlite3_int64 iStart; /* Block number of first allocated block */
  142383. sqlite3_int64 iEnd; /* Block number of last allocated block */
  142384. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  142385. u8 bNoLeafData; /* If true, store 0 for segment size */
  142386. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  142387. };
  142388. /*
  142389. ** An object of the following type is used to read data from a single
  142390. ** FTS segment node. See the following functions:
  142391. **
  142392. ** nodeReaderInit()
  142393. ** nodeReaderNext()
  142394. ** nodeReaderRelease()
  142395. */
  142396. struct NodeReader {
  142397. const char *aNode;
  142398. int nNode;
  142399. int iOff; /* Current offset within aNode[] */
  142400. /* Output variables. Containing the current node entry. */
  142401. sqlite3_int64 iChild; /* Pointer to child node */
  142402. Blob term; /* Current term */
  142403. const char *aDoclist; /* Pointer to doclist */
  142404. int nDoclist; /* Size of doclist in bytes */
  142405. };
  142406. /*
  142407. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  142408. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  142409. ** bytes in size, extend (realloc) it to be so.
  142410. **
  142411. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  142412. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  142413. ** to reflect the new size of the pBlob->a[] buffer.
  142414. */
  142415. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  142416. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  142417. int nAlloc = nMin;
  142418. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  142419. if( a ){
  142420. pBlob->nAlloc = nAlloc;
  142421. pBlob->a = a;
  142422. }else{
  142423. *pRc = SQLITE_NOMEM;
  142424. }
  142425. }
  142426. }
  142427. /*
  142428. ** Attempt to advance the node-reader object passed as the first argument to
  142429. ** the next entry on the node.
  142430. **
  142431. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  142432. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  142433. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  142434. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  142435. ** variables for the new entry.
  142436. */
  142437. static int nodeReaderNext(NodeReader *p){
  142438. int bFirst = (p->term.n==0); /* True for first term on the node */
  142439. int nPrefix = 0; /* Bytes to copy from previous term */
  142440. int nSuffix = 0; /* Bytes to append to the prefix */
  142441. int rc = SQLITE_OK; /* Return code */
  142442. assert( p->aNode );
  142443. if( p->iChild && bFirst==0 ) p->iChild++;
  142444. if( p->iOff>=p->nNode ){
  142445. /* EOF */
  142446. p->aNode = 0;
  142447. }else{
  142448. if( bFirst==0 ){
  142449. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  142450. }
  142451. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  142452. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  142453. if( rc==SQLITE_OK ){
  142454. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  142455. p->term.n = nPrefix+nSuffix;
  142456. p->iOff += nSuffix;
  142457. if( p->iChild==0 ){
  142458. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  142459. p->aDoclist = &p->aNode[p->iOff];
  142460. p->iOff += p->nDoclist;
  142461. }
  142462. }
  142463. }
  142464. assert( p->iOff<=p->nNode );
  142465. return rc;
  142466. }
  142467. /*
  142468. ** Release all dynamic resources held by node-reader object *p.
  142469. */
  142470. static void nodeReaderRelease(NodeReader *p){
  142471. sqlite3_free(p->term.a);
  142472. }
  142473. /*
  142474. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  142475. **
  142476. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  142477. ** point to the first entry on the node (if any). Otherwise, an SQLite
  142478. ** error code is returned.
  142479. */
  142480. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  142481. memset(p, 0, sizeof(NodeReader));
  142482. p->aNode = aNode;
  142483. p->nNode = nNode;
  142484. /* Figure out if this is a leaf or an internal node. */
  142485. if( p->aNode[0] ){
  142486. /* An internal node. */
  142487. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  142488. }else{
  142489. p->iOff = 1;
  142490. }
  142491. return nodeReaderNext(p);
  142492. }
  142493. /*
  142494. ** This function is called while writing an FTS segment each time a leaf o
  142495. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  142496. ** to be greater than the largest key on the node just written, but smaller
  142497. ** than or equal to the first key that will be written to the next leaf
  142498. ** node.
  142499. **
  142500. ** The block id of the leaf node just written to disk may be found in
  142501. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  142502. */
  142503. static int fts3IncrmergePush(
  142504. Fts3Table *p, /* Fts3 table handle */
  142505. IncrmergeWriter *pWriter, /* Writer object */
  142506. const char *zTerm, /* Term to write to internal node */
  142507. int nTerm /* Bytes at zTerm */
  142508. ){
  142509. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  142510. int iLayer;
  142511. assert( nTerm>0 );
  142512. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  142513. sqlite3_int64 iNextPtr = 0;
  142514. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  142515. int rc = SQLITE_OK;
  142516. int nPrefix;
  142517. int nSuffix;
  142518. int nSpace;
  142519. /* Figure out how much space the key will consume if it is written to
  142520. ** the current node of layer iLayer. Due to the prefix compression,
  142521. ** the space required changes depending on which node the key is to
  142522. ** be added to. */
  142523. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  142524. nSuffix = nTerm - nPrefix;
  142525. nSpace = sqlite3Fts3VarintLen(nPrefix);
  142526. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  142527. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  142528. /* If the current node of layer iLayer contains zero keys, or if adding
  142529. ** the key to it will not cause it to grow to larger than nNodeSize
  142530. ** bytes in size, write the key here. */
  142531. Blob *pBlk = &pNode->block;
  142532. if( pBlk->n==0 ){
  142533. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  142534. if( rc==SQLITE_OK ){
  142535. pBlk->a[0] = (char)iLayer;
  142536. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  142537. }
  142538. }
  142539. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  142540. blobGrowBuffer(&pNode->key, nTerm, &rc);
  142541. if( rc==SQLITE_OK ){
  142542. if( pNode->key.n ){
  142543. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  142544. }
  142545. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  142546. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  142547. pBlk->n += nSuffix;
  142548. memcpy(pNode->key.a, zTerm, nTerm);
  142549. pNode->key.n = nTerm;
  142550. }
  142551. }else{
  142552. /* Otherwise, flush the current node of layer iLayer to disk.
  142553. ** Then allocate a new, empty sibling node. The key will be written
  142554. ** into the parent of this node. */
  142555. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  142556. assert( pNode->block.nAlloc>=p->nNodeSize );
  142557. pNode->block.a[0] = (char)iLayer;
  142558. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  142559. iNextPtr = pNode->iBlock;
  142560. pNode->iBlock++;
  142561. pNode->key.n = 0;
  142562. }
  142563. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  142564. iPtr = iNextPtr;
  142565. }
  142566. assert( 0 );
  142567. return 0;
  142568. }
  142569. /*
  142570. ** Append a term and (optionally) doclist to the FTS segment node currently
  142571. ** stored in blob *pNode. The node need not contain any terms, but the
  142572. ** header must be written before this function is called.
  142573. **
  142574. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  142575. ** followed by the left-hand-child varint for an internal node.
  142576. **
  142577. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  142578. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  142579. ** node, both aDoclist and nDoclist must be passed 0.
  142580. **
  142581. ** If the size of the value in blob pPrev is zero, then this is the first
  142582. ** term written to the node. Otherwise, pPrev contains a copy of the
  142583. ** previous term. Before this function returns, it is updated to contain a
  142584. ** copy of zTerm/nTerm.
  142585. **
  142586. ** It is assumed that the buffer associated with pNode is already large
  142587. ** enough to accommodate the new entry. The buffer associated with pPrev
  142588. ** is extended by this function if requrired.
  142589. **
  142590. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  142591. ** returned. Otherwise, SQLITE_OK.
  142592. */
  142593. static int fts3AppendToNode(
  142594. Blob *pNode, /* Current node image to append to */
  142595. Blob *pPrev, /* Buffer containing previous term written */
  142596. const char *zTerm, /* New term to write */
  142597. int nTerm, /* Size of zTerm in bytes */
  142598. const char *aDoclist, /* Doclist (or NULL) to write */
  142599. int nDoclist /* Size of aDoclist in bytes */
  142600. ){
  142601. int rc = SQLITE_OK; /* Return code */
  142602. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  142603. int nPrefix; /* Size of term prefix in bytes */
  142604. int nSuffix; /* Size of term suffix in bytes */
  142605. /* Node must have already been started. There must be a doclist for a
  142606. ** leaf node, and there must not be a doclist for an internal node. */
  142607. assert( pNode->n>0 );
  142608. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  142609. blobGrowBuffer(pPrev, nTerm, &rc);
  142610. if( rc!=SQLITE_OK ) return rc;
  142611. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  142612. nSuffix = nTerm - nPrefix;
  142613. memcpy(pPrev->a, zTerm, nTerm);
  142614. pPrev->n = nTerm;
  142615. if( bFirst==0 ){
  142616. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  142617. }
  142618. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  142619. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  142620. pNode->n += nSuffix;
  142621. if( aDoclist ){
  142622. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  142623. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  142624. pNode->n += nDoclist;
  142625. }
  142626. assert( pNode->n<=pNode->nAlloc );
  142627. return SQLITE_OK;
  142628. }
  142629. /*
  142630. ** Append the current term and doclist pointed to by cursor pCsr to the
  142631. ** appendable b-tree segment opened for writing by pWriter.
  142632. **
  142633. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  142634. */
  142635. static int fts3IncrmergeAppend(
  142636. Fts3Table *p, /* Fts3 table handle */
  142637. IncrmergeWriter *pWriter, /* Writer object */
  142638. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  142639. ){
  142640. const char *zTerm = pCsr->zTerm;
  142641. int nTerm = pCsr->nTerm;
  142642. const char *aDoclist = pCsr->aDoclist;
  142643. int nDoclist = pCsr->nDoclist;
  142644. int rc = SQLITE_OK; /* Return code */
  142645. int nSpace; /* Total space in bytes required on leaf */
  142646. int nPrefix; /* Size of prefix shared with previous term */
  142647. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  142648. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  142649. pLeaf = &pWriter->aNodeWriter[0];
  142650. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  142651. nSuffix = nTerm - nPrefix;
  142652. nSpace = sqlite3Fts3VarintLen(nPrefix);
  142653. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  142654. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  142655. /* If the current block is not empty, and if adding this term/doclist
  142656. ** to the current block would make it larger than Fts3Table.nNodeSize
  142657. ** bytes, write this block out to the database. */
  142658. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  142659. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  142660. pWriter->nWork++;
  142661. /* Add the current term to the parent node. The term added to the
  142662. ** parent must:
  142663. **
  142664. ** a) be greater than the largest term on the leaf node just written
  142665. ** to the database (still available in pLeaf->key), and
  142666. **
  142667. ** b) be less than or equal to the term about to be added to the new
  142668. ** leaf node (zTerm/nTerm).
  142669. **
  142670. ** In other words, it must be the prefix of zTerm 1 byte longer than
  142671. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  142672. */
  142673. if( rc==SQLITE_OK ){
  142674. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  142675. }
  142676. /* Advance to the next output block */
  142677. pLeaf->iBlock++;
  142678. pLeaf->key.n = 0;
  142679. pLeaf->block.n = 0;
  142680. nSuffix = nTerm;
  142681. nSpace = 1;
  142682. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  142683. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  142684. }
  142685. pWriter->nLeafData += nSpace;
  142686. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  142687. if( rc==SQLITE_OK ){
  142688. if( pLeaf->block.n==0 ){
  142689. pLeaf->block.n = 1;
  142690. pLeaf->block.a[0] = '\0';
  142691. }
  142692. rc = fts3AppendToNode(
  142693. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  142694. );
  142695. }
  142696. return rc;
  142697. }
  142698. /*
  142699. ** This function is called to release all dynamic resources held by the
  142700. ** merge-writer object pWriter, and if no error has occurred, to flush
  142701. ** all outstanding node buffers held by pWriter to disk.
  142702. **
  142703. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  142704. ** is made to write any data to disk. Instead, this function serves only
  142705. ** to release outstanding resources.
  142706. **
  142707. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  142708. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  142709. ** returning.
  142710. */
  142711. static void fts3IncrmergeRelease(
  142712. Fts3Table *p, /* FTS3 table handle */
  142713. IncrmergeWriter *pWriter, /* Merge-writer object */
  142714. int *pRc /* IN/OUT: Error code */
  142715. ){
  142716. int i; /* Used to iterate through non-root layers */
  142717. int iRoot; /* Index of root in pWriter->aNodeWriter */
  142718. NodeWriter *pRoot; /* NodeWriter for root node */
  142719. int rc = *pRc; /* Error code */
  142720. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  142721. ** root node. If the segment fits entirely on a single leaf node, iRoot
  142722. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  142723. ** will be 1. And so on. */
  142724. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  142725. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  142726. if( pNode->block.n>0 ) break;
  142727. assert( *pRc || pNode->block.nAlloc==0 );
  142728. assert( *pRc || pNode->key.nAlloc==0 );
  142729. sqlite3_free(pNode->block.a);
  142730. sqlite3_free(pNode->key.a);
  142731. }
  142732. /* Empty output segment. This is a no-op. */
  142733. if( iRoot<0 ) return;
  142734. /* The entire output segment fits on a single node. Normally, this means
  142735. ** the node would be stored as a blob in the "root" column of the %_segdir
  142736. ** table. However, this is not permitted in this case. The problem is that
  142737. ** space has already been reserved in the %_segments table, and so the
  142738. ** start_block and end_block fields of the %_segdir table must be populated.
  142739. ** And, by design or by accident, released versions of FTS cannot handle
  142740. ** segments that fit entirely on the root node with start_block!=0.
  142741. **
  142742. ** Instead, create a synthetic root node that contains nothing but a
  142743. ** pointer to the single content node. So that the segment consists of a
  142744. ** single leaf and a single interior (root) node.
  142745. **
  142746. ** Todo: Better might be to defer allocating space in the %_segments
  142747. ** table until we are sure it is needed.
  142748. */
  142749. if( iRoot==0 ){
  142750. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  142751. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  142752. if( rc==SQLITE_OK ){
  142753. pBlock->a[0] = 0x01;
  142754. pBlock->n = 1 + sqlite3Fts3PutVarint(
  142755. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  142756. );
  142757. }
  142758. iRoot = 1;
  142759. }
  142760. pRoot = &pWriter->aNodeWriter[iRoot];
  142761. /* Flush all currently outstanding nodes to disk. */
  142762. for(i=0; i<iRoot; i++){
  142763. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  142764. if( pNode->block.n>0 && rc==SQLITE_OK ){
  142765. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  142766. }
  142767. sqlite3_free(pNode->block.a);
  142768. sqlite3_free(pNode->key.a);
  142769. }
  142770. /* Write the %_segdir record. */
  142771. if( rc==SQLITE_OK ){
  142772. rc = fts3WriteSegdir(p,
  142773. pWriter->iAbsLevel+1, /* level */
  142774. pWriter->iIdx, /* idx */
  142775. pWriter->iStart, /* start_block */
  142776. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  142777. pWriter->iEnd, /* end_block */
  142778. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  142779. pRoot->block.a, pRoot->block.n /* root */
  142780. );
  142781. }
  142782. sqlite3_free(pRoot->block.a);
  142783. sqlite3_free(pRoot->key.a);
  142784. *pRc = rc;
  142785. }
  142786. /*
  142787. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  142788. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  142789. ** the other, it is considered to be smaller than the other.
  142790. **
  142791. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  142792. ** if it is greater.
  142793. */
  142794. static int fts3TermCmp(
  142795. const char *zLhs, int nLhs, /* LHS of comparison */
  142796. const char *zRhs, int nRhs /* RHS of comparison */
  142797. ){
  142798. int nCmp = MIN(nLhs, nRhs);
  142799. int res;
  142800. res = memcmp(zLhs, zRhs, nCmp);
  142801. if( res==0 ) res = nLhs - nRhs;
  142802. return res;
  142803. }
  142804. /*
  142805. ** Query to see if the entry in the %_segments table with blockid iEnd is
  142806. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  142807. ** returning. Otherwise, set *pbRes to 0.
  142808. **
  142809. ** Or, if an error occurs while querying the database, return an SQLite
  142810. ** error code. The final value of *pbRes is undefined in this case.
  142811. **
  142812. ** This is used to test if a segment is an "appendable" segment. If it
  142813. ** is, then a NULL entry has been inserted into the %_segments table
  142814. ** with blockid %_segdir.end_block.
  142815. */
  142816. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  142817. int bRes = 0; /* Result to set *pbRes to */
  142818. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  142819. int rc; /* Return code */
  142820. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  142821. if( rc==SQLITE_OK ){
  142822. sqlite3_bind_int64(pCheck, 1, iEnd);
  142823. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  142824. rc = sqlite3_reset(pCheck);
  142825. }
  142826. *pbRes = bRes;
  142827. return rc;
  142828. }
  142829. /*
  142830. ** This function is called when initializing an incremental-merge operation.
  142831. ** It checks if the existing segment with index value iIdx at absolute level
  142832. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  142833. ** merge-writer object *pWriter is initialized to write to it.
  142834. **
  142835. ** An existing segment can be appended to by an incremental merge if:
  142836. **
  142837. ** * It was initially created as an appendable segment (with all required
  142838. ** space pre-allocated), and
  142839. **
  142840. ** * The first key read from the input (arguments zKey and nKey) is
  142841. ** greater than the largest key currently stored in the potential
  142842. ** output segment.
  142843. */
  142844. static int fts3IncrmergeLoad(
  142845. Fts3Table *p, /* Fts3 table handle */
  142846. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  142847. int iIdx, /* Index of candidate output segment */
  142848. const char *zKey, /* First key to write */
  142849. int nKey, /* Number of bytes in nKey */
  142850. IncrmergeWriter *pWriter /* Populate this object */
  142851. ){
  142852. int rc; /* Return code */
  142853. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  142854. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  142855. if( rc==SQLITE_OK ){
  142856. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  142857. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  142858. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  142859. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  142860. int nRoot = 0; /* Size of aRoot[] in bytes */
  142861. int rc2; /* Return code from sqlite3_reset() */
  142862. int bAppendable = 0; /* Set to true if segment is appendable */
  142863. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  142864. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  142865. sqlite3_bind_int(pSelect, 2, iIdx);
  142866. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  142867. iStart = sqlite3_column_int64(pSelect, 1);
  142868. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  142869. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  142870. if( pWriter->nLeafData<0 ){
  142871. pWriter->nLeafData = pWriter->nLeafData * -1;
  142872. }
  142873. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  142874. nRoot = sqlite3_column_bytes(pSelect, 4);
  142875. aRoot = sqlite3_column_blob(pSelect, 4);
  142876. }else{
  142877. return sqlite3_reset(pSelect);
  142878. }
  142879. /* Check for the zero-length marker in the %_segments table */
  142880. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  142881. /* Check that zKey/nKey is larger than the largest key the candidate */
  142882. if( rc==SQLITE_OK && bAppendable ){
  142883. char *aLeaf = 0;
  142884. int nLeaf = 0;
  142885. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  142886. if( rc==SQLITE_OK ){
  142887. NodeReader reader;
  142888. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  142889. rc==SQLITE_OK && reader.aNode;
  142890. rc = nodeReaderNext(&reader)
  142891. ){
  142892. assert( reader.aNode );
  142893. }
  142894. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  142895. bAppendable = 0;
  142896. }
  142897. nodeReaderRelease(&reader);
  142898. }
  142899. sqlite3_free(aLeaf);
  142900. }
  142901. if( rc==SQLITE_OK && bAppendable ){
  142902. /* It is possible to append to this segment. Set up the IncrmergeWriter
  142903. ** object to do so. */
  142904. int i;
  142905. int nHeight = (int)aRoot[0];
  142906. NodeWriter *pNode;
  142907. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  142908. pWriter->iStart = iStart;
  142909. pWriter->iEnd = iEnd;
  142910. pWriter->iAbsLevel = iAbsLevel;
  142911. pWriter->iIdx = iIdx;
  142912. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  142913. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  142914. }
  142915. pNode = &pWriter->aNodeWriter[nHeight];
  142916. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  142917. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  142918. if( rc==SQLITE_OK ){
  142919. memcpy(pNode->block.a, aRoot, nRoot);
  142920. pNode->block.n = nRoot;
  142921. }
  142922. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  142923. NodeReader reader;
  142924. pNode = &pWriter->aNodeWriter[i];
  142925. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  142926. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  142927. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  142928. if( rc==SQLITE_OK ){
  142929. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  142930. pNode->key.n = reader.term.n;
  142931. if( i>0 ){
  142932. char *aBlock = 0;
  142933. int nBlock = 0;
  142934. pNode = &pWriter->aNodeWriter[i-1];
  142935. pNode->iBlock = reader.iChild;
  142936. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  142937. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  142938. if( rc==SQLITE_OK ){
  142939. memcpy(pNode->block.a, aBlock, nBlock);
  142940. pNode->block.n = nBlock;
  142941. }
  142942. sqlite3_free(aBlock);
  142943. }
  142944. }
  142945. nodeReaderRelease(&reader);
  142946. }
  142947. }
  142948. rc2 = sqlite3_reset(pSelect);
  142949. if( rc==SQLITE_OK ) rc = rc2;
  142950. }
  142951. return rc;
  142952. }
  142953. /*
  142954. ** Determine the largest segment index value that exists within absolute
  142955. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  142956. ** one before returning SQLITE_OK. Or, if there are no segments at all
  142957. ** within level iAbsLevel, set *piIdx to zero.
  142958. **
  142959. ** If an error occurs, return an SQLite error code. The final value of
  142960. ** *piIdx is undefined in this case.
  142961. */
  142962. static int fts3IncrmergeOutputIdx(
  142963. Fts3Table *p, /* FTS Table handle */
  142964. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  142965. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  142966. ){
  142967. int rc;
  142968. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  142969. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  142970. if( rc==SQLITE_OK ){
  142971. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  142972. sqlite3_step(pOutputIdx);
  142973. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  142974. rc = sqlite3_reset(pOutputIdx);
  142975. }
  142976. return rc;
  142977. }
  142978. /*
  142979. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  142980. ** with idx value iIdx.
  142981. **
  142982. ** In the %_segdir table, a segment is defined by the values in three
  142983. ** columns:
  142984. **
  142985. ** start_block
  142986. ** leaves_end_block
  142987. ** end_block
  142988. **
  142989. ** When an appendable segment is allocated, it is estimated that the
  142990. ** maximum number of leaf blocks that may be required is the sum of the
  142991. ** number of leaf blocks consumed by the input segments, plus the number
  142992. ** of input segments, multiplied by two. This value is stored in stack
  142993. ** variable nLeafEst.
  142994. **
  142995. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  142996. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  142997. ** array of leaf nodes starts at the first block allocated. The array
  142998. ** of interior nodes that are parents of the leaf nodes start at block
  142999. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  143000. **
  143001. ** In the actual code below, the value "16" is replaced with the
  143002. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  143003. */
  143004. static int fts3IncrmergeWriter(
  143005. Fts3Table *p, /* Fts3 table handle */
  143006. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  143007. int iIdx, /* Index of new output segment */
  143008. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  143009. IncrmergeWriter *pWriter /* Populate this object */
  143010. ){
  143011. int rc; /* Return Code */
  143012. int i; /* Iterator variable */
  143013. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  143014. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  143015. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  143016. /* Calculate nLeafEst. */
  143017. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  143018. if( rc==SQLITE_OK ){
  143019. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  143020. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  143021. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  143022. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  143023. }
  143024. rc = sqlite3_reset(pLeafEst);
  143025. }
  143026. if( rc!=SQLITE_OK ) return rc;
  143027. /* Calculate the first block to use in the output segment */
  143028. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  143029. if( rc==SQLITE_OK ){
  143030. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  143031. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  143032. pWriter->iEnd = pWriter->iStart - 1;
  143033. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  143034. }
  143035. rc = sqlite3_reset(pFirstBlock);
  143036. }
  143037. if( rc!=SQLITE_OK ) return rc;
  143038. /* Insert the marker in the %_segments table to make sure nobody tries
  143039. ** to steal the space just allocated. This is also used to identify
  143040. ** appendable segments. */
  143041. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  143042. if( rc!=SQLITE_OK ) return rc;
  143043. pWriter->iAbsLevel = iAbsLevel;
  143044. pWriter->nLeafEst = nLeafEst;
  143045. pWriter->iIdx = iIdx;
  143046. /* Set up the array of NodeWriter objects */
  143047. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  143048. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  143049. }
  143050. return SQLITE_OK;
  143051. }
  143052. /*
  143053. ** Remove an entry from the %_segdir table. This involves running the
  143054. ** following two statements:
  143055. **
  143056. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  143057. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  143058. **
  143059. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  143060. ** statement ensures that the remaining segments have contiguously allocated
  143061. ** idx values.
  143062. */
  143063. static int fts3RemoveSegdirEntry(
  143064. Fts3Table *p, /* FTS3 table handle */
  143065. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  143066. int iIdx /* Index of %_segdir entry to delete */
  143067. ){
  143068. int rc; /* Return code */
  143069. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  143070. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  143071. if( rc==SQLITE_OK ){
  143072. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  143073. sqlite3_bind_int(pDelete, 2, iIdx);
  143074. sqlite3_step(pDelete);
  143075. rc = sqlite3_reset(pDelete);
  143076. }
  143077. return rc;
  143078. }
  143079. /*
  143080. ** One or more segments have just been removed from absolute level iAbsLevel.
  143081. ** Update the 'idx' values of the remaining segments in the level so that
  143082. ** the idx values are a contiguous sequence starting from 0.
  143083. */
  143084. static int fts3RepackSegdirLevel(
  143085. Fts3Table *p, /* FTS3 table handle */
  143086. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  143087. ){
  143088. int rc; /* Return code */
  143089. int *aIdx = 0; /* Array of remaining idx values */
  143090. int nIdx = 0; /* Valid entries in aIdx[] */
  143091. int nAlloc = 0; /* Allocated size of aIdx[] */
  143092. int i; /* Iterator variable */
  143093. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  143094. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  143095. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  143096. if( rc==SQLITE_OK ){
  143097. int rc2;
  143098. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  143099. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  143100. if( nIdx>=nAlloc ){
  143101. int *aNew;
  143102. nAlloc += 16;
  143103. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  143104. if( !aNew ){
  143105. rc = SQLITE_NOMEM;
  143106. break;
  143107. }
  143108. aIdx = aNew;
  143109. }
  143110. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  143111. }
  143112. rc2 = sqlite3_reset(pSelect);
  143113. if( rc==SQLITE_OK ) rc = rc2;
  143114. }
  143115. if( rc==SQLITE_OK ){
  143116. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  143117. }
  143118. if( rc==SQLITE_OK ){
  143119. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  143120. }
  143121. assert( p->bIgnoreSavepoint==0 );
  143122. p->bIgnoreSavepoint = 1;
  143123. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  143124. if( aIdx[i]!=i ){
  143125. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  143126. sqlite3_bind_int(pUpdate, 1, i);
  143127. sqlite3_step(pUpdate);
  143128. rc = sqlite3_reset(pUpdate);
  143129. }
  143130. }
  143131. p->bIgnoreSavepoint = 0;
  143132. sqlite3_free(aIdx);
  143133. return rc;
  143134. }
  143135. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  143136. pNode->a[0] = (char)iHeight;
  143137. if( iChild ){
  143138. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  143139. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  143140. }else{
  143141. assert( pNode->nAlloc>=1 );
  143142. pNode->n = 1;
  143143. }
  143144. }
  143145. /*
  143146. ** The first two arguments are a pointer to and the size of a segment b-tree
  143147. ** node. The node may be a leaf or an internal node.
  143148. **
  143149. ** This function creates a new node image in blob object *pNew by copying
  143150. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  143151. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  143152. */
  143153. static int fts3TruncateNode(
  143154. const char *aNode, /* Current node image */
  143155. int nNode, /* Size of aNode in bytes */
  143156. Blob *pNew, /* OUT: Write new node image here */
  143157. const char *zTerm, /* Omit all terms smaller than this */
  143158. int nTerm, /* Size of zTerm in bytes */
  143159. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  143160. ){
  143161. NodeReader reader; /* Reader object */
  143162. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  143163. int rc = SQLITE_OK; /* Return code */
  143164. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  143165. /* Allocate required output space */
  143166. blobGrowBuffer(pNew, nNode, &rc);
  143167. if( rc!=SQLITE_OK ) return rc;
  143168. pNew->n = 0;
  143169. /* Populate new node buffer */
  143170. for(rc = nodeReaderInit(&reader, aNode, nNode);
  143171. rc==SQLITE_OK && reader.aNode;
  143172. rc = nodeReaderNext(&reader)
  143173. ){
  143174. if( pNew->n==0 ){
  143175. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  143176. if( res<0 || (bLeaf==0 && res==0) ) continue;
  143177. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  143178. *piBlock = reader.iChild;
  143179. }
  143180. rc = fts3AppendToNode(
  143181. pNew, &prev, reader.term.a, reader.term.n,
  143182. reader.aDoclist, reader.nDoclist
  143183. );
  143184. if( rc!=SQLITE_OK ) break;
  143185. }
  143186. if( pNew->n==0 ){
  143187. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  143188. *piBlock = reader.iChild;
  143189. }
  143190. assert( pNew->n<=pNew->nAlloc );
  143191. nodeReaderRelease(&reader);
  143192. sqlite3_free(prev.a);
  143193. return rc;
  143194. }
  143195. /*
  143196. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  143197. ** level iAbsLevel. This may involve deleting entries from the %_segments
  143198. ** table, and modifying existing entries in both the %_segments and %_segdir
  143199. ** tables.
  143200. **
  143201. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  143202. ** SQLite error code otherwise.
  143203. */
  143204. static int fts3TruncateSegment(
  143205. Fts3Table *p, /* FTS3 table handle */
  143206. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  143207. int iIdx, /* Index within level of segment to modify */
  143208. const char *zTerm, /* Remove terms smaller than this */
  143209. int nTerm /* Number of bytes in buffer zTerm */
  143210. ){
  143211. int rc = SQLITE_OK; /* Return code */
  143212. Blob root = {0,0,0}; /* New root page image */
  143213. Blob block = {0,0,0}; /* Buffer used for any other block */
  143214. sqlite3_int64 iBlock = 0; /* Block id */
  143215. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  143216. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  143217. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  143218. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  143219. if( rc==SQLITE_OK ){
  143220. int rc2; /* sqlite3_reset() return code */
  143221. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  143222. sqlite3_bind_int(pFetch, 2, iIdx);
  143223. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  143224. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  143225. int nRoot = sqlite3_column_bytes(pFetch, 4);
  143226. iOldStart = sqlite3_column_int64(pFetch, 1);
  143227. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  143228. }
  143229. rc2 = sqlite3_reset(pFetch);
  143230. if( rc==SQLITE_OK ) rc = rc2;
  143231. }
  143232. while( rc==SQLITE_OK && iBlock ){
  143233. char *aBlock = 0;
  143234. int nBlock = 0;
  143235. iNewStart = iBlock;
  143236. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  143237. if( rc==SQLITE_OK ){
  143238. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  143239. }
  143240. if( rc==SQLITE_OK ){
  143241. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  143242. }
  143243. sqlite3_free(aBlock);
  143244. }
  143245. /* Variable iNewStart now contains the first valid leaf node. */
  143246. if( rc==SQLITE_OK && iNewStart ){
  143247. sqlite3_stmt *pDel = 0;
  143248. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  143249. if( rc==SQLITE_OK ){
  143250. sqlite3_bind_int64(pDel, 1, iOldStart);
  143251. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  143252. sqlite3_step(pDel);
  143253. rc = sqlite3_reset(pDel);
  143254. }
  143255. }
  143256. if( rc==SQLITE_OK ){
  143257. sqlite3_stmt *pChomp = 0;
  143258. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  143259. if( rc==SQLITE_OK ){
  143260. sqlite3_bind_int64(pChomp, 1, iNewStart);
  143261. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  143262. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  143263. sqlite3_bind_int(pChomp, 4, iIdx);
  143264. sqlite3_step(pChomp);
  143265. rc = sqlite3_reset(pChomp);
  143266. }
  143267. }
  143268. sqlite3_free(root.a);
  143269. sqlite3_free(block.a);
  143270. return rc;
  143271. }
  143272. /*
  143273. ** This function is called after an incrmental-merge operation has run to
  143274. ** merge (or partially merge) two or more segments from absolute level
  143275. ** iAbsLevel.
  143276. **
  143277. ** Each input segment is either removed from the db completely (if all of
  143278. ** its data was copied to the output segment by the incrmerge operation)
  143279. ** or modified in place so that it no longer contains those entries that
  143280. ** have been duplicated in the output segment.
  143281. */
  143282. static int fts3IncrmergeChomp(
  143283. Fts3Table *p, /* FTS table handle */
  143284. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  143285. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  143286. int *pnRem /* Number of segments not deleted */
  143287. ){
  143288. int i;
  143289. int nRem = 0;
  143290. int rc = SQLITE_OK;
  143291. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  143292. Fts3SegReader *pSeg = 0;
  143293. int j;
  143294. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  143295. ** somewhere in the pCsr->apSegment[] array. */
  143296. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  143297. pSeg = pCsr->apSegment[j];
  143298. if( pSeg->iIdx==i ) break;
  143299. }
  143300. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  143301. if( pSeg->aNode==0 ){
  143302. /* Seg-reader is at EOF. Remove the entire input segment. */
  143303. rc = fts3DeleteSegment(p, pSeg);
  143304. if( rc==SQLITE_OK ){
  143305. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  143306. }
  143307. *pnRem = 0;
  143308. }else{
  143309. /* The incremental merge did not copy all the data from this
  143310. ** segment to the upper level. The segment is modified in place
  143311. ** so that it contains no keys smaller than zTerm/nTerm. */
  143312. const char *zTerm = pSeg->zTerm;
  143313. int nTerm = pSeg->nTerm;
  143314. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  143315. nRem++;
  143316. }
  143317. }
  143318. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  143319. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  143320. }
  143321. *pnRem = nRem;
  143322. return rc;
  143323. }
  143324. /*
  143325. ** Store an incr-merge hint in the database.
  143326. */
  143327. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  143328. sqlite3_stmt *pReplace = 0;
  143329. int rc; /* Return code */
  143330. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  143331. if( rc==SQLITE_OK ){
  143332. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  143333. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  143334. sqlite3_step(pReplace);
  143335. rc = sqlite3_reset(pReplace);
  143336. }
  143337. return rc;
  143338. }
  143339. /*
  143340. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  143341. ** exists, is stored in the rowid==1 row of the %_stat table.
  143342. **
  143343. ** If successful, populate blob *pHint with the value read from the %_stat
  143344. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  143345. ** SQLite error code.
  143346. */
  143347. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  143348. sqlite3_stmt *pSelect = 0;
  143349. int rc;
  143350. pHint->n = 0;
  143351. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  143352. if( rc==SQLITE_OK ){
  143353. int rc2;
  143354. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  143355. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  143356. const char *aHint = sqlite3_column_blob(pSelect, 0);
  143357. int nHint = sqlite3_column_bytes(pSelect, 0);
  143358. if( aHint ){
  143359. blobGrowBuffer(pHint, nHint, &rc);
  143360. if( rc==SQLITE_OK ){
  143361. memcpy(pHint->a, aHint, nHint);
  143362. pHint->n = nHint;
  143363. }
  143364. }
  143365. }
  143366. rc2 = sqlite3_reset(pSelect);
  143367. if( rc==SQLITE_OK ) rc = rc2;
  143368. }
  143369. return rc;
  143370. }
  143371. /*
  143372. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  143373. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  143374. ** consists of two varints, the absolute level number of the input segments
  143375. ** and the number of input segments.
  143376. **
  143377. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  143378. ** set *pRc to an SQLite error code before returning.
  143379. */
  143380. static void fts3IncrmergeHintPush(
  143381. Blob *pHint, /* Hint blob to append to */
  143382. i64 iAbsLevel, /* First varint to store in hint */
  143383. int nInput, /* Second varint to store in hint */
  143384. int *pRc /* IN/OUT: Error code */
  143385. ){
  143386. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  143387. if( *pRc==SQLITE_OK ){
  143388. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  143389. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  143390. }
  143391. }
  143392. /*
  143393. ** Read the last entry (most recently pushed) from the hint blob *pHint
  143394. ** and then remove the entry. Write the two values read to *piAbsLevel and
  143395. ** *pnInput before returning.
  143396. **
  143397. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  143398. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  143399. */
  143400. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  143401. const int nHint = pHint->n;
  143402. int i;
  143403. i = pHint->n-2;
  143404. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  143405. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  143406. pHint->n = i;
  143407. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  143408. i += fts3GetVarint32(&pHint->a[i], pnInput);
  143409. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  143410. return SQLITE_OK;
  143411. }
  143412. /*
  143413. ** Attempt an incremental merge that writes nMerge leaf blocks.
  143414. **
  143415. ** Incremental merges happen nMin segments at a time. The segments
  143416. ** to be merged are the nMin oldest segments (the ones with the smallest
  143417. ** values for the _segdir.idx field) in the highest level that contains
  143418. ** at least nMin segments. Multiple merges might occur in an attempt to
  143419. ** write the quota of nMerge leaf blocks.
  143420. */
  143421. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  143422. int rc; /* Return code */
  143423. int nRem = nMerge; /* Number of leaf pages yet to be written */
  143424. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  143425. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  143426. IncrmergeWriter *pWriter; /* Writer object */
  143427. int nSeg = 0; /* Number of input segments */
  143428. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  143429. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  143430. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  143431. /* Allocate space for the cursor, filter and writer objects */
  143432. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  143433. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  143434. if( !pWriter ) return SQLITE_NOMEM;
  143435. pFilter = (Fts3SegFilter *)&pWriter[1];
  143436. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  143437. rc = fts3IncrmergeHintLoad(p, &hint);
  143438. while( rc==SQLITE_OK && nRem>0 ){
  143439. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  143440. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  143441. int bUseHint = 0; /* True if attempting to append */
  143442. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  143443. /* Search the %_segdir table for the absolute level with the smallest
  143444. ** relative level number that contains at least nMin segments, if any.
  143445. ** If one is found, set iAbsLevel to the absolute level number and
  143446. ** nSeg to nMin. If no level with at least nMin segments can be found,
  143447. ** set nSeg to -1.
  143448. */
  143449. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  143450. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  143451. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  143452. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  143453. nSeg = sqlite3_column_int(pFindLevel, 1);
  143454. assert( nSeg>=2 );
  143455. }else{
  143456. nSeg = -1;
  143457. }
  143458. rc = sqlite3_reset(pFindLevel);
  143459. /* If the hint read from the %_stat table is not empty, check if the
  143460. ** last entry in it specifies a relative level smaller than or equal
  143461. ** to the level identified by the block above (if any). If so, this
  143462. ** iteration of the loop will work on merging at the hinted level.
  143463. */
  143464. if( rc==SQLITE_OK && hint.n ){
  143465. int nHint = hint.n;
  143466. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  143467. int nHintSeg = 0; /* Hint number of segments */
  143468. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  143469. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  143470. iAbsLevel = iHintAbsLevel;
  143471. nSeg = nHintSeg;
  143472. bUseHint = 1;
  143473. bDirtyHint = 1;
  143474. }else{
  143475. /* This undoes the effect of the HintPop() above - so that no entry
  143476. ** is removed from the hint blob. */
  143477. hint.n = nHint;
  143478. }
  143479. }
  143480. /* If nSeg is less that zero, then there is no level with at least
  143481. ** nMin segments and no hint in the %_stat table. No work to do.
  143482. ** Exit early in this case. */
  143483. if( nSeg<0 ) break;
  143484. /* Open a cursor to iterate through the contents of the oldest nSeg
  143485. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  143486. ** the 'hint' parameters, it is possible that there are less than nSeg
  143487. ** segments available in level iAbsLevel. In this case, no work is
  143488. ** done on iAbsLevel - fall through to the next iteration of the loop
  143489. ** to start work on some other level. */
  143490. memset(pWriter, 0, nAlloc);
  143491. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  143492. if( rc==SQLITE_OK ){
  143493. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  143494. assert( bUseHint==1 || bUseHint==0 );
  143495. if( iIdx==0 || (bUseHint && iIdx==1) ){
  143496. int bIgnore = 0;
  143497. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  143498. if( bIgnore ){
  143499. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  143500. }
  143501. }
  143502. }
  143503. if( rc==SQLITE_OK ){
  143504. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  143505. }
  143506. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  143507. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  143508. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  143509. ){
  143510. if( bUseHint && iIdx>0 ){
  143511. const char *zKey = pCsr->zTerm;
  143512. int nKey = pCsr->nTerm;
  143513. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  143514. }else{
  143515. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  143516. }
  143517. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  143518. fts3LogMerge(nSeg, iAbsLevel);
  143519. do {
  143520. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  143521. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  143522. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  143523. }while( rc==SQLITE_ROW );
  143524. /* Update or delete the input segments */
  143525. if( rc==SQLITE_OK ){
  143526. nRem -= (1 + pWriter->nWork);
  143527. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  143528. if( nSeg!=0 ){
  143529. bDirtyHint = 1;
  143530. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  143531. }
  143532. }
  143533. }
  143534. if( nSeg!=0 ){
  143535. pWriter->nLeafData = pWriter->nLeafData * -1;
  143536. }
  143537. fts3IncrmergeRelease(p, pWriter, &rc);
  143538. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  143539. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  143540. }
  143541. }
  143542. sqlite3Fts3SegReaderFinish(pCsr);
  143543. }
  143544. /* Write the hint values into the %_stat table for the next incr-merger */
  143545. if( bDirtyHint && rc==SQLITE_OK ){
  143546. rc = fts3IncrmergeHintStore(p, &hint);
  143547. }
  143548. sqlite3_free(pWriter);
  143549. sqlite3_free(hint.a);
  143550. return rc;
  143551. }
  143552. /*
  143553. ** Convert the text beginning at *pz into an integer and return
  143554. ** its value. Advance *pz to point to the first character past
  143555. ** the integer.
  143556. */
  143557. static int fts3Getint(const char **pz){
  143558. const char *z = *pz;
  143559. int i = 0;
  143560. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  143561. *pz = z;
  143562. return i;
  143563. }
  143564. /*
  143565. ** Process statements of the form:
  143566. **
  143567. ** INSERT INTO table(table) VALUES('merge=A,B');
  143568. **
  143569. ** A and B are integers that decode to be the number of leaf pages
  143570. ** written for the merge, and the minimum number of segments on a level
  143571. ** before it will be selected for a merge, respectively.
  143572. */
  143573. static int fts3DoIncrmerge(
  143574. Fts3Table *p, /* FTS3 table handle */
  143575. const char *zParam /* Nul-terminated string containing "A,B" */
  143576. ){
  143577. int rc;
  143578. int nMin = (FTS3_MERGE_COUNT / 2);
  143579. int nMerge = 0;
  143580. const char *z = zParam;
  143581. /* Read the first integer value */
  143582. nMerge = fts3Getint(&z);
  143583. /* If the first integer value is followed by a ',', read the second
  143584. ** integer value. */
  143585. if( z[0]==',' && z[1]!='\0' ){
  143586. z++;
  143587. nMin = fts3Getint(&z);
  143588. }
  143589. if( z[0]!='\0' || nMin<2 ){
  143590. rc = SQLITE_ERROR;
  143591. }else{
  143592. rc = SQLITE_OK;
  143593. if( !p->bHasStat ){
  143594. assert( p->bFts4==0 );
  143595. sqlite3Fts3CreateStatTable(&rc, p);
  143596. }
  143597. if( rc==SQLITE_OK ){
  143598. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  143599. }
  143600. sqlite3Fts3SegmentsClose(p);
  143601. }
  143602. return rc;
  143603. }
  143604. /*
  143605. ** Process statements of the form:
  143606. **
  143607. ** INSERT INTO table(table) VALUES('automerge=X');
  143608. **
  143609. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  143610. ** turn it on. The setting is persistent.
  143611. */
  143612. static int fts3DoAutoincrmerge(
  143613. Fts3Table *p, /* FTS3 table handle */
  143614. const char *zParam /* Nul-terminated string containing boolean */
  143615. ){
  143616. int rc = SQLITE_OK;
  143617. sqlite3_stmt *pStmt = 0;
  143618. p->nAutoincrmerge = fts3Getint(&zParam);
  143619. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  143620. p->nAutoincrmerge = 8;
  143621. }
  143622. if( !p->bHasStat ){
  143623. assert( p->bFts4==0 );
  143624. sqlite3Fts3CreateStatTable(&rc, p);
  143625. if( rc ) return rc;
  143626. }
  143627. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  143628. if( rc ) return rc;
  143629. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  143630. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  143631. sqlite3_step(pStmt);
  143632. rc = sqlite3_reset(pStmt);
  143633. return rc;
  143634. }
  143635. /*
  143636. ** Return a 64-bit checksum for the FTS index entry specified by the
  143637. ** arguments to this function.
  143638. */
  143639. static u64 fts3ChecksumEntry(
  143640. const char *zTerm, /* Pointer to buffer containing term */
  143641. int nTerm, /* Size of zTerm in bytes */
  143642. int iLangid, /* Language id for current row */
  143643. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  143644. i64 iDocid, /* Docid for current row. */
  143645. int iCol, /* Column number */
  143646. int iPos /* Position */
  143647. ){
  143648. int i;
  143649. u64 ret = (u64)iDocid;
  143650. ret += (ret<<3) + iLangid;
  143651. ret += (ret<<3) + iIndex;
  143652. ret += (ret<<3) + iCol;
  143653. ret += (ret<<3) + iPos;
  143654. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  143655. return ret;
  143656. }
  143657. /*
  143658. ** Return a checksum of all entries in the FTS index that correspond to
  143659. ** language id iLangid. The checksum is calculated by XORing the checksums
  143660. ** of each individual entry (see fts3ChecksumEntry()) together.
  143661. **
  143662. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  143663. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  143664. ** return value is undefined in this case.
  143665. */
  143666. static u64 fts3ChecksumIndex(
  143667. Fts3Table *p, /* FTS3 table handle */
  143668. int iLangid, /* Language id to return cksum for */
  143669. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  143670. int *pRc /* OUT: Return code */
  143671. ){
  143672. Fts3SegFilter filter;
  143673. Fts3MultiSegReader csr;
  143674. int rc;
  143675. u64 cksum = 0;
  143676. assert( *pRc==SQLITE_OK );
  143677. memset(&filter, 0, sizeof(filter));
  143678. memset(&csr, 0, sizeof(csr));
  143679. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  143680. filter.flags |= FTS3_SEGMENT_SCAN;
  143681. rc = sqlite3Fts3SegReaderCursor(
  143682. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  143683. );
  143684. if( rc==SQLITE_OK ){
  143685. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  143686. }
  143687. if( rc==SQLITE_OK ){
  143688. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  143689. char *pCsr = csr.aDoclist;
  143690. char *pEnd = &pCsr[csr.nDoclist];
  143691. i64 iDocid = 0;
  143692. i64 iCol = 0;
  143693. i64 iPos = 0;
  143694. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  143695. while( pCsr<pEnd ){
  143696. i64 iVal = 0;
  143697. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  143698. if( pCsr<pEnd ){
  143699. if( iVal==0 || iVal==1 ){
  143700. iCol = 0;
  143701. iPos = 0;
  143702. if( iVal ){
  143703. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  143704. }else{
  143705. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  143706. iDocid += iVal;
  143707. }
  143708. }else{
  143709. iPos += (iVal - 2);
  143710. cksum = cksum ^ fts3ChecksumEntry(
  143711. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  143712. (int)iCol, (int)iPos
  143713. );
  143714. }
  143715. }
  143716. }
  143717. }
  143718. }
  143719. sqlite3Fts3SegReaderFinish(&csr);
  143720. *pRc = rc;
  143721. return cksum;
  143722. }
  143723. /*
  143724. ** Check if the contents of the FTS index match the current contents of the
  143725. ** content table. If no error occurs and the contents do match, set *pbOk
  143726. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  143727. ** to false before returning.
  143728. **
  143729. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  143730. ** code. The final value of *pbOk is undefined in this case.
  143731. */
  143732. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  143733. int rc = SQLITE_OK; /* Return code */
  143734. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  143735. u64 cksum2 = 0; /* Checksum based on %_content contents */
  143736. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  143737. /* This block calculates the checksum according to the FTS index. */
  143738. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  143739. if( rc==SQLITE_OK ){
  143740. int rc2;
  143741. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  143742. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  143743. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  143744. int iLangid = sqlite3_column_int(pAllLangid, 0);
  143745. int i;
  143746. for(i=0; i<p->nIndex; i++){
  143747. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  143748. }
  143749. }
  143750. rc2 = sqlite3_reset(pAllLangid);
  143751. if( rc==SQLITE_OK ) rc = rc2;
  143752. }
  143753. /* This block calculates the checksum according to the %_content table */
  143754. if( rc==SQLITE_OK ){
  143755. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  143756. sqlite3_stmt *pStmt = 0;
  143757. char *zSql;
  143758. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  143759. if( !zSql ){
  143760. rc = SQLITE_NOMEM;
  143761. }else{
  143762. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  143763. sqlite3_free(zSql);
  143764. }
  143765. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  143766. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  143767. int iLang = langidFromSelect(p, pStmt);
  143768. int iCol;
  143769. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  143770. if( p->abNotindexed[iCol]==0 ){
  143771. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  143772. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  143773. sqlite3_tokenizer_cursor *pT = 0;
  143774. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  143775. while( rc==SQLITE_OK ){
  143776. char const *zToken; /* Buffer containing token */
  143777. int nToken = 0; /* Number of bytes in token */
  143778. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  143779. int iPos = 0; /* Position of token in zText */
  143780. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  143781. if( rc==SQLITE_OK ){
  143782. int i;
  143783. cksum2 = cksum2 ^ fts3ChecksumEntry(
  143784. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  143785. );
  143786. for(i=1; i<p->nIndex; i++){
  143787. if( p->aIndex[i].nPrefix<=nToken ){
  143788. cksum2 = cksum2 ^ fts3ChecksumEntry(
  143789. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  143790. );
  143791. }
  143792. }
  143793. }
  143794. }
  143795. if( pT ) pModule->xClose(pT);
  143796. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  143797. }
  143798. }
  143799. }
  143800. sqlite3_finalize(pStmt);
  143801. }
  143802. *pbOk = (cksum1==cksum2);
  143803. return rc;
  143804. }
  143805. /*
  143806. ** Run the integrity-check. If no error occurs and the current contents of
  143807. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  143808. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  143809. **
  143810. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  143811. ** error code.
  143812. **
  143813. ** The integrity-check works as follows. For each token and indexed token
  143814. ** prefix in the document set, a 64-bit checksum is calculated (by code
  143815. ** in fts3ChecksumEntry()) based on the following:
  143816. **
  143817. ** + The index number (0 for the main index, 1 for the first prefix
  143818. ** index etc.),
  143819. ** + The token (or token prefix) text itself,
  143820. ** + The language-id of the row it appears in,
  143821. ** + The docid of the row it appears in,
  143822. ** + The column it appears in, and
  143823. ** + The tokens position within that column.
  143824. **
  143825. ** The checksums for all entries in the index are XORed together to create
  143826. ** a single checksum for the entire index.
  143827. **
  143828. ** The integrity-check code calculates the same checksum in two ways:
  143829. **
  143830. ** 1. By scanning the contents of the FTS index, and
  143831. ** 2. By scanning and tokenizing the content table.
  143832. **
  143833. ** If the two checksums are identical, the integrity-check is deemed to have
  143834. ** passed.
  143835. */
  143836. static int fts3DoIntegrityCheck(
  143837. Fts3Table *p /* FTS3 table handle */
  143838. ){
  143839. int rc;
  143840. int bOk = 0;
  143841. rc = fts3IntegrityCheck(p, &bOk);
  143842. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  143843. return rc;
  143844. }
  143845. /*
  143846. ** Handle a 'special' INSERT of the form:
  143847. **
  143848. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  143849. **
  143850. ** Argument pVal contains the result of <expr>. Currently the only
  143851. ** meaningful value to insert is the text 'optimize'.
  143852. */
  143853. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  143854. int rc; /* Return Code */
  143855. const char *zVal = (const char *)sqlite3_value_text(pVal);
  143856. int nVal = sqlite3_value_bytes(pVal);
  143857. if( !zVal ){
  143858. return SQLITE_NOMEM;
  143859. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  143860. rc = fts3DoOptimize(p, 0);
  143861. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  143862. rc = fts3DoRebuild(p);
  143863. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  143864. rc = fts3DoIntegrityCheck(p);
  143865. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  143866. rc = fts3DoIncrmerge(p, &zVal[6]);
  143867. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  143868. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  143869. #ifdef SQLITE_TEST
  143870. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  143871. p->nNodeSize = atoi(&zVal[9]);
  143872. rc = SQLITE_OK;
  143873. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  143874. p->nMaxPendingData = atoi(&zVal[11]);
  143875. rc = SQLITE_OK;
  143876. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  143877. p->bNoIncrDoclist = atoi(&zVal[21]);
  143878. rc = SQLITE_OK;
  143879. #endif
  143880. }else{
  143881. rc = SQLITE_ERROR;
  143882. }
  143883. return rc;
  143884. }
  143885. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  143886. /*
  143887. ** Delete all cached deferred doclists. Deferred doclists are cached
  143888. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  143889. */
  143890. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  143891. Fts3DeferredToken *pDef;
  143892. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  143893. fts3PendingListDelete(pDef->pList);
  143894. pDef->pList = 0;
  143895. }
  143896. }
  143897. /*
  143898. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  143899. ** this list using sqlite3Fts3DeferToken().
  143900. */
  143901. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  143902. Fts3DeferredToken *pDef;
  143903. Fts3DeferredToken *pNext;
  143904. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  143905. pNext = pDef->pNext;
  143906. fts3PendingListDelete(pDef->pList);
  143907. sqlite3_free(pDef);
  143908. }
  143909. pCsr->pDeferred = 0;
  143910. }
  143911. /*
  143912. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  143913. ** based on the row that pCsr currently points to.
  143914. **
  143915. ** A deferred-doclist is like any other doclist with position information
  143916. ** included, except that it only contains entries for a single row of the
  143917. ** table, not for all rows.
  143918. */
  143919. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  143920. int rc = SQLITE_OK; /* Return code */
  143921. if( pCsr->pDeferred ){
  143922. int i; /* Used to iterate through table columns */
  143923. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  143924. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  143925. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  143926. sqlite3_tokenizer *pT = p->pTokenizer;
  143927. sqlite3_tokenizer_module const *pModule = pT->pModule;
  143928. assert( pCsr->isRequireSeek==0 );
  143929. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  143930. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  143931. if( p->abNotindexed[i]==0 ){
  143932. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  143933. sqlite3_tokenizer_cursor *pTC = 0;
  143934. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  143935. while( rc==SQLITE_OK ){
  143936. char const *zToken; /* Buffer containing token */
  143937. int nToken = 0; /* Number of bytes in token */
  143938. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  143939. int iPos = 0; /* Position of token in zText */
  143940. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  143941. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  143942. Fts3PhraseToken *pPT = pDef->pToken;
  143943. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  143944. && (pPT->bFirst==0 || iPos==0)
  143945. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  143946. && (0==memcmp(zToken, pPT->z, pPT->n))
  143947. ){
  143948. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  143949. }
  143950. }
  143951. }
  143952. if( pTC ) pModule->xClose(pTC);
  143953. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  143954. }
  143955. }
  143956. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  143957. if( pDef->pList ){
  143958. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  143959. }
  143960. }
  143961. }
  143962. return rc;
  143963. }
  143964. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  143965. Fts3DeferredToken *p,
  143966. char **ppData,
  143967. int *pnData
  143968. ){
  143969. char *pRet;
  143970. int nSkip;
  143971. sqlite3_int64 dummy;
  143972. *ppData = 0;
  143973. *pnData = 0;
  143974. if( p->pList==0 ){
  143975. return SQLITE_OK;
  143976. }
  143977. pRet = (char *)sqlite3_malloc(p->pList->nData);
  143978. if( !pRet ) return SQLITE_NOMEM;
  143979. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  143980. *pnData = p->pList->nData - nSkip;
  143981. *ppData = pRet;
  143982. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  143983. return SQLITE_OK;
  143984. }
  143985. /*
  143986. ** Add an entry for token pToken to the pCsr->pDeferred list.
  143987. */
  143988. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  143989. Fts3Cursor *pCsr, /* Fts3 table cursor */
  143990. Fts3PhraseToken *pToken, /* Token to defer */
  143991. int iCol /* Column that token must appear in (or -1) */
  143992. ){
  143993. Fts3DeferredToken *pDeferred;
  143994. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  143995. if( !pDeferred ){
  143996. return SQLITE_NOMEM;
  143997. }
  143998. memset(pDeferred, 0, sizeof(*pDeferred));
  143999. pDeferred->pToken = pToken;
  144000. pDeferred->pNext = pCsr->pDeferred;
  144001. pDeferred->iCol = iCol;
  144002. pCsr->pDeferred = pDeferred;
  144003. assert( pToken->pDeferred==0 );
  144004. pToken->pDeferred = pDeferred;
  144005. return SQLITE_OK;
  144006. }
  144007. #endif
  144008. /*
  144009. ** SQLite value pRowid contains the rowid of a row that may or may not be
  144010. ** present in the FTS3 table. If it is, delete it and adjust the contents
  144011. ** of subsiduary data structures accordingly.
  144012. */
  144013. static int fts3DeleteByRowid(
  144014. Fts3Table *p,
  144015. sqlite3_value *pRowid,
  144016. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  144017. u32 *aSzDel
  144018. ){
  144019. int rc = SQLITE_OK; /* Return code */
  144020. int bFound = 0; /* True if *pRowid really is in the table */
  144021. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  144022. if( bFound && rc==SQLITE_OK ){
  144023. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  144024. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  144025. if( rc==SQLITE_OK ){
  144026. if( isEmpty ){
  144027. /* Deleting this row means the whole table is empty. In this case
  144028. ** delete the contents of all three tables and throw away any
  144029. ** data in the pendingTerms hash table. */
  144030. rc = fts3DeleteAll(p, 1);
  144031. *pnChng = 0;
  144032. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  144033. }else{
  144034. *pnChng = *pnChng - 1;
  144035. if( p->zContentTbl==0 ){
  144036. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  144037. }
  144038. if( p->bHasDocsize ){
  144039. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  144040. }
  144041. }
  144042. }
  144043. }
  144044. return rc;
  144045. }
  144046. /*
  144047. ** This function does the work for the xUpdate method of FTS3 virtual
  144048. ** tables. The schema of the virtual table being:
  144049. **
  144050. ** CREATE TABLE <table name>(
  144051. ** <user columns>,
  144052. ** <table name> HIDDEN,
  144053. ** docid HIDDEN,
  144054. ** <langid> HIDDEN
  144055. ** );
  144056. **
  144057. **
  144058. */
  144059. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  144060. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  144061. int nArg, /* Size of argument array */
  144062. sqlite3_value **apVal, /* Array of arguments */
  144063. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  144064. ){
  144065. Fts3Table *p = (Fts3Table *)pVtab;
  144066. int rc = SQLITE_OK; /* Return Code */
  144067. int isRemove = 0; /* True for an UPDATE or DELETE */
  144068. u32 *aSzIns = 0; /* Sizes of inserted documents */
  144069. u32 *aSzDel = 0; /* Sizes of deleted documents */
  144070. int nChng = 0; /* Net change in number of documents */
  144071. int bInsertDone = 0;
  144072. /* At this point it must be known if the %_stat table exists or not.
  144073. ** So bHasStat may not be 2. */
  144074. assert( p->bHasStat==0 || p->bHasStat==1 );
  144075. assert( p->pSegments==0 );
  144076. assert(
  144077. nArg==1 /* DELETE operations */
  144078. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  144079. );
  144080. /* Check for a "special" INSERT operation. One of the form:
  144081. **
  144082. ** INSERT INTO xyz(xyz) VALUES('command');
  144083. */
  144084. if( nArg>1
  144085. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  144086. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  144087. ){
  144088. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  144089. goto update_out;
  144090. }
  144091. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  144092. rc = SQLITE_CONSTRAINT;
  144093. goto update_out;
  144094. }
  144095. /* Allocate space to hold the change in document sizes */
  144096. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  144097. if( aSzDel==0 ){
  144098. rc = SQLITE_NOMEM;
  144099. goto update_out;
  144100. }
  144101. aSzIns = &aSzDel[p->nColumn+1];
  144102. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  144103. rc = fts3Writelock(p);
  144104. if( rc!=SQLITE_OK ) goto update_out;
  144105. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  144106. ** value, then this operation requires constraint handling.
  144107. **
  144108. ** If the on-conflict mode is REPLACE, this means that the existing row
  144109. ** should be deleted from the database before inserting the new row. Or,
  144110. ** if the on-conflict mode is other than REPLACE, then this method must
  144111. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  144112. ** modify the database file.
  144113. */
  144114. if( nArg>1 && p->zContentTbl==0 ){
  144115. /* Find the value object that holds the new rowid value. */
  144116. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  144117. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  144118. pNewRowid = apVal[1];
  144119. }
  144120. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  144121. sqlite3_value_type(apVal[0])==SQLITE_NULL
  144122. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  144123. )){
  144124. /* The new rowid is not NULL (in this case the rowid will be
  144125. ** automatically assigned and there is no chance of a conflict), and
  144126. ** the statement is either an INSERT or an UPDATE that modifies the
  144127. ** rowid column. So if the conflict mode is REPLACE, then delete any
  144128. ** existing row with rowid=pNewRowid.
  144129. **
  144130. ** Or, if the conflict mode is not REPLACE, insert the new record into
  144131. ** the %_content table. If we hit the duplicate rowid constraint (or any
  144132. ** other error) while doing so, return immediately.
  144133. **
  144134. ** This branch may also run if pNewRowid contains a value that cannot
  144135. ** be losslessly converted to an integer. In this case, the eventual
  144136. ** call to fts3InsertData() (either just below or further on in this
  144137. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  144138. ** invoked, it will delete zero rows (since no row will have
  144139. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  144140. */
  144141. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  144142. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  144143. }else{
  144144. rc = fts3InsertData(p, apVal, pRowid);
  144145. bInsertDone = 1;
  144146. }
  144147. }
  144148. }
  144149. if( rc!=SQLITE_OK ){
  144150. goto update_out;
  144151. }
  144152. /* If this is a DELETE or UPDATE operation, remove the old record. */
  144153. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  144154. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  144155. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  144156. isRemove = 1;
  144157. }
  144158. /* If this is an INSERT or UPDATE operation, insert the new record. */
  144159. if( nArg>1 && rc==SQLITE_OK ){
  144160. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  144161. if( bInsertDone==0 ){
  144162. rc = fts3InsertData(p, apVal, pRowid);
  144163. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  144164. rc = FTS_CORRUPT_VTAB;
  144165. }
  144166. }
  144167. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  144168. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  144169. }
  144170. if( rc==SQLITE_OK ){
  144171. assert( p->iPrevDocid==*pRowid );
  144172. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  144173. }
  144174. if( p->bHasDocsize ){
  144175. fts3InsertDocsize(&rc, p, aSzIns);
  144176. }
  144177. nChng++;
  144178. }
  144179. if( p->bFts4 ){
  144180. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  144181. }
  144182. update_out:
  144183. sqlite3_free(aSzDel);
  144184. sqlite3Fts3SegmentsClose(p);
  144185. return rc;
  144186. }
  144187. /*
  144188. ** Flush any data in the pending-terms hash table to disk. If successful,
  144189. ** merge all segments in the database (including the new segment, if
  144190. ** there was any data to flush) into a single segment.
  144191. */
  144192. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  144193. int rc;
  144194. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  144195. if( rc==SQLITE_OK ){
  144196. rc = fts3DoOptimize(p, 1);
  144197. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  144198. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  144199. if( rc2!=SQLITE_OK ) rc = rc2;
  144200. }else{
  144201. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  144202. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  144203. }
  144204. }
  144205. sqlite3Fts3SegmentsClose(p);
  144206. return rc;
  144207. }
  144208. #endif
  144209. /************** End of fts3_write.c ******************************************/
  144210. /************** Begin file fts3_snippet.c ************************************/
  144211. /*
  144212. ** 2009 Oct 23
  144213. **
  144214. ** The author disclaims copyright to this source code. In place of
  144215. ** a legal notice, here is a blessing:
  144216. **
  144217. ** May you do good and not evil.
  144218. ** May you find forgiveness for yourself and forgive others.
  144219. ** May you share freely, never taking more than you give.
  144220. **
  144221. ******************************************************************************
  144222. */
  144223. /* #include "fts3Int.h" */
  144224. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144225. /* #include <string.h> */
  144226. /* #include <assert.h> */
  144227. /*
  144228. ** Characters that may appear in the second argument to matchinfo().
  144229. */
  144230. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  144231. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  144232. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  144233. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  144234. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  144235. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  144236. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  144237. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  144238. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  144239. /*
  144240. ** The default value for the second argument to matchinfo().
  144241. */
  144242. #define FTS3_MATCHINFO_DEFAULT "pcx"
  144243. /*
  144244. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  144245. ** Fts3Expr.aDoclist[]/nDoclist.
  144246. */
  144247. typedef struct LoadDoclistCtx LoadDoclistCtx;
  144248. struct LoadDoclistCtx {
  144249. Fts3Cursor *pCsr; /* FTS3 Cursor */
  144250. int nPhrase; /* Number of phrases seen so far */
  144251. int nToken; /* Number of tokens seen so far */
  144252. };
  144253. /*
  144254. ** The following types are used as part of the implementation of the
  144255. ** fts3BestSnippet() routine.
  144256. */
  144257. typedef struct SnippetIter SnippetIter;
  144258. typedef struct SnippetPhrase SnippetPhrase;
  144259. typedef struct SnippetFragment SnippetFragment;
  144260. struct SnippetIter {
  144261. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  144262. int iCol; /* Extract snippet from this column */
  144263. int nSnippet; /* Requested snippet length (in tokens) */
  144264. int nPhrase; /* Number of phrases in query */
  144265. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  144266. int iCurrent; /* First token of current snippet */
  144267. };
  144268. struct SnippetPhrase {
  144269. int nToken; /* Number of tokens in phrase */
  144270. char *pList; /* Pointer to start of phrase position list */
  144271. int iHead; /* Next value in position list */
  144272. char *pHead; /* Position list data following iHead */
  144273. int iTail; /* Next value in trailing position list */
  144274. char *pTail; /* Position list data following iTail */
  144275. };
  144276. struct SnippetFragment {
  144277. int iCol; /* Column snippet is extracted from */
  144278. int iPos; /* Index of first token in snippet */
  144279. u64 covered; /* Mask of query phrases covered */
  144280. u64 hlmask; /* Mask of snippet terms to highlight */
  144281. };
  144282. /*
  144283. ** This type is used as an fts3ExprIterate() context object while
  144284. ** accumulating the data returned by the matchinfo() function.
  144285. */
  144286. typedef struct MatchInfo MatchInfo;
  144287. struct MatchInfo {
  144288. Fts3Cursor *pCursor; /* FTS3 Cursor */
  144289. int nCol; /* Number of columns in table */
  144290. int nPhrase; /* Number of matchable phrases in query */
  144291. sqlite3_int64 nDoc; /* Number of docs in database */
  144292. char flag;
  144293. u32 *aMatchinfo; /* Pre-allocated buffer */
  144294. };
  144295. /*
  144296. ** An instance of this structure is used to manage a pair of buffers, each
  144297. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  144298. ** for details.
  144299. */
  144300. struct MatchinfoBuffer {
  144301. u8 aRef[3];
  144302. int nElem;
  144303. int bGlobal; /* Set if global data is loaded */
  144304. char *zMatchinfo;
  144305. u32 aMatchinfo[1];
  144306. };
  144307. /*
  144308. ** The snippet() and offsets() functions both return text values. An instance
  144309. ** of the following structure is used to accumulate those values while the
  144310. ** functions are running. See fts3StringAppend() for details.
  144311. */
  144312. typedef struct StrBuffer StrBuffer;
  144313. struct StrBuffer {
  144314. char *z; /* Pointer to buffer containing string */
  144315. int n; /* Length of z in bytes (excl. nul-term) */
  144316. int nAlloc; /* Allocated size of buffer z in bytes */
  144317. };
  144318. /*************************************************************************
  144319. ** Start of MatchinfoBuffer code.
  144320. */
  144321. /*
  144322. ** Allocate a two-slot MatchinfoBuffer object.
  144323. */
  144324. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  144325. MatchinfoBuffer *pRet;
  144326. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  144327. int nStr = (int)strlen(zMatchinfo);
  144328. pRet = sqlite3_malloc(nByte + nStr+1);
  144329. if( pRet ){
  144330. memset(pRet, 0, nByte);
  144331. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  144332. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  144333. pRet->nElem = nElem;
  144334. pRet->zMatchinfo = ((char*)pRet) + nByte;
  144335. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  144336. pRet->aRef[0] = 1;
  144337. }
  144338. return pRet;
  144339. }
  144340. static void fts3MIBufferFree(void *p){
  144341. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  144342. assert( (u32*)p==&pBuf->aMatchinfo[1]
  144343. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  144344. );
  144345. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  144346. pBuf->aRef[1] = 0;
  144347. }else{
  144348. pBuf->aRef[2] = 0;
  144349. }
  144350. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  144351. sqlite3_free(pBuf);
  144352. }
  144353. }
  144354. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  144355. void (*xRet)(void*) = 0;
  144356. u32 *aOut = 0;
  144357. if( p->aRef[1]==0 ){
  144358. p->aRef[1] = 1;
  144359. aOut = &p->aMatchinfo[1];
  144360. xRet = fts3MIBufferFree;
  144361. }
  144362. else if( p->aRef[2]==0 ){
  144363. p->aRef[2] = 1;
  144364. aOut = &p->aMatchinfo[p->nElem+2];
  144365. xRet = fts3MIBufferFree;
  144366. }else{
  144367. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  144368. if( aOut ){
  144369. xRet = sqlite3_free;
  144370. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  144371. }
  144372. }
  144373. *paOut = aOut;
  144374. return xRet;
  144375. }
  144376. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  144377. p->bGlobal = 1;
  144378. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  144379. }
  144380. /*
  144381. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  144382. */
  144383. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  144384. if( p ){
  144385. assert( p->aRef[0]==1 );
  144386. p->aRef[0] = 0;
  144387. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  144388. sqlite3_free(p);
  144389. }
  144390. }
  144391. }
  144392. /*
  144393. ** End of MatchinfoBuffer code.
  144394. *************************************************************************/
  144395. /*
  144396. ** This function is used to help iterate through a position-list. A position
  144397. ** list is a list of unique integers, sorted from smallest to largest. Each
  144398. ** element of the list is represented by an FTS3 varint that takes the value
  144399. ** of the difference between the current element and the previous one plus
  144400. ** two. For example, to store the position-list:
  144401. **
  144402. ** 4 9 113
  144403. **
  144404. ** the three varints:
  144405. **
  144406. ** 6 7 106
  144407. **
  144408. ** are encoded.
  144409. **
  144410. ** When this function is called, *pp points to the start of an element of
  144411. ** the list. *piPos contains the value of the previous entry in the list.
  144412. ** After it returns, *piPos contains the value of the next element of the
  144413. ** list and *pp is advanced to the following varint.
  144414. */
  144415. static void fts3GetDeltaPosition(char **pp, int *piPos){
  144416. int iVal;
  144417. *pp += fts3GetVarint32(*pp, &iVal);
  144418. *piPos += (iVal-2);
  144419. }
  144420. /*
  144421. ** Helper function for fts3ExprIterate() (see below).
  144422. */
  144423. static int fts3ExprIterate2(
  144424. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  144425. int *piPhrase, /* Pointer to phrase counter */
  144426. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  144427. void *pCtx /* Second argument to pass to callback */
  144428. ){
  144429. int rc; /* Return code */
  144430. int eType = pExpr->eType; /* Type of expression node pExpr */
  144431. if( eType!=FTSQUERY_PHRASE ){
  144432. assert( pExpr->pLeft && pExpr->pRight );
  144433. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  144434. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  144435. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  144436. }
  144437. }else{
  144438. rc = x(pExpr, *piPhrase, pCtx);
  144439. (*piPhrase)++;
  144440. }
  144441. return rc;
  144442. }
  144443. /*
  144444. ** Iterate through all phrase nodes in an FTS3 query, except those that
  144445. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  144446. ** For each phrase node found, the supplied callback function is invoked.
  144447. **
  144448. ** If the callback function returns anything other than SQLITE_OK,
  144449. ** the iteration is abandoned and the error code returned immediately.
  144450. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  144451. ** all eligible phrase nodes.
  144452. */
  144453. static int fts3ExprIterate(
  144454. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  144455. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  144456. void *pCtx /* Second argument to pass to callback */
  144457. ){
  144458. int iPhrase = 0; /* Variable used as the phrase counter */
  144459. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  144460. }
  144461. /*
  144462. ** This is an fts3ExprIterate() callback used while loading the doclists
  144463. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  144464. ** fts3ExprLoadDoclists().
  144465. */
  144466. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  144467. int rc = SQLITE_OK;
  144468. Fts3Phrase *pPhrase = pExpr->pPhrase;
  144469. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  144470. UNUSED_PARAMETER(iPhrase);
  144471. p->nPhrase++;
  144472. p->nToken += pPhrase->nToken;
  144473. return rc;
  144474. }
  144475. /*
  144476. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  144477. ** pCsr.
  144478. **
  144479. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  144480. ** phrases in the expression (all phrases except those directly or
  144481. ** indirectly descended from the right-hand-side of a NOT operator). If
  144482. ** pnToken is not NULL, then it is set to the number of tokens in all
  144483. ** matchable phrases of the expression.
  144484. */
  144485. static int fts3ExprLoadDoclists(
  144486. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  144487. int *pnPhrase, /* OUT: Number of phrases in query */
  144488. int *pnToken /* OUT: Number of tokens in query */
  144489. ){
  144490. int rc; /* Return Code */
  144491. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  144492. sCtx.pCsr = pCsr;
  144493. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  144494. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  144495. if( pnToken ) *pnToken = sCtx.nToken;
  144496. return rc;
  144497. }
  144498. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  144499. (*(int *)ctx)++;
  144500. pExpr->iPhrase = iPhrase;
  144501. return SQLITE_OK;
  144502. }
  144503. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  144504. int nPhrase = 0;
  144505. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  144506. return nPhrase;
  144507. }
  144508. /*
  144509. ** Advance the position list iterator specified by the first two
  144510. ** arguments so that it points to the first element with a value greater
  144511. ** than or equal to parameter iNext.
  144512. */
  144513. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  144514. char *pIter = *ppIter;
  144515. if( pIter ){
  144516. int iIter = *piIter;
  144517. while( iIter<iNext ){
  144518. if( 0==(*pIter & 0xFE) ){
  144519. iIter = -1;
  144520. pIter = 0;
  144521. break;
  144522. }
  144523. fts3GetDeltaPosition(&pIter, &iIter);
  144524. }
  144525. *piIter = iIter;
  144526. *ppIter = pIter;
  144527. }
  144528. }
  144529. /*
  144530. ** Advance the snippet iterator to the next candidate snippet.
  144531. */
  144532. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  144533. int i; /* Loop counter */
  144534. if( pIter->iCurrent<0 ){
  144535. /* The SnippetIter object has just been initialized. The first snippet
  144536. ** candidate always starts at offset 0 (even if this candidate has a
  144537. ** score of 0.0).
  144538. */
  144539. pIter->iCurrent = 0;
  144540. /* Advance the 'head' iterator of each phrase to the first offset that
  144541. ** is greater than or equal to (iNext+nSnippet).
  144542. */
  144543. for(i=0; i<pIter->nPhrase; i++){
  144544. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  144545. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  144546. }
  144547. }else{
  144548. int iStart;
  144549. int iEnd = 0x7FFFFFFF;
  144550. for(i=0; i<pIter->nPhrase; i++){
  144551. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  144552. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  144553. iEnd = pPhrase->iHead;
  144554. }
  144555. }
  144556. if( iEnd==0x7FFFFFFF ){
  144557. return 1;
  144558. }
  144559. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  144560. for(i=0; i<pIter->nPhrase; i++){
  144561. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  144562. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  144563. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  144564. }
  144565. }
  144566. return 0;
  144567. }
  144568. /*
  144569. ** Retrieve information about the current candidate snippet of snippet
  144570. ** iterator pIter.
  144571. */
  144572. static void fts3SnippetDetails(
  144573. SnippetIter *pIter, /* Snippet iterator */
  144574. u64 mCovered, /* Bitmask of phrases already covered */
  144575. int *piToken, /* OUT: First token of proposed snippet */
  144576. int *piScore, /* OUT: "Score" for this snippet */
  144577. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  144578. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  144579. ){
  144580. int iStart = pIter->iCurrent; /* First token of snippet */
  144581. int iScore = 0; /* Score of this snippet */
  144582. int i; /* Loop counter */
  144583. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  144584. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  144585. for(i=0; i<pIter->nPhrase; i++){
  144586. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  144587. if( pPhrase->pTail ){
  144588. char *pCsr = pPhrase->pTail;
  144589. int iCsr = pPhrase->iTail;
  144590. while( iCsr<(iStart+pIter->nSnippet) ){
  144591. int j;
  144592. u64 mPhrase = (u64)1 << i;
  144593. u64 mPos = (u64)1 << (iCsr - iStart);
  144594. assert( iCsr>=iStart );
  144595. if( (mCover|mCovered)&mPhrase ){
  144596. iScore++;
  144597. }else{
  144598. iScore += 1000;
  144599. }
  144600. mCover |= mPhrase;
  144601. for(j=0; j<pPhrase->nToken; j++){
  144602. mHighlight |= (mPos>>j);
  144603. }
  144604. if( 0==(*pCsr & 0x0FE) ) break;
  144605. fts3GetDeltaPosition(&pCsr, &iCsr);
  144606. }
  144607. }
  144608. }
  144609. /* Set the output variables before returning. */
  144610. *piToken = iStart;
  144611. *piScore = iScore;
  144612. *pmCover = mCover;
  144613. *pmHighlight = mHighlight;
  144614. }
  144615. /*
  144616. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  144617. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  144618. */
  144619. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  144620. SnippetIter *p = (SnippetIter *)ctx;
  144621. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  144622. char *pCsr;
  144623. int rc;
  144624. pPhrase->nToken = pExpr->pPhrase->nToken;
  144625. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  144626. assert( rc==SQLITE_OK || pCsr==0 );
  144627. if( pCsr ){
  144628. int iFirst = 0;
  144629. pPhrase->pList = pCsr;
  144630. fts3GetDeltaPosition(&pCsr, &iFirst);
  144631. assert( iFirst>=0 );
  144632. pPhrase->pHead = pCsr;
  144633. pPhrase->pTail = pCsr;
  144634. pPhrase->iHead = iFirst;
  144635. pPhrase->iTail = iFirst;
  144636. }else{
  144637. assert( rc!=SQLITE_OK || (
  144638. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  144639. ));
  144640. }
  144641. return rc;
  144642. }
  144643. /*
  144644. ** Select the fragment of text consisting of nFragment contiguous tokens
  144645. ** from column iCol that represent the "best" snippet. The best snippet
  144646. ** is the snippet with the highest score, where scores are calculated
  144647. ** by adding:
  144648. **
  144649. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  144650. **
  144651. ** (b) +1000 points for the first occurrence of each matchable phrase in
  144652. ** the snippet for which the corresponding mCovered bit is not set.
  144653. **
  144654. ** The selected snippet parameters are stored in structure *pFragment before
  144655. ** returning. The score of the selected snippet is stored in *piScore
  144656. ** before returning.
  144657. */
  144658. static int fts3BestSnippet(
  144659. int nSnippet, /* Desired snippet length */
  144660. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  144661. int iCol, /* Index of column to create snippet from */
  144662. u64 mCovered, /* Mask of phrases already covered */
  144663. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  144664. SnippetFragment *pFragment, /* OUT: Best snippet found */
  144665. int *piScore /* OUT: Score of snippet pFragment */
  144666. ){
  144667. int rc; /* Return Code */
  144668. int nList; /* Number of phrases in expression */
  144669. SnippetIter sIter; /* Iterates through snippet candidates */
  144670. int nByte; /* Number of bytes of space to allocate */
  144671. int iBestScore = -1; /* Best snippet score found so far */
  144672. int i; /* Loop counter */
  144673. memset(&sIter, 0, sizeof(sIter));
  144674. /* Iterate through the phrases in the expression to count them. The same
  144675. ** callback makes sure the doclists are loaded for each phrase.
  144676. */
  144677. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  144678. if( rc!=SQLITE_OK ){
  144679. return rc;
  144680. }
  144681. /* Now that it is known how many phrases there are, allocate and zero
  144682. ** the required space using malloc().
  144683. */
  144684. nByte = sizeof(SnippetPhrase) * nList;
  144685. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  144686. if( !sIter.aPhrase ){
  144687. return SQLITE_NOMEM;
  144688. }
  144689. memset(sIter.aPhrase, 0, nByte);
  144690. /* Initialize the contents of the SnippetIter object. Then iterate through
  144691. ** the set of phrases in the expression to populate the aPhrase[] array.
  144692. */
  144693. sIter.pCsr = pCsr;
  144694. sIter.iCol = iCol;
  144695. sIter.nSnippet = nSnippet;
  144696. sIter.nPhrase = nList;
  144697. sIter.iCurrent = -1;
  144698. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  144699. if( rc==SQLITE_OK ){
  144700. /* Set the *pmSeen output variable. */
  144701. for(i=0; i<nList; i++){
  144702. if( sIter.aPhrase[i].pHead ){
  144703. *pmSeen |= (u64)1 << i;
  144704. }
  144705. }
  144706. /* Loop through all candidate snippets. Store the best snippet in
  144707. ** *pFragment. Store its associated 'score' in iBestScore.
  144708. */
  144709. pFragment->iCol = iCol;
  144710. while( !fts3SnippetNextCandidate(&sIter) ){
  144711. int iPos;
  144712. int iScore;
  144713. u64 mCover;
  144714. u64 mHighlite;
  144715. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  144716. assert( iScore>=0 );
  144717. if( iScore>iBestScore ){
  144718. pFragment->iPos = iPos;
  144719. pFragment->hlmask = mHighlite;
  144720. pFragment->covered = mCover;
  144721. iBestScore = iScore;
  144722. }
  144723. }
  144724. *piScore = iBestScore;
  144725. }
  144726. sqlite3_free(sIter.aPhrase);
  144727. return rc;
  144728. }
  144729. /*
  144730. ** Append a string to the string-buffer passed as the first argument.
  144731. **
  144732. ** If nAppend is negative, then the length of the string zAppend is
  144733. ** determined using strlen().
  144734. */
  144735. static int fts3StringAppend(
  144736. StrBuffer *pStr, /* Buffer to append to */
  144737. const char *zAppend, /* Pointer to data to append to buffer */
  144738. int nAppend /* Size of zAppend in bytes (or -1) */
  144739. ){
  144740. if( nAppend<0 ){
  144741. nAppend = (int)strlen(zAppend);
  144742. }
  144743. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  144744. ** to grow the buffer until so that it is big enough to accomadate the
  144745. ** appended data.
  144746. */
  144747. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  144748. int nAlloc = pStr->nAlloc+nAppend+100;
  144749. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  144750. if( !zNew ){
  144751. return SQLITE_NOMEM;
  144752. }
  144753. pStr->z = zNew;
  144754. pStr->nAlloc = nAlloc;
  144755. }
  144756. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  144757. /* Append the data to the string buffer. */
  144758. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  144759. pStr->n += nAppend;
  144760. pStr->z[pStr->n] = '\0';
  144761. return SQLITE_OK;
  144762. }
  144763. /*
  144764. ** The fts3BestSnippet() function often selects snippets that end with a
  144765. ** query term. That is, the final term of the snippet is always a term
  144766. ** that requires highlighting. For example, if 'X' is a highlighted term
  144767. ** and '.' is a non-highlighted term, BestSnippet() may select:
  144768. **
  144769. ** ........X.....X
  144770. **
  144771. ** This function "shifts" the beginning of the snippet forward in the
  144772. ** document so that there are approximately the same number of
  144773. ** non-highlighted terms to the right of the final highlighted term as there
  144774. ** are to the left of the first highlighted term. For example, to this:
  144775. **
  144776. ** ....X.....X....
  144777. **
  144778. ** This is done as part of extracting the snippet text, not when selecting
  144779. ** the snippet. Snippet selection is done based on doclists only, so there
  144780. ** is no way for fts3BestSnippet() to know whether or not the document
  144781. ** actually contains terms that follow the final highlighted term.
  144782. */
  144783. static int fts3SnippetShift(
  144784. Fts3Table *pTab, /* FTS3 table snippet comes from */
  144785. int iLangid, /* Language id to use in tokenizing */
  144786. int nSnippet, /* Number of tokens desired for snippet */
  144787. const char *zDoc, /* Document text to extract snippet from */
  144788. int nDoc, /* Size of buffer zDoc in bytes */
  144789. int *piPos, /* IN/OUT: First token of snippet */
  144790. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  144791. ){
  144792. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  144793. if( hlmask ){
  144794. int nLeft; /* Tokens to the left of first highlight */
  144795. int nRight; /* Tokens to the right of last highlight */
  144796. int nDesired; /* Ideal number of tokens to shift forward */
  144797. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  144798. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  144799. nDesired = (nLeft-nRight)/2;
  144800. /* Ideally, the start of the snippet should be pushed forward in the
  144801. ** document nDesired tokens. This block checks if there are actually
  144802. ** nDesired tokens to the right of the snippet. If so, *piPos and
  144803. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  144804. ** right. Otherwise, the snippet is shifted by the number of tokens
  144805. ** available.
  144806. */
  144807. if( nDesired>0 ){
  144808. int nShift; /* Number of tokens to shift snippet by */
  144809. int iCurrent = 0; /* Token counter */
  144810. int rc; /* Return Code */
  144811. sqlite3_tokenizer_module *pMod;
  144812. sqlite3_tokenizer_cursor *pC;
  144813. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  144814. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  144815. ** or more tokens in zDoc/nDoc.
  144816. */
  144817. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  144818. if( rc!=SQLITE_OK ){
  144819. return rc;
  144820. }
  144821. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  144822. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  144823. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  144824. }
  144825. pMod->xClose(pC);
  144826. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  144827. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  144828. assert( nShift<=nDesired );
  144829. if( nShift>0 ){
  144830. *piPos += nShift;
  144831. *pHlmask = hlmask >> nShift;
  144832. }
  144833. }
  144834. }
  144835. return SQLITE_OK;
  144836. }
  144837. /*
  144838. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  144839. ** append it to string buffer pOut.
  144840. */
  144841. static int fts3SnippetText(
  144842. Fts3Cursor *pCsr, /* FTS3 Cursor */
  144843. SnippetFragment *pFragment, /* Snippet to extract */
  144844. int iFragment, /* Fragment number */
  144845. int isLast, /* True for final fragment in snippet */
  144846. int nSnippet, /* Number of tokens in extracted snippet */
  144847. const char *zOpen, /* String inserted before highlighted term */
  144848. const char *zClose, /* String inserted after highlighted term */
  144849. const char *zEllipsis, /* String inserted between snippets */
  144850. StrBuffer *pOut /* Write output here */
  144851. ){
  144852. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  144853. int rc; /* Return code */
  144854. const char *zDoc; /* Document text to extract snippet from */
  144855. int nDoc; /* Size of zDoc in bytes */
  144856. int iCurrent = 0; /* Current token number of document */
  144857. int iEnd = 0; /* Byte offset of end of current token */
  144858. int isShiftDone = 0; /* True after snippet is shifted */
  144859. int iPos = pFragment->iPos; /* First token of snippet */
  144860. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  144861. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  144862. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  144863. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  144864. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  144865. if( zDoc==0 ){
  144866. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  144867. return SQLITE_NOMEM;
  144868. }
  144869. return SQLITE_OK;
  144870. }
  144871. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  144872. /* Open a token cursor on the document. */
  144873. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  144874. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  144875. if( rc!=SQLITE_OK ){
  144876. return rc;
  144877. }
  144878. while( rc==SQLITE_OK ){
  144879. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  144880. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  144881. int iBegin = 0; /* Offset in zDoc of start of token */
  144882. int iFin = 0; /* Offset in zDoc of end of token */
  144883. int isHighlight = 0; /* True for highlighted terms */
  144884. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  144885. ** in the FTS code the variable that the third argument to xNext points to
  144886. ** is initialized to zero before the first (*but not necessarily
  144887. ** subsequent*) call to xNext(). This is done for a particular application
  144888. ** that needs to know whether or not the tokenizer is being used for
  144889. ** snippet generation or for some other purpose.
  144890. **
  144891. ** Extreme care is required when writing code to depend on this
  144892. ** initialization. It is not a documented part of the tokenizer interface.
  144893. ** If a tokenizer is used directly by any code outside of FTS, this
  144894. ** convention might not be respected. */
  144895. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  144896. if( rc!=SQLITE_OK ){
  144897. if( rc==SQLITE_DONE ){
  144898. /* Special case - the last token of the snippet is also the last token
  144899. ** of the column. Append any punctuation that occurred between the end
  144900. ** of the previous token and the end of the document to the output.
  144901. ** Then break out of the loop. */
  144902. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  144903. }
  144904. break;
  144905. }
  144906. if( iCurrent<iPos ){ continue; }
  144907. if( !isShiftDone ){
  144908. int n = nDoc - iBegin;
  144909. rc = fts3SnippetShift(
  144910. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  144911. );
  144912. isShiftDone = 1;
  144913. /* Now that the shift has been done, check if the initial "..." are
  144914. ** required. They are required if (a) this is not the first fragment,
  144915. ** or (b) this fragment does not begin at position 0 of its column.
  144916. */
  144917. if( rc==SQLITE_OK ){
  144918. if( iPos>0 || iFragment>0 ){
  144919. rc = fts3StringAppend(pOut, zEllipsis, -1);
  144920. }else if( iBegin ){
  144921. rc = fts3StringAppend(pOut, zDoc, iBegin);
  144922. }
  144923. }
  144924. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  144925. }
  144926. if( iCurrent>=(iPos+nSnippet) ){
  144927. if( isLast ){
  144928. rc = fts3StringAppend(pOut, zEllipsis, -1);
  144929. }
  144930. break;
  144931. }
  144932. /* Set isHighlight to true if this term should be highlighted. */
  144933. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  144934. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  144935. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  144936. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  144937. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  144938. iEnd = iFin;
  144939. }
  144940. pMod->xClose(pC);
  144941. return rc;
  144942. }
  144943. /*
  144944. ** This function is used to count the entries in a column-list (a
  144945. ** delta-encoded list of term offsets within a single column of a single
  144946. ** row). When this function is called, *ppCollist should point to the
  144947. ** beginning of the first varint in the column-list (the varint that
  144948. ** contains the position of the first matching term in the column data).
  144949. ** Before returning, *ppCollist is set to point to the first byte after
  144950. ** the last varint in the column-list (either the 0x00 signifying the end
  144951. ** of the position-list, or the 0x01 that precedes the column number of
  144952. ** the next column in the position-list).
  144953. **
  144954. ** The number of elements in the column-list is returned.
  144955. */
  144956. static int fts3ColumnlistCount(char **ppCollist){
  144957. char *pEnd = *ppCollist;
  144958. char c = 0;
  144959. int nEntry = 0;
  144960. /* A column-list is terminated by either a 0x01 or 0x00. */
  144961. while( 0xFE & (*pEnd | c) ){
  144962. c = *pEnd++ & 0x80;
  144963. if( !c ) nEntry++;
  144964. }
  144965. *ppCollist = pEnd;
  144966. return nEntry;
  144967. }
  144968. /*
  144969. ** This function gathers 'y' or 'b' data for a single phrase.
  144970. */
  144971. static void fts3ExprLHits(
  144972. Fts3Expr *pExpr, /* Phrase expression node */
  144973. MatchInfo *p /* Matchinfo context */
  144974. ){
  144975. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  144976. int iStart;
  144977. Fts3Phrase *pPhrase = pExpr->pPhrase;
  144978. char *pIter = pPhrase->doclist.pList;
  144979. int iCol = 0;
  144980. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  144981. if( p->flag==FTS3_MATCHINFO_LHITS ){
  144982. iStart = pExpr->iPhrase * p->nCol;
  144983. }else{
  144984. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  144985. }
  144986. while( 1 ){
  144987. int nHit = fts3ColumnlistCount(&pIter);
  144988. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  144989. if( p->flag==FTS3_MATCHINFO_LHITS ){
  144990. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  144991. }else if( nHit ){
  144992. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  144993. }
  144994. }
  144995. assert( *pIter==0x00 || *pIter==0x01 );
  144996. if( *pIter!=0x01 ) break;
  144997. pIter++;
  144998. pIter += fts3GetVarint32(pIter, &iCol);
  144999. }
  145000. }
  145001. /*
  145002. ** Gather the results for matchinfo directives 'y' and 'b'.
  145003. */
  145004. static void fts3ExprLHitGather(
  145005. Fts3Expr *pExpr,
  145006. MatchInfo *p
  145007. ){
  145008. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  145009. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  145010. if( pExpr->pLeft ){
  145011. fts3ExprLHitGather(pExpr->pLeft, p);
  145012. fts3ExprLHitGather(pExpr->pRight, p);
  145013. }else{
  145014. fts3ExprLHits(pExpr, p);
  145015. }
  145016. }
  145017. }
  145018. /*
  145019. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  145020. ** for a single query.
  145021. **
  145022. ** fts3ExprIterate() callback to load the 'global' elements of a
  145023. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  145024. ** of the matchinfo array that are constant for all rows returned by the
  145025. ** current query.
  145026. **
  145027. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  145028. ** function populates Matchinfo.aMatchinfo[] as follows:
  145029. **
  145030. ** for(iCol=0; iCol<nCol; iCol++){
  145031. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  145032. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  145033. ** }
  145034. **
  145035. ** where X is the number of matches for phrase iPhrase is column iCol of all
  145036. ** rows of the table. Y is the number of rows for which column iCol contains
  145037. ** at least one instance of phrase iPhrase.
  145038. **
  145039. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  145040. ** Y values are set to nDoc, where nDoc is the number of documents in the
  145041. ** file system. This is done because the full-text index doclist is required
  145042. ** to calculate these values properly, and the full-text index doclist is
  145043. ** not available for deferred tokens.
  145044. */
  145045. static int fts3ExprGlobalHitsCb(
  145046. Fts3Expr *pExpr, /* Phrase expression node */
  145047. int iPhrase, /* Phrase number (numbered from zero) */
  145048. void *pCtx /* Pointer to MatchInfo structure */
  145049. ){
  145050. MatchInfo *p = (MatchInfo *)pCtx;
  145051. return sqlite3Fts3EvalPhraseStats(
  145052. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  145053. );
  145054. }
  145055. /*
  145056. ** fts3ExprIterate() callback used to collect the "local" part of the
  145057. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  145058. ** array that are different for each row returned by the query.
  145059. */
  145060. static int fts3ExprLocalHitsCb(
  145061. Fts3Expr *pExpr, /* Phrase expression node */
  145062. int iPhrase, /* Phrase number */
  145063. void *pCtx /* Pointer to MatchInfo structure */
  145064. ){
  145065. int rc = SQLITE_OK;
  145066. MatchInfo *p = (MatchInfo *)pCtx;
  145067. int iStart = iPhrase * p->nCol * 3;
  145068. int i;
  145069. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  145070. char *pCsr;
  145071. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  145072. if( pCsr ){
  145073. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  145074. }else{
  145075. p->aMatchinfo[iStart+i*3] = 0;
  145076. }
  145077. }
  145078. return rc;
  145079. }
  145080. static int fts3MatchinfoCheck(
  145081. Fts3Table *pTab,
  145082. char cArg,
  145083. char **pzErr
  145084. ){
  145085. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  145086. || (cArg==FTS3_MATCHINFO_NCOL)
  145087. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  145088. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  145089. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  145090. || (cArg==FTS3_MATCHINFO_LCS)
  145091. || (cArg==FTS3_MATCHINFO_HITS)
  145092. || (cArg==FTS3_MATCHINFO_LHITS)
  145093. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  145094. ){
  145095. return SQLITE_OK;
  145096. }
  145097. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  145098. return SQLITE_ERROR;
  145099. }
  145100. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  145101. int nVal; /* Number of integers output by cArg */
  145102. switch( cArg ){
  145103. case FTS3_MATCHINFO_NDOC:
  145104. case FTS3_MATCHINFO_NPHRASE:
  145105. case FTS3_MATCHINFO_NCOL:
  145106. nVal = 1;
  145107. break;
  145108. case FTS3_MATCHINFO_AVGLENGTH:
  145109. case FTS3_MATCHINFO_LENGTH:
  145110. case FTS3_MATCHINFO_LCS:
  145111. nVal = pInfo->nCol;
  145112. break;
  145113. case FTS3_MATCHINFO_LHITS:
  145114. nVal = pInfo->nCol * pInfo->nPhrase;
  145115. break;
  145116. case FTS3_MATCHINFO_LHITS_BM:
  145117. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  145118. break;
  145119. default:
  145120. assert( cArg==FTS3_MATCHINFO_HITS );
  145121. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  145122. break;
  145123. }
  145124. return nVal;
  145125. }
  145126. static int fts3MatchinfoSelectDoctotal(
  145127. Fts3Table *pTab,
  145128. sqlite3_stmt **ppStmt,
  145129. sqlite3_int64 *pnDoc,
  145130. const char **paLen
  145131. ){
  145132. sqlite3_stmt *pStmt;
  145133. const char *a;
  145134. sqlite3_int64 nDoc;
  145135. if( !*ppStmt ){
  145136. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  145137. if( rc!=SQLITE_OK ) return rc;
  145138. }
  145139. pStmt = *ppStmt;
  145140. assert( sqlite3_data_count(pStmt)==1 );
  145141. a = sqlite3_column_blob(pStmt, 0);
  145142. a += sqlite3Fts3GetVarint(a, &nDoc);
  145143. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  145144. *pnDoc = (u32)nDoc;
  145145. if( paLen ) *paLen = a;
  145146. return SQLITE_OK;
  145147. }
  145148. /*
  145149. ** An instance of the following structure is used to store state while
  145150. ** iterating through a multi-column position-list corresponding to the
  145151. ** hits for a single phrase on a single row in order to calculate the
  145152. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  145153. */
  145154. typedef struct LcsIterator LcsIterator;
  145155. struct LcsIterator {
  145156. Fts3Expr *pExpr; /* Pointer to phrase expression */
  145157. int iPosOffset; /* Tokens count up to end of this phrase */
  145158. char *pRead; /* Cursor used to iterate through aDoclist */
  145159. int iPos; /* Current position */
  145160. };
  145161. /*
  145162. ** If LcsIterator.iCol is set to the following value, the iterator has
  145163. ** finished iterating through all offsets for all columns.
  145164. */
  145165. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  145166. static int fts3MatchinfoLcsCb(
  145167. Fts3Expr *pExpr, /* Phrase expression node */
  145168. int iPhrase, /* Phrase number (numbered from zero) */
  145169. void *pCtx /* Pointer to MatchInfo structure */
  145170. ){
  145171. LcsIterator *aIter = (LcsIterator *)pCtx;
  145172. aIter[iPhrase].pExpr = pExpr;
  145173. return SQLITE_OK;
  145174. }
  145175. /*
  145176. ** Advance the iterator passed as an argument to the next position. Return
  145177. ** 1 if the iterator is at EOF or if it now points to the start of the
  145178. ** position list for the next column.
  145179. */
  145180. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  145181. char *pRead = pIter->pRead;
  145182. sqlite3_int64 iRead;
  145183. int rc = 0;
  145184. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  145185. if( iRead==0 || iRead==1 ){
  145186. pRead = 0;
  145187. rc = 1;
  145188. }else{
  145189. pIter->iPos += (int)(iRead-2);
  145190. }
  145191. pIter->pRead = pRead;
  145192. return rc;
  145193. }
  145194. /*
  145195. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  145196. **
  145197. ** If the call is successful, the longest-common-substring lengths for each
  145198. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  145199. ** array before returning. SQLITE_OK is returned in this case.
  145200. **
  145201. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  145202. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  145203. ** undefined.
  145204. */
  145205. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  145206. LcsIterator *aIter;
  145207. int i;
  145208. int iCol;
  145209. int nToken = 0;
  145210. /* Allocate and populate the array of LcsIterator objects. The array
  145211. ** contains one element for each matchable phrase in the query.
  145212. **/
  145213. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  145214. if( !aIter ) return SQLITE_NOMEM;
  145215. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  145216. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  145217. for(i=0; i<pInfo->nPhrase; i++){
  145218. LcsIterator *pIter = &aIter[i];
  145219. nToken -= pIter->pExpr->pPhrase->nToken;
  145220. pIter->iPosOffset = nToken;
  145221. }
  145222. for(iCol=0; iCol<pInfo->nCol; iCol++){
  145223. int nLcs = 0; /* LCS value for this column */
  145224. int nLive = 0; /* Number of iterators in aIter not at EOF */
  145225. for(i=0; i<pInfo->nPhrase; i++){
  145226. int rc;
  145227. LcsIterator *pIt = &aIter[i];
  145228. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  145229. if( rc!=SQLITE_OK ) return rc;
  145230. if( pIt->pRead ){
  145231. pIt->iPos = pIt->iPosOffset;
  145232. fts3LcsIteratorAdvance(&aIter[i]);
  145233. nLive++;
  145234. }
  145235. }
  145236. while( nLive>0 ){
  145237. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  145238. int nThisLcs = 0; /* LCS for the current iterator positions */
  145239. for(i=0; i<pInfo->nPhrase; i++){
  145240. LcsIterator *pIter = &aIter[i];
  145241. if( pIter->pRead==0 ){
  145242. /* This iterator is already at EOF for this column. */
  145243. nThisLcs = 0;
  145244. }else{
  145245. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  145246. pAdv = pIter;
  145247. }
  145248. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  145249. nThisLcs++;
  145250. }else{
  145251. nThisLcs = 1;
  145252. }
  145253. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  145254. }
  145255. }
  145256. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  145257. }
  145258. pInfo->aMatchinfo[iCol] = nLcs;
  145259. }
  145260. sqlite3_free(aIter);
  145261. return SQLITE_OK;
  145262. }
  145263. /*
  145264. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  145265. ** be returned by the matchinfo() function. Argument zArg contains the
  145266. ** format string passed as the second argument to matchinfo (or the
  145267. ** default value "pcx" if no second argument was specified). The format
  145268. ** string has already been validated and the pInfo->aMatchinfo[] array
  145269. ** is guaranteed to be large enough for the output.
  145270. **
  145271. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  145272. ** If it is false, then assume that those fields that do not change between
  145273. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  145274. ** have already been populated.
  145275. **
  145276. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  145277. ** occurs. If a value other than SQLITE_OK is returned, the state the
  145278. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  145279. */
  145280. static int fts3MatchinfoValues(
  145281. Fts3Cursor *pCsr, /* FTS3 cursor object */
  145282. int bGlobal, /* True to grab the global stats */
  145283. MatchInfo *pInfo, /* Matchinfo context object */
  145284. const char *zArg /* Matchinfo format string */
  145285. ){
  145286. int rc = SQLITE_OK;
  145287. int i;
  145288. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145289. sqlite3_stmt *pSelect = 0;
  145290. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  145291. pInfo->flag = zArg[i];
  145292. switch( zArg[i] ){
  145293. case FTS3_MATCHINFO_NPHRASE:
  145294. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  145295. break;
  145296. case FTS3_MATCHINFO_NCOL:
  145297. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  145298. break;
  145299. case FTS3_MATCHINFO_NDOC:
  145300. if( bGlobal ){
  145301. sqlite3_int64 nDoc = 0;
  145302. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  145303. pInfo->aMatchinfo[0] = (u32)nDoc;
  145304. }
  145305. break;
  145306. case FTS3_MATCHINFO_AVGLENGTH:
  145307. if( bGlobal ){
  145308. sqlite3_int64 nDoc; /* Number of rows in table */
  145309. const char *a; /* Aggregate column length array */
  145310. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  145311. if( rc==SQLITE_OK ){
  145312. int iCol;
  145313. for(iCol=0; iCol<pInfo->nCol; iCol++){
  145314. u32 iVal;
  145315. sqlite3_int64 nToken;
  145316. a += sqlite3Fts3GetVarint(a, &nToken);
  145317. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  145318. pInfo->aMatchinfo[iCol] = iVal;
  145319. }
  145320. }
  145321. }
  145322. break;
  145323. case FTS3_MATCHINFO_LENGTH: {
  145324. sqlite3_stmt *pSelectDocsize = 0;
  145325. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  145326. if( rc==SQLITE_OK ){
  145327. int iCol;
  145328. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  145329. for(iCol=0; iCol<pInfo->nCol; iCol++){
  145330. sqlite3_int64 nToken;
  145331. a += sqlite3Fts3GetVarint(a, &nToken);
  145332. pInfo->aMatchinfo[iCol] = (u32)nToken;
  145333. }
  145334. }
  145335. sqlite3_reset(pSelectDocsize);
  145336. break;
  145337. }
  145338. case FTS3_MATCHINFO_LCS:
  145339. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  145340. if( rc==SQLITE_OK ){
  145341. rc = fts3MatchinfoLcs(pCsr, pInfo);
  145342. }
  145343. break;
  145344. case FTS3_MATCHINFO_LHITS_BM:
  145345. case FTS3_MATCHINFO_LHITS: {
  145346. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  145347. memset(pInfo->aMatchinfo, 0, nZero);
  145348. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  145349. break;
  145350. }
  145351. default: {
  145352. Fts3Expr *pExpr;
  145353. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  145354. pExpr = pCsr->pExpr;
  145355. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  145356. if( rc!=SQLITE_OK ) break;
  145357. if( bGlobal ){
  145358. if( pCsr->pDeferred ){
  145359. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  145360. if( rc!=SQLITE_OK ) break;
  145361. }
  145362. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  145363. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  145364. if( rc!=SQLITE_OK ) break;
  145365. }
  145366. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  145367. break;
  145368. }
  145369. }
  145370. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  145371. }
  145372. sqlite3_reset(pSelect);
  145373. return rc;
  145374. }
  145375. /*
  145376. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  145377. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  145378. */
  145379. static void fts3GetMatchinfo(
  145380. sqlite3_context *pCtx, /* Return results here */
  145381. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  145382. const char *zArg /* Second argument to matchinfo() function */
  145383. ){
  145384. MatchInfo sInfo;
  145385. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145386. int rc = SQLITE_OK;
  145387. int bGlobal = 0; /* Collect 'global' stats as well as local */
  145388. u32 *aOut = 0;
  145389. void (*xDestroyOut)(void*) = 0;
  145390. memset(&sInfo, 0, sizeof(MatchInfo));
  145391. sInfo.pCursor = pCsr;
  145392. sInfo.nCol = pTab->nColumn;
  145393. /* If there is cached matchinfo() data, but the format string for the
  145394. ** cache does not match the format string for this request, discard
  145395. ** the cached data. */
  145396. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  145397. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  145398. pCsr->pMIBuffer = 0;
  145399. }
  145400. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  145401. ** matchinfo function has been called for this query. In this case
  145402. ** allocate the array used to accumulate the matchinfo data and
  145403. ** initialize those elements that are constant for every row.
  145404. */
  145405. if( pCsr->pMIBuffer==0 ){
  145406. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  145407. int i; /* Used to iterate through zArg */
  145408. /* Determine the number of phrases in the query */
  145409. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  145410. sInfo.nPhrase = pCsr->nPhrase;
  145411. /* Determine the number of integers in the buffer returned by this call. */
  145412. for(i=0; zArg[i]; i++){
  145413. char *zErr = 0;
  145414. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  145415. sqlite3_result_error(pCtx, zErr, -1);
  145416. sqlite3_free(zErr);
  145417. return;
  145418. }
  145419. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  145420. }
  145421. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  145422. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  145423. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  145424. pCsr->isMatchinfoNeeded = 1;
  145425. bGlobal = 1;
  145426. }
  145427. if( rc==SQLITE_OK ){
  145428. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  145429. if( xDestroyOut==0 ){
  145430. rc = SQLITE_NOMEM;
  145431. }
  145432. }
  145433. if( rc==SQLITE_OK ){
  145434. sInfo.aMatchinfo = aOut;
  145435. sInfo.nPhrase = pCsr->nPhrase;
  145436. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  145437. if( bGlobal ){
  145438. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  145439. }
  145440. }
  145441. if( rc!=SQLITE_OK ){
  145442. sqlite3_result_error_code(pCtx, rc);
  145443. if( xDestroyOut ) xDestroyOut(aOut);
  145444. }else{
  145445. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  145446. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  145447. }
  145448. }
  145449. /*
  145450. ** Implementation of snippet() function.
  145451. */
  145452. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  145453. sqlite3_context *pCtx, /* SQLite function call context */
  145454. Fts3Cursor *pCsr, /* Cursor object */
  145455. const char *zStart, /* Snippet start text - "<b>" */
  145456. const char *zEnd, /* Snippet end text - "</b>" */
  145457. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  145458. int iCol, /* Extract snippet from this column */
  145459. int nToken /* Approximate number of tokens in snippet */
  145460. ){
  145461. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145462. int rc = SQLITE_OK;
  145463. int i;
  145464. StrBuffer res = {0, 0, 0};
  145465. /* The returned text includes up to four fragments of text extracted from
  145466. ** the data in the current row. The first iteration of the for(...) loop
  145467. ** below attempts to locate a single fragment of text nToken tokens in
  145468. ** size that contains at least one instance of all phrases in the query
  145469. ** expression that appear in the current row. If such a fragment of text
  145470. ** cannot be found, the second iteration of the loop attempts to locate
  145471. ** a pair of fragments, and so on.
  145472. */
  145473. int nSnippet = 0; /* Number of fragments in this snippet */
  145474. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  145475. int nFToken = -1; /* Number of tokens in each fragment */
  145476. if( !pCsr->pExpr ){
  145477. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  145478. return;
  145479. }
  145480. for(nSnippet=1; 1; nSnippet++){
  145481. int iSnip; /* Loop counter 0..nSnippet-1 */
  145482. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  145483. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  145484. if( nToken>=0 ){
  145485. nFToken = (nToken+nSnippet-1) / nSnippet;
  145486. }else{
  145487. nFToken = -1 * nToken;
  145488. }
  145489. for(iSnip=0; iSnip<nSnippet; iSnip++){
  145490. int iBestScore = -1; /* Best score of columns checked so far */
  145491. int iRead; /* Used to iterate through columns */
  145492. SnippetFragment *pFragment = &aSnippet[iSnip];
  145493. memset(pFragment, 0, sizeof(*pFragment));
  145494. /* Loop through all columns of the table being considered for snippets.
  145495. ** If the iCol argument to this function was negative, this means all
  145496. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  145497. */
  145498. for(iRead=0; iRead<pTab->nColumn; iRead++){
  145499. SnippetFragment sF = {0, 0, 0, 0};
  145500. int iS = 0;
  145501. if( iCol>=0 && iRead!=iCol ) continue;
  145502. /* Find the best snippet of nFToken tokens in column iRead. */
  145503. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  145504. if( rc!=SQLITE_OK ){
  145505. goto snippet_out;
  145506. }
  145507. if( iS>iBestScore ){
  145508. *pFragment = sF;
  145509. iBestScore = iS;
  145510. }
  145511. }
  145512. mCovered |= pFragment->covered;
  145513. }
  145514. /* If all query phrases seen by fts3BestSnippet() are present in at least
  145515. ** one of the nSnippet snippet fragments, break out of the loop.
  145516. */
  145517. assert( (mCovered&mSeen)==mCovered );
  145518. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  145519. }
  145520. assert( nFToken>0 );
  145521. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  145522. rc = fts3SnippetText(pCsr, &aSnippet[i],
  145523. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  145524. );
  145525. }
  145526. snippet_out:
  145527. sqlite3Fts3SegmentsClose(pTab);
  145528. if( rc!=SQLITE_OK ){
  145529. sqlite3_result_error_code(pCtx, rc);
  145530. sqlite3_free(res.z);
  145531. }else{
  145532. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  145533. }
  145534. }
  145535. typedef struct TermOffset TermOffset;
  145536. typedef struct TermOffsetCtx TermOffsetCtx;
  145537. struct TermOffset {
  145538. char *pList; /* Position-list */
  145539. int iPos; /* Position just read from pList */
  145540. int iOff; /* Offset of this term from read positions */
  145541. };
  145542. struct TermOffsetCtx {
  145543. Fts3Cursor *pCsr;
  145544. int iCol; /* Column of table to populate aTerm for */
  145545. int iTerm;
  145546. sqlite3_int64 iDocid;
  145547. TermOffset *aTerm;
  145548. };
  145549. /*
  145550. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  145551. */
  145552. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  145553. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  145554. int nTerm; /* Number of tokens in phrase */
  145555. int iTerm; /* For looping through nTerm phrase terms */
  145556. char *pList; /* Pointer to position list for phrase */
  145557. int iPos = 0; /* First position in position-list */
  145558. int rc;
  145559. UNUSED_PARAMETER(iPhrase);
  145560. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  145561. nTerm = pExpr->pPhrase->nToken;
  145562. if( pList ){
  145563. fts3GetDeltaPosition(&pList, &iPos);
  145564. assert( iPos>=0 );
  145565. }
  145566. for(iTerm=0; iTerm<nTerm; iTerm++){
  145567. TermOffset *pT = &p->aTerm[p->iTerm++];
  145568. pT->iOff = nTerm-iTerm-1;
  145569. pT->pList = pList;
  145570. pT->iPos = iPos;
  145571. }
  145572. return rc;
  145573. }
  145574. /*
  145575. ** Implementation of offsets() function.
  145576. */
  145577. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  145578. sqlite3_context *pCtx, /* SQLite function call context */
  145579. Fts3Cursor *pCsr /* Cursor object */
  145580. ){
  145581. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145582. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  145583. int rc; /* Return Code */
  145584. int nToken; /* Number of tokens in query */
  145585. int iCol; /* Column currently being processed */
  145586. StrBuffer res = {0, 0, 0}; /* Result string */
  145587. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  145588. if( !pCsr->pExpr ){
  145589. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  145590. return;
  145591. }
  145592. memset(&sCtx, 0, sizeof(sCtx));
  145593. assert( pCsr->isRequireSeek==0 );
  145594. /* Count the number of terms in the query */
  145595. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  145596. if( rc!=SQLITE_OK ) goto offsets_out;
  145597. /* Allocate the array of TermOffset iterators. */
  145598. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  145599. if( 0==sCtx.aTerm ){
  145600. rc = SQLITE_NOMEM;
  145601. goto offsets_out;
  145602. }
  145603. sCtx.iDocid = pCsr->iPrevId;
  145604. sCtx.pCsr = pCsr;
  145605. /* Loop through the table columns, appending offset information to
  145606. ** string-buffer res for each column.
  145607. */
  145608. for(iCol=0; iCol<pTab->nColumn; iCol++){
  145609. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  145610. const char *ZDUMMY; /* Dummy argument used with xNext() */
  145611. int NDUMMY = 0; /* Dummy argument used with xNext() */
  145612. int iStart = 0;
  145613. int iEnd = 0;
  145614. int iCurrent = 0;
  145615. const char *zDoc;
  145616. int nDoc;
  145617. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  145618. ** no way that this operation can fail, so the return code from
  145619. ** fts3ExprIterate() can be discarded.
  145620. */
  145621. sCtx.iCol = iCol;
  145622. sCtx.iTerm = 0;
  145623. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  145624. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  145625. ** in column iCol, jump immediately to the next iteration of the loop.
  145626. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  145627. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  145628. ** to the caller.
  145629. */
  145630. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  145631. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  145632. if( zDoc==0 ){
  145633. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  145634. continue;
  145635. }
  145636. rc = SQLITE_NOMEM;
  145637. goto offsets_out;
  145638. }
  145639. /* Initialize a tokenizer iterator to iterate through column iCol. */
  145640. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  145641. zDoc, nDoc, &pC
  145642. );
  145643. if( rc!=SQLITE_OK ) goto offsets_out;
  145644. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  145645. while( rc==SQLITE_OK ){
  145646. int i; /* Used to loop through terms */
  145647. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  145648. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  145649. for(i=0; i<nToken; i++){
  145650. TermOffset *pT = &sCtx.aTerm[i];
  145651. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  145652. iMinPos = pT->iPos-pT->iOff;
  145653. pTerm = pT;
  145654. }
  145655. }
  145656. if( !pTerm ){
  145657. /* All offsets for this column have been gathered. */
  145658. rc = SQLITE_DONE;
  145659. }else{
  145660. assert( iCurrent<=iMinPos );
  145661. if( 0==(0xFE&*pTerm->pList) ){
  145662. pTerm->pList = 0;
  145663. }else{
  145664. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  145665. }
  145666. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  145667. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  145668. }
  145669. if( rc==SQLITE_OK ){
  145670. char aBuffer[64];
  145671. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  145672. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  145673. );
  145674. rc = fts3StringAppend(&res, aBuffer, -1);
  145675. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  145676. rc = FTS_CORRUPT_VTAB;
  145677. }
  145678. }
  145679. }
  145680. if( rc==SQLITE_DONE ){
  145681. rc = SQLITE_OK;
  145682. }
  145683. pMod->xClose(pC);
  145684. if( rc!=SQLITE_OK ) goto offsets_out;
  145685. }
  145686. offsets_out:
  145687. sqlite3_free(sCtx.aTerm);
  145688. assert( rc!=SQLITE_DONE );
  145689. sqlite3Fts3SegmentsClose(pTab);
  145690. if( rc!=SQLITE_OK ){
  145691. sqlite3_result_error_code(pCtx, rc);
  145692. sqlite3_free(res.z);
  145693. }else{
  145694. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  145695. }
  145696. return;
  145697. }
  145698. /*
  145699. ** Implementation of matchinfo() function.
  145700. */
  145701. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  145702. sqlite3_context *pContext, /* Function call context */
  145703. Fts3Cursor *pCsr, /* FTS3 table cursor */
  145704. const char *zArg /* Second arg to matchinfo() function */
  145705. ){
  145706. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145707. const char *zFormat;
  145708. if( zArg ){
  145709. zFormat = zArg;
  145710. }else{
  145711. zFormat = FTS3_MATCHINFO_DEFAULT;
  145712. }
  145713. if( !pCsr->pExpr ){
  145714. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  145715. return;
  145716. }else{
  145717. /* Retrieve matchinfo() data. */
  145718. fts3GetMatchinfo(pContext, pCsr, zFormat);
  145719. sqlite3Fts3SegmentsClose(pTab);
  145720. }
  145721. }
  145722. #endif
  145723. /************** End of fts3_snippet.c ****************************************/
  145724. /************** Begin file fts3_unicode.c ************************************/
  145725. /*
  145726. ** 2012 May 24
  145727. **
  145728. ** The author disclaims copyright to this source code. In place of
  145729. ** a legal notice, here is a blessing:
  145730. **
  145731. ** May you do good and not evil.
  145732. ** May you find forgiveness for yourself and forgive others.
  145733. ** May you share freely, never taking more than you give.
  145734. **
  145735. ******************************************************************************
  145736. **
  145737. ** Implementation of the "unicode" full-text-search tokenizer.
  145738. */
  145739. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  145740. /* #include "fts3Int.h" */
  145741. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145742. /* #include <assert.h> */
  145743. /* #include <stdlib.h> */
  145744. /* #include <stdio.h> */
  145745. /* #include <string.h> */
  145746. /* #include "fts3_tokenizer.h" */
  145747. /*
  145748. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  145749. ** from the sqlite3 source file utf.c. If this file is compiled as part
  145750. ** of the amalgamation, they are not required.
  145751. */
  145752. #ifndef SQLITE_AMALGAMATION
  145753. static const unsigned char sqlite3Utf8Trans1[] = {
  145754. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  145755. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  145756. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  145757. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  145758. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  145759. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  145760. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  145761. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  145762. };
  145763. #define READ_UTF8(zIn, zTerm, c) \
  145764. c = *(zIn++); \
  145765. if( c>=0xc0 ){ \
  145766. c = sqlite3Utf8Trans1[c-0xc0]; \
  145767. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  145768. c = (c<<6) + (0x3f & *(zIn++)); \
  145769. } \
  145770. if( c<0x80 \
  145771. || (c&0xFFFFF800)==0xD800 \
  145772. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  145773. }
  145774. #define WRITE_UTF8(zOut, c) { \
  145775. if( c<0x00080 ){ \
  145776. *zOut++ = (u8)(c&0xFF); \
  145777. } \
  145778. else if( c<0x00800 ){ \
  145779. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  145780. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  145781. } \
  145782. else if( c<0x10000 ){ \
  145783. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  145784. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  145785. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  145786. }else{ \
  145787. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  145788. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  145789. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  145790. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  145791. } \
  145792. }
  145793. #endif /* ifndef SQLITE_AMALGAMATION */
  145794. typedef struct unicode_tokenizer unicode_tokenizer;
  145795. typedef struct unicode_cursor unicode_cursor;
  145796. struct unicode_tokenizer {
  145797. sqlite3_tokenizer base;
  145798. int bRemoveDiacritic;
  145799. int nException;
  145800. int *aiException;
  145801. };
  145802. struct unicode_cursor {
  145803. sqlite3_tokenizer_cursor base;
  145804. const unsigned char *aInput; /* Input text being tokenized */
  145805. int nInput; /* Size of aInput[] in bytes */
  145806. int iOff; /* Current offset within aInput[] */
  145807. int iToken; /* Index of next token to be returned */
  145808. char *zToken; /* storage for current token */
  145809. int nAlloc; /* space allocated at zToken */
  145810. };
  145811. /*
  145812. ** Destroy a tokenizer allocated by unicodeCreate().
  145813. */
  145814. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  145815. if( pTokenizer ){
  145816. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  145817. sqlite3_free(p->aiException);
  145818. sqlite3_free(p);
  145819. }
  145820. return SQLITE_OK;
  145821. }
  145822. /*
  145823. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  145824. ** statement has specified that the tokenizer for this table shall consider
  145825. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  145826. ** token characters (if bAlnum==1).
  145827. **
  145828. ** For each codepoint in the zIn/nIn string, this function checks if the
  145829. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  145830. ** If so, no action is taken. Otherwise, the codepoint is added to the
  145831. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  145832. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  145833. ** codepoints in the aiException[] array.
  145834. **
  145835. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  145836. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  145837. ** It is not possible to change the behavior of the tokenizer with respect
  145838. ** to these codepoints.
  145839. */
  145840. static int unicodeAddExceptions(
  145841. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  145842. int bAlnum, /* Replace Isalnum() return value with this */
  145843. const char *zIn, /* Array of characters to make exceptions */
  145844. int nIn /* Length of z in bytes */
  145845. ){
  145846. const unsigned char *z = (const unsigned char *)zIn;
  145847. const unsigned char *zTerm = &z[nIn];
  145848. int iCode;
  145849. int nEntry = 0;
  145850. assert( bAlnum==0 || bAlnum==1 );
  145851. while( z<zTerm ){
  145852. READ_UTF8(z, zTerm, iCode);
  145853. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  145854. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  145855. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  145856. ){
  145857. nEntry++;
  145858. }
  145859. }
  145860. if( nEntry ){
  145861. int *aNew; /* New aiException[] array */
  145862. int nNew; /* Number of valid entries in array aNew[] */
  145863. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  145864. if( aNew==0 ) return SQLITE_NOMEM;
  145865. nNew = p->nException;
  145866. z = (const unsigned char *)zIn;
  145867. while( z<zTerm ){
  145868. READ_UTF8(z, zTerm, iCode);
  145869. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  145870. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  145871. ){
  145872. int i, j;
  145873. for(i=0; i<nNew && aNew[i]<iCode; i++);
  145874. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  145875. aNew[i] = iCode;
  145876. nNew++;
  145877. }
  145878. }
  145879. p->aiException = aNew;
  145880. p->nException = nNew;
  145881. }
  145882. return SQLITE_OK;
  145883. }
  145884. /*
  145885. ** Return true if the p->aiException[] array contains the value iCode.
  145886. */
  145887. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  145888. if( p->nException>0 ){
  145889. int *a = p->aiException;
  145890. int iLo = 0;
  145891. int iHi = p->nException-1;
  145892. while( iHi>=iLo ){
  145893. int iTest = (iHi + iLo) / 2;
  145894. if( iCode==a[iTest] ){
  145895. return 1;
  145896. }else if( iCode>a[iTest] ){
  145897. iLo = iTest+1;
  145898. }else{
  145899. iHi = iTest-1;
  145900. }
  145901. }
  145902. }
  145903. return 0;
  145904. }
  145905. /*
  145906. ** Return true if, for the purposes of tokenization, codepoint iCode is
  145907. ** considered a token character (not a separator).
  145908. */
  145909. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  145910. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  145911. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  145912. }
  145913. /*
  145914. ** Create a new tokenizer instance.
  145915. */
  145916. static int unicodeCreate(
  145917. int nArg, /* Size of array argv[] */
  145918. const char * const *azArg, /* Tokenizer creation arguments */
  145919. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  145920. ){
  145921. unicode_tokenizer *pNew; /* New tokenizer object */
  145922. int i;
  145923. int rc = SQLITE_OK;
  145924. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  145925. if( pNew==NULL ) return SQLITE_NOMEM;
  145926. memset(pNew, 0, sizeof(unicode_tokenizer));
  145927. pNew->bRemoveDiacritic = 1;
  145928. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  145929. const char *z = azArg[i];
  145930. int n = (int)strlen(z);
  145931. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  145932. pNew->bRemoveDiacritic = 1;
  145933. }
  145934. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  145935. pNew->bRemoveDiacritic = 0;
  145936. }
  145937. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  145938. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  145939. }
  145940. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  145941. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  145942. }
  145943. else{
  145944. /* Unrecognized argument */
  145945. rc = SQLITE_ERROR;
  145946. }
  145947. }
  145948. if( rc!=SQLITE_OK ){
  145949. unicodeDestroy((sqlite3_tokenizer *)pNew);
  145950. pNew = 0;
  145951. }
  145952. *pp = (sqlite3_tokenizer *)pNew;
  145953. return rc;
  145954. }
  145955. /*
  145956. ** Prepare to begin tokenizing a particular string. The input
  145957. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  145958. ** used to incrementally tokenize this string is returned in
  145959. ** *ppCursor.
  145960. */
  145961. static int unicodeOpen(
  145962. sqlite3_tokenizer *p, /* The tokenizer */
  145963. const char *aInput, /* Input string */
  145964. int nInput, /* Size of string aInput in bytes */
  145965. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  145966. ){
  145967. unicode_cursor *pCsr;
  145968. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  145969. if( pCsr==0 ){
  145970. return SQLITE_NOMEM;
  145971. }
  145972. memset(pCsr, 0, sizeof(unicode_cursor));
  145973. pCsr->aInput = (const unsigned char *)aInput;
  145974. if( aInput==0 ){
  145975. pCsr->nInput = 0;
  145976. }else if( nInput<0 ){
  145977. pCsr->nInput = (int)strlen(aInput);
  145978. }else{
  145979. pCsr->nInput = nInput;
  145980. }
  145981. *pp = &pCsr->base;
  145982. UNUSED_PARAMETER(p);
  145983. return SQLITE_OK;
  145984. }
  145985. /*
  145986. ** Close a tokenization cursor previously opened by a call to
  145987. ** simpleOpen() above.
  145988. */
  145989. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  145990. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  145991. sqlite3_free(pCsr->zToken);
  145992. sqlite3_free(pCsr);
  145993. return SQLITE_OK;
  145994. }
  145995. /*
  145996. ** Extract the next token from a tokenization cursor. The cursor must
  145997. ** have been opened by a prior call to simpleOpen().
  145998. */
  145999. static int unicodeNext(
  146000. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  146001. const char **paToken, /* OUT: Token text */
  146002. int *pnToken, /* OUT: Number of bytes at *paToken */
  146003. int *piStart, /* OUT: Starting offset of token */
  146004. int *piEnd, /* OUT: Ending offset of token */
  146005. int *piPos /* OUT: Position integer of token */
  146006. ){
  146007. unicode_cursor *pCsr = (unicode_cursor *)pC;
  146008. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  146009. int iCode = 0;
  146010. char *zOut;
  146011. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  146012. const unsigned char *zStart = z;
  146013. const unsigned char *zEnd;
  146014. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  146015. /* Scan past any delimiter characters before the start of the next token.
  146016. ** Return SQLITE_DONE early if this takes us all the way to the end of
  146017. ** the input. */
  146018. while( z<zTerm ){
  146019. READ_UTF8(z, zTerm, iCode);
  146020. if( unicodeIsAlnum(p, iCode) ) break;
  146021. zStart = z;
  146022. }
  146023. if( zStart>=zTerm ) return SQLITE_DONE;
  146024. zOut = pCsr->zToken;
  146025. do {
  146026. int iOut;
  146027. /* Grow the output buffer if required. */
  146028. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  146029. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  146030. if( !zNew ) return SQLITE_NOMEM;
  146031. zOut = &zNew[zOut - pCsr->zToken];
  146032. pCsr->zToken = zNew;
  146033. pCsr->nAlloc += 64;
  146034. }
  146035. /* Write the folded case of the last character read to the output */
  146036. zEnd = z;
  146037. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  146038. if( iOut ){
  146039. WRITE_UTF8(zOut, iOut);
  146040. }
  146041. /* If the cursor is not at EOF, read the next character */
  146042. if( z>=zTerm ) break;
  146043. READ_UTF8(z, zTerm, iCode);
  146044. }while( unicodeIsAlnum(p, iCode)
  146045. || sqlite3FtsUnicodeIsdiacritic(iCode)
  146046. );
  146047. /* Set the output variables and return. */
  146048. pCsr->iOff = (int)(z - pCsr->aInput);
  146049. *paToken = pCsr->zToken;
  146050. *pnToken = (int)(zOut - pCsr->zToken);
  146051. *piStart = (int)(zStart - pCsr->aInput);
  146052. *piEnd = (int)(zEnd - pCsr->aInput);
  146053. *piPos = pCsr->iToken++;
  146054. return SQLITE_OK;
  146055. }
  146056. /*
  146057. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  146058. ** structure for the unicode tokenizer.
  146059. */
  146060. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  146061. static const sqlite3_tokenizer_module module = {
  146062. 0,
  146063. unicodeCreate,
  146064. unicodeDestroy,
  146065. unicodeOpen,
  146066. unicodeClose,
  146067. unicodeNext,
  146068. 0,
  146069. };
  146070. *ppModule = &module;
  146071. }
  146072. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  146073. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  146074. /************** End of fts3_unicode.c ****************************************/
  146075. /************** Begin file fts3_unicode2.c ***********************************/
  146076. /*
  146077. ** 2012 May 25
  146078. **
  146079. ** The author disclaims copyright to this source code. In place of
  146080. ** a legal notice, here is a blessing:
  146081. **
  146082. ** May you do good and not evil.
  146083. ** May you find forgiveness for yourself and forgive others.
  146084. ** May you share freely, never taking more than you give.
  146085. **
  146086. ******************************************************************************
  146087. */
  146088. /*
  146089. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  146090. */
  146091. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  146092. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  146093. /* #include <assert.h> */
  146094. /*
  146095. ** Return true if the argument corresponds to a unicode codepoint
  146096. ** classified as either a letter or a number. Otherwise false.
  146097. **
  146098. ** The results are undefined if the value passed to this function
  146099. ** is less than zero.
  146100. */
  146101. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  146102. /* Each unsigned integer in the following array corresponds to a contiguous
  146103. ** range of unicode codepoints that are not either letters or numbers (i.e.
  146104. ** codepoints for which this function should return 0).
  146105. **
  146106. ** The most significant 22 bits in each 32-bit value contain the first
  146107. ** codepoint in the range. The least significant 10 bits are used to store
  146108. ** the size of the range (always at least 1). In other words, the value
  146109. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  146110. ** C. It is not possible to represent a range larger than 1023 codepoints
  146111. ** using this format.
  146112. */
  146113. static const unsigned int aEntry[] = {
  146114. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  146115. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  146116. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  146117. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  146118. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  146119. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  146120. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  146121. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  146122. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  146123. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  146124. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  146125. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  146126. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  146127. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  146128. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  146129. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  146130. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  146131. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  146132. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  146133. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  146134. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  146135. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  146136. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  146137. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  146138. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  146139. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  146140. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  146141. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  146142. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  146143. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  146144. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  146145. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  146146. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  146147. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  146148. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  146149. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  146150. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  146151. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  146152. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  146153. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  146154. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  146155. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  146156. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  146157. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  146158. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  146159. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  146160. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  146161. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  146162. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  146163. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  146164. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  146165. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  146166. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  146167. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  146168. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  146169. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  146170. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  146171. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  146172. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  146173. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  146174. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  146175. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  146176. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  146177. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  146178. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  146179. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  146180. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  146181. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  146182. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  146183. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  146184. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  146185. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  146186. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  146187. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  146188. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  146189. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  146190. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  146191. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  146192. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  146193. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  146194. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  146195. 0x380400F0,
  146196. };
  146197. static const unsigned int aAscii[4] = {
  146198. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  146199. };
  146200. if( c<128 ){
  146201. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  146202. }else if( c<(1<<22) ){
  146203. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  146204. int iRes = 0;
  146205. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  146206. int iLo = 0;
  146207. while( iHi>=iLo ){
  146208. int iTest = (iHi + iLo) / 2;
  146209. if( key >= aEntry[iTest] ){
  146210. iRes = iTest;
  146211. iLo = iTest+1;
  146212. }else{
  146213. iHi = iTest-1;
  146214. }
  146215. }
  146216. assert( aEntry[0]<key );
  146217. assert( key>=aEntry[iRes] );
  146218. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  146219. }
  146220. return 1;
  146221. }
  146222. /*
  146223. ** If the argument is a codepoint corresponding to a lowercase letter
  146224. ** in the ASCII range with a diacritic added, return the codepoint
  146225. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  146226. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  146227. ** E"). The resuls of passing a codepoint that corresponds to an
  146228. ** uppercase letter are undefined.
  146229. */
  146230. static int remove_diacritic(int c){
  146231. unsigned short aDia[] = {
  146232. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  146233. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  146234. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  146235. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  146236. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  146237. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  146238. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  146239. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  146240. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  146241. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  146242. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  146243. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  146244. 62924, 63050, 63082, 63274, 63390,
  146245. };
  146246. char aChar[] = {
  146247. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  146248. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  146249. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  146250. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  146251. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  146252. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  146253. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  146254. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  146255. 'e', 'i', 'o', 'u', 'y',
  146256. };
  146257. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  146258. int iRes = 0;
  146259. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  146260. int iLo = 0;
  146261. while( iHi>=iLo ){
  146262. int iTest = (iHi + iLo) / 2;
  146263. if( key >= aDia[iTest] ){
  146264. iRes = iTest;
  146265. iLo = iTest+1;
  146266. }else{
  146267. iHi = iTest-1;
  146268. }
  146269. }
  146270. assert( key>=aDia[iRes] );
  146271. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  146272. }
  146273. /*
  146274. ** Return true if the argument interpreted as a unicode codepoint
  146275. ** is a diacritical modifier character.
  146276. */
  146277. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  146278. unsigned int mask0 = 0x08029FDF;
  146279. unsigned int mask1 = 0x000361F8;
  146280. if( c<768 || c>817 ) return 0;
  146281. return (c < 768+32) ?
  146282. (mask0 & (1 << (c-768))) :
  146283. (mask1 & (1 << (c-768-32)));
  146284. }
  146285. /*
  146286. ** Interpret the argument as a unicode codepoint. If the codepoint
  146287. ** is an upper case character that has a lower case equivalent,
  146288. ** return the codepoint corresponding to the lower case version.
  146289. ** Otherwise, return a copy of the argument.
  146290. **
  146291. ** The results are undefined if the value passed to this function
  146292. ** is less than zero.
  146293. */
  146294. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  146295. /* Each entry in the following array defines a rule for folding a range
  146296. ** of codepoints to lower case. The rule applies to a range of nRange
  146297. ** codepoints starting at codepoint iCode.
  146298. **
  146299. ** If the least significant bit in flags is clear, then the rule applies
  146300. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  146301. ** need to be folded). Or, if it is set, then the rule only applies to
  146302. ** every second codepoint in the range, starting with codepoint C.
  146303. **
  146304. ** The 7 most significant bits in flags are an index into the aiOff[]
  146305. ** array. If a specific codepoint C does require folding, then its lower
  146306. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  146307. **
  146308. ** The contents of this array are generated by parsing the CaseFolding.txt
  146309. ** file distributed as part of the "Unicode Character Database". See
  146310. ** http://www.unicode.org for details.
  146311. */
  146312. static const struct TableEntry {
  146313. unsigned short iCode;
  146314. unsigned char flags;
  146315. unsigned char nRange;
  146316. } aEntry[] = {
  146317. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  146318. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  146319. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  146320. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  146321. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  146322. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  146323. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  146324. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  146325. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  146326. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  146327. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  146328. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  146329. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  146330. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  146331. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  146332. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  146333. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  146334. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  146335. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  146336. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  146337. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  146338. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  146339. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  146340. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  146341. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  146342. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  146343. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  146344. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  146345. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  146346. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  146347. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  146348. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  146349. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  146350. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  146351. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  146352. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  146353. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  146354. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  146355. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  146356. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  146357. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  146358. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  146359. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  146360. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  146361. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  146362. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  146363. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  146364. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  146365. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  146366. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  146367. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  146368. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  146369. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  146370. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  146371. {65313, 14, 26},
  146372. };
  146373. static const unsigned short aiOff[] = {
  146374. 1, 2, 8, 15, 16, 26, 28, 32,
  146375. 37, 38, 40, 48, 63, 64, 69, 71,
  146376. 79, 80, 116, 202, 203, 205, 206, 207,
  146377. 209, 210, 211, 213, 214, 217, 218, 219,
  146378. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  146379. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  146380. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  146381. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  146382. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  146383. 65514, 65521, 65527, 65528, 65529,
  146384. };
  146385. int ret = c;
  146386. assert( c>=0 );
  146387. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  146388. if( c<128 ){
  146389. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  146390. }else if( c<65536 ){
  146391. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  146392. int iLo = 0;
  146393. int iRes = -1;
  146394. while( iHi>=iLo ){
  146395. int iTest = (iHi + iLo) / 2;
  146396. int cmp = (c - aEntry[iTest].iCode);
  146397. if( cmp>=0 ){
  146398. iRes = iTest;
  146399. iLo = iTest+1;
  146400. }else{
  146401. iHi = iTest-1;
  146402. }
  146403. }
  146404. assert( iRes<0 || c>=aEntry[iRes].iCode );
  146405. if( iRes>=0 ){
  146406. const struct TableEntry *p = &aEntry[iRes];
  146407. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  146408. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  146409. assert( ret>0 );
  146410. }
  146411. }
  146412. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  146413. }
  146414. else if( c>=66560 && c<66600 ){
  146415. ret = c + 40;
  146416. }
  146417. return ret;
  146418. }
  146419. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  146420. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  146421. /************** End of fts3_unicode2.c ***************************************/
  146422. /************** Begin file rtree.c *******************************************/
  146423. /*
  146424. ** 2001 September 15
  146425. **
  146426. ** The author disclaims copyright to this source code. In place of
  146427. ** a legal notice, here is a blessing:
  146428. **
  146429. ** May you do good and not evil.
  146430. ** May you find forgiveness for yourself and forgive others.
  146431. ** May you share freely, never taking more than you give.
  146432. **
  146433. *************************************************************************
  146434. ** This file contains code for implementations of the r-tree and r*-tree
  146435. ** algorithms packaged as an SQLite virtual table module.
  146436. */
  146437. /*
  146438. ** Database Format of R-Tree Tables
  146439. ** --------------------------------
  146440. **
  146441. ** The data structure for a single virtual r-tree table is stored in three
  146442. ** native SQLite tables declared as follows. In each case, the '%' character
  146443. ** in the table name is replaced with the user-supplied name of the r-tree
  146444. ** table.
  146445. **
  146446. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  146447. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  146448. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  146449. **
  146450. ** The data for each node of the r-tree structure is stored in the %_node
  146451. ** table. For each node that is not the root node of the r-tree, there is
  146452. ** an entry in the %_parent table associating the node with its parent.
  146453. ** And for each row of data in the table, there is an entry in the %_rowid
  146454. ** table that maps from the entries rowid to the id of the node that it
  146455. ** is stored on.
  146456. **
  146457. ** The root node of an r-tree always exists, even if the r-tree table is
  146458. ** empty. The nodeno of the root node is always 1. All other nodes in the
  146459. ** table must be the same size as the root node. The content of each node
  146460. ** is formatted as follows:
  146461. **
  146462. ** 1. If the node is the root node (node 1), then the first 2 bytes
  146463. ** of the node contain the tree depth as a big-endian integer.
  146464. ** For non-root nodes, the first 2 bytes are left unused.
  146465. **
  146466. ** 2. The next 2 bytes contain the number of entries currently
  146467. ** stored in the node.
  146468. **
  146469. ** 3. The remainder of the node contains the node entries. Each entry
  146470. ** consists of a single 8-byte integer followed by an even number
  146471. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  146472. ** of a record. For internal nodes it is the node number of a
  146473. ** child page.
  146474. */
  146475. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  146476. #ifndef SQLITE_CORE
  146477. /* #include "sqlite3ext.h" */
  146478. SQLITE_EXTENSION_INIT1
  146479. #else
  146480. /* #include "sqlite3.h" */
  146481. #endif
  146482. /* #include <string.h> */
  146483. /* #include <assert.h> */
  146484. /* #include <stdio.h> */
  146485. #ifndef SQLITE_AMALGAMATION
  146486. #include "sqlite3rtree.h"
  146487. typedef sqlite3_int64 i64;
  146488. typedef unsigned char u8;
  146489. typedef unsigned short u16;
  146490. typedef unsigned int u32;
  146491. #endif
  146492. /* The following macro is used to suppress compiler warnings.
  146493. */
  146494. #ifndef UNUSED_PARAMETER
  146495. # define UNUSED_PARAMETER(x) (void)(x)
  146496. #endif
  146497. typedef struct Rtree Rtree;
  146498. typedef struct RtreeCursor RtreeCursor;
  146499. typedef struct RtreeNode RtreeNode;
  146500. typedef struct RtreeCell RtreeCell;
  146501. typedef struct RtreeConstraint RtreeConstraint;
  146502. typedef struct RtreeMatchArg RtreeMatchArg;
  146503. typedef struct RtreeGeomCallback RtreeGeomCallback;
  146504. typedef union RtreeCoord RtreeCoord;
  146505. typedef struct RtreeSearchPoint RtreeSearchPoint;
  146506. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  146507. #define RTREE_MAX_DIMENSIONS 5
  146508. /* Size of hash table Rtree.aHash. This hash table is not expected to
  146509. ** ever contain very many entries, so a fixed number of buckets is
  146510. ** used.
  146511. */
  146512. #define HASHSIZE 97
  146513. /* The xBestIndex method of this virtual table requires an estimate of
  146514. ** the number of rows in the virtual table to calculate the costs of
  146515. ** various strategies. If possible, this estimate is loaded from the
  146516. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  146517. ** Otherwise, if no sqlite_stat1 entry is available, use
  146518. ** RTREE_DEFAULT_ROWEST.
  146519. */
  146520. #define RTREE_DEFAULT_ROWEST 1048576
  146521. #define RTREE_MIN_ROWEST 100
  146522. /*
  146523. ** An rtree virtual-table object.
  146524. */
  146525. struct Rtree {
  146526. sqlite3_vtab base; /* Base class. Must be first */
  146527. sqlite3 *db; /* Host database connection */
  146528. int iNodeSize; /* Size in bytes of each node in the node table */
  146529. u8 nDim; /* Number of dimensions */
  146530. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  146531. u8 nBytesPerCell; /* Bytes consumed per cell */
  146532. int iDepth; /* Current depth of the r-tree structure */
  146533. char *zDb; /* Name of database containing r-tree table */
  146534. char *zName; /* Name of r-tree table */
  146535. int nBusy; /* Current number of users of this structure */
  146536. i64 nRowEst; /* Estimated number of rows in this table */
  146537. /* List of nodes removed during a CondenseTree operation. List is
  146538. ** linked together via the pointer normally used for hash chains -
  146539. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  146540. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  146541. */
  146542. RtreeNode *pDeleted;
  146543. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  146544. /* Statements to read/write/delete a record from xxx_node */
  146545. sqlite3_stmt *pReadNode;
  146546. sqlite3_stmt *pWriteNode;
  146547. sqlite3_stmt *pDeleteNode;
  146548. /* Statements to read/write/delete a record from xxx_rowid */
  146549. sqlite3_stmt *pReadRowid;
  146550. sqlite3_stmt *pWriteRowid;
  146551. sqlite3_stmt *pDeleteRowid;
  146552. /* Statements to read/write/delete a record from xxx_parent */
  146553. sqlite3_stmt *pReadParent;
  146554. sqlite3_stmt *pWriteParent;
  146555. sqlite3_stmt *pDeleteParent;
  146556. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  146557. };
  146558. /* Possible values for Rtree.eCoordType: */
  146559. #define RTREE_COORD_REAL32 0
  146560. #define RTREE_COORD_INT32 1
  146561. /*
  146562. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  146563. ** only deal with integer coordinates. No floating point operations
  146564. ** will be done.
  146565. */
  146566. #ifdef SQLITE_RTREE_INT_ONLY
  146567. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  146568. typedef int RtreeValue; /* Low accuracy coordinate */
  146569. # define RTREE_ZERO 0
  146570. #else
  146571. typedef double RtreeDValue; /* High accuracy coordinate */
  146572. typedef float RtreeValue; /* Low accuracy coordinate */
  146573. # define RTREE_ZERO 0.0
  146574. #endif
  146575. /*
  146576. ** When doing a search of an r-tree, instances of the following structure
  146577. ** record intermediate results from the tree walk.
  146578. **
  146579. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  146580. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  146581. ** the id is of the parent node and the cell that RtreeSearchPoint
  146582. ** represents is the iCell-th entry in the parent node.
  146583. */
  146584. struct RtreeSearchPoint {
  146585. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  146586. sqlite3_int64 id; /* Node ID */
  146587. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  146588. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  146589. u8 iCell; /* Cell index within the node */
  146590. };
  146591. /*
  146592. ** The minimum number of cells allowed for a node is a third of the
  146593. ** maximum. In Gutman's notation:
  146594. **
  146595. ** m = M/3
  146596. **
  146597. ** If an R*-tree "Reinsert" operation is required, the same number of
  146598. ** cells are removed from the overfull node and reinserted into the tree.
  146599. */
  146600. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  146601. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  146602. #define RTREE_MAXCELLS 51
  146603. /*
  146604. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  146605. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  146606. ** Therefore all non-root nodes must contain at least 3 entries. Since
  146607. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  146608. ** 40 or less.
  146609. */
  146610. #define RTREE_MAX_DEPTH 40
  146611. /*
  146612. ** Number of entries in the cursor RtreeNode cache. The first entry is
  146613. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  146614. ** entries cache the RtreeNode for the first elements of the priority queue.
  146615. */
  146616. #define RTREE_CACHE_SZ 5
  146617. /*
  146618. ** An rtree cursor object.
  146619. */
  146620. struct RtreeCursor {
  146621. sqlite3_vtab_cursor base; /* Base class. Must be first */
  146622. u8 atEOF; /* True if at end of search */
  146623. u8 bPoint; /* True if sPoint is valid */
  146624. int iStrategy; /* Copy of idxNum search parameter */
  146625. int nConstraint; /* Number of entries in aConstraint */
  146626. RtreeConstraint *aConstraint; /* Search constraints. */
  146627. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  146628. int nPoint; /* Number of slots used in aPoint[] */
  146629. int mxLevel; /* iLevel value for root of the tree */
  146630. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  146631. RtreeSearchPoint sPoint; /* Cached next search point */
  146632. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  146633. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  146634. };
  146635. /* Return the Rtree of a RtreeCursor */
  146636. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  146637. /*
  146638. ** A coordinate can be either a floating point number or a integer. All
  146639. ** coordinates within a single R-Tree are always of the same time.
  146640. */
  146641. union RtreeCoord {
  146642. RtreeValue f; /* Floating point value */
  146643. int i; /* Integer value */
  146644. u32 u; /* Unsigned for byte-order conversions */
  146645. };
  146646. /*
  146647. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  146648. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  146649. ** variable pRtree points to the Rtree structure associated with the
  146650. ** RtreeCoord.
  146651. */
  146652. #ifdef SQLITE_RTREE_INT_ONLY
  146653. # define DCOORD(coord) ((RtreeDValue)coord.i)
  146654. #else
  146655. # define DCOORD(coord) ( \
  146656. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  146657. ((double)coord.f) : \
  146658. ((double)coord.i) \
  146659. )
  146660. #endif
  146661. /*
  146662. ** A search constraint.
  146663. */
  146664. struct RtreeConstraint {
  146665. int iCoord; /* Index of constrained coordinate */
  146666. int op; /* Constraining operation */
  146667. union {
  146668. RtreeDValue rValue; /* Constraint value. */
  146669. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  146670. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  146671. } u;
  146672. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  146673. };
  146674. /* Possible values for RtreeConstraint.op */
  146675. #define RTREE_EQ 0x41 /* A */
  146676. #define RTREE_LE 0x42 /* B */
  146677. #define RTREE_LT 0x43 /* C */
  146678. #define RTREE_GE 0x44 /* D */
  146679. #define RTREE_GT 0x45 /* E */
  146680. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  146681. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  146682. /*
  146683. ** An rtree structure node.
  146684. */
  146685. struct RtreeNode {
  146686. RtreeNode *pParent; /* Parent node */
  146687. i64 iNode; /* The node number */
  146688. int nRef; /* Number of references to this node */
  146689. int isDirty; /* True if the node needs to be written to disk */
  146690. u8 *zData; /* Content of the node, as should be on disk */
  146691. RtreeNode *pNext; /* Next node in this hash collision chain */
  146692. };
  146693. /* Return the number of cells in a node */
  146694. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  146695. /*
  146696. ** A single cell from a node, deserialized
  146697. */
  146698. struct RtreeCell {
  146699. i64 iRowid; /* Node or entry ID */
  146700. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  146701. };
  146702. /*
  146703. ** This object becomes the sqlite3_user_data() for the SQL functions
  146704. ** that are created by sqlite3_rtree_geometry_callback() and
  146705. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  146706. ** operators in order to constrain a search.
  146707. **
  146708. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  146709. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  146710. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  146711. ** sqlite3_rtree_query_callback().
  146712. **
  146713. ** This object is deleted automatically by the destructor mechanism in
  146714. ** sqlite3_create_function_v2().
  146715. */
  146716. struct RtreeGeomCallback {
  146717. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  146718. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  146719. void (*xDestructor)(void*);
  146720. void *pContext;
  146721. };
  146722. /*
  146723. ** Value for the first field of every RtreeMatchArg object. The MATCH
  146724. ** operator tests that the first field of a blob operand matches this
  146725. ** value to avoid operating on invalid blobs (which could cause a segfault).
  146726. */
  146727. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  146728. /*
  146729. ** An instance of this structure (in the form of a BLOB) is returned by
  146730. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  146731. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  146732. ** operand to the MATCH operator of an R-Tree.
  146733. */
  146734. struct RtreeMatchArg {
  146735. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  146736. RtreeGeomCallback cb; /* Info about the callback functions */
  146737. int nParam; /* Number of parameters to the SQL function */
  146738. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  146739. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  146740. };
  146741. #ifndef MAX
  146742. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  146743. #endif
  146744. #ifndef MIN
  146745. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  146746. #endif
  146747. /*
  146748. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  146749. ** 64 bit integer. The deserialized value is returned.
  146750. */
  146751. static int readInt16(u8 *p){
  146752. return (p[0]<<8) + p[1];
  146753. }
  146754. static void readCoord(u8 *p, RtreeCoord *pCoord){
  146755. pCoord->u = (
  146756. (((u32)p[0]) << 24) +
  146757. (((u32)p[1]) << 16) +
  146758. (((u32)p[2]) << 8) +
  146759. (((u32)p[3]) << 0)
  146760. );
  146761. }
  146762. static i64 readInt64(u8 *p){
  146763. return (
  146764. (((i64)p[0]) << 56) +
  146765. (((i64)p[1]) << 48) +
  146766. (((i64)p[2]) << 40) +
  146767. (((i64)p[3]) << 32) +
  146768. (((i64)p[4]) << 24) +
  146769. (((i64)p[5]) << 16) +
  146770. (((i64)p[6]) << 8) +
  146771. (((i64)p[7]) << 0)
  146772. );
  146773. }
  146774. /*
  146775. ** Functions to serialize a 16 bit integer, 32 bit real number and
  146776. ** 64 bit integer. The value returned is the number of bytes written
  146777. ** to the argument buffer (always 2, 4 and 8 respectively).
  146778. */
  146779. static int writeInt16(u8 *p, int i){
  146780. p[0] = (i>> 8)&0xFF;
  146781. p[1] = (i>> 0)&0xFF;
  146782. return 2;
  146783. }
  146784. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  146785. u32 i;
  146786. assert( sizeof(RtreeCoord)==4 );
  146787. assert( sizeof(u32)==4 );
  146788. i = pCoord->u;
  146789. p[0] = (i>>24)&0xFF;
  146790. p[1] = (i>>16)&0xFF;
  146791. p[2] = (i>> 8)&0xFF;
  146792. p[3] = (i>> 0)&0xFF;
  146793. return 4;
  146794. }
  146795. static int writeInt64(u8 *p, i64 i){
  146796. p[0] = (i>>56)&0xFF;
  146797. p[1] = (i>>48)&0xFF;
  146798. p[2] = (i>>40)&0xFF;
  146799. p[3] = (i>>32)&0xFF;
  146800. p[4] = (i>>24)&0xFF;
  146801. p[5] = (i>>16)&0xFF;
  146802. p[6] = (i>> 8)&0xFF;
  146803. p[7] = (i>> 0)&0xFF;
  146804. return 8;
  146805. }
  146806. /*
  146807. ** Increment the reference count of node p.
  146808. */
  146809. static void nodeReference(RtreeNode *p){
  146810. if( p ){
  146811. p->nRef++;
  146812. }
  146813. }
  146814. /*
  146815. ** Clear the content of node p (set all bytes to 0x00).
  146816. */
  146817. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  146818. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  146819. p->isDirty = 1;
  146820. }
  146821. /*
  146822. ** Given a node number iNode, return the corresponding key to use
  146823. ** in the Rtree.aHash table.
  146824. */
  146825. static int nodeHash(i64 iNode){
  146826. return iNode % HASHSIZE;
  146827. }
  146828. /*
  146829. ** Search the node hash table for node iNode. If found, return a pointer
  146830. ** to it. Otherwise, return 0.
  146831. */
  146832. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  146833. RtreeNode *p;
  146834. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  146835. return p;
  146836. }
  146837. /*
  146838. ** Add node pNode to the node hash table.
  146839. */
  146840. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  146841. int iHash;
  146842. assert( pNode->pNext==0 );
  146843. iHash = nodeHash(pNode->iNode);
  146844. pNode->pNext = pRtree->aHash[iHash];
  146845. pRtree->aHash[iHash] = pNode;
  146846. }
  146847. /*
  146848. ** Remove node pNode from the node hash table.
  146849. */
  146850. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  146851. RtreeNode **pp;
  146852. if( pNode->iNode!=0 ){
  146853. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  146854. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  146855. *pp = pNode->pNext;
  146856. pNode->pNext = 0;
  146857. }
  146858. }
  146859. /*
  146860. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  146861. ** indicating that node has not yet been assigned a node number. It is
  146862. ** assigned a node number when nodeWrite() is called to write the
  146863. ** node contents out to the database.
  146864. */
  146865. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  146866. RtreeNode *pNode;
  146867. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  146868. if( pNode ){
  146869. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  146870. pNode->zData = (u8 *)&pNode[1];
  146871. pNode->nRef = 1;
  146872. pNode->pParent = pParent;
  146873. pNode->isDirty = 1;
  146874. nodeReference(pParent);
  146875. }
  146876. return pNode;
  146877. }
  146878. /*
  146879. ** Obtain a reference to an r-tree node.
  146880. */
  146881. static int nodeAcquire(
  146882. Rtree *pRtree, /* R-tree structure */
  146883. i64 iNode, /* Node number to load */
  146884. RtreeNode *pParent, /* Either the parent node or NULL */
  146885. RtreeNode **ppNode /* OUT: Acquired node */
  146886. ){
  146887. int rc;
  146888. int rc2 = SQLITE_OK;
  146889. RtreeNode *pNode;
  146890. /* Check if the requested node is already in the hash table. If so,
  146891. ** increase its reference count and return it.
  146892. */
  146893. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  146894. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  146895. if( pParent && !pNode->pParent ){
  146896. nodeReference(pParent);
  146897. pNode->pParent = pParent;
  146898. }
  146899. pNode->nRef++;
  146900. *ppNode = pNode;
  146901. return SQLITE_OK;
  146902. }
  146903. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  146904. rc = sqlite3_step(pRtree->pReadNode);
  146905. if( rc==SQLITE_ROW ){
  146906. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  146907. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  146908. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  146909. if( !pNode ){
  146910. rc2 = SQLITE_NOMEM;
  146911. }else{
  146912. pNode->pParent = pParent;
  146913. pNode->zData = (u8 *)&pNode[1];
  146914. pNode->nRef = 1;
  146915. pNode->iNode = iNode;
  146916. pNode->isDirty = 0;
  146917. pNode->pNext = 0;
  146918. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  146919. nodeReference(pParent);
  146920. }
  146921. }
  146922. }
  146923. rc = sqlite3_reset(pRtree->pReadNode);
  146924. if( rc==SQLITE_OK ) rc = rc2;
  146925. /* If the root node was just loaded, set pRtree->iDepth to the height
  146926. ** of the r-tree structure. A height of zero means all data is stored on
  146927. ** the root node. A height of one means the children of the root node
  146928. ** are the leaves, and so on. If the depth as specified on the root node
  146929. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  146930. */
  146931. if( pNode && iNode==1 ){
  146932. pRtree->iDepth = readInt16(pNode->zData);
  146933. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  146934. rc = SQLITE_CORRUPT_VTAB;
  146935. }
  146936. }
  146937. /* If no error has occurred so far, check if the "number of entries"
  146938. ** field on the node is too large. If so, set the return code to
  146939. ** SQLITE_CORRUPT_VTAB.
  146940. */
  146941. if( pNode && rc==SQLITE_OK ){
  146942. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  146943. rc = SQLITE_CORRUPT_VTAB;
  146944. }
  146945. }
  146946. if( rc==SQLITE_OK ){
  146947. if( pNode!=0 ){
  146948. nodeHashInsert(pRtree, pNode);
  146949. }else{
  146950. rc = SQLITE_CORRUPT_VTAB;
  146951. }
  146952. *ppNode = pNode;
  146953. }else{
  146954. sqlite3_free(pNode);
  146955. *ppNode = 0;
  146956. }
  146957. return rc;
  146958. }
  146959. /*
  146960. ** Overwrite cell iCell of node pNode with the contents of pCell.
  146961. */
  146962. static void nodeOverwriteCell(
  146963. Rtree *pRtree, /* The overall R-Tree */
  146964. RtreeNode *pNode, /* The node into which the cell is to be written */
  146965. RtreeCell *pCell, /* The cell to write */
  146966. int iCell /* Index into pNode into which pCell is written */
  146967. ){
  146968. int ii;
  146969. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  146970. p += writeInt64(p, pCell->iRowid);
  146971. for(ii=0; ii<(pRtree->nDim*2); ii++){
  146972. p += writeCoord(p, &pCell->aCoord[ii]);
  146973. }
  146974. pNode->isDirty = 1;
  146975. }
  146976. /*
  146977. ** Remove the cell with index iCell from node pNode.
  146978. */
  146979. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  146980. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  146981. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  146982. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  146983. memmove(pDst, pSrc, nByte);
  146984. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  146985. pNode->isDirty = 1;
  146986. }
  146987. /*
  146988. ** Insert the contents of cell pCell into node pNode. If the insert
  146989. ** is successful, return SQLITE_OK.
  146990. **
  146991. ** If there is not enough free space in pNode, return SQLITE_FULL.
  146992. */
  146993. static int nodeInsertCell(
  146994. Rtree *pRtree, /* The overall R-Tree */
  146995. RtreeNode *pNode, /* Write new cell into this node */
  146996. RtreeCell *pCell /* The cell to be inserted */
  146997. ){
  146998. int nCell; /* Current number of cells in pNode */
  146999. int nMaxCell; /* Maximum number of cells for pNode */
  147000. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  147001. nCell = NCELL(pNode);
  147002. assert( nCell<=nMaxCell );
  147003. if( nCell<nMaxCell ){
  147004. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  147005. writeInt16(&pNode->zData[2], nCell+1);
  147006. pNode->isDirty = 1;
  147007. }
  147008. return (nCell==nMaxCell);
  147009. }
  147010. /*
  147011. ** If the node is dirty, write it out to the database.
  147012. */
  147013. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  147014. int rc = SQLITE_OK;
  147015. if( pNode->isDirty ){
  147016. sqlite3_stmt *p = pRtree->pWriteNode;
  147017. if( pNode->iNode ){
  147018. sqlite3_bind_int64(p, 1, pNode->iNode);
  147019. }else{
  147020. sqlite3_bind_null(p, 1);
  147021. }
  147022. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  147023. sqlite3_step(p);
  147024. pNode->isDirty = 0;
  147025. rc = sqlite3_reset(p);
  147026. if( pNode->iNode==0 && rc==SQLITE_OK ){
  147027. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  147028. nodeHashInsert(pRtree, pNode);
  147029. }
  147030. }
  147031. return rc;
  147032. }
  147033. /*
  147034. ** Release a reference to a node. If the node is dirty and the reference
  147035. ** count drops to zero, the node data is written to the database.
  147036. */
  147037. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  147038. int rc = SQLITE_OK;
  147039. if( pNode ){
  147040. assert( pNode->nRef>0 );
  147041. pNode->nRef--;
  147042. if( pNode->nRef==0 ){
  147043. if( pNode->iNode==1 ){
  147044. pRtree->iDepth = -1;
  147045. }
  147046. if( pNode->pParent ){
  147047. rc = nodeRelease(pRtree, pNode->pParent);
  147048. }
  147049. if( rc==SQLITE_OK ){
  147050. rc = nodeWrite(pRtree, pNode);
  147051. }
  147052. nodeHashDelete(pRtree, pNode);
  147053. sqlite3_free(pNode);
  147054. }
  147055. }
  147056. return rc;
  147057. }
  147058. /*
  147059. ** Return the 64-bit integer value associated with cell iCell of
  147060. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  147061. ** an internal node, then the 64-bit integer is a child page number.
  147062. */
  147063. static i64 nodeGetRowid(
  147064. Rtree *pRtree, /* The overall R-Tree */
  147065. RtreeNode *pNode, /* The node from which to extract the ID */
  147066. int iCell /* The cell index from which to extract the ID */
  147067. ){
  147068. assert( iCell<NCELL(pNode) );
  147069. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  147070. }
  147071. /*
  147072. ** Return coordinate iCoord from cell iCell in node pNode.
  147073. */
  147074. static void nodeGetCoord(
  147075. Rtree *pRtree, /* The overall R-Tree */
  147076. RtreeNode *pNode, /* The node from which to extract a coordinate */
  147077. int iCell, /* The index of the cell within the node */
  147078. int iCoord, /* Which coordinate to extract */
  147079. RtreeCoord *pCoord /* OUT: Space to write result to */
  147080. ){
  147081. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  147082. }
  147083. /*
  147084. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  147085. ** to by pCell with the results.
  147086. */
  147087. static void nodeGetCell(
  147088. Rtree *pRtree, /* The overall R-Tree */
  147089. RtreeNode *pNode, /* The node containing the cell to be read */
  147090. int iCell, /* Index of the cell within the node */
  147091. RtreeCell *pCell /* OUT: Write the cell contents here */
  147092. ){
  147093. u8 *pData;
  147094. RtreeCoord *pCoord;
  147095. int ii;
  147096. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  147097. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  147098. pCoord = pCell->aCoord;
  147099. for(ii=0; ii<pRtree->nDim*2; ii++){
  147100. readCoord(&pData[ii*4], &pCoord[ii]);
  147101. }
  147102. }
  147103. /* Forward declaration for the function that does the work of
  147104. ** the virtual table module xCreate() and xConnect() methods.
  147105. */
  147106. static int rtreeInit(
  147107. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  147108. );
  147109. /*
  147110. ** Rtree virtual table module xCreate method.
  147111. */
  147112. static int rtreeCreate(
  147113. sqlite3 *db,
  147114. void *pAux,
  147115. int argc, const char *const*argv,
  147116. sqlite3_vtab **ppVtab,
  147117. char **pzErr
  147118. ){
  147119. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  147120. }
  147121. /*
  147122. ** Rtree virtual table module xConnect method.
  147123. */
  147124. static int rtreeConnect(
  147125. sqlite3 *db,
  147126. void *pAux,
  147127. int argc, const char *const*argv,
  147128. sqlite3_vtab **ppVtab,
  147129. char **pzErr
  147130. ){
  147131. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  147132. }
  147133. /*
  147134. ** Increment the r-tree reference count.
  147135. */
  147136. static void rtreeReference(Rtree *pRtree){
  147137. pRtree->nBusy++;
  147138. }
  147139. /*
  147140. ** Decrement the r-tree reference count. When the reference count reaches
  147141. ** zero the structure is deleted.
  147142. */
  147143. static void rtreeRelease(Rtree *pRtree){
  147144. pRtree->nBusy--;
  147145. if( pRtree->nBusy==0 ){
  147146. sqlite3_finalize(pRtree->pReadNode);
  147147. sqlite3_finalize(pRtree->pWriteNode);
  147148. sqlite3_finalize(pRtree->pDeleteNode);
  147149. sqlite3_finalize(pRtree->pReadRowid);
  147150. sqlite3_finalize(pRtree->pWriteRowid);
  147151. sqlite3_finalize(pRtree->pDeleteRowid);
  147152. sqlite3_finalize(pRtree->pReadParent);
  147153. sqlite3_finalize(pRtree->pWriteParent);
  147154. sqlite3_finalize(pRtree->pDeleteParent);
  147155. sqlite3_free(pRtree);
  147156. }
  147157. }
  147158. /*
  147159. ** Rtree virtual table module xDisconnect method.
  147160. */
  147161. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  147162. rtreeRelease((Rtree *)pVtab);
  147163. return SQLITE_OK;
  147164. }
  147165. /*
  147166. ** Rtree virtual table module xDestroy method.
  147167. */
  147168. static int rtreeDestroy(sqlite3_vtab *pVtab){
  147169. Rtree *pRtree = (Rtree *)pVtab;
  147170. int rc;
  147171. char *zCreate = sqlite3_mprintf(
  147172. "DROP TABLE '%q'.'%q_node';"
  147173. "DROP TABLE '%q'.'%q_rowid';"
  147174. "DROP TABLE '%q'.'%q_parent';",
  147175. pRtree->zDb, pRtree->zName,
  147176. pRtree->zDb, pRtree->zName,
  147177. pRtree->zDb, pRtree->zName
  147178. );
  147179. if( !zCreate ){
  147180. rc = SQLITE_NOMEM;
  147181. }else{
  147182. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  147183. sqlite3_free(zCreate);
  147184. }
  147185. if( rc==SQLITE_OK ){
  147186. rtreeRelease(pRtree);
  147187. }
  147188. return rc;
  147189. }
  147190. /*
  147191. ** Rtree virtual table module xOpen method.
  147192. */
  147193. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  147194. int rc = SQLITE_NOMEM;
  147195. RtreeCursor *pCsr;
  147196. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  147197. if( pCsr ){
  147198. memset(pCsr, 0, sizeof(RtreeCursor));
  147199. pCsr->base.pVtab = pVTab;
  147200. rc = SQLITE_OK;
  147201. }
  147202. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  147203. return rc;
  147204. }
  147205. /*
  147206. ** Free the RtreeCursor.aConstraint[] array and its contents.
  147207. */
  147208. static void freeCursorConstraints(RtreeCursor *pCsr){
  147209. if( pCsr->aConstraint ){
  147210. int i; /* Used to iterate through constraint array */
  147211. for(i=0; i<pCsr->nConstraint; i++){
  147212. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  147213. if( pInfo ){
  147214. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  147215. sqlite3_free(pInfo);
  147216. }
  147217. }
  147218. sqlite3_free(pCsr->aConstraint);
  147219. pCsr->aConstraint = 0;
  147220. }
  147221. }
  147222. /*
  147223. ** Rtree virtual table module xClose method.
  147224. */
  147225. static int rtreeClose(sqlite3_vtab_cursor *cur){
  147226. Rtree *pRtree = (Rtree *)(cur->pVtab);
  147227. int ii;
  147228. RtreeCursor *pCsr = (RtreeCursor *)cur;
  147229. freeCursorConstraints(pCsr);
  147230. sqlite3_free(pCsr->aPoint);
  147231. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  147232. sqlite3_free(pCsr);
  147233. return SQLITE_OK;
  147234. }
  147235. /*
  147236. ** Rtree virtual table module xEof method.
  147237. **
  147238. ** Return non-zero if the cursor does not currently point to a valid
  147239. ** record (i.e if the scan has finished), or zero otherwise.
  147240. */
  147241. static int rtreeEof(sqlite3_vtab_cursor *cur){
  147242. RtreeCursor *pCsr = (RtreeCursor *)cur;
  147243. return pCsr->atEOF;
  147244. }
  147245. /*
  147246. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  147247. ** The on-disk format is big-endian and needs to be converted for little-
  147248. ** endian platforms. The on-disk record stores integer coordinates if
  147249. ** eInt is true and it stores 32-bit floating point records if eInt is
  147250. ** false. a[] is the four bytes of the on-disk record to be decoded.
  147251. ** Store the results in "r".
  147252. **
  147253. ** There are three versions of this macro, one each for little-endian and
  147254. ** big-endian processors and a third generic implementation. The endian-
  147255. ** specific implementations are much faster and are preferred if the
  147256. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  147257. ** macro is part of sqliteInt.h and hence the endian-specific
  147258. ** implementation will only be used if this module is compiled as part
  147259. ** of the amalgamation.
  147260. */
  147261. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  147262. #define RTREE_DECODE_COORD(eInt, a, r) { \
  147263. RtreeCoord c; /* Coordinate decoded */ \
  147264. memcpy(&c.u,a,4); \
  147265. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  147266. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  147267. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  147268. }
  147269. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  147270. #define RTREE_DECODE_COORD(eInt, a, r) { \
  147271. RtreeCoord c; /* Coordinate decoded */ \
  147272. memcpy(&c.u,a,4); \
  147273. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  147274. }
  147275. #else
  147276. #define RTREE_DECODE_COORD(eInt, a, r) { \
  147277. RtreeCoord c; /* Coordinate decoded */ \
  147278. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  147279. +((u32)a[2]<<8) + a[3]; \
  147280. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  147281. }
  147282. #endif
  147283. /*
  147284. ** Check the RTree node or entry given by pCellData and p against the MATCH
  147285. ** constraint pConstraint.
  147286. */
  147287. static int rtreeCallbackConstraint(
  147288. RtreeConstraint *pConstraint, /* The constraint to test */
  147289. int eInt, /* True if RTree holding integer coordinates */
  147290. u8 *pCellData, /* Raw cell content */
  147291. RtreeSearchPoint *pSearch, /* Container of this cell */
  147292. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  147293. int *peWithin /* OUT: visibility of the cell */
  147294. ){
  147295. int i; /* Loop counter */
  147296. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  147297. int nCoord = pInfo->nCoord; /* No. of coordinates */
  147298. int rc; /* Callback return code */
  147299. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  147300. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  147301. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  147302. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  147303. pInfo->iRowid = readInt64(pCellData);
  147304. }
  147305. pCellData += 8;
  147306. for(i=0; i<nCoord; i++, pCellData += 4){
  147307. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  147308. }
  147309. if( pConstraint->op==RTREE_MATCH ){
  147310. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  147311. nCoord, aCoord, &i);
  147312. if( i==0 ) *peWithin = NOT_WITHIN;
  147313. *prScore = RTREE_ZERO;
  147314. }else{
  147315. pInfo->aCoord = aCoord;
  147316. pInfo->iLevel = pSearch->iLevel - 1;
  147317. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  147318. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  147319. rc = pConstraint->u.xQueryFunc(pInfo);
  147320. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  147321. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  147322. *prScore = pInfo->rScore;
  147323. }
  147324. }
  147325. return rc;
  147326. }
  147327. /*
  147328. ** Check the internal RTree node given by pCellData against constraint p.
  147329. ** If this constraint cannot be satisfied by any child within the node,
  147330. ** set *peWithin to NOT_WITHIN.
  147331. */
  147332. static void rtreeNonleafConstraint(
  147333. RtreeConstraint *p, /* The constraint to test */
  147334. int eInt, /* True if RTree holds integer coordinates */
  147335. u8 *pCellData, /* Raw cell content as appears on disk */
  147336. int *peWithin /* Adjust downward, as appropriate */
  147337. ){
  147338. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  147339. /* p->iCoord might point to either a lower or upper bound coordinate
  147340. ** in a coordinate pair. But make pCellData point to the lower bound.
  147341. */
  147342. pCellData += 8 + 4*(p->iCoord&0xfe);
  147343. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  147344. || p->op==RTREE_GT || p->op==RTREE_EQ );
  147345. switch( p->op ){
  147346. case RTREE_LE:
  147347. case RTREE_LT:
  147348. case RTREE_EQ:
  147349. RTREE_DECODE_COORD(eInt, pCellData, val);
  147350. /* val now holds the lower bound of the coordinate pair */
  147351. if( p->u.rValue>=val ) return;
  147352. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  147353. /* Fall through for the RTREE_EQ case */
  147354. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  147355. pCellData += 4;
  147356. RTREE_DECODE_COORD(eInt, pCellData, val);
  147357. /* val now holds the upper bound of the coordinate pair */
  147358. if( p->u.rValue<=val ) return;
  147359. }
  147360. *peWithin = NOT_WITHIN;
  147361. }
  147362. /*
  147363. ** Check the leaf RTree cell given by pCellData against constraint p.
  147364. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  147365. ** If the constraint is satisfied, leave *peWithin unchanged.
  147366. **
  147367. ** The constraint is of the form: xN op $val
  147368. **
  147369. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  147370. ** pCellData. $val is given by p->u.rValue.
  147371. */
  147372. static void rtreeLeafConstraint(
  147373. RtreeConstraint *p, /* The constraint to test */
  147374. int eInt, /* True if RTree holds integer coordinates */
  147375. u8 *pCellData, /* Raw cell content as appears on disk */
  147376. int *peWithin /* Adjust downward, as appropriate */
  147377. ){
  147378. RtreeDValue xN; /* Coordinate value converted to a double */
  147379. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  147380. || p->op==RTREE_GT || p->op==RTREE_EQ );
  147381. pCellData += 8 + p->iCoord*4;
  147382. RTREE_DECODE_COORD(eInt, pCellData, xN);
  147383. switch( p->op ){
  147384. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  147385. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  147386. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  147387. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  147388. default: if( xN == p->u.rValue ) return; break;
  147389. }
  147390. *peWithin = NOT_WITHIN;
  147391. }
  147392. /*
  147393. ** One of the cells in node pNode is guaranteed to have a 64-bit
  147394. ** integer value equal to iRowid. Return the index of this cell.
  147395. */
  147396. static int nodeRowidIndex(
  147397. Rtree *pRtree,
  147398. RtreeNode *pNode,
  147399. i64 iRowid,
  147400. int *piIndex
  147401. ){
  147402. int ii;
  147403. int nCell = NCELL(pNode);
  147404. assert( nCell<200 );
  147405. for(ii=0; ii<nCell; ii++){
  147406. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  147407. *piIndex = ii;
  147408. return SQLITE_OK;
  147409. }
  147410. }
  147411. return SQLITE_CORRUPT_VTAB;
  147412. }
  147413. /*
  147414. ** Return the index of the cell containing a pointer to node pNode
  147415. ** in its parent. If pNode is the root node, return -1.
  147416. */
  147417. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  147418. RtreeNode *pParent = pNode->pParent;
  147419. if( pParent ){
  147420. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  147421. }
  147422. *piIndex = -1;
  147423. return SQLITE_OK;
  147424. }
  147425. /*
  147426. ** Compare two search points. Return negative, zero, or positive if the first
  147427. ** is less than, equal to, or greater than the second.
  147428. **
  147429. ** The rScore is the primary key. Smaller rScore values come first.
  147430. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  147431. ** iLevel values coming first. In this way, if rScore is the same for all
  147432. ** SearchPoints, then iLevel becomes the deciding factor and the result
  147433. ** is a depth-first search, which is the desired default behavior.
  147434. */
  147435. static int rtreeSearchPointCompare(
  147436. const RtreeSearchPoint *pA,
  147437. const RtreeSearchPoint *pB
  147438. ){
  147439. if( pA->rScore<pB->rScore ) return -1;
  147440. if( pA->rScore>pB->rScore ) return +1;
  147441. if( pA->iLevel<pB->iLevel ) return -1;
  147442. if( pA->iLevel>pB->iLevel ) return +1;
  147443. return 0;
  147444. }
  147445. /*
  147446. ** Interchange to search points in a cursor.
  147447. */
  147448. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  147449. RtreeSearchPoint t = p->aPoint[i];
  147450. assert( i<j );
  147451. p->aPoint[i] = p->aPoint[j];
  147452. p->aPoint[j] = t;
  147453. i++; j++;
  147454. if( i<RTREE_CACHE_SZ ){
  147455. if( j>=RTREE_CACHE_SZ ){
  147456. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  147457. p->aNode[i] = 0;
  147458. }else{
  147459. RtreeNode *pTemp = p->aNode[i];
  147460. p->aNode[i] = p->aNode[j];
  147461. p->aNode[j] = pTemp;
  147462. }
  147463. }
  147464. }
  147465. /*
  147466. ** Return the search point with the lowest current score.
  147467. */
  147468. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  147469. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  147470. }
  147471. /*
  147472. ** Get the RtreeNode for the search point with the lowest score.
  147473. */
  147474. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  147475. sqlite3_int64 id;
  147476. int ii = 1 - pCur->bPoint;
  147477. assert( ii==0 || ii==1 );
  147478. assert( pCur->bPoint || pCur->nPoint );
  147479. if( pCur->aNode[ii]==0 ){
  147480. assert( pRC!=0 );
  147481. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  147482. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  147483. }
  147484. return pCur->aNode[ii];
  147485. }
  147486. /*
  147487. ** Push a new element onto the priority queue
  147488. */
  147489. static RtreeSearchPoint *rtreeEnqueue(
  147490. RtreeCursor *pCur, /* The cursor */
  147491. RtreeDValue rScore, /* Score for the new search point */
  147492. u8 iLevel /* Level for the new search point */
  147493. ){
  147494. int i, j;
  147495. RtreeSearchPoint *pNew;
  147496. if( pCur->nPoint>=pCur->nPointAlloc ){
  147497. int nNew = pCur->nPointAlloc*2 + 8;
  147498. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  147499. if( pNew==0 ) return 0;
  147500. pCur->aPoint = pNew;
  147501. pCur->nPointAlloc = nNew;
  147502. }
  147503. i = pCur->nPoint++;
  147504. pNew = pCur->aPoint + i;
  147505. pNew->rScore = rScore;
  147506. pNew->iLevel = iLevel;
  147507. assert( iLevel<=RTREE_MAX_DEPTH );
  147508. while( i>0 ){
  147509. RtreeSearchPoint *pParent;
  147510. j = (i-1)/2;
  147511. pParent = pCur->aPoint + j;
  147512. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  147513. rtreeSearchPointSwap(pCur, j, i);
  147514. i = j;
  147515. pNew = pParent;
  147516. }
  147517. return pNew;
  147518. }
  147519. /*
  147520. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  147521. ** NULL if malloc fails.
  147522. */
  147523. static RtreeSearchPoint *rtreeSearchPointNew(
  147524. RtreeCursor *pCur, /* The cursor */
  147525. RtreeDValue rScore, /* Score for the new search point */
  147526. u8 iLevel /* Level for the new search point */
  147527. ){
  147528. RtreeSearchPoint *pNew, *pFirst;
  147529. pFirst = rtreeSearchPointFirst(pCur);
  147530. pCur->anQueue[iLevel]++;
  147531. if( pFirst==0
  147532. || pFirst->rScore>rScore
  147533. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  147534. ){
  147535. if( pCur->bPoint ){
  147536. int ii;
  147537. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  147538. if( pNew==0 ) return 0;
  147539. ii = (int)(pNew - pCur->aPoint) + 1;
  147540. if( ii<RTREE_CACHE_SZ ){
  147541. assert( pCur->aNode[ii]==0 );
  147542. pCur->aNode[ii] = pCur->aNode[0];
  147543. }else{
  147544. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  147545. }
  147546. pCur->aNode[0] = 0;
  147547. *pNew = pCur->sPoint;
  147548. }
  147549. pCur->sPoint.rScore = rScore;
  147550. pCur->sPoint.iLevel = iLevel;
  147551. pCur->bPoint = 1;
  147552. return &pCur->sPoint;
  147553. }else{
  147554. return rtreeEnqueue(pCur, rScore, iLevel);
  147555. }
  147556. }
  147557. #if 0
  147558. /* Tracing routines for the RtreeSearchPoint queue */
  147559. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  147560. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  147561. printf(" %d.%05lld.%02d %g %d",
  147562. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  147563. );
  147564. idx++;
  147565. if( idx<RTREE_CACHE_SZ ){
  147566. printf(" %p\n", pCur->aNode[idx]);
  147567. }else{
  147568. printf("\n");
  147569. }
  147570. }
  147571. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  147572. int ii;
  147573. printf("=== %9s ", zPrefix);
  147574. if( pCur->bPoint ){
  147575. tracePoint(&pCur->sPoint, -1, pCur);
  147576. }
  147577. for(ii=0; ii<pCur->nPoint; ii++){
  147578. if( ii>0 || pCur->bPoint ) printf(" ");
  147579. tracePoint(&pCur->aPoint[ii], ii, pCur);
  147580. }
  147581. }
  147582. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  147583. #else
  147584. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  147585. #endif
  147586. /* Remove the search point with the lowest current score.
  147587. */
  147588. static void rtreeSearchPointPop(RtreeCursor *p){
  147589. int i, j, k, n;
  147590. i = 1 - p->bPoint;
  147591. assert( i==0 || i==1 );
  147592. if( p->aNode[i] ){
  147593. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  147594. p->aNode[i] = 0;
  147595. }
  147596. if( p->bPoint ){
  147597. p->anQueue[p->sPoint.iLevel]--;
  147598. p->bPoint = 0;
  147599. }else if( p->nPoint ){
  147600. p->anQueue[p->aPoint[0].iLevel]--;
  147601. n = --p->nPoint;
  147602. p->aPoint[0] = p->aPoint[n];
  147603. if( n<RTREE_CACHE_SZ-1 ){
  147604. p->aNode[1] = p->aNode[n+1];
  147605. p->aNode[n+1] = 0;
  147606. }
  147607. i = 0;
  147608. while( (j = i*2+1)<n ){
  147609. k = j+1;
  147610. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  147611. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  147612. rtreeSearchPointSwap(p, i, k);
  147613. i = k;
  147614. }else{
  147615. break;
  147616. }
  147617. }else{
  147618. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  147619. rtreeSearchPointSwap(p, i, j);
  147620. i = j;
  147621. }else{
  147622. break;
  147623. }
  147624. }
  147625. }
  147626. }
  147627. }
  147628. /*
  147629. ** Continue the search on cursor pCur until the front of the queue
  147630. ** contains an entry suitable for returning as a result-set row,
  147631. ** or until the RtreeSearchPoint queue is empty, indicating that the
  147632. ** query has completed.
  147633. */
  147634. static int rtreeStepToLeaf(RtreeCursor *pCur){
  147635. RtreeSearchPoint *p;
  147636. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  147637. RtreeNode *pNode;
  147638. int eWithin;
  147639. int rc = SQLITE_OK;
  147640. int nCell;
  147641. int nConstraint = pCur->nConstraint;
  147642. int ii;
  147643. int eInt;
  147644. RtreeSearchPoint x;
  147645. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  147646. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  147647. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  147648. if( rc ) return rc;
  147649. nCell = NCELL(pNode);
  147650. assert( nCell<200 );
  147651. while( p->iCell<nCell ){
  147652. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  147653. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  147654. eWithin = FULLY_WITHIN;
  147655. for(ii=0; ii<nConstraint; ii++){
  147656. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  147657. if( pConstraint->op>=RTREE_MATCH ){
  147658. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  147659. &rScore, &eWithin);
  147660. if( rc ) return rc;
  147661. }else if( p->iLevel==1 ){
  147662. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  147663. }else{
  147664. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  147665. }
  147666. if( eWithin==NOT_WITHIN ) break;
  147667. }
  147668. p->iCell++;
  147669. if( eWithin==NOT_WITHIN ) continue;
  147670. x.iLevel = p->iLevel - 1;
  147671. if( x.iLevel ){
  147672. x.id = readInt64(pCellData);
  147673. x.iCell = 0;
  147674. }else{
  147675. x.id = p->id;
  147676. x.iCell = p->iCell - 1;
  147677. }
  147678. if( p->iCell>=nCell ){
  147679. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  147680. rtreeSearchPointPop(pCur);
  147681. }
  147682. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  147683. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  147684. if( p==0 ) return SQLITE_NOMEM;
  147685. p->eWithin = eWithin;
  147686. p->id = x.id;
  147687. p->iCell = x.iCell;
  147688. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  147689. break;
  147690. }
  147691. if( p->iCell>=nCell ){
  147692. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  147693. rtreeSearchPointPop(pCur);
  147694. }
  147695. }
  147696. pCur->atEOF = p==0;
  147697. return SQLITE_OK;
  147698. }
  147699. /*
  147700. ** Rtree virtual table module xNext method.
  147701. */
  147702. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  147703. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  147704. int rc = SQLITE_OK;
  147705. /* Move to the next entry that matches the configured constraints. */
  147706. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  147707. rtreeSearchPointPop(pCsr);
  147708. rc = rtreeStepToLeaf(pCsr);
  147709. return rc;
  147710. }
  147711. /*
  147712. ** Rtree virtual table module xRowid method.
  147713. */
  147714. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  147715. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  147716. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  147717. int rc = SQLITE_OK;
  147718. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  147719. if( rc==SQLITE_OK && p ){
  147720. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  147721. }
  147722. return rc;
  147723. }
  147724. /*
  147725. ** Rtree virtual table module xColumn method.
  147726. */
  147727. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  147728. Rtree *pRtree = (Rtree *)cur->pVtab;
  147729. RtreeCursor *pCsr = (RtreeCursor *)cur;
  147730. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  147731. RtreeCoord c;
  147732. int rc = SQLITE_OK;
  147733. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  147734. if( rc ) return rc;
  147735. if( p==0 ) return SQLITE_OK;
  147736. if( i==0 ){
  147737. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  147738. }else{
  147739. if( rc ) return rc;
  147740. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  147741. #ifndef SQLITE_RTREE_INT_ONLY
  147742. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  147743. sqlite3_result_double(ctx, c.f);
  147744. }else
  147745. #endif
  147746. {
  147747. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  147748. sqlite3_result_int(ctx, c.i);
  147749. }
  147750. }
  147751. return SQLITE_OK;
  147752. }
  147753. /*
  147754. ** Use nodeAcquire() to obtain the leaf node containing the record with
  147755. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  147756. ** return SQLITE_OK. If there is no such record in the table, set
  147757. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  147758. ** to zero and return an SQLite error code.
  147759. */
  147760. static int findLeafNode(
  147761. Rtree *pRtree, /* RTree to search */
  147762. i64 iRowid, /* The rowid searching for */
  147763. RtreeNode **ppLeaf, /* Write the node here */
  147764. sqlite3_int64 *piNode /* Write the node-id here */
  147765. ){
  147766. int rc;
  147767. *ppLeaf = 0;
  147768. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  147769. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  147770. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  147771. if( piNode ) *piNode = iNode;
  147772. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  147773. sqlite3_reset(pRtree->pReadRowid);
  147774. }else{
  147775. rc = sqlite3_reset(pRtree->pReadRowid);
  147776. }
  147777. return rc;
  147778. }
  147779. /*
  147780. ** This function is called to configure the RtreeConstraint object passed
  147781. ** as the second argument for a MATCH constraint. The value passed as the
  147782. ** first argument to this function is the right-hand operand to the MATCH
  147783. ** operator.
  147784. */
  147785. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  147786. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  147787. sqlite3_rtree_query_info *pInfo; /* Callback information */
  147788. int nBlob; /* Size of the geometry function blob */
  147789. int nExpected; /* Expected size of the BLOB */
  147790. /* Check that value is actually a blob. */
  147791. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  147792. /* Check that the blob is roughly the right size. */
  147793. nBlob = sqlite3_value_bytes(pValue);
  147794. if( nBlob<(int)sizeof(RtreeMatchArg) ){
  147795. return SQLITE_ERROR;
  147796. }
  147797. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  147798. if( !pInfo ) return SQLITE_NOMEM;
  147799. memset(pInfo, 0, sizeof(*pInfo));
  147800. pBlob = (RtreeMatchArg*)&pInfo[1];
  147801. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  147802. nExpected = (int)(sizeof(RtreeMatchArg) +
  147803. pBlob->nParam*sizeof(sqlite3_value*) +
  147804. (pBlob->nParam-1)*sizeof(RtreeDValue));
  147805. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  147806. sqlite3_free(pInfo);
  147807. return SQLITE_ERROR;
  147808. }
  147809. pInfo->pContext = pBlob->cb.pContext;
  147810. pInfo->nParam = pBlob->nParam;
  147811. pInfo->aParam = pBlob->aParam;
  147812. pInfo->apSqlParam = pBlob->apSqlParam;
  147813. if( pBlob->cb.xGeom ){
  147814. pCons->u.xGeom = pBlob->cb.xGeom;
  147815. }else{
  147816. pCons->op = RTREE_QUERY;
  147817. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  147818. }
  147819. pCons->pInfo = pInfo;
  147820. return SQLITE_OK;
  147821. }
  147822. /*
  147823. ** Rtree virtual table module xFilter method.
  147824. */
  147825. static int rtreeFilter(
  147826. sqlite3_vtab_cursor *pVtabCursor,
  147827. int idxNum, const char *idxStr,
  147828. int argc, sqlite3_value **argv
  147829. ){
  147830. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  147831. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  147832. RtreeNode *pRoot = 0;
  147833. int ii;
  147834. int rc = SQLITE_OK;
  147835. int iCell = 0;
  147836. rtreeReference(pRtree);
  147837. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  147838. freeCursorConstraints(pCsr);
  147839. sqlite3_free(pCsr->aPoint);
  147840. memset(pCsr, 0, sizeof(RtreeCursor));
  147841. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  147842. pCsr->iStrategy = idxNum;
  147843. if( idxNum==1 ){
  147844. /* Special case - lookup by rowid. */
  147845. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  147846. RtreeSearchPoint *p; /* Search point for the the leaf */
  147847. i64 iRowid = sqlite3_value_int64(argv[0]);
  147848. i64 iNode = 0;
  147849. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  147850. if( rc==SQLITE_OK && pLeaf!=0 ){
  147851. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  147852. assert( p!=0 ); /* Always returns pCsr->sPoint */
  147853. pCsr->aNode[0] = pLeaf;
  147854. p->id = iNode;
  147855. p->eWithin = PARTLY_WITHIN;
  147856. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  147857. p->iCell = iCell;
  147858. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  147859. }else{
  147860. pCsr->atEOF = 1;
  147861. }
  147862. }else{
  147863. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  147864. ** with the configured constraints.
  147865. */
  147866. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  147867. if( rc==SQLITE_OK && argc>0 ){
  147868. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  147869. pCsr->nConstraint = argc;
  147870. if( !pCsr->aConstraint ){
  147871. rc = SQLITE_NOMEM;
  147872. }else{
  147873. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  147874. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  147875. assert( (idxStr==0 && argc==0)
  147876. || (idxStr && (int)strlen(idxStr)==argc*2) );
  147877. for(ii=0; ii<argc; ii++){
  147878. RtreeConstraint *p = &pCsr->aConstraint[ii];
  147879. p->op = idxStr[ii*2];
  147880. p->iCoord = idxStr[ii*2+1]-'0';
  147881. if( p->op>=RTREE_MATCH ){
  147882. /* A MATCH operator. The right-hand-side must be a blob that
  147883. ** can be cast into an RtreeMatchArg object. One created using
  147884. ** an sqlite3_rtree_geometry_callback() SQL user function.
  147885. */
  147886. rc = deserializeGeometry(argv[ii], p);
  147887. if( rc!=SQLITE_OK ){
  147888. break;
  147889. }
  147890. p->pInfo->nCoord = pRtree->nDim*2;
  147891. p->pInfo->anQueue = pCsr->anQueue;
  147892. p->pInfo->mxLevel = pRtree->iDepth + 1;
  147893. }else{
  147894. #ifdef SQLITE_RTREE_INT_ONLY
  147895. p->u.rValue = sqlite3_value_int64(argv[ii]);
  147896. #else
  147897. p->u.rValue = sqlite3_value_double(argv[ii]);
  147898. #endif
  147899. }
  147900. }
  147901. }
  147902. }
  147903. if( rc==SQLITE_OK ){
  147904. RtreeSearchPoint *pNew;
  147905. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  147906. if( pNew==0 ) return SQLITE_NOMEM;
  147907. pNew->id = 1;
  147908. pNew->iCell = 0;
  147909. pNew->eWithin = PARTLY_WITHIN;
  147910. assert( pCsr->bPoint==1 );
  147911. pCsr->aNode[0] = pRoot;
  147912. pRoot = 0;
  147913. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  147914. rc = rtreeStepToLeaf(pCsr);
  147915. }
  147916. }
  147917. nodeRelease(pRtree, pRoot);
  147918. rtreeRelease(pRtree);
  147919. return rc;
  147920. }
  147921. /*
  147922. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  147923. ** extension is currently being used by a version of SQLite too old to
  147924. ** support estimatedRows. In that case this function is a no-op.
  147925. */
  147926. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  147927. #if SQLITE_VERSION_NUMBER>=3008002
  147928. if( sqlite3_libversion_number()>=3008002 ){
  147929. pIdxInfo->estimatedRows = nRow;
  147930. }
  147931. #endif
  147932. }
  147933. /*
  147934. ** Rtree virtual table module xBestIndex method. There are three
  147935. ** table scan strategies to choose from (in order from most to
  147936. ** least desirable):
  147937. **
  147938. ** idxNum idxStr Strategy
  147939. ** ------------------------------------------------
  147940. ** 1 Unused Direct lookup by rowid.
  147941. ** 2 See below R-tree query or full-table scan.
  147942. ** ------------------------------------------------
  147943. **
  147944. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  147945. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  147946. ** constraint used. The first two bytes of idxStr correspond to
  147947. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  147948. ** (argvIndex==1) etc.
  147949. **
  147950. ** The first of each pair of bytes in idxStr identifies the constraint
  147951. ** operator as follows:
  147952. **
  147953. ** Operator Byte Value
  147954. ** ----------------------
  147955. ** = 0x41 ('A')
  147956. ** <= 0x42 ('B')
  147957. ** < 0x43 ('C')
  147958. ** >= 0x44 ('D')
  147959. ** > 0x45 ('E')
  147960. ** MATCH 0x46 ('F')
  147961. ** ----------------------
  147962. **
  147963. ** The second of each pair of bytes identifies the coordinate column
  147964. ** to which the constraint applies. The leftmost coordinate column
  147965. ** is 'a', the second from the left 'b' etc.
  147966. */
  147967. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  147968. Rtree *pRtree = (Rtree*)tab;
  147969. int rc = SQLITE_OK;
  147970. int ii;
  147971. int bMatch = 0; /* True if there exists a MATCH constraint */
  147972. i64 nRow; /* Estimated rows returned by this scan */
  147973. int iIdx = 0;
  147974. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  147975. memset(zIdxStr, 0, sizeof(zIdxStr));
  147976. /* Check if there exists a MATCH constraint - even an unusable one. If there
  147977. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  147978. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  147979. ** possible. */
  147980. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  147981. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  147982. bMatch = 1;
  147983. }
  147984. }
  147985. assert( pIdxInfo->idxStr==0 );
  147986. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  147987. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  147988. if( bMatch==0 && p->usable
  147989. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  147990. ){
  147991. /* We have an equality constraint on the rowid. Use strategy 1. */
  147992. int jj;
  147993. for(jj=0; jj<ii; jj++){
  147994. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  147995. pIdxInfo->aConstraintUsage[jj].omit = 0;
  147996. }
  147997. pIdxInfo->idxNum = 1;
  147998. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  147999. pIdxInfo->aConstraintUsage[jj].omit = 1;
  148000. /* This strategy involves a two rowid lookups on an B-Tree structures
  148001. ** and then a linear search of an R-Tree node. This should be
  148002. ** considered almost as quick as a direct rowid lookup (for which
  148003. ** sqlite uses an internal cost of 0.0). It is expected to return
  148004. ** a single row.
  148005. */
  148006. pIdxInfo->estimatedCost = 30.0;
  148007. setEstimatedRows(pIdxInfo, 1);
  148008. return SQLITE_OK;
  148009. }
  148010. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  148011. u8 op;
  148012. switch( p->op ){
  148013. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  148014. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  148015. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  148016. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  148017. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  148018. default:
  148019. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  148020. op = RTREE_MATCH;
  148021. break;
  148022. }
  148023. zIdxStr[iIdx++] = op;
  148024. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  148025. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  148026. pIdxInfo->aConstraintUsage[ii].omit = 1;
  148027. }
  148028. }
  148029. pIdxInfo->idxNum = 2;
  148030. pIdxInfo->needToFreeIdxStr = 1;
  148031. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  148032. return SQLITE_NOMEM;
  148033. }
  148034. nRow = pRtree->nRowEst >> (iIdx/2);
  148035. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  148036. setEstimatedRows(pIdxInfo, nRow);
  148037. return rc;
  148038. }
  148039. /*
  148040. ** Return the N-dimensional volumn of the cell stored in *p.
  148041. */
  148042. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  148043. RtreeDValue area = (RtreeDValue)1;
  148044. int ii;
  148045. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  148046. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  148047. }
  148048. return area;
  148049. }
  148050. /*
  148051. ** Return the margin length of cell p. The margin length is the sum
  148052. ** of the objects size in each dimension.
  148053. */
  148054. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  148055. RtreeDValue margin = (RtreeDValue)0;
  148056. int ii;
  148057. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  148058. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  148059. }
  148060. return margin;
  148061. }
  148062. /*
  148063. ** Store the union of cells p1 and p2 in p1.
  148064. */
  148065. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  148066. int ii;
  148067. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  148068. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  148069. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  148070. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  148071. }
  148072. }else{
  148073. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  148074. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  148075. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  148076. }
  148077. }
  148078. }
  148079. /*
  148080. ** Return true if the area covered by p2 is a subset of the area covered
  148081. ** by p1. False otherwise.
  148082. */
  148083. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  148084. int ii;
  148085. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  148086. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  148087. RtreeCoord *a1 = &p1->aCoord[ii];
  148088. RtreeCoord *a2 = &p2->aCoord[ii];
  148089. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  148090. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  148091. ){
  148092. return 0;
  148093. }
  148094. }
  148095. return 1;
  148096. }
  148097. /*
  148098. ** Return the amount cell p would grow by if it were unioned with pCell.
  148099. */
  148100. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  148101. RtreeDValue area;
  148102. RtreeCell cell;
  148103. memcpy(&cell, p, sizeof(RtreeCell));
  148104. area = cellArea(pRtree, &cell);
  148105. cellUnion(pRtree, &cell, pCell);
  148106. return (cellArea(pRtree, &cell)-area);
  148107. }
  148108. static RtreeDValue cellOverlap(
  148109. Rtree *pRtree,
  148110. RtreeCell *p,
  148111. RtreeCell *aCell,
  148112. int nCell
  148113. ){
  148114. int ii;
  148115. RtreeDValue overlap = RTREE_ZERO;
  148116. for(ii=0; ii<nCell; ii++){
  148117. int jj;
  148118. RtreeDValue o = (RtreeDValue)1;
  148119. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  148120. RtreeDValue x1, x2;
  148121. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  148122. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  148123. if( x2<x1 ){
  148124. o = (RtreeDValue)0;
  148125. break;
  148126. }else{
  148127. o = o * (x2-x1);
  148128. }
  148129. }
  148130. overlap += o;
  148131. }
  148132. return overlap;
  148133. }
  148134. /*
  148135. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  148136. ** ChooseSubTree in r*tree terminology.
  148137. */
  148138. static int ChooseLeaf(
  148139. Rtree *pRtree, /* Rtree table */
  148140. RtreeCell *pCell, /* Cell to insert into rtree */
  148141. int iHeight, /* Height of sub-tree rooted at pCell */
  148142. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  148143. ){
  148144. int rc;
  148145. int ii;
  148146. RtreeNode *pNode;
  148147. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  148148. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  148149. int iCell;
  148150. sqlite3_int64 iBest = 0;
  148151. RtreeDValue fMinGrowth = RTREE_ZERO;
  148152. RtreeDValue fMinArea = RTREE_ZERO;
  148153. int nCell = NCELL(pNode);
  148154. RtreeCell cell;
  148155. RtreeNode *pChild;
  148156. RtreeCell *aCell = 0;
  148157. /* Select the child node which will be enlarged the least if pCell
  148158. ** is inserted into it. Resolve ties by choosing the entry with
  148159. ** the smallest area.
  148160. */
  148161. for(iCell=0; iCell<nCell; iCell++){
  148162. int bBest = 0;
  148163. RtreeDValue growth;
  148164. RtreeDValue area;
  148165. nodeGetCell(pRtree, pNode, iCell, &cell);
  148166. growth = cellGrowth(pRtree, &cell, pCell);
  148167. area = cellArea(pRtree, &cell);
  148168. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  148169. bBest = 1;
  148170. }
  148171. if( bBest ){
  148172. fMinGrowth = growth;
  148173. fMinArea = area;
  148174. iBest = cell.iRowid;
  148175. }
  148176. }
  148177. sqlite3_free(aCell);
  148178. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  148179. nodeRelease(pRtree, pNode);
  148180. pNode = pChild;
  148181. }
  148182. *ppLeaf = pNode;
  148183. return rc;
  148184. }
  148185. /*
  148186. ** A cell with the same content as pCell has just been inserted into
  148187. ** the node pNode. This function updates the bounding box cells in
  148188. ** all ancestor elements.
  148189. */
  148190. static int AdjustTree(
  148191. Rtree *pRtree, /* Rtree table */
  148192. RtreeNode *pNode, /* Adjust ancestry of this node. */
  148193. RtreeCell *pCell /* This cell was just inserted */
  148194. ){
  148195. RtreeNode *p = pNode;
  148196. while( p->pParent ){
  148197. RtreeNode *pParent = p->pParent;
  148198. RtreeCell cell;
  148199. int iCell;
  148200. if( nodeParentIndex(pRtree, p, &iCell) ){
  148201. return SQLITE_CORRUPT_VTAB;
  148202. }
  148203. nodeGetCell(pRtree, pParent, iCell, &cell);
  148204. if( !cellContains(pRtree, &cell, pCell) ){
  148205. cellUnion(pRtree, &cell, pCell);
  148206. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  148207. }
  148208. p = pParent;
  148209. }
  148210. return SQLITE_OK;
  148211. }
  148212. /*
  148213. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  148214. */
  148215. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  148216. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  148217. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  148218. sqlite3_step(pRtree->pWriteRowid);
  148219. return sqlite3_reset(pRtree->pWriteRowid);
  148220. }
  148221. /*
  148222. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  148223. */
  148224. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  148225. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  148226. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  148227. sqlite3_step(pRtree->pWriteParent);
  148228. return sqlite3_reset(pRtree->pWriteParent);
  148229. }
  148230. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  148231. /*
  148232. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  148233. ** nIdx. The aIdx array contains the set of integers from 0 to
  148234. ** (nIdx-1) in no particular order. This function sorts the values
  148235. ** in aIdx according to the indexed values in aDistance. For
  148236. ** example, assuming the inputs:
  148237. **
  148238. ** aIdx = { 0, 1, 2, 3 }
  148239. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  148240. **
  148241. ** this function sets the aIdx array to contain:
  148242. **
  148243. ** aIdx = { 0, 1, 2, 3 }
  148244. **
  148245. ** The aSpare array is used as temporary working space by the
  148246. ** sorting algorithm.
  148247. */
  148248. static void SortByDistance(
  148249. int *aIdx,
  148250. int nIdx,
  148251. RtreeDValue *aDistance,
  148252. int *aSpare
  148253. ){
  148254. if( nIdx>1 ){
  148255. int iLeft = 0;
  148256. int iRight = 0;
  148257. int nLeft = nIdx/2;
  148258. int nRight = nIdx-nLeft;
  148259. int *aLeft = aIdx;
  148260. int *aRight = &aIdx[nLeft];
  148261. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  148262. SortByDistance(aRight, nRight, aDistance, aSpare);
  148263. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  148264. aLeft = aSpare;
  148265. while( iLeft<nLeft || iRight<nRight ){
  148266. if( iLeft==nLeft ){
  148267. aIdx[iLeft+iRight] = aRight[iRight];
  148268. iRight++;
  148269. }else if( iRight==nRight ){
  148270. aIdx[iLeft+iRight] = aLeft[iLeft];
  148271. iLeft++;
  148272. }else{
  148273. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  148274. RtreeDValue fRight = aDistance[aRight[iRight]];
  148275. if( fLeft<fRight ){
  148276. aIdx[iLeft+iRight] = aLeft[iLeft];
  148277. iLeft++;
  148278. }else{
  148279. aIdx[iLeft+iRight] = aRight[iRight];
  148280. iRight++;
  148281. }
  148282. }
  148283. }
  148284. #if 0
  148285. /* Check that the sort worked */
  148286. {
  148287. int jj;
  148288. for(jj=1; jj<nIdx; jj++){
  148289. RtreeDValue left = aDistance[aIdx[jj-1]];
  148290. RtreeDValue right = aDistance[aIdx[jj]];
  148291. assert( left<=right );
  148292. }
  148293. }
  148294. #endif
  148295. }
  148296. }
  148297. /*
  148298. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  148299. ** nIdx. The aIdx array contains the set of integers from 0 to
  148300. ** (nIdx-1) in no particular order. This function sorts the values
  148301. ** in aIdx according to dimension iDim of the cells in aCell. The
  148302. ** minimum value of dimension iDim is considered first, the
  148303. ** maximum used to break ties.
  148304. **
  148305. ** The aSpare array is used as temporary working space by the
  148306. ** sorting algorithm.
  148307. */
  148308. static void SortByDimension(
  148309. Rtree *pRtree,
  148310. int *aIdx,
  148311. int nIdx,
  148312. int iDim,
  148313. RtreeCell *aCell,
  148314. int *aSpare
  148315. ){
  148316. if( nIdx>1 ){
  148317. int iLeft = 0;
  148318. int iRight = 0;
  148319. int nLeft = nIdx/2;
  148320. int nRight = nIdx-nLeft;
  148321. int *aLeft = aIdx;
  148322. int *aRight = &aIdx[nLeft];
  148323. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  148324. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  148325. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  148326. aLeft = aSpare;
  148327. while( iLeft<nLeft || iRight<nRight ){
  148328. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  148329. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  148330. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  148331. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  148332. if( (iLeft!=nLeft) && ((iRight==nRight)
  148333. || (xleft1<xright1)
  148334. || (xleft1==xright1 && xleft2<xright2)
  148335. )){
  148336. aIdx[iLeft+iRight] = aLeft[iLeft];
  148337. iLeft++;
  148338. }else{
  148339. aIdx[iLeft+iRight] = aRight[iRight];
  148340. iRight++;
  148341. }
  148342. }
  148343. #if 0
  148344. /* Check that the sort worked */
  148345. {
  148346. int jj;
  148347. for(jj=1; jj<nIdx; jj++){
  148348. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  148349. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  148350. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  148351. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  148352. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  148353. }
  148354. }
  148355. #endif
  148356. }
  148357. }
  148358. /*
  148359. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  148360. */
  148361. static int splitNodeStartree(
  148362. Rtree *pRtree,
  148363. RtreeCell *aCell,
  148364. int nCell,
  148365. RtreeNode *pLeft,
  148366. RtreeNode *pRight,
  148367. RtreeCell *pBboxLeft,
  148368. RtreeCell *pBboxRight
  148369. ){
  148370. int **aaSorted;
  148371. int *aSpare;
  148372. int ii;
  148373. int iBestDim = 0;
  148374. int iBestSplit = 0;
  148375. RtreeDValue fBestMargin = RTREE_ZERO;
  148376. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  148377. aaSorted = (int **)sqlite3_malloc(nByte);
  148378. if( !aaSorted ){
  148379. return SQLITE_NOMEM;
  148380. }
  148381. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  148382. memset(aaSorted, 0, nByte);
  148383. for(ii=0; ii<pRtree->nDim; ii++){
  148384. int jj;
  148385. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  148386. for(jj=0; jj<nCell; jj++){
  148387. aaSorted[ii][jj] = jj;
  148388. }
  148389. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  148390. }
  148391. for(ii=0; ii<pRtree->nDim; ii++){
  148392. RtreeDValue margin = RTREE_ZERO;
  148393. RtreeDValue fBestOverlap = RTREE_ZERO;
  148394. RtreeDValue fBestArea = RTREE_ZERO;
  148395. int iBestLeft = 0;
  148396. int nLeft;
  148397. for(
  148398. nLeft=RTREE_MINCELLS(pRtree);
  148399. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  148400. nLeft++
  148401. ){
  148402. RtreeCell left;
  148403. RtreeCell right;
  148404. int kk;
  148405. RtreeDValue overlap;
  148406. RtreeDValue area;
  148407. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  148408. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  148409. for(kk=1; kk<(nCell-1); kk++){
  148410. if( kk<nLeft ){
  148411. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  148412. }else{
  148413. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  148414. }
  148415. }
  148416. margin += cellMargin(pRtree, &left);
  148417. margin += cellMargin(pRtree, &right);
  148418. overlap = cellOverlap(pRtree, &left, &right, 1);
  148419. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  148420. if( (nLeft==RTREE_MINCELLS(pRtree))
  148421. || (overlap<fBestOverlap)
  148422. || (overlap==fBestOverlap && area<fBestArea)
  148423. ){
  148424. iBestLeft = nLeft;
  148425. fBestOverlap = overlap;
  148426. fBestArea = area;
  148427. }
  148428. }
  148429. if( ii==0 || margin<fBestMargin ){
  148430. iBestDim = ii;
  148431. fBestMargin = margin;
  148432. iBestSplit = iBestLeft;
  148433. }
  148434. }
  148435. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  148436. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  148437. for(ii=0; ii<nCell; ii++){
  148438. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  148439. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  148440. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  148441. nodeInsertCell(pRtree, pTarget, pCell);
  148442. cellUnion(pRtree, pBbox, pCell);
  148443. }
  148444. sqlite3_free(aaSorted);
  148445. return SQLITE_OK;
  148446. }
  148447. static int updateMapping(
  148448. Rtree *pRtree,
  148449. i64 iRowid,
  148450. RtreeNode *pNode,
  148451. int iHeight
  148452. ){
  148453. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  148454. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  148455. if( iHeight>0 ){
  148456. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  148457. if( pChild ){
  148458. nodeRelease(pRtree, pChild->pParent);
  148459. nodeReference(pNode);
  148460. pChild->pParent = pNode;
  148461. }
  148462. }
  148463. return xSetMapping(pRtree, iRowid, pNode->iNode);
  148464. }
  148465. static int SplitNode(
  148466. Rtree *pRtree,
  148467. RtreeNode *pNode,
  148468. RtreeCell *pCell,
  148469. int iHeight
  148470. ){
  148471. int i;
  148472. int newCellIsRight = 0;
  148473. int rc = SQLITE_OK;
  148474. int nCell = NCELL(pNode);
  148475. RtreeCell *aCell;
  148476. int *aiUsed;
  148477. RtreeNode *pLeft = 0;
  148478. RtreeNode *pRight = 0;
  148479. RtreeCell leftbbox;
  148480. RtreeCell rightbbox;
  148481. /* Allocate an array and populate it with a copy of pCell and
  148482. ** all cells from node pLeft. Then zero the original node.
  148483. */
  148484. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  148485. if( !aCell ){
  148486. rc = SQLITE_NOMEM;
  148487. goto splitnode_out;
  148488. }
  148489. aiUsed = (int *)&aCell[nCell+1];
  148490. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  148491. for(i=0; i<nCell; i++){
  148492. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  148493. }
  148494. nodeZero(pRtree, pNode);
  148495. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  148496. nCell++;
  148497. if( pNode->iNode==1 ){
  148498. pRight = nodeNew(pRtree, pNode);
  148499. pLeft = nodeNew(pRtree, pNode);
  148500. pRtree->iDepth++;
  148501. pNode->isDirty = 1;
  148502. writeInt16(pNode->zData, pRtree->iDepth);
  148503. }else{
  148504. pLeft = pNode;
  148505. pRight = nodeNew(pRtree, pLeft->pParent);
  148506. nodeReference(pLeft);
  148507. }
  148508. if( !pLeft || !pRight ){
  148509. rc = SQLITE_NOMEM;
  148510. goto splitnode_out;
  148511. }
  148512. memset(pLeft->zData, 0, pRtree->iNodeSize);
  148513. memset(pRight->zData, 0, pRtree->iNodeSize);
  148514. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  148515. &leftbbox, &rightbbox);
  148516. if( rc!=SQLITE_OK ){
  148517. goto splitnode_out;
  148518. }
  148519. /* Ensure both child nodes have node numbers assigned to them by calling
  148520. ** nodeWrite(). Node pRight always needs a node number, as it was created
  148521. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  148522. ** In this case avoid the all to nodeWrite().
  148523. */
  148524. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  148525. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  148526. ){
  148527. goto splitnode_out;
  148528. }
  148529. rightbbox.iRowid = pRight->iNode;
  148530. leftbbox.iRowid = pLeft->iNode;
  148531. if( pNode->iNode==1 ){
  148532. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  148533. if( rc!=SQLITE_OK ){
  148534. goto splitnode_out;
  148535. }
  148536. }else{
  148537. RtreeNode *pParent = pLeft->pParent;
  148538. int iCell;
  148539. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  148540. if( rc==SQLITE_OK ){
  148541. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  148542. rc = AdjustTree(pRtree, pParent, &leftbbox);
  148543. }
  148544. if( rc!=SQLITE_OK ){
  148545. goto splitnode_out;
  148546. }
  148547. }
  148548. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  148549. goto splitnode_out;
  148550. }
  148551. for(i=0; i<NCELL(pRight); i++){
  148552. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  148553. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  148554. if( iRowid==pCell->iRowid ){
  148555. newCellIsRight = 1;
  148556. }
  148557. if( rc!=SQLITE_OK ){
  148558. goto splitnode_out;
  148559. }
  148560. }
  148561. if( pNode->iNode==1 ){
  148562. for(i=0; i<NCELL(pLeft); i++){
  148563. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  148564. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  148565. if( rc!=SQLITE_OK ){
  148566. goto splitnode_out;
  148567. }
  148568. }
  148569. }else if( newCellIsRight==0 ){
  148570. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  148571. }
  148572. if( rc==SQLITE_OK ){
  148573. rc = nodeRelease(pRtree, pRight);
  148574. pRight = 0;
  148575. }
  148576. if( rc==SQLITE_OK ){
  148577. rc = nodeRelease(pRtree, pLeft);
  148578. pLeft = 0;
  148579. }
  148580. splitnode_out:
  148581. nodeRelease(pRtree, pRight);
  148582. nodeRelease(pRtree, pLeft);
  148583. sqlite3_free(aCell);
  148584. return rc;
  148585. }
  148586. /*
  148587. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  148588. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  148589. ** the pLeaf->pParent chain all the way up to the root node.
  148590. **
  148591. ** This operation is required when a row is deleted (or updated - an update
  148592. ** is implemented as a delete followed by an insert). SQLite provides the
  148593. ** rowid of the row to delete, which can be used to find the leaf on which
  148594. ** the entry resides (argument pLeaf). Once the leaf is located, this
  148595. ** function is called to determine its ancestry.
  148596. */
  148597. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  148598. int rc = SQLITE_OK;
  148599. RtreeNode *pChild = pLeaf;
  148600. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  148601. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  148602. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  148603. rc = sqlite3_step(pRtree->pReadParent);
  148604. if( rc==SQLITE_ROW ){
  148605. RtreeNode *pTest; /* Used to test for reference loops */
  148606. i64 iNode; /* Node number of parent node */
  148607. /* Before setting pChild->pParent, test that we are not creating a
  148608. ** loop of references (as we would if, say, pChild==pParent). We don't
  148609. ** want to do this as it leads to a memory leak when trying to delete
  148610. ** the referenced counted node structures.
  148611. */
  148612. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  148613. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  148614. if( !pTest ){
  148615. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  148616. }
  148617. }
  148618. rc = sqlite3_reset(pRtree->pReadParent);
  148619. if( rc==SQLITE_OK ) rc = rc2;
  148620. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  148621. pChild = pChild->pParent;
  148622. }
  148623. return rc;
  148624. }
  148625. static int deleteCell(Rtree *, RtreeNode *, int, int);
  148626. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  148627. int rc;
  148628. int rc2;
  148629. RtreeNode *pParent = 0;
  148630. int iCell;
  148631. assert( pNode->nRef==1 );
  148632. /* Remove the entry in the parent cell. */
  148633. rc = nodeParentIndex(pRtree, pNode, &iCell);
  148634. if( rc==SQLITE_OK ){
  148635. pParent = pNode->pParent;
  148636. pNode->pParent = 0;
  148637. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  148638. }
  148639. rc2 = nodeRelease(pRtree, pParent);
  148640. if( rc==SQLITE_OK ){
  148641. rc = rc2;
  148642. }
  148643. if( rc!=SQLITE_OK ){
  148644. return rc;
  148645. }
  148646. /* Remove the xxx_node entry. */
  148647. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  148648. sqlite3_step(pRtree->pDeleteNode);
  148649. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  148650. return rc;
  148651. }
  148652. /* Remove the xxx_parent entry. */
  148653. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  148654. sqlite3_step(pRtree->pDeleteParent);
  148655. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  148656. return rc;
  148657. }
  148658. /* Remove the node from the in-memory hash table and link it into
  148659. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  148660. */
  148661. nodeHashDelete(pRtree, pNode);
  148662. pNode->iNode = iHeight;
  148663. pNode->pNext = pRtree->pDeleted;
  148664. pNode->nRef++;
  148665. pRtree->pDeleted = pNode;
  148666. return SQLITE_OK;
  148667. }
  148668. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  148669. RtreeNode *pParent = pNode->pParent;
  148670. int rc = SQLITE_OK;
  148671. if( pParent ){
  148672. int ii;
  148673. int nCell = NCELL(pNode);
  148674. RtreeCell box; /* Bounding box for pNode */
  148675. nodeGetCell(pRtree, pNode, 0, &box);
  148676. for(ii=1; ii<nCell; ii++){
  148677. RtreeCell cell;
  148678. nodeGetCell(pRtree, pNode, ii, &cell);
  148679. cellUnion(pRtree, &box, &cell);
  148680. }
  148681. box.iRowid = pNode->iNode;
  148682. rc = nodeParentIndex(pRtree, pNode, &ii);
  148683. if( rc==SQLITE_OK ){
  148684. nodeOverwriteCell(pRtree, pParent, &box, ii);
  148685. rc = fixBoundingBox(pRtree, pParent);
  148686. }
  148687. }
  148688. return rc;
  148689. }
  148690. /*
  148691. ** Delete the cell at index iCell of node pNode. After removing the
  148692. ** cell, adjust the r-tree data structure if required.
  148693. */
  148694. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  148695. RtreeNode *pParent;
  148696. int rc;
  148697. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  148698. return rc;
  148699. }
  148700. /* Remove the cell from the node. This call just moves bytes around
  148701. ** the in-memory node image, so it cannot fail.
  148702. */
  148703. nodeDeleteCell(pRtree, pNode, iCell);
  148704. /* If the node is not the tree root and now has less than the minimum
  148705. ** number of cells, remove it from the tree. Otherwise, update the
  148706. ** cell in the parent node so that it tightly contains the updated
  148707. ** node.
  148708. */
  148709. pParent = pNode->pParent;
  148710. assert( pParent || pNode->iNode==1 );
  148711. if( pParent ){
  148712. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  148713. rc = removeNode(pRtree, pNode, iHeight);
  148714. }else{
  148715. rc = fixBoundingBox(pRtree, pNode);
  148716. }
  148717. }
  148718. return rc;
  148719. }
  148720. static int Reinsert(
  148721. Rtree *pRtree,
  148722. RtreeNode *pNode,
  148723. RtreeCell *pCell,
  148724. int iHeight
  148725. ){
  148726. int *aOrder;
  148727. int *aSpare;
  148728. RtreeCell *aCell;
  148729. RtreeDValue *aDistance;
  148730. int nCell;
  148731. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  148732. int iDim;
  148733. int ii;
  148734. int rc = SQLITE_OK;
  148735. int n;
  148736. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  148737. nCell = NCELL(pNode)+1;
  148738. n = (nCell+1)&(~1);
  148739. /* Allocate the buffers used by this operation. The allocation is
  148740. ** relinquished before this function returns.
  148741. */
  148742. aCell = (RtreeCell *)sqlite3_malloc(n * (
  148743. sizeof(RtreeCell) + /* aCell array */
  148744. sizeof(int) + /* aOrder array */
  148745. sizeof(int) + /* aSpare array */
  148746. sizeof(RtreeDValue) /* aDistance array */
  148747. ));
  148748. if( !aCell ){
  148749. return SQLITE_NOMEM;
  148750. }
  148751. aOrder = (int *)&aCell[n];
  148752. aSpare = (int *)&aOrder[n];
  148753. aDistance = (RtreeDValue *)&aSpare[n];
  148754. for(ii=0; ii<nCell; ii++){
  148755. if( ii==(nCell-1) ){
  148756. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  148757. }else{
  148758. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  148759. }
  148760. aOrder[ii] = ii;
  148761. for(iDim=0; iDim<pRtree->nDim; iDim++){
  148762. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  148763. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  148764. }
  148765. }
  148766. for(iDim=0; iDim<pRtree->nDim; iDim++){
  148767. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  148768. }
  148769. for(ii=0; ii<nCell; ii++){
  148770. aDistance[ii] = RTREE_ZERO;
  148771. for(iDim=0; iDim<pRtree->nDim; iDim++){
  148772. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  148773. DCOORD(aCell[ii].aCoord[iDim*2]));
  148774. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  148775. }
  148776. }
  148777. SortByDistance(aOrder, nCell, aDistance, aSpare);
  148778. nodeZero(pRtree, pNode);
  148779. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  148780. RtreeCell *p = &aCell[aOrder[ii]];
  148781. nodeInsertCell(pRtree, pNode, p);
  148782. if( p->iRowid==pCell->iRowid ){
  148783. if( iHeight==0 ){
  148784. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  148785. }else{
  148786. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  148787. }
  148788. }
  148789. }
  148790. if( rc==SQLITE_OK ){
  148791. rc = fixBoundingBox(pRtree, pNode);
  148792. }
  148793. for(; rc==SQLITE_OK && ii<nCell; ii++){
  148794. /* Find a node to store this cell in. pNode->iNode currently contains
  148795. ** the height of the sub-tree headed by the cell.
  148796. */
  148797. RtreeNode *pInsert;
  148798. RtreeCell *p = &aCell[aOrder[ii]];
  148799. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  148800. if( rc==SQLITE_OK ){
  148801. int rc2;
  148802. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  148803. rc2 = nodeRelease(pRtree, pInsert);
  148804. if( rc==SQLITE_OK ){
  148805. rc = rc2;
  148806. }
  148807. }
  148808. }
  148809. sqlite3_free(aCell);
  148810. return rc;
  148811. }
  148812. /*
  148813. ** Insert cell pCell into node pNode. Node pNode is the head of a
  148814. ** subtree iHeight high (leaf nodes have iHeight==0).
  148815. */
  148816. static int rtreeInsertCell(
  148817. Rtree *pRtree,
  148818. RtreeNode *pNode,
  148819. RtreeCell *pCell,
  148820. int iHeight
  148821. ){
  148822. int rc = SQLITE_OK;
  148823. if( iHeight>0 ){
  148824. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  148825. if( pChild ){
  148826. nodeRelease(pRtree, pChild->pParent);
  148827. nodeReference(pNode);
  148828. pChild->pParent = pNode;
  148829. }
  148830. }
  148831. if( nodeInsertCell(pRtree, pNode, pCell) ){
  148832. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  148833. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  148834. }else{
  148835. pRtree->iReinsertHeight = iHeight;
  148836. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  148837. }
  148838. }else{
  148839. rc = AdjustTree(pRtree, pNode, pCell);
  148840. if( rc==SQLITE_OK ){
  148841. if( iHeight==0 ){
  148842. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  148843. }else{
  148844. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  148845. }
  148846. }
  148847. }
  148848. return rc;
  148849. }
  148850. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  148851. int ii;
  148852. int rc = SQLITE_OK;
  148853. int nCell = NCELL(pNode);
  148854. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  148855. RtreeNode *pInsert;
  148856. RtreeCell cell;
  148857. nodeGetCell(pRtree, pNode, ii, &cell);
  148858. /* Find a node to store this cell in. pNode->iNode currently contains
  148859. ** the height of the sub-tree headed by the cell.
  148860. */
  148861. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  148862. if( rc==SQLITE_OK ){
  148863. int rc2;
  148864. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  148865. rc2 = nodeRelease(pRtree, pInsert);
  148866. if( rc==SQLITE_OK ){
  148867. rc = rc2;
  148868. }
  148869. }
  148870. }
  148871. return rc;
  148872. }
  148873. /*
  148874. ** Select a currently unused rowid for a new r-tree record.
  148875. */
  148876. static int newRowid(Rtree *pRtree, i64 *piRowid){
  148877. int rc;
  148878. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  148879. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  148880. sqlite3_step(pRtree->pWriteRowid);
  148881. rc = sqlite3_reset(pRtree->pWriteRowid);
  148882. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  148883. return rc;
  148884. }
  148885. /*
  148886. ** Remove the entry with rowid=iDelete from the r-tree structure.
  148887. */
  148888. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  148889. int rc; /* Return code */
  148890. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  148891. int iCell; /* Index of iDelete cell in pLeaf */
  148892. RtreeNode *pRoot; /* Root node of rtree structure */
  148893. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  148894. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  148895. /* Obtain a reference to the leaf node that contains the entry
  148896. ** about to be deleted.
  148897. */
  148898. if( rc==SQLITE_OK ){
  148899. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  148900. }
  148901. /* Delete the cell in question from the leaf node. */
  148902. if( rc==SQLITE_OK ){
  148903. int rc2;
  148904. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  148905. if( rc==SQLITE_OK ){
  148906. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  148907. }
  148908. rc2 = nodeRelease(pRtree, pLeaf);
  148909. if( rc==SQLITE_OK ){
  148910. rc = rc2;
  148911. }
  148912. }
  148913. /* Delete the corresponding entry in the <rtree>_rowid table. */
  148914. if( rc==SQLITE_OK ){
  148915. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  148916. sqlite3_step(pRtree->pDeleteRowid);
  148917. rc = sqlite3_reset(pRtree->pDeleteRowid);
  148918. }
  148919. /* Check if the root node now has exactly one child. If so, remove
  148920. ** it, schedule the contents of the child for reinsertion and
  148921. ** reduce the tree height by one.
  148922. **
  148923. ** This is equivalent to copying the contents of the child into
  148924. ** the root node (the operation that Gutman's paper says to perform
  148925. ** in this scenario).
  148926. */
  148927. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  148928. int rc2;
  148929. RtreeNode *pChild;
  148930. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  148931. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  148932. if( rc==SQLITE_OK ){
  148933. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  148934. }
  148935. rc2 = nodeRelease(pRtree, pChild);
  148936. if( rc==SQLITE_OK ) rc = rc2;
  148937. if( rc==SQLITE_OK ){
  148938. pRtree->iDepth--;
  148939. writeInt16(pRoot->zData, pRtree->iDepth);
  148940. pRoot->isDirty = 1;
  148941. }
  148942. }
  148943. /* Re-insert the contents of any underfull nodes removed from the tree. */
  148944. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  148945. if( rc==SQLITE_OK ){
  148946. rc = reinsertNodeContent(pRtree, pLeaf);
  148947. }
  148948. pRtree->pDeleted = pLeaf->pNext;
  148949. sqlite3_free(pLeaf);
  148950. }
  148951. /* Release the reference to the root node. */
  148952. if( rc==SQLITE_OK ){
  148953. rc = nodeRelease(pRtree, pRoot);
  148954. }else{
  148955. nodeRelease(pRtree, pRoot);
  148956. }
  148957. return rc;
  148958. }
  148959. /*
  148960. ** Rounding constants for float->double conversion.
  148961. */
  148962. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  148963. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  148964. #if !defined(SQLITE_RTREE_INT_ONLY)
  148965. /*
  148966. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  148967. ** while taking care to round toward negative or positive, respectively.
  148968. */
  148969. static RtreeValue rtreeValueDown(sqlite3_value *v){
  148970. double d = sqlite3_value_double(v);
  148971. float f = (float)d;
  148972. if( f>d ){
  148973. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  148974. }
  148975. return f;
  148976. }
  148977. static RtreeValue rtreeValueUp(sqlite3_value *v){
  148978. double d = sqlite3_value_double(v);
  148979. float f = (float)d;
  148980. if( f<d ){
  148981. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  148982. }
  148983. return f;
  148984. }
  148985. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  148986. /*
  148987. ** The xUpdate method for rtree module virtual tables.
  148988. */
  148989. static int rtreeUpdate(
  148990. sqlite3_vtab *pVtab,
  148991. int nData,
  148992. sqlite3_value **azData,
  148993. sqlite_int64 *pRowid
  148994. ){
  148995. Rtree *pRtree = (Rtree *)pVtab;
  148996. int rc = SQLITE_OK;
  148997. RtreeCell cell; /* New cell to insert if nData>1 */
  148998. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  148999. rtreeReference(pRtree);
  149000. assert(nData>=1);
  149001. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  149002. /* Constraint handling. A write operation on an r-tree table may return
  149003. ** SQLITE_CONSTRAINT for two reasons:
  149004. **
  149005. ** 1. A duplicate rowid value, or
  149006. ** 2. The supplied data violates the "x2>=x1" constraint.
  149007. **
  149008. ** In the first case, if the conflict-handling mode is REPLACE, then
  149009. ** the conflicting row can be removed before proceeding. In the second
  149010. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  149011. ** conflict-handling mode specified by the user.
  149012. */
  149013. if( nData>1 ){
  149014. int ii;
  149015. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  149016. **
  149017. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  149018. ** with "column" that are interpreted as table constraints.
  149019. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  149020. ** This problem was discovered after years of use, so we silently ignore
  149021. ** these kinds of misdeclared tables to avoid breaking any legacy.
  149022. */
  149023. assert( nData<=(pRtree->nDim*2 + 3) );
  149024. #ifndef SQLITE_RTREE_INT_ONLY
  149025. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  149026. for(ii=0; ii<nData-4; ii+=2){
  149027. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  149028. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  149029. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  149030. rc = SQLITE_CONSTRAINT;
  149031. goto constraint;
  149032. }
  149033. }
  149034. }else
  149035. #endif
  149036. {
  149037. for(ii=0; ii<nData-4; ii+=2){
  149038. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  149039. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  149040. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  149041. rc = SQLITE_CONSTRAINT;
  149042. goto constraint;
  149043. }
  149044. }
  149045. }
  149046. /* If a rowid value was supplied, check if it is already present in
  149047. ** the table. If so, the constraint has failed. */
  149048. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  149049. cell.iRowid = sqlite3_value_int64(azData[2]);
  149050. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  149051. || sqlite3_value_int64(azData[0])!=cell.iRowid
  149052. ){
  149053. int steprc;
  149054. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  149055. steprc = sqlite3_step(pRtree->pReadRowid);
  149056. rc = sqlite3_reset(pRtree->pReadRowid);
  149057. if( SQLITE_ROW==steprc ){
  149058. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  149059. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  149060. }else{
  149061. rc = SQLITE_CONSTRAINT;
  149062. goto constraint;
  149063. }
  149064. }
  149065. }
  149066. bHaveRowid = 1;
  149067. }
  149068. }
  149069. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  149070. ** record to delete from the r-tree table. The following block does
  149071. ** just that.
  149072. */
  149073. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  149074. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  149075. }
  149076. /* If the azData[] array contains more than one element, elements
  149077. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  149078. ** the r-tree structure.
  149079. */
  149080. if( rc==SQLITE_OK && nData>1 ){
  149081. /* Insert the new record into the r-tree */
  149082. RtreeNode *pLeaf = 0;
  149083. /* Figure out the rowid of the new row. */
  149084. if( bHaveRowid==0 ){
  149085. rc = newRowid(pRtree, &cell.iRowid);
  149086. }
  149087. *pRowid = cell.iRowid;
  149088. if( rc==SQLITE_OK ){
  149089. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  149090. }
  149091. if( rc==SQLITE_OK ){
  149092. int rc2;
  149093. pRtree->iReinsertHeight = -1;
  149094. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  149095. rc2 = nodeRelease(pRtree, pLeaf);
  149096. if( rc==SQLITE_OK ){
  149097. rc = rc2;
  149098. }
  149099. }
  149100. }
  149101. constraint:
  149102. rtreeRelease(pRtree);
  149103. return rc;
  149104. }
  149105. /*
  149106. ** The xRename method for rtree module virtual tables.
  149107. */
  149108. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  149109. Rtree *pRtree = (Rtree *)pVtab;
  149110. int rc = SQLITE_NOMEM;
  149111. char *zSql = sqlite3_mprintf(
  149112. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  149113. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  149114. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  149115. , pRtree->zDb, pRtree->zName, zNewName
  149116. , pRtree->zDb, pRtree->zName, zNewName
  149117. , pRtree->zDb, pRtree->zName, zNewName
  149118. );
  149119. if( zSql ){
  149120. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  149121. sqlite3_free(zSql);
  149122. }
  149123. return rc;
  149124. }
  149125. /*
  149126. ** This function populates the pRtree->nRowEst variable with an estimate
  149127. ** of the number of rows in the virtual table. If possible, this is based
  149128. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  149129. */
  149130. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  149131. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  149132. char *zSql;
  149133. sqlite3_stmt *p;
  149134. int rc;
  149135. i64 nRow = 0;
  149136. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  149137. if( zSql==0 ){
  149138. rc = SQLITE_NOMEM;
  149139. }else{
  149140. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  149141. if( rc==SQLITE_OK ){
  149142. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  149143. rc = sqlite3_finalize(p);
  149144. }else if( rc!=SQLITE_NOMEM ){
  149145. rc = SQLITE_OK;
  149146. }
  149147. if( rc==SQLITE_OK ){
  149148. if( nRow==0 ){
  149149. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  149150. }else{
  149151. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  149152. }
  149153. }
  149154. sqlite3_free(zSql);
  149155. }
  149156. return rc;
  149157. }
  149158. static sqlite3_module rtreeModule = {
  149159. 0, /* iVersion */
  149160. rtreeCreate, /* xCreate - create a table */
  149161. rtreeConnect, /* xConnect - connect to an existing table */
  149162. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  149163. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  149164. rtreeDestroy, /* xDestroy - Drop a table */
  149165. rtreeOpen, /* xOpen - open a cursor */
  149166. rtreeClose, /* xClose - close a cursor */
  149167. rtreeFilter, /* xFilter - configure scan constraints */
  149168. rtreeNext, /* xNext - advance a cursor */
  149169. rtreeEof, /* xEof */
  149170. rtreeColumn, /* xColumn - read data */
  149171. rtreeRowid, /* xRowid - read data */
  149172. rtreeUpdate, /* xUpdate - write data */
  149173. 0, /* xBegin - begin transaction */
  149174. 0, /* xSync - sync transaction */
  149175. 0, /* xCommit - commit transaction */
  149176. 0, /* xRollback - rollback transaction */
  149177. 0, /* xFindFunction - function overloading */
  149178. rtreeRename, /* xRename - rename the table */
  149179. 0, /* xSavepoint */
  149180. 0, /* xRelease */
  149181. 0 /* xRollbackTo */
  149182. };
  149183. static int rtreeSqlInit(
  149184. Rtree *pRtree,
  149185. sqlite3 *db,
  149186. const char *zDb,
  149187. const char *zPrefix,
  149188. int isCreate
  149189. ){
  149190. int rc = SQLITE_OK;
  149191. #define N_STATEMENT 9
  149192. static const char *azSql[N_STATEMENT] = {
  149193. /* Read and write the xxx_node table */
  149194. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  149195. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  149196. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  149197. /* Read and write the xxx_rowid table */
  149198. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  149199. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  149200. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  149201. /* Read and write the xxx_parent table */
  149202. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  149203. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  149204. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  149205. };
  149206. sqlite3_stmt **appStmt[N_STATEMENT];
  149207. int i;
  149208. pRtree->db = db;
  149209. if( isCreate ){
  149210. char *zCreate = sqlite3_mprintf(
  149211. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  149212. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  149213. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  149214. " parentnode INTEGER);"
  149215. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  149216. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  149217. );
  149218. if( !zCreate ){
  149219. return SQLITE_NOMEM;
  149220. }
  149221. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  149222. sqlite3_free(zCreate);
  149223. if( rc!=SQLITE_OK ){
  149224. return rc;
  149225. }
  149226. }
  149227. appStmt[0] = &pRtree->pReadNode;
  149228. appStmt[1] = &pRtree->pWriteNode;
  149229. appStmt[2] = &pRtree->pDeleteNode;
  149230. appStmt[3] = &pRtree->pReadRowid;
  149231. appStmt[4] = &pRtree->pWriteRowid;
  149232. appStmt[5] = &pRtree->pDeleteRowid;
  149233. appStmt[6] = &pRtree->pReadParent;
  149234. appStmt[7] = &pRtree->pWriteParent;
  149235. appStmt[8] = &pRtree->pDeleteParent;
  149236. rc = rtreeQueryStat1(db, pRtree);
  149237. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  149238. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  149239. if( zSql ){
  149240. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  149241. }else{
  149242. rc = SQLITE_NOMEM;
  149243. }
  149244. sqlite3_free(zSql);
  149245. }
  149246. return rc;
  149247. }
  149248. /*
  149249. ** The second argument to this function contains the text of an SQL statement
  149250. ** that returns a single integer value. The statement is compiled and executed
  149251. ** using database connection db. If successful, the integer value returned
  149252. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  149253. ** code is returned and the value of *piVal after returning is not defined.
  149254. */
  149255. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  149256. int rc = SQLITE_NOMEM;
  149257. if( zSql ){
  149258. sqlite3_stmt *pStmt = 0;
  149259. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  149260. if( rc==SQLITE_OK ){
  149261. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149262. *piVal = sqlite3_column_int(pStmt, 0);
  149263. }
  149264. rc = sqlite3_finalize(pStmt);
  149265. }
  149266. }
  149267. return rc;
  149268. }
  149269. /*
  149270. ** This function is called from within the xConnect() or xCreate() method to
  149271. ** determine the node-size used by the rtree table being created or connected
  149272. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  149273. ** Otherwise, an SQLite error code is returned.
  149274. **
  149275. ** If this function is being called as part of an xConnect(), then the rtree
  149276. ** table already exists. In this case the node-size is determined by inspecting
  149277. ** the root node of the tree.
  149278. **
  149279. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  149280. ** This ensures that each node is stored on a single database page. If the
  149281. ** database page-size is so large that more than RTREE_MAXCELLS entries
  149282. ** would fit in a single node, use a smaller node-size.
  149283. */
  149284. static int getNodeSize(
  149285. sqlite3 *db, /* Database handle */
  149286. Rtree *pRtree, /* Rtree handle */
  149287. int isCreate, /* True for xCreate, false for xConnect */
  149288. char **pzErr /* OUT: Error message, if any */
  149289. ){
  149290. int rc;
  149291. char *zSql;
  149292. if( isCreate ){
  149293. int iPageSize = 0;
  149294. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  149295. rc = getIntFromStmt(db, zSql, &iPageSize);
  149296. if( rc==SQLITE_OK ){
  149297. pRtree->iNodeSize = iPageSize-64;
  149298. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  149299. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  149300. }
  149301. }else{
  149302. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  149303. }
  149304. }else{
  149305. zSql = sqlite3_mprintf(
  149306. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  149307. pRtree->zDb, pRtree->zName
  149308. );
  149309. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  149310. if( rc!=SQLITE_OK ){
  149311. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  149312. }
  149313. }
  149314. sqlite3_free(zSql);
  149315. return rc;
  149316. }
  149317. /*
  149318. ** This function is the implementation of both the xConnect and xCreate
  149319. ** methods of the r-tree virtual table.
  149320. **
  149321. ** argv[0] -> module name
  149322. ** argv[1] -> database name
  149323. ** argv[2] -> table name
  149324. ** argv[...] -> column names...
  149325. */
  149326. static int rtreeInit(
  149327. sqlite3 *db, /* Database connection */
  149328. void *pAux, /* One of the RTREE_COORD_* constants */
  149329. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  149330. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  149331. char **pzErr, /* OUT: Error message, if any */
  149332. int isCreate /* True for xCreate, false for xConnect */
  149333. ){
  149334. int rc = SQLITE_OK;
  149335. Rtree *pRtree;
  149336. int nDb; /* Length of string argv[1] */
  149337. int nName; /* Length of string argv[2] */
  149338. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  149339. const char *aErrMsg[] = {
  149340. 0, /* 0 */
  149341. "Wrong number of columns for an rtree table", /* 1 */
  149342. "Too few columns for an rtree table", /* 2 */
  149343. "Too many columns for an rtree table" /* 3 */
  149344. };
  149345. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  149346. if( aErrMsg[iErr] ){
  149347. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  149348. return SQLITE_ERROR;
  149349. }
  149350. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  149351. /* Allocate the sqlite3_vtab structure */
  149352. nDb = (int)strlen(argv[1]);
  149353. nName = (int)strlen(argv[2]);
  149354. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  149355. if( !pRtree ){
  149356. return SQLITE_NOMEM;
  149357. }
  149358. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  149359. pRtree->nBusy = 1;
  149360. pRtree->base.pModule = &rtreeModule;
  149361. pRtree->zDb = (char *)&pRtree[1];
  149362. pRtree->zName = &pRtree->zDb[nDb+1];
  149363. pRtree->nDim = (argc-4)/2;
  149364. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  149365. pRtree->eCoordType = eCoordType;
  149366. memcpy(pRtree->zDb, argv[1], nDb);
  149367. memcpy(pRtree->zName, argv[2], nName);
  149368. /* Figure out the node size to use. */
  149369. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  149370. /* Create/Connect to the underlying relational database schema. If
  149371. ** that is successful, call sqlite3_declare_vtab() to configure
  149372. ** the r-tree table schema.
  149373. */
  149374. if( rc==SQLITE_OK ){
  149375. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  149376. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  149377. }else{
  149378. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  149379. char *zTmp;
  149380. int ii;
  149381. for(ii=4; zSql && ii<argc; ii++){
  149382. zTmp = zSql;
  149383. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  149384. sqlite3_free(zTmp);
  149385. }
  149386. if( zSql ){
  149387. zTmp = zSql;
  149388. zSql = sqlite3_mprintf("%s);", zTmp);
  149389. sqlite3_free(zTmp);
  149390. }
  149391. if( !zSql ){
  149392. rc = SQLITE_NOMEM;
  149393. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  149394. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  149395. }
  149396. sqlite3_free(zSql);
  149397. }
  149398. }
  149399. if( rc==SQLITE_OK ){
  149400. *ppVtab = (sqlite3_vtab *)pRtree;
  149401. }else{
  149402. assert( *ppVtab==0 );
  149403. assert( pRtree->nBusy==1 );
  149404. rtreeRelease(pRtree);
  149405. }
  149406. return rc;
  149407. }
  149408. /*
  149409. ** Implementation of a scalar function that decodes r-tree nodes to
  149410. ** human readable strings. This can be used for debugging and analysis.
  149411. **
  149412. ** The scalar function takes two arguments: (1) the number of dimensions
  149413. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  149414. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  149415. ** deserialize all nodes, a statement like:
  149416. **
  149417. ** SELECT rtreenode(2, data) FROM rt_node;
  149418. **
  149419. ** The human readable string takes the form of a Tcl list with one
  149420. ** entry for each cell in the r-tree node. Each entry is itself a
  149421. ** list, containing the 8-byte rowid/pageno followed by the
  149422. ** <num-dimension>*2 coordinates.
  149423. */
  149424. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  149425. char *zText = 0;
  149426. RtreeNode node;
  149427. Rtree tree;
  149428. int ii;
  149429. UNUSED_PARAMETER(nArg);
  149430. memset(&node, 0, sizeof(RtreeNode));
  149431. memset(&tree, 0, sizeof(Rtree));
  149432. tree.nDim = sqlite3_value_int(apArg[0]);
  149433. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  149434. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  149435. for(ii=0; ii<NCELL(&node); ii++){
  149436. char zCell[512];
  149437. int nCell = 0;
  149438. RtreeCell cell;
  149439. int jj;
  149440. nodeGetCell(&tree, &node, ii, &cell);
  149441. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  149442. nCell = (int)strlen(zCell);
  149443. for(jj=0; jj<tree.nDim*2; jj++){
  149444. #ifndef SQLITE_RTREE_INT_ONLY
  149445. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  149446. (double)cell.aCoord[jj].f);
  149447. #else
  149448. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  149449. cell.aCoord[jj].i);
  149450. #endif
  149451. nCell = (int)strlen(zCell);
  149452. }
  149453. if( zText ){
  149454. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  149455. sqlite3_free(zText);
  149456. zText = zTextNew;
  149457. }else{
  149458. zText = sqlite3_mprintf("{%s}", zCell);
  149459. }
  149460. }
  149461. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  149462. }
  149463. /* This routine implements an SQL function that returns the "depth" parameter
  149464. ** from the front of a blob that is an r-tree node. For example:
  149465. **
  149466. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  149467. **
  149468. ** The depth value is 0 for all nodes other than the root node, and the root
  149469. ** node always has nodeno=1, so the example above is the primary use for this
  149470. ** routine. This routine is intended for testing and analysis only.
  149471. */
  149472. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  149473. UNUSED_PARAMETER(nArg);
  149474. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  149475. || sqlite3_value_bytes(apArg[0])<2
  149476. ){
  149477. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  149478. }else{
  149479. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  149480. sqlite3_result_int(ctx, readInt16(zBlob));
  149481. }
  149482. }
  149483. /*
  149484. ** Register the r-tree module with database handle db. This creates the
  149485. ** virtual table module "rtree" and the debugging/analysis scalar
  149486. ** function "rtreenode".
  149487. */
  149488. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  149489. const int utf8 = SQLITE_UTF8;
  149490. int rc;
  149491. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  149492. if( rc==SQLITE_OK ){
  149493. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  149494. }
  149495. if( rc==SQLITE_OK ){
  149496. #ifdef SQLITE_RTREE_INT_ONLY
  149497. void *c = (void *)RTREE_COORD_INT32;
  149498. #else
  149499. void *c = (void *)RTREE_COORD_REAL32;
  149500. #endif
  149501. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  149502. }
  149503. if( rc==SQLITE_OK ){
  149504. void *c = (void *)RTREE_COORD_INT32;
  149505. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  149506. }
  149507. return rc;
  149508. }
  149509. /*
  149510. ** This routine deletes the RtreeGeomCallback object that was attached
  149511. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  149512. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  149513. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  149514. ** the corresponding SQL function is deleted.
  149515. */
  149516. static void rtreeFreeCallback(void *p){
  149517. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  149518. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  149519. sqlite3_free(p);
  149520. }
  149521. /*
  149522. ** This routine frees the BLOB that is returned by geomCallback().
  149523. */
  149524. static void rtreeMatchArgFree(void *pArg){
  149525. int i;
  149526. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  149527. for(i=0; i<p->nParam; i++){
  149528. sqlite3_value_free(p->apSqlParam[i]);
  149529. }
  149530. sqlite3_free(p);
  149531. }
  149532. /*
  149533. ** Each call to sqlite3_rtree_geometry_callback() or
  149534. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  149535. ** scalar function that is implemented by this routine.
  149536. **
  149537. ** All this function does is construct an RtreeMatchArg object that
  149538. ** contains the geometry-checking callback routines and a list of
  149539. ** parameters to this function, then return that RtreeMatchArg object
  149540. ** as a BLOB.
  149541. **
  149542. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  149543. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  149544. ** out which elements of the R-Tree should be returned by the query.
  149545. */
  149546. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  149547. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  149548. RtreeMatchArg *pBlob;
  149549. int nBlob;
  149550. int memErr = 0;
  149551. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  149552. + nArg*sizeof(sqlite3_value*);
  149553. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  149554. if( !pBlob ){
  149555. sqlite3_result_error_nomem(ctx);
  149556. }else{
  149557. int i;
  149558. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  149559. pBlob->cb = pGeomCtx[0];
  149560. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  149561. pBlob->nParam = nArg;
  149562. for(i=0; i<nArg; i++){
  149563. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  149564. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  149565. #ifdef SQLITE_RTREE_INT_ONLY
  149566. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  149567. #else
  149568. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  149569. #endif
  149570. }
  149571. if( memErr ){
  149572. sqlite3_result_error_nomem(ctx);
  149573. rtreeMatchArgFree(pBlob);
  149574. }else{
  149575. sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
  149576. }
  149577. }
  149578. }
  149579. /*
  149580. ** Register a new geometry function for use with the r-tree MATCH operator.
  149581. */
  149582. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  149583. sqlite3 *db, /* Register SQL function on this connection */
  149584. const char *zGeom, /* Name of the new SQL function */
  149585. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  149586. void *pContext /* Extra data associated with the callback */
  149587. ){
  149588. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  149589. /* Allocate and populate the context object. */
  149590. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  149591. if( !pGeomCtx ) return SQLITE_NOMEM;
  149592. pGeomCtx->xGeom = xGeom;
  149593. pGeomCtx->xQueryFunc = 0;
  149594. pGeomCtx->xDestructor = 0;
  149595. pGeomCtx->pContext = pContext;
  149596. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  149597. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  149598. );
  149599. }
  149600. /*
  149601. ** Register a new 2nd-generation geometry function for use with the
  149602. ** r-tree MATCH operator.
  149603. */
  149604. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  149605. sqlite3 *db, /* Register SQL function on this connection */
  149606. const char *zQueryFunc, /* Name of new SQL function */
  149607. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  149608. void *pContext, /* Extra data passed into the callback */
  149609. void (*xDestructor)(void*) /* Destructor for the extra data */
  149610. ){
  149611. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  149612. /* Allocate and populate the context object. */
  149613. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  149614. if( !pGeomCtx ) return SQLITE_NOMEM;
  149615. pGeomCtx->xGeom = 0;
  149616. pGeomCtx->xQueryFunc = xQueryFunc;
  149617. pGeomCtx->xDestructor = xDestructor;
  149618. pGeomCtx->pContext = pContext;
  149619. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  149620. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  149621. );
  149622. }
  149623. #if !SQLITE_CORE
  149624. #ifdef _WIN32
  149625. __declspec(dllexport)
  149626. #endif
  149627. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
  149628. sqlite3 *db,
  149629. char **pzErrMsg,
  149630. const sqlite3_api_routines *pApi
  149631. ){
  149632. SQLITE_EXTENSION_INIT2(pApi)
  149633. return sqlite3RtreeInit(db);
  149634. }
  149635. #endif
  149636. #endif
  149637. /************** End of rtree.c ***********************************************/
  149638. /************** Begin file icu.c *********************************************/
  149639. /*
  149640. ** 2007 May 6
  149641. **
  149642. ** The author disclaims copyright to this source code. In place of
  149643. ** a legal notice, here is a blessing:
  149644. **
  149645. ** May you do good and not evil.
  149646. ** May you find forgiveness for yourself and forgive others.
  149647. ** May you share freely, never taking more than you give.
  149648. **
  149649. *************************************************************************
  149650. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  149651. **
  149652. ** This file implements an integration between the ICU library
  149653. ** ("International Components for Unicode", an open-source library
  149654. ** for handling unicode data) and SQLite. The integration uses
  149655. ** ICU to provide the following to SQLite:
  149656. **
  149657. ** * An implementation of the SQL regexp() function (and hence REGEXP
  149658. ** operator) using the ICU uregex_XX() APIs.
  149659. **
  149660. ** * Implementations of the SQL scalar upper() and lower() functions
  149661. ** for case mapping.
  149662. **
  149663. ** * Integration of ICU and SQLite collation sequences.
  149664. **
  149665. ** * An implementation of the LIKE operator that uses ICU to
  149666. ** provide case-independent matching.
  149667. */
  149668. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  149669. /* Include ICU headers */
  149670. #include <unicode/utypes.h>
  149671. #include <unicode/uregex.h>
  149672. #include <unicode/ustring.h>
  149673. #include <unicode/ucol.h>
  149674. /* #include <assert.h> */
  149675. #ifndef SQLITE_CORE
  149676. /* #include "sqlite3ext.h" */
  149677. SQLITE_EXTENSION_INIT1
  149678. #else
  149679. /* #include "sqlite3.h" */
  149680. #endif
  149681. /*
  149682. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  149683. ** operator.
  149684. */
  149685. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  149686. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  149687. #endif
  149688. /*
  149689. ** Version of sqlite3_free() that is always a function, never a macro.
  149690. */
  149691. static void xFree(void *p){
  149692. sqlite3_free(p);
  149693. }
  149694. /*
  149695. ** This lookup table is used to help decode the first byte of
  149696. ** a multi-byte UTF8 character. It is copied here from SQLite source
  149697. ** code file utf8.c.
  149698. */
  149699. static const unsigned char icuUtf8Trans1[] = {
  149700. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  149701. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  149702. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  149703. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  149704. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  149705. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  149706. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  149707. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  149708. };
  149709. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  149710. c = *(zIn++); \
  149711. if( c>=0xc0 ){ \
  149712. c = icuUtf8Trans1[c-0xc0]; \
  149713. while( (*zIn & 0xc0)==0x80 ){ \
  149714. c = (c<<6) + (0x3f & *(zIn++)); \
  149715. } \
  149716. }
  149717. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  149718. assert( *zIn ); \
  149719. if( *(zIn++)>=0xc0 ){ \
  149720. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  149721. }
  149722. /*
  149723. ** Compare two UTF-8 strings for equality where the first string is
  149724. ** a "LIKE" expression. Return true (1) if they are the same and
  149725. ** false (0) if they are different.
  149726. */
  149727. static int icuLikeCompare(
  149728. const uint8_t *zPattern, /* LIKE pattern */
  149729. const uint8_t *zString, /* The UTF-8 string to compare against */
  149730. const UChar32 uEsc /* The escape character */
  149731. ){
  149732. static const int MATCH_ONE = (UChar32)'_';
  149733. static const int MATCH_ALL = (UChar32)'%';
  149734. int prevEscape = 0; /* True if the previous character was uEsc */
  149735. while( 1 ){
  149736. /* Read (and consume) the next character from the input pattern. */
  149737. UChar32 uPattern;
  149738. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  149739. if( uPattern==0 ) break;
  149740. /* There are now 4 possibilities:
  149741. **
  149742. ** 1. uPattern is an unescaped match-all character "%",
  149743. ** 2. uPattern is an unescaped match-one character "_",
  149744. ** 3. uPattern is an unescaped escape character, or
  149745. ** 4. uPattern is to be handled as an ordinary character
  149746. */
  149747. if( !prevEscape && uPattern==MATCH_ALL ){
  149748. /* Case 1. */
  149749. uint8_t c;
  149750. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  149751. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  149752. ** test string.
  149753. */
  149754. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  149755. if( c==MATCH_ONE ){
  149756. if( *zString==0 ) return 0;
  149757. SQLITE_ICU_SKIP_UTF8(zString);
  149758. }
  149759. zPattern++;
  149760. }
  149761. if( *zPattern==0 ) return 1;
  149762. while( *zString ){
  149763. if( icuLikeCompare(zPattern, zString, uEsc) ){
  149764. return 1;
  149765. }
  149766. SQLITE_ICU_SKIP_UTF8(zString);
  149767. }
  149768. return 0;
  149769. }else if( !prevEscape && uPattern==MATCH_ONE ){
  149770. /* Case 2. */
  149771. if( *zString==0 ) return 0;
  149772. SQLITE_ICU_SKIP_UTF8(zString);
  149773. }else if( !prevEscape && uPattern==uEsc){
  149774. /* Case 3. */
  149775. prevEscape = 1;
  149776. }else{
  149777. /* Case 4. */
  149778. UChar32 uString;
  149779. SQLITE_ICU_READ_UTF8(zString, uString);
  149780. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  149781. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  149782. if( uString!=uPattern ){
  149783. return 0;
  149784. }
  149785. prevEscape = 0;
  149786. }
  149787. }
  149788. return *zString==0;
  149789. }
  149790. /*
  149791. ** Implementation of the like() SQL function. This function implements
  149792. ** the build-in LIKE operator. The first argument to the function is the
  149793. ** pattern and the second argument is the string. So, the SQL statements:
  149794. **
  149795. ** A LIKE B
  149796. **
  149797. ** is implemented as like(B, A). If there is an escape character E,
  149798. **
  149799. ** A LIKE B ESCAPE E
  149800. **
  149801. ** is mapped to like(B, A, E).
  149802. */
  149803. static void icuLikeFunc(
  149804. sqlite3_context *context,
  149805. int argc,
  149806. sqlite3_value **argv
  149807. ){
  149808. const unsigned char *zA = sqlite3_value_text(argv[0]);
  149809. const unsigned char *zB = sqlite3_value_text(argv[1]);
  149810. UChar32 uEsc = 0;
  149811. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  149812. ** of deep recursion and N*N behavior in patternCompare().
  149813. */
  149814. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  149815. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  149816. return;
  149817. }
  149818. if( argc==3 ){
  149819. /* The escape character string must consist of a single UTF-8 character.
  149820. ** Otherwise, return an error.
  149821. */
  149822. int nE= sqlite3_value_bytes(argv[2]);
  149823. const unsigned char *zE = sqlite3_value_text(argv[2]);
  149824. int i = 0;
  149825. if( zE==0 ) return;
  149826. U8_NEXT(zE, i, nE, uEsc);
  149827. if( i!=nE){
  149828. sqlite3_result_error(context,
  149829. "ESCAPE expression must be a single character", -1);
  149830. return;
  149831. }
  149832. }
  149833. if( zA && zB ){
  149834. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  149835. }
  149836. }
  149837. /*
  149838. ** This function is called when an ICU function called from within
  149839. ** the implementation of an SQL scalar function returns an error.
  149840. **
  149841. ** The scalar function context passed as the first argument is
  149842. ** loaded with an error message based on the following two args.
  149843. */
  149844. static void icuFunctionError(
  149845. sqlite3_context *pCtx, /* SQLite scalar function context */
  149846. const char *zName, /* Name of ICU function that failed */
  149847. UErrorCode e /* Error code returned by ICU function */
  149848. ){
  149849. char zBuf[128];
  149850. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  149851. zBuf[127] = '\0';
  149852. sqlite3_result_error(pCtx, zBuf, -1);
  149853. }
  149854. /*
  149855. ** Function to delete compiled regexp objects. Registered as
  149856. ** a destructor function with sqlite3_set_auxdata().
  149857. */
  149858. static void icuRegexpDelete(void *p){
  149859. URegularExpression *pExpr = (URegularExpression *)p;
  149860. uregex_close(pExpr);
  149861. }
  149862. /*
  149863. ** Implementation of SQLite REGEXP operator. This scalar function takes
  149864. ** two arguments. The first is a regular expression pattern to compile
  149865. ** the second is a string to match against that pattern. If either
  149866. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  149867. ** is 1 if the string matches the pattern, or 0 otherwise.
  149868. **
  149869. ** SQLite maps the regexp() function to the regexp() operator such
  149870. ** that the following two are equivalent:
  149871. **
  149872. ** zString REGEXP zPattern
  149873. ** regexp(zPattern, zString)
  149874. **
  149875. ** Uses the following ICU regexp APIs:
  149876. **
  149877. ** uregex_open()
  149878. ** uregex_matches()
  149879. ** uregex_close()
  149880. */
  149881. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  149882. UErrorCode status = U_ZERO_ERROR;
  149883. URegularExpression *pExpr;
  149884. UBool res;
  149885. const UChar *zString = sqlite3_value_text16(apArg[1]);
  149886. (void)nArg; /* Unused parameter */
  149887. /* If the left hand side of the regexp operator is NULL,
  149888. ** then the result is also NULL.
  149889. */
  149890. if( !zString ){
  149891. return;
  149892. }
  149893. pExpr = sqlite3_get_auxdata(p, 0);
  149894. if( !pExpr ){
  149895. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  149896. if( !zPattern ){
  149897. return;
  149898. }
  149899. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  149900. if( U_SUCCESS(status) ){
  149901. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  149902. }else{
  149903. assert(!pExpr);
  149904. icuFunctionError(p, "uregex_open", status);
  149905. return;
  149906. }
  149907. }
  149908. /* Configure the text that the regular expression operates on. */
  149909. uregex_setText(pExpr, zString, -1, &status);
  149910. if( !U_SUCCESS(status) ){
  149911. icuFunctionError(p, "uregex_setText", status);
  149912. return;
  149913. }
  149914. /* Attempt the match */
  149915. res = uregex_matches(pExpr, 0, &status);
  149916. if( !U_SUCCESS(status) ){
  149917. icuFunctionError(p, "uregex_matches", status);
  149918. return;
  149919. }
  149920. /* Set the text that the regular expression operates on to a NULL
  149921. ** pointer. This is not really necessary, but it is tidier than
  149922. ** leaving the regular expression object configured with an invalid
  149923. ** pointer after this function returns.
  149924. */
  149925. uregex_setText(pExpr, 0, 0, &status);
  149926. /* Return 1 or 0. */
  149927. sqlite3_result_int(p, res ? 1 : 0);
  149928. }
  149929. /*
  149930. ** Implementations of scalar functions for case mapping - upper() and
  149931. ** lower(). Function upper() converts its input to upper-case (ABC).
  149932. ** Function lower() converts to lower-case (abc).
  149933. **
  149934. ** ICU provides two types of case mapping, "general" case mapping and
  149935. ** "language specific". Refer to ICU documentation for the differences
  149936. ** between the two.
  149937. **
  149938. ** To utilise "general" case mapping, the upper() or lower() scalar
  149939. ** functions are invoked with one argument:
  149940. **
  149941. ** upper('ABC') -> 'abc'
  149942. ** lower('abc') -> 'ABC'
  149943. **
  149944. ** To access ICU "language specific" case mapping, upper() or lower()
  149945. ** should be invoked with two arguments. The second argument is the name
  149946. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  149947. ** as the second argument is the same as invoking the 1 argument version
  149948. ** of upper() or lower().
  149949. **
  149950. ** lower('I', 'en_us') -> 'i'
  149951. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  149952. **
  149953. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  149954. */
  149955. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  149956. const UChar *zInput;
  149957. UChar *zOutput = 0;
  149958. int nInput;
  149959. int nOut;
  149960. int cnt;
  149961. UErrorCode status;
  149962. const char *zLocale = 0;
  149963. assert(nArg==1 || nArg==2);
  149964. if( nArg==2 ){
  149965. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  149966. }
  149967. zInput = sqlite3_value_text16(apArg[0]);
  149968. if( !zInput ){
  149969. return;
  149970. }
  149971. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  149972. if( nOut==0 ){
  149973. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  149974. return;
  149975. }
  149976. for(cnt=0; cnt<2; cnt++){
  149977. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  149978. if( zNew==0 ){
  149979. sqlite3_free(zOutput);
  149980. sqlite3_result_error_nomem(p);
  149981. return;
  149982. }
  149983. zOutput = zNew;
  149984. status = U_ZERO_ERROR;
  149985. if( sqlite3_user_data(p) ){
  149986. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  149987. }else{
  149988. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  149989. }
  149990. if( !U_SUCCESS(status) ){
  149991. if( status==U_BUFFER_OVERFLOW_ERROR ) continue;
  149992. icuFunctionError(p,
  149993. sqlite3_user_data(p) ? "u_strToUpper" : "u_strToLower", status);
  149994. return;
  149995. }
  149996. }
  149997. sqlite3_result_text16(p, zOutput, nOut, xFree);
  149998. }
  149999. /*
  150000. ** Collation sequence destructor function. The pCtx argument points to
  150001. ** a UCollator structure previously allocated using ucol_open().
  150002. */
  150003. static void icuCollationDel(void *pCtx){
  150004. UCollator *p = (UCollator *)pCtx;
  150005. ucol_close(p);
  150006. }
  150007. /*
  150008. ** Collation sequence comparison function. The pCtx argument points to
  150009. ** a UCollator structure previously allocated using ucol_open().
  150010. */
  150011. static int icuCollationColl(
  150012. void *pCtx,
  150013. int nLeft,
  150014. const void *zLeft,
  150015. int nRight,
  150016. const void *zRight
  150017. ){
  150018. UCollationResult res;
  150019. UCollator *p = (UCollator *)pCtx;
  150020. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  150021. switch( res ){
  150022. case UCOL_LESS: return -1;
  150023. case UCOL_GREATER: return +1;
  150024. case UCOL_EQUAL: return 0;
  150025. }
  150026. assert(!"Unexpected return value from ucol_strcoll()");
  150027. return 0;
  150028. }
  150029. /*
  150030. ** Implementation of the scalar function icu_load_collation().
  150031. **
  150032. ** This scalar function is used to add ICU collation based collation
  150033. ** types to an SQLite database connection. It is intended to be called
  150034. ** as follows:
  150035. **
  150036. ** SELECT icu_load_collation(<locale>, <collation-name>);
  150037. **
  150038. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  150039. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  150040. ** collation sequence to create.
  150041. */
  150042. static void icuLoadCollation(
  150043. sqlite3_context *p,
  150044. int nArg,
  150045. sqlite3_value **apArg
  150046. ){
  150047. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  150048. UErrorCode status = U_ZERO_ERROR;
  150049. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  150050. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  150051. UCollator *pUCollator; /* ICU library collation object */
  150052. int rc; /* Return code from sqlite3_create_collation_x() */
  150053. assert(nArg==2);
  150054. (void)nArg; /* Unused parameter */
  150055. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  150056. zName = (const char *)sqlite3_value_text(apArg[1]);
  150057. if( !zLocale || !zName ){
  150058. return;
  150059. }
  150060. pUCollator = ucol_open(zLocale, &status);
  150061. if( !U_SUCCESS(status) ){
  150062. icuFunctionError(p, "ucol_open", status);
  150063. return;
  150064. }
  150065. assert(p);
  150066. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  150067. icuCollationColl, icuCollationDel
  150068. );
  150069. if( rc!=SQLITE_OK ){
  150070. ucol_close(pUCollator);
  150071. sqlite3_result_error(p, "Error registering collation function", -1);
  150072. }
  150073. }
  150074. /*
  150075. ** Register the ICU extension functions with database db.
  150076. */
  150077. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  150078. struct IcuScalar {
  150079. const char *zName; /* Function name */
  150080. int nArg; /* Number of arguments */
  150081. int enc; /* Optimal text encoding */
  150082. void *pContext; /* sqlite3_user_data() context */
  150083. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  150084. } scalars[] = {
  150085. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  150086. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  150087. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  150088. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  150089. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  150090. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  150091. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  150092. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  150093. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  150094. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  150095. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  150096. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  150097. };
  150098. int rc = SQLITE_OK;
  150099. int i;
  150100. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  150101. struct IcuScalar *p = &scalars[i];
  150102. rc = sqlite3_create_function(
  150103. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  150104. );
  150105. }
  150106. return rc;
  150107. }
  150108. #if !SQLITE_CORE
  150109. #ifdef _WIN32
  150110. __declspec(dllexport)
  150111. #endif
  150112. SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
  150113. sqlite3 *db,
  150114. char **pzErrMsg,
  150115. const sqlite3_api_routines *pApi
  150116. ){
  150117. SQLITE_EXTENSION_INIT2(pApi)
  150118. return sqlite3IcuInit(db);
  150119. }
  150120. #endif
  150121. #endif
  150122. /************** End of icu.c *************************************************/
  150123. /************** Begin file fts3_icu.c ****************************************/
  150124. /*
  150125. ** 2007 June 22
  150126. **
  150127. ** The author disclaims copyright to this source code. In place of
  150128. ** a legal notice, here is a blessing:
  150129. **
  150130. ** May you do good and not evil.
  150131. ** May you find forgiveness for yourself and forgive others.
  150132. ** May you share freely, never taking more than you give.
  150133. **
  150134. *************************************************************************
  150135. ** This file implements a tokenizer for fts3 based on the ICU library.
  150136. */
  150137. /* #include "fts3Int.h" */
  150138. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150139. #ifdef SQLITE_ENABLE_ICU
  150140. /* #include <assert.h> */
  150141. /* #include <string.h> */
  150142. /* #include "fts3_tokenizer.h" */
  150143. #include <unicode/ubrk.h>
  150144. /* #include <unicode/ucol.h> */
  150145. /* #include <unicode/ustring.h> */
  150146. #include <unicode/utf16.h>
  150147. typedef struct IcuTokenizer IcuTokenizer;
  150148. typedef struct IcuCursor IcuCursor;
  150149. struct IcuTokenizer {
  150150. sqlite3_tokenizer base;
  150151. char *zLocale;
  150152. };
  150153. struct IcuCursor {
  150154. sqlite3_tokenizer_cursor base;
  150155. UBreakIterator *pIter; /* ICU break-iterator object */
  150156. int nChar; /* Number of UChar elements in pInput */
  150157. UChar *aChar; /* Copy of input using utf-16 encoding */
  150158. int *aOffset; /* Offsets of each character in utf-8 input */
  150159. int nBuffer;
  150160. char *zBuffer;
  150161. int iToken;
  150162. };
  150163. /*
  150164. ** Create a new tokenizer instance.
  150165. */
  150166. static int icuCreate(
  150167. int argc, /* Number of entries in argv[] */
  150168. const char * const *argv, /* Tokenizer creation arguments */
  150169. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  150170. ){
  150171. IcuTokenizer *p;
  150172. int n = 0;
  150173. if( argc>0 ){
  150174. n = strlen(argv[0])+1;
  150175. }
  150176. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  150177. if( !p ){
  150178. return SQLITE_NOMEM;
  150179. }
  150180. memset(p, 0, sizeof(IcuTokenizer));
  150181. if( n ){
  150182. p->zLocale = (char *)&p[1];
  150183. memcpy(p->zLocale, argv[0], n);
  150184. }
  150185. *ppTokenizer = (sqlite3_tokenizer *)p;
  150186. return SQLITE_OK;
  150187. }
  150188. /*
  150189. ** Destroy a tokenizer
  150190. */
  150191. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  150192. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  150193. sqlite3_free(p);
  150194. return SQLITE_OK;
  150195. }
  150196. /*
  150197. ** Prepare to begin tokenizing a particular string. The input
  150198. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  150199. ** used to incrementally tokenize this string is returned in
  150200. ** *ppCursor.
  150201. */
  150202. static int icuOpen(
  150203. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  150204. const char *zInput, /* Input string */
  150205. int nInput, /* Length of zInput in bytes */
  150206. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  150207. ){
  150208. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  150209. IcuCursor *pCsr;
  150210. const int32_t opt = U_FOLD_CASE_DEFAULT;
  150211. UErrorCode status = U_ZERO_ERROR;
  150212. int nChar;
  150213. UChar32 c;
  150214. int iInput = 0;
  150215. int iOut = 0;
  150216. *ppCursor = 0;
  150217. if( zInput==0 ){
  150218. nInput = 0;
  150219. zInput = "";
  150220. }else if( nInput<0 ){
  150221. nInput = strlen(zInput);
  150222. }
  150223. nChar = nInput+1;
  150224. pCsr = (IcuCursor *)sqlite3_malloc(
  150225. sizeof(IcuCursor) + /* IcuCursor */
  150226. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  150227. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  150228. );
  150229. if( !pCsr ){
  150230. return SQLITE_NOMEM;
  150231. }
  150232. memset(pCsr, 0, sizeof(IcuCursor));
  150233. pCsr->aChar = (UChar *)&pCsr[1];
  150234. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  150235. pCsr->aOffset[iOut] = iInput;
  150236. U8_NEXT(zInput, iInput, nInput, c);
  150237. while( c>0 ){
  150238. int isError = 0;
  150239. c = u_foldCase(c, opt);
  150240. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  150241. if( isError ){
  150242. sqlite3_free(pCsr);
  150243. return SQLITE_ERROR;
  150244. }
  150245. pCsr->aOffset[iOut] = iInput;
  150246. if( iInput<nInput ){
  150247. U8_NEXT(zInput, iInput, nInput, c);
  150248. }else{
  150249. c = 0;
  150250. }
  150251. }
  150252. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  150253. if( !U_SUCCESS(status) ){
  150254. sqlite3_free(pCsr);
  150255. return SQLITE_ERROR;
  150256. }
  150257. pCsr->nChar = iOut;
  150258. ubrk_first(pCsr->pIter);
  150259. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  150260. return SQLITE_OK;
  150261. }
  150262. /*
  150263. ** Close a tokenization cursor previously opened by a call to icuOpen().
  150264. */
  150265. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  150266. IcuCursor *pCsr = (IcuCursor *)pCursor;
  150267. ubrk_close(pCsr->pIter);
  150268. sqlite3_free(pCsr->zBuffer);
  150269. sqlite3_free(pCsr);
  150270. return SQLITE_OK;
  150271. }
  150272. /*
  150273. ** Extract the next token from a tokenization cursor.
  150274. */
  150275. static int icuNext(
  150276. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  150277. const char **ppToken, /* OUT: *ppToken is the token text */
  150278. int *pnBytes, /* OUT: Number of bytes in token */
  150279. int *piStartOffset, /* OUT: Starting offset of token */
  150280. int *piEndOffset, /* OUT: Ending offset of token */
  150281. int *piPosition /* OUT: Position integer of token */
  150282. ){
  150283. IcuCursor *pCsr = (IcuCursor *)pCursor;
  150284. int iStart = 0;
  150285. int iEnd = 0;
  150286. int nByte = 0;
  150287. while( iStart==iEnd ){
  150288. UChar32 c;
  150289. iStart = ubrk_current(pCsr->pIter);
  150290. iEnd = ubrk_next(pCsr->pIter);
  150291. if( iEnd==UBRK_DONE ){
  150292. return SQLITE_DONE;
  150293. }
  150294. while( iStart<iEnd ){
  150295. int iWhite = iStart;
  150296. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  150297. if( u_isspace(c) ){
  150298. iStart = iWhite;
  150299. }else{
  150300. break;
  150301. }
  150302. }
  150303. assert(iStart<=iEnd);
  150304. }
  150305. do {
  150306. UErrorCode status = U_ZERO_ERROR;
  150307. if( nByte ){
  150308. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  150309. if( !zNew ){
  150310. return SQLITE_NOMEM;
  150311. }
  150312. pCsr->zBuffer = zNew;
  150313. pCsr->nBuffer = nByte;
  150314. }
  150315. u_strToUTF8(
  150316. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  150317. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  150318. &status /* Output success/failure */
  150319. );
  150320. } while( nByte>pCsr->nBuffer );
  150321. *ppToken = pCsr->zBuffer;
  150322. *pnBytes = nByte;
  150323. *piStartOffset = pCsr->aOffset[iStart];
  150324. *piEndOffset = pCsr->aOffset[iEnd];
  150325. *piPosition = pCsr->iToken++;
  150326. return SQLITE_OK;
  150327. }
  150328. /*
  150329. ** The set of routines that implement the simple tokenizer
  150330. */
  150331. static const sqlite3_tokenizer_module icuTokenizerModule = {
  150332. 0, /* iVersion */
  150333. icuCreate, /* xCreate */
  150334. icuDestroy, /* xCreate */
  150335. icuOpen, /* xOpen */
  150336. icuClose, /* xClose */
  150337. icuNext, /* xNext */
  150338. 0, /* xLanguageid */
  150339. };
  150340. /*
  150341. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  150342. */
  150343. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  150344. sqlite3_tokenizer_module const**ppModule
  150345. ){
  150346. *ppModule = &icuTokenizerModule;
  150347. }
  150348. #endif /* defined(SQLITE_ENABLE_ICU) */
  150349. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  150350. /************** End of fts3_icu.c ********************************************/
  150351. /************** Begin file sqlite3rbu.c **************************************/
  150352. /*
  150353. ** 2014 August 30
  150354. **
  150355. ** The author disclaims copyright to this source code. In place of
  150356. ** a legal notice, here is a blessing:
  150357. **
  150358. ** May you do good and not evil.
  150359. ** May you find forgiveness for yourself and forgive others.
  150360. ** May you share freely, never taking more than you give.
  150361. **
  150362. *************************************************************************
  150363. **
  150364. **
  150365. ** OVERVIEW
  150366. **
  150367. ** The RBU extension requires that the RBU update be packaged as an
  150368. ** SQLite database. The tables it expects to find are described in
  150369. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  150370. ** that the user wishes to write to, a corresponding data_xyz table is
  150371. ** created in the RBU database and populated with one row for each row to
  150372. ** update, insert or delete from the target table.
  150373. **
  150374. ** The update proceeds in three stages:
  150375. **
  150376. ** 1) The database is updated. The modified database pages are written
  150377. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  150378. ** that it is named "<database>-oal" instead of "<database>-wal".
  150379. ** Because regular SQLite clients do not look for file named
  150380. ** "<database>-oal", they go on using the original database in
  150381. ** rollback mode while the *-oal file is being generated.
  150382. **
  150383. ** During this stage RBU does not update the database by writing
  150384. ** directly to the target tables. Instead it creates "imposter"
  150385. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  150386. ** to update each b-tree individually. All updates required by each
  150387. ** b-tree are completed before moving on to the next, and all
  150388. ** updates are done in sorted key order.
  150389. **
  150390. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  150391. ** location using a call to rename(2). Before doing this the RBU
  150392. ** module takes an EXCLUSIVE lock on the database file, ensuring
  150393. ** that there are no other active readers.
  150394. **
  150395. ** Once the EXCLUSIVE lock is released, any other database readers
  150396. ** detect the new *-wal file and read the database in wal mode. At
  150397. ** this point they see the new version of the database - including
  150398. ** the updates made as part of the RBU update.
  150399. **
  150400. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  150401. ** as a regular database checkpoint, except that a single frame is
  150402. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  150403. ** handle is closed before the entire *-wal file is checkpointed,
  150404. ** the checkpoint progress is saved in the RBU database and the
  150405. ** checkpoint can be resumed by another RBU client at some point in
  150406. ** the future.
  150407. **
  150408. ** POTENTIAL PROBLEMS
  150409. **
  150410. ** The rename() call might not be portable. And RBU is not currently
  150411. ** syncing the directory after renaming the file.
  150412. **
  150413. ** When state is saved, any commit to the *-oal file and the commit to
  150414. ** the RBU update database are not atomic. So if the power fails at the
  150415. ** wrong moment they might get out of sync. As the main database will be
  150416. ** committed before the RBU update database this will likely either just
  150417. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  150418. ** constraint violations).
  150419. **
  150420. ** If some client does modify the target database mid RBU update, or some
  150421. ** other error occurs, the RBU extension will keep throwing errors. It's
  150422. ** not really clear how to get out of this state. The system could just
  150423. ** by delete the RBU update database and *-oal file and have the device
  150424. ** download the update again and start over.
  150425. **
  150426. ** At present, for an UPDATE, both the new.* and old.* records are
  150427. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  150428. ** fields are collected. This means we're probably writing a lot more
  150429. ** data to disk when saving the state of an ongoing update to the RBU
  150430. ** update database than is strictly necessary.
  150431. **
  150432. */
  150433. /* #include <assert.h> */
  150434. /* #include <string.h> */
  150435. /* #include <stdio.h> */
  150436. /* #include "sqlite3.h" */
  150437. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  150438. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  150439. /************** Begin file sqlite3rbu.h **************************************/
  150440. /*
  150441. ** 2014 August 30
  150442. **
  150443. ** The author disclaims copyright to this source code. In place of
  150444. ** a legal notice, here is a blessing:
  150445. **
  150446. ** May you do good and not evil.
  150447. ** May you find forgiveness for yourself and forgive others.
  150448. ** May you share freely, never taking more than you give.
  150449. **
  150450. *************************************************************************
  150451. **
  150452. ** This file contains the public interface for the RBU extension.
  150453. */
  150454. /*
  150455. ** SUMMARY
  150456. **
  150457. ** Writing a transaction containing a large number of operations on
  150458. ** b-tree indexes that are collectively larger than the available cache
  150459. ** memory can be very inefficient.
  150460. **
  150461. ** The problem is that in order to update a b-tree, the leaf page (at least)
  150462. ** containing the entry being inserted or deleted must be modified. If the
  150463. ** working set of leaves is larger than the available cache memory, then a
  150464. ** single leaf that is modified more than once as part of the transaction
  150465. ** may be loaded from or written to the persistent media multiple times.
  150466. ** Additionally, because the index updates are likely to be applied in
  150467. ** random order, access to pages within the database is also likely to be in
  150468. ** random order, which is itself quite inefficient.
  150469. **
  150470. ** One way to improve the situation is to sort the operations on each index
  150471. ** by index key before applying them to the b-tree. This leads to an IO
  150472. ** pattern that resembles a single linear scan through the index b-tree,
  150473. ** and all but guarantees each modified leaf page is loaded and stored
  150474. ** exactly once. SQLite uses this trick to improve the performance of
  150475. ** CREATE INDEX commands. This extension allows it to be used to improve
  150476. ** the performance of large transactions on existing databases.
  150477. **
  150478. ** Additionally, this extension allows the work involved in writing the
  150479. ** large transaction to be broken down into sub-transactions performed
  150480. ** sequentially by separate processes. This is useful if the system cannot
  150481. ** guarantee that a single update process will run for long enough to apply
  150482. ** the entire update, for example because the update is being applied on a
  150483. ** mobile device that is frequently rebooted. Even after the writer process
  150484. ** has committed one or more sub-transactions, other database clients continue
  150485. ** to read from the original database snapshot. In other words, partially
  150486. ** applied transactions are not visible to other clients.
  150487. **
  150488. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  150489. ** transmitted via a wireless network to a mobile device. A transaction
  150490. ** applied using this extension is hence refered to as an "RBU update".
  150491. **
  150492. **
  150493. ** LIMITATIONS
  150494. **
  150495. ** An "RBU update" transaction is subject to the following limitations:
  150496. **
  150497. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  150498. ** only.
  150499. **
  150500. ** * INSERT statements may not use any default values.
  150501. **
  150502. ** * UPDATE and DELETE statements must identify their target rows by
  150503. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  150504. ** KEY fields may not be updated or deleted. If the table being written
  150505. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  150506. **
  150507. ** * UPDATE statements may not modify PRIMARY KEY columns.
  150508. **
  150509. ** * No triggers will be fired.
  150510. **
  150511. ** * No foreign key violations are detected or reported.
  150512. **
  150513. ** * CHECK constraints are not enforced.
  150514. **
  150515. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  150516. **
  150517. **
  150518. ** PREPARATION
  150519. **
  150520. ** An "RBU update" is stored as a separate SQLite database. A database
  150521. ** containing an RBU update is an "RBU database". For each table in the
  150522. ** target database to be updated, the RBU database should contain a table
  150523. ** named "data_<target name>" containing the same set of columns as the
  150524. ** target table, and one more - "rbu_control". The data_% table should
  150525. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  150526. ** the same type as the corresponding column in the target database.
  150527. ** The "rbu_control" column should have no type at all. For example, if
  150528. ** the target database contains:
  150529. **
  150530. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  150531. **
  150532. ** Then the RBU database should contain:
  150533. **
  150534. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  150535. **
  150536. ** The order of the columns in the data_% table does not matter.
  150537. **
  150538. ** Instead of a regular table, the RBU database may also contain virtual
  150539. ** tables or view named using the data_<target> naming scheme.
  150540. **
  150541. ** Instead of the plain data_<target> naming scheme, RBU database tables
  150542. ** may also be named data<integer>_<target>, where <integer> is any sequence
  150543. ** of zero or more numeric characters (0-9). This can be significant because
  150544. ** tables within the RBU database are always processed in order sorted by
  150545. ** name. By judicious selection of the the <integer> portion of the names
  150546. ** of the RBU tables the user can therefore control the order in which they
  150547. ** are processed. This can be useful, for example, to ensure that "external
  150548. ** content" FTS4 tables are updated before their underlying content tables.
  150549. **
  150550. ** If the target database table is a virtual table or a table that has no
  150551. ** PRIMARY KEY declaration, the data_% table must also contain a column
  150552. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  150553. ** key column - "rowid". Virtual tables for which the "rowid" column does
  150554. ** not function like a primary key value cannot be updated using RBU. For
  150555. ** example, if the target db contains either of the following:
  150556. **
  150557. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  150558. ** CREATE TABLE x1(a, b)
  150559. **
  150560. ** then the RBU database should contain:
  150561. **
  150562. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  150563. **
  150564. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  150565. ** target table must be present in the input table. For virtual tables,
  150566. ** hidden columns are optional - they are updated by RBU if present in
  150567. ** the input table, or not otherwise. For example, to write to an fts4
  150568. ** table with a hidden languageid column such as:
  150569. **
  150570. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  150571. **
  150572. ** Either of the following input table schemas may be used:
  150573. **
  150574. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  150575. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  150576. **
  150577. ** For each row to INSERT into the target database as part of the RBU
  150578. ** update, the corresponding data_% table should contain a single record
  150579. ** with the "rbu_control" column set to contain integer value 0. The
  150580. ** other columns should be set to the values that make up the new record
  150581. ** to insert.
  150582. **
  150583. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  150584. ** possible to insert a NULL value into the IPK column. Attempting to
  150585. ** do so results in an SQLITE_MISMATCH error.
  150586. **
  150587. ** For each row to DELETE from the target database as part of the RBU
  150588. ** update, the corresponding data_% table should contain a single record
  150589. ** with the "rbu_control" column set to contain integer value 1. The
  150590. ** real primary key values of the row to delete should be stored in the
  150591. ** corresponding columns of the data_% table. The values stored in the
  150592. ** other columns are not used.
  150593. **
  150594. ** For each row to UPDATE from the target database as part of the RBU
  150595. ** update, the corresponding data_% table should contain a single record
  150596. ** with the "rbu_control" column set to contain a value of type text.
  150597. ** The real primary key values identifying the row to update should be
  150598. ** stored in the corresponding columns of the data_% table row, as should
  150599. ** the new values of all columns being update. The text value in the
  150600. ** "rbu_control" column must contain the same number of characters as
  150601. ** there are columns in the target database table, and must consist entirely
  150602. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  150603. ** each column that is being updated, the corresponding character is set to
  150604. ** 'x'. For those that remain as they are, the corresponding character of the
  150605. ** rbu_control value should be set to '.'. For example, given the tables
  150606. ** above, the update statement:
  150607. **
  150608. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  150609. **
  150610. ** is represented by the data_t1 row created by:
  150611. **
  150612. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  150613. **
  150614. ** Instead of an 'x' character, characters of the rbu_control value specified
  150615. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  150616. ** target table with the value stored in the corresponding data_% column, the
  150617. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  150618. ** the target table column. rbu_delta() is invoked with two arguments - the
  150619. ** original value currently stored in the target table column and the
  150620. ** value specified in the data_xxx table.
  150621. **
  150622. ** For example, this row:
  150623. **
  150624. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  150625. **
  150626. ** is similar to an UPDATE statement such as:
  150627. **
  150628. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  150629. **
  150630. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  150631. ** ota_control string, the contents of the data_xxx table column is assumed
  150632. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  150633. ** format used by the fossil source-code management system. In this case
  150634. ** the existing value within the target database table must be of type BLOB.
  150635. ** It is replaced by the result of applying the specified fossil delta to
  150636. ** itself.
  150637. **
  150638. ** If the target database table is a virtual table or a table with no PRIMARY
  150639. ** KEY, the rbu_control value should not include a character corresponding
  150640. ** to the rbu_rowid value. For example, this:
  150641. **
  150642. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  150643. ** VALUES(NULL, 'usa', 12, '.x');
  150644. **
  150645. ** causes a result similar to:
  150646. **
  150647. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  150648. **
  150649. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  150650. ** However, RBU is more efficient if reading the rows in from each data_xxx
  150651. ** table in "rowid" order is roughly the same as reading them sorted by
  150652. ** the PRIMARY KEY of the corresponding target database table. In other
  150653. ** words, rows should be sorted using the destination table PRIMARY KEY
  150654. ** fields before they are inserted into the data_xxx tables.
  150655. **
  150656. ** USAGE
  150657. **
  150658. ** The API declared below allows an application to apply an RBU update
  150659. ** stored on disk to an existing target database. Essentially, the
  150660. ** application:
  150661. **
  150662. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  150663. **
  150664. ** 2) Registers any required virtual table modules with the database
  150665. ** handle returned by sqlite3rbu_db(). Also, if required, register
  150666. ** the rbu_delta() implementation.
  150667. **
  150668. ** 3) Calls the sqlite3rbu_step() function one or more times on
  150669. ** the new handle. Each call to sqlite3rbu_step() performs a single
  150670. ** b-tree operation, so thousands of calls may be required to apply
  150671. ** a complete update.
  150672. **
  150673. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  150674. ** sqlite3rbu_step() has been called enough times to completely
  150675. ** apply the update to the target database, then the RBU database
  150676. ** is marked as fully applied. Otherwise, the state of the RBU
  150677. ** update application is saved in the RBU database for later
  150678. ** resumption.
  150679. **
  150680. ** See comments below for more detail on APIs.
  150681. **
  150682. ** If an update is only partially applied to the target database by the
  150683. ** time sqlite3rbu_close() is called, various state information is saved
  150684. ** within the RBU database. This allows subsequent processes to automatically
  150685. ** resume the RBU update from where it left off.
  150686. **
  150687. ** To remove all RBU extension state information, returning an RBU database
  150688. ** to its original contents, it is sufficient to drop all tables that begin
  150689. ** with the prefix "rbu_"
  150690. **
  150691. ** DATABASE LOCKING
  150692. **
  150693. ** An RBU update may not be applied to a database in WAL mode. Attempting
  150694. ** to do so is an error (SQLITE_ERROR).
  150695. **
  150696. ** While an RBU handle is open, a SHARED lock may be held on the target
  150697. ** database file. This means it is possible for other clients to read the
  150698. ** database, but not to write it.
  150699. **
  150700. ** If an RBU update is started and then suspended before it is completed,
  150701. ** then an external client writes to the database, then attempting to resume
  150702. ** the suspended RBU update is also an error (SQLITE_BUSY).
  150703. */
  150704. #ifndef _SQLITE3RBU_H
  150705. #define _SQLITE3RBU_H
  150706. /* #include "sqlite3.h" ** Required for error code definitions ** */
  150707. #if 0
  150708. extern "C" {
  150709. #endif
  150710. typedef struct sqlite3rbu sqlite3rbu;
  150711. /*
  150712. ** Open an RBU handle.
  150713. **
  150714. ** Argument zTarget is the path to the target database. Argument zRbu is
  150715. ** the path to the RBU database. Each call to this function must be matched
  150716. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  150717. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  150718. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  150719. ** database URI, not a regular file name.
  150720. **
  150721. ** If the zState argument is passed a NULL value, the RBU extension stores
  150722. ** the current state of the update (how many rows have been updated, which
  150723. ** indexes are yet to be updated etc.) within the RBU database itself. This
  150724. ** can be convenient, as it means that the RBU application does not need to
  150725. ** organize removing a separate state file after the update is concluded.
  150726. ** Or, if zState is non-NULL, it must be a path to a database file in which
  150727. ** the RBU extension can store the state of the update.
  150728. **
  150729. ** When resuming an RBU update, the zState argument must be passed the same
  150730. ** value as when the RBU update was started.
  150731. **
  150732. ** Once the RBU update is finished, the RBU extension does not
  150733. ** automatically remove any zState database file, even if it created it.
  150734. **
  150735. ** By default, RBU uses the default VFS to access the files on disk. To
  150736. ** use a VFS other than the default, an SQLite "file:" URI containing a
  150737. ** "vfs=..." option may be passed as the zTarget option.
  150738. **
  150739. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  150740. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  150741. ** not work out of the box with zipvfs. Refer to the comment describing
  150742. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  150743. */
  150744. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  150745. const char *zTarget,
  150746. const char *zRbu,
  150747. const char *zState
  150748. );
  150749. /*
  150750. ** Internally, each RBU connection uses a separate SQLite database
  150751. ** connection to access the target and rbu update databases. This
  150752. ** API allows the application direct access to these database handles.
  150753. **
  150754. ** The first argument passed to this function must be a valid, open, RBU
  150755. ** handle. The second argument should be passed zero to access the target
  150756. ** database handle, or non-zero to access the rbu update database handle.
  150757. ** Accessing the underlying database handles may be useful in the
  150758. ** following scenarios:
  150759. **
  150760. ** * If any target tables are virtual tables, it may be necessary to
  150761. ** call sqlite3_create_module() on the target database handle to
  150762. ** register the required virtual table implementations.
  150763. **
  150764. ** * If the data_xxx tables in the RBU source database are virtual
  150765. ** tables, the application may need to call sqlite3_create_module() on
  150766. ** the rbu update db handle to any required virtual table
  150767. ** implementations.
  150768. **
  150769. ** * If the application uses the "rbu_delta()" feature described above,
  150770. ** it must use sqlite3_create_function() or similar to register the
  150771. ** rbu_delta() implementation with the target database handle.
  150772. **
  150773. ** If an error has occurred, either while opening or stepping the RBU object,
  150774. ** this function may return NULL. The error code and message may be collected
  150775. ** when sqlite3rbu_close() is called.
  150776. **
  150777. ** Database handles returned by this function remain valid until the next
  150778. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  150779. */
  150780. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
  150781. /*
  150782. ** Do some work towards applying the RBU update to the target db.
  150783. **
  150784. ** Return SQLITE_DONE if the update has been completely applied, or
  150785. ** SQLITE_OK if no error occurs but there remains work to do to apply
  150786. ** the RBU update. If an error does occur, some other error code is
  150787. ** returned.
  150788. **
  150789. ** Once a call to sqlite3rbu_step() has returned a value other than
  150790. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  150791. ** that immediately return the same value.
  150792. */
  150793. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
  150794. /*
  150795. ** Force RBU to save its state to disk.
  150796. **
  150797. ** If a power failure or application crash occurs during an update, following
  150798. ** system recovery RBU may resume the update from the point at which the state
  150799. ** was last saved. In other words, from the most recent successful call to
  150800. ** sqlite3rbu_close() or this function.
  150801. **
  150802. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  150803. */
  150804. SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
  150805. /*
  150806. ** Close an RBU handle.
  150807. **
  150808. ** If the RBU update has been completely applied, mark the RBU database
  150809. ** as fully applied. Otherwise, assuming no error has occurred, save the
  150810. ** current state of the RBU update appliation to the RBU database.
  150811. **
  150812. ** If an error has already occurred as part of an sqlite3rbu_step()
  150813. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  150814. ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
  150815. ** point to a buffer containing a utf-8 formatted English language error
  150816. ** message. It is the responsibility of the caller to eventually free any
  150817. ** such buffer using sqlite3_free().
  150818. **
  150819. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  150820. ** update has been partially applied, or SQLITE_DONE if it has been
  150821. ** completely applied.
  150822. */
  150823. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  150824. /*
  150825. ** Return the total number of key-value operations (inserts, deletes or
  150826. ** updates) that have been performed on the target database since the
  150827. ** current RBU update was started.
  150828. */
  150829. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
  150830. /*
  150831. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  150832. ** progress indications for the two stages of an RBU update. This API may
  150833. ** be useful for driving GUI progress indicators and similar.
  150834. **
  150835. ** An RBU update is divided into two stages:
  150836. **
  150837. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  150838. ** * Stage 2, in which the contents of the wal file are copied into the
  150839. ** main database.
  150840. **
  150841. ** The update is visible to non-RBU clients during stage 2. During stage 1
  150842. ** non-RBU reader clients may see the original database.
  150843. **
  150844. ** If this API is called during stage 2 of the update, output variable
  150845. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  150846. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  150847. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  150848. ** 9000 indicates that it is 90% finished, and so on.
  150849. **
  150850. ** If this API is called during stage 1 of the update, output variable
  150851. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  150852. ** value to which (*pnOne) is set depends on whether or not the RBU
  150853. ** database contains an "rbu_count" table. The rbu_count table, if it
  150854. ** exists, must contain the same columns as the following:
  150855. **
  150856. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  150857. **
  150858. ** There must be one row in the table for each source (data_xxx) table within
  150859. ** the RBU database. The 'tbl' column should contain the name of the source
  150860. ** table. The 'cnt' column should contain the number of rows within the
  150861. ** source table.
  150862. **
  150863. ** If the rbu_count table is present and populated correctly and this
  150864. ** API is called during stage 1, the *pnOne output variable is set to the
  150865. ** permyriadage progress of the same stage. If the rbu_count table does
  150866. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  150867. ** table exists but is not correctly populated, the value of the *pnOne
  150868. ** output variable during stage 1 is undefined.
  150869. */
  150870. SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
  150871. /*
  150872. ** Create an RBU VFS named zName that accesses the underlying file-system
  150873. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  150874. ** then the new RBU VFS uses the default system VFS to access the file-system.
  150875. ** The new object is registered as a non-default VFS with SQLite before
  150876. ** returning.
  150877. **
  150878. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  150879. ** object is created and deleted automatically by RBU.
  150880. **
  150881. ** The exception is for applications that also use zipvfs. In this case,
  150882. ** the custom VFS must be explicitly created by the user before the RBU
  150883. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  150884. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  150885. ** (for example multiplexor) to access the file-system. For example,
  150886. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  150887. ** multiplexor (error checking omitted):
  150888. **
  150889. ** // Create a VFS named "multiplex" (not the default).
  150890. ** sqlite3_multiplex_initialize(0, 0);
  150891. **
  150892. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  150893. ** // second argument were replaced with NULL, the "rbu" VFS would
  150894. ** // access the file-system via the system default VFS, bypassing the
  150895. ** // multiplexor.
  150896. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  150897. **
  150898. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  150899. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  150900. **
  150901. ** // Make zipvfs the default VFS.
  150902. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  150903. **
  150904. ** Because the default VFS created above includes a RBU functionality, it
  150905. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  150906. ** that does not include the RBU layer results in an error.
  150907. **
  150908. ** The overhead of adding the "rbu" VFS to the system is negligible for
  150909. ** non-RBU users. There is no harm in an application accessing the
  150910. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  150911. ** occasionally.
  150912. */
  150913. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  150914. /*
  150915. ** Deregister and destroy an RBU vfs created by an earlier call to
  150916. ** sqlite3rbu_create_vfs().
  150917. **
  150918. ** VFS objects are not reference counted. If a VFS object is destroyed
  150919. ** before all database handles that use it have been closed, the results
  150920. ** are undefined.
  150921. */
  150922. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
  150923. #if 0
  150924. } /* end of the 'extern "C"' block */
  150925. #endif
  150926. #endif /* _SQLITE3RBU_H */
  150927. /************** End of sqlite3rbu.h ******************************************/
  150928. /************** Continuing where we left off in sqlite3rbu.c *****************/
  150929. #if defined(_WIN32_WCE)
  150930. /* #include "windows.h" */
  150931. #endif
  150932. /* Maximum number of prepared UPDATE statements held by this module */
  150933. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  150934. /*
  150935. ** Swap two objects of type TYPE.
  150936. */
  150937. #if !defined(SQLITE_AMALGAMATION)
  150938. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  150939. #endif
  150940. /*
  150941. ** The rbu_state table is used to save the state of a partially applied
  150942. ** update so that it can be resumed later. The table consists of integer
  150943. ** keys mapped to values as follows:
  150944. **
  150945. ** RBU_STATE_STAGE:
  150946. ** May be set to integer values 1, 2, 4 or 5. As follows:
  150947. ** 1: the *-rbu file is currently under construction.
  150948. ** 2: the *-rbu file has been constructed, but not yet moved
  150949. ** to the *-wal path.
  150950. ** 4: the checkpoint is underway.
  150951. ** 5: the rbu update has been checkpointed.
  150952. **
  150953. ** RBU_STATE_TBL:
  150954. ** Only valid if STAGE==1. The target database name of the table
  150955. ** currently being written.
  150956. **
  150957. ** RBU_STATE_IDX:
  150958. ** Only valid if STAGE==1. The target database name of the index
  150959. ** currently being written, or NULL if the main table is currently being
  150960. ** updated.
  150961. **
  150962. ** RBU_STATE_ROW:
  150963. ** Only valid if STAGE==1. Number of rows already processed for the current
  150964. ** table/index.
  150965. **
  150966. ** RBU_STATE_PROGRESS:
  150967. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  150968. ** rbu update.
  150969. **
  150970. ** RBU_STATE_CKPT:
  150971. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  150972. ** header created by recovering the *-wal file. This is used to detect
  150973. ** cases when another client appends frames to the *-wal file in the
  150974. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  150975. ** be continued if this happens).
  150976. **
  150977. ** RBU_STATE_COOKIE:
  150978. ** Valid if STAGE==1. The current change-counter cookie value in the
  150979. ** target db file.
  150980. **
  150981. ** RBU_STATE_OALSZ:
  150982. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  150983. */
  150984. #define RBU_STATE_STAGE 1
  150985. #define RBU_STATE_TBL 2
  150986. #define RBU_STATE_IDX 3
  150987. #define RBU_STATE_ROW 4
  150988. #define RBU_STATE_PROGRESS 5
  150989. #define RBU_STATE_CKPT 6
  150990. #define RBU_STATE_COOKIE 7
  150991. #define RBU_STATE_OALSZ 8
  150992. #define RBU_STATE_PHASEONESTEP 9
  150993. #define RBU_STAGE_OAL 1
  150994. #define RBU_STAGE_MOVE 2
  150995. #define RBU_STAGE_CAPTURE 3
  150996. #define RBU_STAGE_CKPT 4
  150997. #define RBU_STAGE_DONE 5
  150998. #define RBU_CREATE_STATE \
  150999. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  151000. typedef struct RbuFrame RbuFrame;
  151001. typedef struct RbuObjIter RbuObjIter;
  151002. typedef struct RbuState RbuState;
  151003. typedef struct rbu_vfs rbu_vfs;
  151004. typedef struct rbu_file rbu_file;
  151005. typedef struct RbuUpdateStmt RbuUpdateStmt;
  151006. #if !defined(SQLITE_AMALGAMATION)
  151007. typedef unsigned int u32;
  151008. typedef unsigned char u8;
  151009. typedef sqlite3_int64 i64;
  151010. #endif
  151011. /*
  151012. ** These values must match the values defined in wal.c for the equivalent
  151013. ** locks. These are not magic numbers as they are part of the SQLite file
  151014. ** format.
  151015. */
  151016. #define WAL_LOCK_WRITE 0
  151017. #define WAL_LOCK_CKPT 1
  151018. #define WAL_LOCK_READ0 3
  151019. /*
  151020. ** A structure to store values read from the rbu_state table in memory.
  151021. */
  151022. struct RbuState {
  151023. int eStage;
  151024. char *zTbl;
  151025. char *zIdx;
  151026. i64 iWalCksum;
  151027. int nRow;
  151028. i64 nProgress;
  151029. u32 iCookie;
  151030. i64 iOalSz;
  151031. i64 nPhaseOneStep;
  151032. };
  151033. struct RbuUpdateStmt {
  151034. char *zMask; /* Copy of update mask used with pUpdate */
  151035. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  151036. RbuUpdateStmt *pNext;
  151037. };
  151038. /*
  151039. ** An iterator of this type is used to iterate through all objects in
  151040. ** the target database that require updating. For each such table, the
  151041. ** iterator visits, in order:
  151042. **
  151043. ** * the table itself,
  151044. ** * each index of the table (zero or more points to visit), and
  151045. ** * a special "cleanup table" state.
  151046. **
  151047. ** abIndexed:
  151048. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  151049. ** it points to an array of flags nTblCol elements in size. The flag is
  151050. ** set for each column that is either a part of the PK or a part of an
  151051. ** index. Or clear otherwise.
  151052. **
  151053. */
  151054. struct RbuObjIter {
  151055. sqlite3_stmt *pTblIter; /* Iterate through tables */
  151056. sqlite3_stmt *pIdxIter; /* Index iterator */
  151057. int nTblCol; /* Size of azTblCol[] array */
  151058. char **azTblCol; /* Array of unquoted target column names */
  151059. char **azTblType; /* Array of target column types */
  151060. int *aiSrcOrder; /* src table col -> target table col */
  151061. u8 *abTblPk; /* Array of flags, set on target PK columns */
  151062. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  151063. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  151064. int eType; /* Table type - an RBU_PK_XXX value */
  151065. /* Output variables. zTbl==0 implies EOF. */
  151066. int bCleanup; /* True in "cleanup" state */
  151067. const char *zTbl; /* Name of target db table */
  151068. const char *zDataTbl; /* Name of rbu db table (or null) */
  151069. const char *zIdx; /* Name of target db index (or null) */
  151070. int iTnum; /* Root page of current object */
  151071. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  151072. int bUnique; /* Current index is unique */
  151073. int nIndex; /* Number of aux. indexes on table zTbl */
  151074. /* Statements created by rbuObjIterPrepareAll() */
  151075. int nCol; /* Number of columns in current object */
  151076. sqlite3_stmt *pSelect; /* Source data */
  151077. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  151078. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  151079. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  151080. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  151081. RbuUpdateStmt *pRbuUpdate;
  151082. };
  151083. /*
  151084. ** Values for RbuObjIter.eType
  151085. **
  151086. ** 0: Table does not exist (error)
  151087. ** 1: Table has an implicit rowid.
  151088. ** 2: Table has an explicit IPK column.
  151089. ** 3: Table has an external PK index.
  151090. ** 4: Table is WITHOUT ROWID.
  151091. ** 5: Table is a virtual table.
  151092. */
  151093. #define RBU_PK_NOTABLE 0
  151094. #define RBU_PK_NONE 1
  151095. #define RBU_PK_IPK 2
  151096. #define RBU_PK_EXTERNAL 3
  151097. #define RBU_PK_WITHOUT_ROWID 4
  151098. #define RBU_PK_VTAB 5
  151099. /*
  151100. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  151101. ** one of the following operations.
  151102. */
  151103. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  151104. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  151105. #define RBU_REPLACE 3 /* Delete and then insert a row */
  151106. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  151107. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  151108. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  151109. /*
  151110. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  151111. ** file should be copied to page iDbPage of the database file.
  151112. */
  151113. struct RbuFrame {
  151114. u32 iDbPage;
  151115. u32 iWalFrame;
  151116. };
  151117. /*
  151118. ** RBU handle.
  151119. **
  151120. ** nPhaseOneStep:
  151121. ** If the RBU database contains an rbu_count table, this value is set to
  151122. ** a running estimate of the number of b-tree operations required to
  151123. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  151124. ** API to calculate the permyriadage progress of populating the *-oal file
  151125. ** using the formula:
  151126. **
  151127. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  151128. **
  151129. ** nPhaseOneStep is initialized to the sum of:
  151130. **
  151131. ** nRow * (nIndex + 1)
  151132. **
  151133. ** for all source tables in the RBU database, where nRow is the number
  151134. ** of rows in the source table and nIndex the number of indexes on the
  151135. ** corresponding target database table.
  151136. **
  151137. ** This estimate is accurate if the RBU update consists entirely of
  151138. ** INSERT operations. However, it is inaccurate if:
  151139. **
  151140. ** * the RBU update contains any UPDATE operations. If the PK specified
  151141. ** for an UPDATE operation does not exist in the target table, then
  151142. ** no b-tree operations are required on index b-trees. Or if the
  151143. ** specified PK does exist, then (nIndex*2) such operations are
  151144. ** required (one delete and one insert on each index b-tree).
  151145. **
  151146. ** * the RBU update contains any DELETE operations for which the specified
  151147. ** PK does not exist. In this case no operations are required on index
  151148. ** b-trees.
  151149. **
  151150. ** * the RBU update contains REPLACE operations. These are similar to
  151151. ** UPDATE operations.
  151152. **
  151153. ** nPhaseOneStep is updated to account for the conditions above during the
  151154. ** first pass of each source table. The updated nPhaseOneStep value is
  151155. ** stored in the rbu_state table if the RBU update is suspended.
  151156. */
  151157. struct sqlite3rbu {
  151158. int eStage; /* Value of RBU_STATE_STAGE field */
  151159. sqlite3 *dbMain; /* target database handle */
  151160. sqlite3 *dbRbu; /* rbu database handle */
  151161. char *zTarget; /* Path to target db */
  151162. char *zRbu; /* Path to rbu db */
  151163. char *zState; /* Path to state db (or NULL if zRbu) */
  151164. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  151165. int rc; /* Value returned by last rbu_step() call */
  151166. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  151167. int nStep; /* Rows processed for current object */
  151168. int nProgress; /* Rows processed for all objects */
  151169. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  151170. const char *zVfsName; /* Name of automatically created rbu vfs */
  151171. rbu_file *pTargetFd; /* File handle open on target db */
  151172. i64 iOalSz;
  151173. i64 nPhaseOneStep;
  151174. /* The following state variables are used as part of the incremental
  151175. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  151176. ** function rbuSetupCheckpoint() for details. */
  151177. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  151178. u32 mLock;
  151179. int nFrame; /* Entries in aFrame[] array */
  151180. int nFrameAlloc; /* Allocated size of aFrame[] array */
  151181. RbuFrame *aFrame;
  151182. int pgsz;
  151183. u8 *aBuf;
  151184. i64 iWalCksum;
  151185. };
  151186. /*
  151187. ** An rbu VFS is implemented using an instance of this structure.
  151188. */
  151189. struct rbu_vfs {
  151190. sqlite3_vfs base; /* rbu VFS shim methods */
  151191. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  151192. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  151193. rbu_file *pMain; /* Linked list of main db files */
  151194. };
  151195. /*
  151196. ** Each file opened by an rbu VFS is represented by an instance of
  151197. ** the following structure.
  151198. */
  151199. struct rbu_file {
  151200. sqlite3_file base; /* sqlite3_file methods */
  151201. sqlite3_file *pReal; /* Underlying file handle */
  151202. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  151203. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  151204. int openFlags; /* Flags this file was opened with */
  151205. u32 iCookie; /* Cookie value for main db files */
  151206. u8 iWriteVer; /* "write-version" value for main db files */
  151207. int nShm; /* Number of entries in apShm[] array */
  151208. char **apShm; /* Array of mmap'd *-shm regions */
  151209. char *zDel; /* Delete this when closing file */
  151210. const char *zWal; /* Wal filename for this main db file */
  151211. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  151212. rbu_file *pMainNext; /* Next MAIN_DB file */
  151213. };
  151214. /*************************************************************************
  151215. ** The following three functions, found below:
  151216. **
  151217. ** rbuDeltaGetInt()
  151218. ** rbuDeltaChecksum()
  151219. ** rbuDeltaApply()
  151220. **
  151221. ** are lifted from the fossil source code (http://fossil-scm.org). They
  151222. ** are used to implement the scalar SQL function rbu_fossil_delta().
  151223. */
  151224. /*
  151225. ** Read bytes from *pz and convert them into a positive integer. When
  151226. ** finished, leave *pz pointing to the first character past the end of
  151227. ** the integer. The *pLen parameter holds the length of the string
  151228. ** in *pz and is decremented once for each character in the integer.
  151229. */
  151230. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  151231. static const signed char zValue[] = {
  151232. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  151233. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  151234. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  151235. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  151236. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  151237. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  151238. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  151239. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  151240. };
  151241. unsigned int v = 0;
  151242. int c;
  151243. unsigned char *z = (unsigned char*)*pz;
  151244. unsigned char *zStart = z;
  151245. while( (c = zValue[0x7f&*(z++)])>=0 ){
  151246. v = (v<<6) + c;
  151247. }
  151248. z--;
  151249. *pLen -= z - zStart;
  151250. *pz = (char*)z;
  151251. return v;
  151252. }
  151253. /*
  151254. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  151255. */
  151256. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  151257. const unsigned char *z = (const unsigned char *)zIn;
  151258. unsigned sum0 = 0;
  151259. unsigned sum1 = 0;
  151260. unsigned sum2 = 0;
  151261. unsigned sum3 = 0;
  151262. while(N >= 16){
  151263. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  151264. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  151265. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  151266. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  151267. z += 16;
  151268. N -= 16;
  151269. }
  151270. while(N >= 4){
  151271. sum0 += z[0];
  151272. sum1 += z[1];
  151273. sum2 += z[2];
  151274. sum3 += z[3];
  151275. z += 4;
  151276. N -= 4;
  151277. }
  151278. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  151279. switch(N){
  151280. case 3: sum3 += (z[2] << 8);
  151281. case 2: sum3 += (z[1] << 16);
  151282. case 1: sum3 += (z[0] << 24);
  151283. default: ;
  151284. }
  151285. return sum3;
  151286. }
  151287. /*
  151288. ** Apply a delta.
  151289. **
  151290. ** The output buffer should be big enough to hold the whole output
  151291. ** file and a NUL terminator at the end. The delta_output_size()
  151292. ** routine will determine this size for you.
  151293. **
  151294. ** The delta string should be null-terminated. But the delta string
  151295. ** may contain embedded NUL characters (if the input and output are
  151296. ** binary files) so we also have to pass in the length of the delta in
  151297. ** the lenDelta parameter.
  151298. **
  151299. ** This function returns the size of the output file in bytes (excluding
  151300. ** the final NUL terminator character). Except, if the delta string is
  151301. ** malformed or intended for use with a source file other than zSrc,
  151302. ** then this routine returns -1.
  151303. **
  151304. ** Refer to the delta_create() documentation above for a description
  151305. ** of the delta file format.
  151306. */
  151307. static int rbuDeltaApply(
  151308. const char *zSrc, /* The source or pattern file */
  151309. int lenSrc, /* Length of the source file */
  151310. const char *zDelta, /* Delta to apply to the pattern */
  151311. int lenDelta, /* Length of the delta */
  151312. char *zOut /* Write the output into this preallocated buffer */
  151313. ){
  151314. unsigned int limit;
  151315. unsigned int total = 0;
  151316. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  151317. char *zOrigOut = zOut;
  151318. #endif
  151319. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  151320. if( *zDelta!='\n' ){
  151321. /* ERROR: size integer not terminated by "\n" */
  151322. return -1;
  151323. }
  151324. zDelta++; lenDelta--;
  151325. while( *zDelta && lenDelta>0 ){
  151326. unsigned int cnt, ofst;
  151327. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  151328. switch( zDelta[0] ){
  151329. case '@': {
  151330. zDelta++; lenDelta--;
  151331. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  151332. if( lenDelta>0 && zDelta[0]!=',' ){
  151333. /* ERROR: copy command not terminated by ',' */
  151334. return -1;
  151335. }
  151336. zDelta++; lenDelta--;
  151337. total += cnt;
  151338. if( total>limit ){
  151339. /* ERROR: copy exceeds output file size */
  151340. return -1;
  151341. }
  151342. if( (int)(ofst+cnt) > lenSrc ){
  151343. /* ERROR: copy extends past end of input */
  151344. return -1;
  151345. }
  151346. memcpy(zOut, &zSrc[ofst], cnt);
  151347. zOut += cnt;
  151348. break;
  151349. }
  151350. case ':': {
  151351. zDelta++; lenDelta--;
  151352. total += cnt;
  151353. if( total>limit ){
  151354. /* ERROR: insert command gives an output larger than predicted */
  151355. return -1;
  151356. }
  151357. if( (int)cnt>lenDelta ){
  151358. /* ERROR: insert count exceeds size of delta */
  151359. return -1;
  151360. }
  151361. memcpy(zOut, zDelta, cnt);
  151362. zOut += cnt;
  151363. zDelta += cnt;
  151364. lenDelta -= cnt;
  151365. break;
  151366. }
  151367. case ';': {
  151368. zDelta++; lenDelta--;
  151369. zOut[0] = 0;
  151370. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  151371. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  151372. /* ERROR: bad checksum */
  151373. return -1;
  151374. }
  151375. #endif
  151376. if( total!=limit ){
  151377. /* ERROR: generated size does not match predicted size */
  151378. return -1;
  151379. }
  151380. return total;
  151381. }
  151382. default: {
  151383. /* ERROR: unknown delta operator */
  151384. return -1;
  151385. }
  151386. }
  151387. }
  151388. /* ERROR: unterminated delta */
  151389. return -1;
  151390. }
  151391. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  151392. int size;
  151393. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  151394. if( *zDelta!='\n' ){
  151395. /* ERROR: size integer not terminated by "\n" */
  151396. return -1;
  151397. }
  151398. return size;
  151399. }
  151400. /*
  151401. ** End of code taken from fossil.
  151402. *************************************************************************/
  151403. /*
  151404. ** Implementation of SQL scalar function rbu_fossil_delta().
  151405. **
  151406. ** This function applies a fossil delta patch to a blob. Exactly two
  151407. ** arguments must be passed to this function. The first is the blob to
  151408. ** patch and the second the patch to apply. If no error occurs, this
  151409. ** function returns the patched blob.
  151410. */
  151411. static void rbuFossilDeltaFunc(
  151412. sqlite3_context *context,
  151413. int argc,
  151414. sqlite3_value **argv
  151415. ){
  151416. const char *aDelta;
  151417. int nDelta;
  151418. const char *aOrig;
  151419. int nOrig;
  151420. int nOut;
  151421. int nOut2;
  151422. char *aOut;
  151423. assert( argc==2 );
  151424. nOrig = sqlite3_value_bytes(argv[0]);
  151425. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  151426. nDelta = sqlite3_value_bytes(argv[1]);
  151427. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  151428. /* Figure out the size of the output */
  151429. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  151430. if( nOut<0 ){
  151431. sqlite3_result_error(context, "corrupt fossil delta", -1);
  151432. return;
  151433. }
  151434. aOut = sqlite3_malloc(nOut+1);
  151435. if( aOut==0 ){
  151436. sqlite3_result_error_nomem(context);
  151437. }else{
  151438. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  151439. if( nOut2!=nOut ){
  151440. sqlite3_result_error(context, "corrupt fossil delta", -1);
  151441. }else{
  151442. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  151443. }
  151444. }
  151445. }
  151446. /*
  151447. ** Prepare the SQL statement in buffer zSql against database handle db.
  151448. ** If successful, set *ppStmt to point to the new statement and return
  151449. ** SQLITE_OK.
  151450. **
  151451. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  151452. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  151453. ** point to a buffer containing an error message. It is the responsibility
  151454. ** of the caller to (eventually) free this buffer using sqlite3_free().
  151455. */
  151456. static int prepareAndCollectError(
  151457. sqlite3 *db,
  151458. sqlite3_stmt **ppStmt,
  151459. char **pzErrmsg,
  151460. const char *zSql
  151461. ){
  151462. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  151463. if( rc!=SQLITE_OK ){
  151464. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  151465. *ppStmt = 0;
  151466. }
  151467. return rc;
  151468. }
  151469. /*
  151470. ** Reset the SQL statement passed as the first argument. Return a copy
  151471. ** of the value returned by sqlite3_reset().
  151472. **
  151473. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  151474. ** containing an error message. It is the responsibility of the caller
  151475. ** to eventually free this buffer using sqlite3_free().
  151476. */
  151477. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  151478. int rc = sqlite3_reset(pStmt);
  151479. if( rc!=SQLITE_OK ){
  151480. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  151481. }
  151482. return rc;
  151483. }
  151484. /*
  151485. ** Unless it is NULL, argument zSql points to a buffer allocated using
  151486. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  151487. ** statement against database db and frees the buffer. If statement
  151488. ** compilation is successful, *ppStmt is set to point to the new statement
  151489. ** handle and SQLITE_OK is returned.
  151490. **
  151491. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  151492. ** returned. In this case, *pzErrmsg may also be set to point to an error
  151493. ** message. It is the responsibility of the caller to free this error message
  151494. ** buffer using sqlite3_free().
  151495. **
  151496. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  151497. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  151498. */
  151499. static int prepareFreeAndCollectError(
  151500. sqlite3 *db,
  151501. sqlite3_stmt **ppStmt,
  151502. char **pzErrmsg,
  151503. char *zSql
  151504. ){
  151505. int rc;
  151506. assert( *pzErrmsg==0 );
  151507. if( zSql==0 ){
  151508. rc = SQLITE_NOMEM;
  151509. *ppStmt = 0;
  151510. }else{
  151511. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  151512. sqlite3_free(zSql);
  151513. }
  151514. return rc;
  151515. }
  151516. /*
  151517. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  151518. ** by an earlier call to rbuObjIterCacheTableInfo().
  151519. */
  151520. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  151521. int i;
  151522. for(i=0; i<pIter->nTblCol; i++){
  151523. sqlite3_free(pIter->azTblCol[i]);
  151524. sqlite3_free(pIter->azTblType[i]);
  151525. }
  151526. sqlite3_free(pIter->azTblCol);
  151527. pIter->azTblCol = 0;
  151528. pIter->azTblType = 0;
  151529. pIter->aiSrcOrder = 0;
  151530. pIter->abTblPk = 0;
  151531. pIter->abNotNull = 0;
  151532. pIter->nTblCol = 0;
  151533. pIter->eType = 0; /* Invalid value */
  151534. }
  151535. /*
  151536. ** Finalize all statements and free all allocations that are specific to
  151537. ** the current object (table/index pair).
  151538. */
  151539. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  151540. RbuUpdateStmt *pUp;
  151541. sqlite3_finalize(pIter->pSelect);
  151542. sqlite3_finalize(pIter->pInsert);
  151543. sqlite3_finalize(pIter->pDelete);
  151544. sqlite3_finalize(pIter->pTmpInsert);
  151545. pUp = pIter->pRbuUpdate;
  151546. while( pUp ){
  151547. RbuUpdateStmt *pTmp = pUp->pNext;
  151548. sqlite3_finalize(pUp->pUpdate);
  151549. sqlite3_free(pUp);
  151550. pUp = pTmp;
  151551. }
  151552. pIter->pSelect = 0;
  151553. pIter->pInsert = 0;
  151554. pIter->pDelete = 0;
  151555. pIter->pRbuUpdate = 0;
  151556. pIter->pTmpInsert = 0;
  151557. pIter->nCol = 0;
  151558. }
  151559. /*
  151560. ** Clean up any resources allocated as part of the iterator object passed
  151561. ** as the only argument.
  151562. */
  151563. static void rbuObjIterFinalize(RbuObjIter *pIter){
  151564. rbuObjIterClearStatements(pIter);
  151565. sqlite3_finalize(pIter->pTblIter);
  151566. sqlite3_finalize(pIter->pIdxIter);
  151567. rbuObjIterFreeCols(pIter);
  151568. memset(pIter, 0, sizeof(RbuObjIter));
  151569. }
  151570. /*
  151571. ** Advance the iterator to the next position.
  151572. **
  151573. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  151574. ** pointing to the next entry. Otherwise, an error code and message is
  151575. ** left in the RBU handle passed as the first argument. A copy of the
  151576. ** error code is returned.
  151577. */
  151578. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  151579. int rc = p->rc;
  151580. if( rc==SQLITE_OK ){
  151581. /* Free any SQLite statements used while processing the previous object */
  151582. rbuObjIterClearStatements(pIter);
  151583. if( pIter->zIdx==0 ){
  151584. rc = sqlite3_exec(p->dbMain,
  151585. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  151586. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  151587. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  151588. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  151589. , 0, 0, &p->zErrmsg
  151590. );
  151591. }
  151592. if( rc==SQLITE_OK ){
  151593. if( pIter->bCleanup ){
  151594. rbuObjIterFreeCols(pIter);
  151595. pIter->bCleanup = 0;
  151596. rc = sqlite3_step(pIter->pTblIter);
  151597. if( rc!=SQLITE_ROW ){
  151598. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  151599. pIter->zTbl = 0;
  151600. }else{
  151601. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  151602. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  151603. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  151604. }
  151605. }else{
  151606. if( pIter->zIdx==0 ){
  151607. sqlite3_stmt *pIdx = pIter->pIdxIter;
  151608. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  151609. }
  151610. if( rc==SQLITE_OK ){
  151611. rc = sqlite3_step(pIter->pIdxIter);
  151612. if( rc!=SQLITE_ROW ){
  151613. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  151614. pIter->bCleanup = 1;
  151615. pIter->zIdx = 0;
  151616. }else{
  151617. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  151618. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  151619. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  151620. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  151621. }
  151622. }
  151623. }
  151624. }
  151625. }
  151626. if( rc!=SQLITE_OK ){
  151627. rbuObjIterFinalize(pIter);
  151628. p->rc = rc;
  151629. }
  151630. return rc;
  151631. }
  151632. /*
  151633. ** The implementation of the rbu_target_name() SQL function. This function
  151634. ** accepts one argument - the name of a table in the RBU database. If the
  151635. ** table name matches the pattern:
  151636. **
  151637. ** data[0-9]_<name>
  151638. **
  151639. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  151640. ** Otherwise, if the only argument does not match the above pattern, an SQL
  151641. ** NULL is returned.
  151642. **
  151643. ** "data_t1" -> "t1"
  151644. ** "data0123_t2" -> "t2"
  151645. ** "dataAB_t3" -> NULL
  151646. */
  151647. static void rbuTargetNameFunc(
  151648. sqlite3_context *context,
  151649. int argc,
  151650. sqlite3_value **argv
  151651. ){
  151652. const char *zIn;
  151653. assert( argc==1 );
  151654. zIn = (const char*)sqlite3_value_text(argv[0]);
  151655. if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  151656. int i;
  151657. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  151658. if( zIn[i]=='_' && zIn[i+1] ){
  151659. sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
  151660. }
  151661. }
  151662. }
  151663. /*
  151664. ** Initialize the iterator structure passed as the second argument.
  151665. **
  151666. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  151667. ** pointing to the first entry. Otherwise, an error code and message is
  151668. ** left in the RBU handle passed as the first argument. A copy of the
  151669. ** error code is returned.
  151670. */
  151671. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  151672. int rc;
  151673. memset(pIter, 0, sizeof(RbuObjIter));
  151674. rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  151675. "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
  151676. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  151677. "ORDER BY name"
  151678. );
  151679. if( rc==SQLITE_OK ){
  151680. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  151681. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  151682. " FROM main.sqlite_master "
  151683. " WHERE type='index' AND tbl_name = ?"
  151684. );
  151685. }
  151686. pIter->bCleanup = 1;
  151687. p->rc = rc;
  151688. return rbuObjIterNext(p, pIter);
  151689. }
  151690. /*
  151691. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  151692. ** an error code is stored in the RBU handle passed as the first argument.
  151693. **
  151694. ** If an error has already occurred (p->rc is already set to something other
  151695. ** than SQLITE_OK), then this function returns NULL without modifying the
  151696. ** stored error code. In this case it still calls sqlite3_free() on any
  151697. ** printf() parameters associated with %z conversions.
  151698. */
  151699. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  151700. char *zSql = 0;
  151701. va_list ap;
  151702. va_start(ap, zFmt);
  151703. zSql = sqlite3_vmprintf(zFmt, ap);
  151704. if( p->rc==SQLITE_OK ){
  151705. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  151706. }else{
  151707. sqlite3_free(zSql);
  151708. zSql = 0;
  151709. }
  151710. va_end(ap);
  151711. return zSql;
  151712. }
  151713. /*
  151714. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  151715. ** arguments are the usual subsitution values. This function performs
  151716. ** the printf() style substitutions and executes the result as an SQL
  151717. ** statement on the RBU handles database.
  151718. **
  151719. ** If an error occurs, an error code and error message is stored in the
  151720. ** RBU handle. If an error has already occurred when this function is
  151721. ** called, it is a no-op.
  151722. */
  151723. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  151724. va_list ap;
  151725. char *zSql;
  151726. va_start(ap, zFmt);
  151727. zSql = sqlite3_vmprintf(zFmt, ap);
  151728. if( p->rc==SQLITE_OK ){
  151729. if( zSql==0 ){
  151730. p->rc = SQLITE_NOMEM;
  151731. }else{
  151732. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  151733. }
  151734. }
  151735. sqlite3_free(zSql);
  151736. va_end(ap);
  151737. return p->rc;
  151738. }
  151739. /*
  151740. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  151741. ** bytes.
  151742. **
  151743. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  151744. ** error code in the rbu handle passed as the first argument. Or, if an
  151745. ** error has already occurred when this function is called, return NULL
  151746. ** immediately without attempting the allocation or modifying the stored
  151747. ** error code.
  151748. */
  151749. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  151750. void *pRet = 0;
  151751. if( p->rc==SQLITE_OK ){
  151752. assert( nByte>0 );
  151753. pRet = sqlite3_malloc64(nByte);
  151754. if( pRet==0 ){
  151755. p->rc = SQLITE_NOMEM;
  151756. }else{
  151757. memset(pRet, 0, nByte);
  151758. }
  151759. }
  151760. return pRet;
  151761. }
  151762. /*
  151763. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  151764. ** there is room for at least nCol elements. If an OOM occurs, store an
  151765. ** error code in the RBU handle passed as the first argument.
  151766. */
  151767. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  151768. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  151769. char **azNew;
  151770. azNew = (char**)rbuMalloc(p, nByte);
  151771. if( azNew ){
  151772. pIter->azTblCol = azNew;
  151773. pIter->azTblType = &azNew[nCol];
  151774. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  151775. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  151776. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  151777. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  151778. }
  151779. }
  151780. /*
  151781. ** The first argument must be a nul-terminated string. This function
  151782. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  151783. ** It is the responsibility of the caller to eventually free this memory
  151784. ** using sqlite3_free().
  151785. **
  151786. ** If an OOM condition is encountered when attempting to allocate memory,
  151787. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  151788. ** if the allocation succeeds, (*pRc) is left unchanged.
  151789. */
  151790. static char *rbuStrndup(const char *zStr, int *pRc){
  151791. char *zRet = 0;
  151792. assert( *pRc==SQLITE_OK );
  151793. if( zStr ){
  151794. size_t nCopy = strlen(zStr) + 1;
  151795. zRet = (char*)sqlite3_malloc64(nCopy);
  151796. if( zRet ){
  151797. memcpy(zRet, zStr, nCopy);
  151798. }else{
  151799. *pRc = SQLITE_NOMEM;
  151800. }
  151801. }
  151802. return zRet;
  151803. }
  151804. /*
  151805. ** Finalize the statement passed as the second argument.
  151806. **
  151807. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  151808. ** rbu handle error code is not already set, set the error code and error
  151809. ** message accordingly.
  151810. */
  151811. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  151812. sqlite3 *db = sqlite3_db_handle(pStmt);
  151813. int rc = sqlite3_finalize(pStmt);
  151814. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  151815. p->rc = rc;
  151816. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  151817. }
  151818. }
  151819. /* Determine the type of a table.
  151820. **
  151821. ** peType is of type (int*), a pointer to an output parameter of type
  151822. ** (int). This call sets the output parameter as follows, depending
  151823. ** on the type of the table specified by parameters dbName and zTbl.
  151824. **
  151825. ** RBU_PK_NOTABLE: No such table.
  151826. ** RBU_PK_NONE: Table has an implicit rowid.
  151827. ** RBU_PK_IPK: Table has an explicit IPK column.
  151828. ** RBU_PK_EXTERNAL: Table has an external PK index.
  151829. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  151830. ** RBU_PK_VTAB: Table is a virtual table.
  151831. **
  151832. ** Argument *piPk is also of type (int*), and also points to an output
  151833. ** parameter. Unless the table has an external primary key index
  151834. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  151835. ** if the table does have an external primary key index, then *piPk
  151836. ** is set to the root page number of the primary key index before
  151837. ** returning.
  151838. **
  151839. ** ALGORITHM:
  151840. **
  151841. ** if( no entry exists in sqlite_master ){
  151842. ** return RBU_PK_NOTABLE
  151843. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  151844. ** return RBU_PK_VTAB
  151845. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  151846. ** if( the index that is the pk exists in sqlite_master ){
  151847. ** *piPK = rootpage of that index.
  151848. ** return RBU_PK_EXTERNAL
  151849. ** }else{
  151850. ** return RBU_PK_WITHOUT_ROWID
  151851. ** }
  151852. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  151853. ** return RBU_PK_IPK
  151854. ** }else{
  151855. ** return RBU_PK_NONE
  151856. ** }
  151857. */
  151858. static void rbuTableType(
  151859. sqlite3rbu *p,
  151860. const char *zTab,
  151861. int *peType,
  151862. int *piTnum,
  151863. int *piPk
  151864. ){
  151865. /*
  151866. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  151867. ** 1) PRAGMA index_list = ?
  151868. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  151869. ** 3) PRAGMA table_info = ?
  151870. */
  151871. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  151872. *peType = RBU_PK_NOTABLE;
  151873. *piPk = 0;
  151874. assert( p->rc==SQLITE_OK );
  151875. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  151876. sqlite3_mprintf(
  151877. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  151878. " FROM sqlite_master"
  151879. " WHERE name=%Q", zTab
  151880. ));
  151881. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  151882. /* Either an error, or no such table. */
  151883. goto rbuTableType_end;
  151884. }
  151885. if( sqlite3_column_int(aStmt[0], 0) ){
  151886. *peType = RBU_PK_VTAB; /* virtual table */
  151887. goto rbuTableType_end;
  151888. }
  151889. *piTnum = sqlite3_column_int(aStmt[0], 1);
  151890. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  151891. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  151892. );
  151893. if( p->rc ) goto rbuTableType_end;
  151894. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  151895. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  151896. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  151897. if( zOrig && zIdx && zOrig[0]=='p' ){
  151898. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  151899. sqlite3_mprintf(
  151900. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  151901. ));
  151902. if( p->rc==SQLITE_OK ){
  151903. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  151904. *piPk = sqlite3_column_int(aStmt[2], 0);
  151905. *peType = RBU_PK_EXTERNAL;
  151906. }else{
  151907. *peType = RBU_PK_WITHOUT_ROWID;
  151908. }
  151909. }
  151910. goto rbuTableType_end;
  151911. }
  151912. }
  151913. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  151914. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  151915. );
  151916. if( p->rc==SQLITE_OK ){
  151917. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  151918. if( sqlite3_column_int(aStmt[3],5)>0 ){
  151919. *peType = RBU_PK_IPK; /* explicit IPK column */
  151920. goto rbuTableType_end;
  151921. }
  151922. }
  151923. *peType = RBU_PK_NONE;
  151924. }
  151925. rbuTableType_end: {
  151926. unsigned int i;
  151927. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  151928. rbuFinalize(p, aStmt[i]);
  151929. }
  151930. }
  151931. }
  151932. /*
  151933. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  151934. ** the pIter->abIndexed[] array.
  151935. */
  151936. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  151937. sqlite3_stmt *pList = 0;
  151938. int bIndex = 0;
  151939. if( p->rc==SQLITE_OK ){
  151940. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  151941. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  151942. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  151943. );
  151944. }
  151945. pIter->nIndex = 0;
  151946. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  151947. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  151948. sqlite3_stmt *pXInfo = 0;
  151949. if( zIdx==0 ) break;
  151950. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  151951. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  151952. );
  151953. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  151954. int iCid = sqlite3_column_int(pXInfo, 1);
  151955. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  151956. }
  151957. rbuFinalize(p, pXInfo);
  151958. bIndex = 1;
  151959. pIter->nIndex++;
  151960. }
  151961. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  151962. /* "PRAGMA index_list" includes the main PK b-tree */
  151963. pIter->nIndex--;
  151964. }
  151965. rbuFinalize(p, pList);
  151966. if( bIndex==0 ) pIter->abIndexed = 0;
  151967. }
  151968. /*
  151969. ** If they are not already populated, populate the pIter->azTblCol[],
  151970. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  151971. ** the table (not index) that the iterator currently points to.
  151972. **
  151973. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  151974. ** an error does occur, an error code and error message are also left in
  151975. ** the RBU handle.
  151976. */
  151977. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  151978. if( pIter->azTblCol==0 ){
  151979. sqlite3_stmt *pStmt = 0;
  151980. int nCol = 0;
  151981. int i; /* for() loop iterator variable */
  151982. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  151983. int iOrder = 0;
  151984. int iTnum = 0;
  151985. /* Figure out the type of table this step will deal with. */
  151986. assert( pIter->eType==0 );
  151987. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  151988. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  151989. p->rc = SQLITE_ERROR;
  151990. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  151991. }
  151992. if( p->rc ) return p->rc;
  151993. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  151994. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  151995. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  151996. || pIter->eType==RBU_PK_VTAB
  151997. );
  151998. /* Populate the azTblCol[] and nTblCol variables based on the columns
  151999. ** of the input table. Ignore any input table columns that begin with
  152000. ** "rbu_". */
  152001. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  152002. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  152003. );
  152004. if( p->rc==SQLITE_OK ){
  152005. nCol = sqlite3_column_count(pStmt);
  152006. rbuAllocateIterArrays(p, pIter, nCol);
  152007. }
  152008. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  152009. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  152010. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  152011. char *zCopy = rbuStrndup(zName, &p->rc);
  152012. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  152013. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  152014. }
  152015. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  152016. bRbuRowid = 1;
  152017. }
  152018. }
  152019. sqlite3_finalize(pStmt);
  152020. pStmt = 0;
  152021. if( p->rc==SQLITE_OK
  152022. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  152023. ){
  152024. p->rc = SQLITE_ERROR;
  152025. p->zErrmsg = sqlite3_mprintf(
  152026. "table %q %s rbu_rowid column", pIter->zDataTbl,
  152027. (bRbuRowid ? "may not have" : "requires")
  152028. );
  152029. }
  152030. /* Check that all non-HIDDEN columns in the destination table are also
  152031. ** present in the input table. Populate the abTblPk[], azTblType[] and
  152032. ** aiTblOrder[] arrays at the same time. */
  152033. if( p->rc==SQLITE_OK ){
  152034. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  152035. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  152036. );
  152037. }
  152038. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  152039. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  152040. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  152041. for(i=iOrder; i<pIter->nTblCol; i++){
  152042. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  152043. }
  152044. if( i==pIter->nTblCol ){
  152045. p->rc = SQLITE_ERROR;
  152046. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  152047. pIter->zDataTbl, zName
  152048. );
  152049. }else{
  152050. int iPk = sqlite3_column_int(pStmt, 5);
  152051. int bNotNull = sqlite3_column_int(pStmt, 3);
  152052. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  152053. if( i!=iOrder ){
  152054. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  152055. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  152056. }
  152057. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  152058. pIter->abTblPk[iOrder] = (iPk!=0);
  152059. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  152060. iOrder++;
  152061. }
  152062. }
  152063. rbuFinalize(p, pStmt);
  152064. rbuObjIterCacheIndexedCols(p, pIter);
  152065. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  152066. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  152067. }
  152068. return p->rc;
  152069. }
  152070. /*
  152071. ** This function constructs and returns a pointer to a nul-terminated
  152072. ** string containing some SQL clause or list based on one or more of the
  152073. ** column names currently stored in the pIter->azTblCol[] array.
  152074. */
  152075. static char *rbuObjIterGetCollist(
  152076. sqlite3rbu *p, /* RBU object */
  152077. RbuObjIter *pIter /* Object iterator for column names */
  152078. ){
  152079. char *zList = 0;
  152080. const char *zSep = "";
  152081. int i;
  152082. for(i=0; i<pIter->nTblCol; i++){
  152083. const char *z = pIter->azTblCol[i];
  152084. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  152085. zSep = ", ";
  152086. }
  152087. return zList;
  152088. }
  152089. /*
  152090. ** This function is used to create a SELECT list (the list of SQL
  152091. ** expressions that follows a SELECT keyword) for a SELECT statement
  152092. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  152093. ** index object currently indicated by the iterator object passed as the
  152094. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  152095. ** to obtain the required information.
  152096. **
  152097. ** If the index is of the following form:
  152098. **
  152099. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  152100. **
  152101. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  152102. ** "ipk", the returned string is:
  152103. **
  152104. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  152105. **
  152106. ** As well as the returned string, three other malloc'd strings are
  152107. ** returned via output parameters. As follows:
  152108. **
  152109. ** pzImposterCols: ...
  152110. ** pzImposterPk: ...
  152111. ** pzWhere: ...
  152112. */
  152113. static char *rbuObjIterGetIndexCols(
  152114. sqlite3rbu *p, /* RBU object */
  152115. RbuObjIter *pIter, /* Object iterator for column names */
  152116. char **pzImposterCols, /* OUT: Columns for imposter table */
  152117. char **pzImposterPk, /* OUT: Imposter PK clause */
  152118. char **pzWhere, /* OUT: WHERE clause */
  152119. int *pnBind /* OUT: Trbul number of columns */
  152120. ){
  152121. int rc = p->rc; /* Error code */
  152122. int rc2; /* sqlite3_finalize() return code */
  152123. char *zRet = 0; /* String to return */
  152124. char *zImpCols = 0; /* String to return via *pzImposterCols */
  152125. char *zImpPK = 0; /* String to return via *pzImposterPK */
  152126. char *zWhere = 0; /* String to return via *pzWhere */
  152127. int nBind = 0; /* Value to return via *pnBind */
  152128. const char *zCom = ""; /* Set to ", " later on */
  152129. const char *zAnd = ""; /* Set to " AND " later on */
  152130. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  152131. if( rc==SQLITE_OK ){
  152132. assert( p->zErrmsg==0 );
  152133. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  152134. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  152135. );
  152136. }
  152137. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  152138. int iCid = sqlite3_column_int(pXInfo, 1);
  152139. int bDesc = sqlite3_column_int(pXInfo, 3);
  152140. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  152141. const char *zCol;
  152142. const char *zType;
  152143. if( iCid<0 ){
  152144. /* An integer primary key. If the table has an explicit IPK, use
  152145. ** its name. Otherwise, use "rbu_rowid". */
  152146. if( pIter->eType==RBU_PK_IPK ){
  152147. int i;
  152148. for(i=0; pIter->abTblPk[i]==0; i++);
  152149. assert( i<pIter->nTblCol );
  152150. zCol = pIter->azTblCol[i];
  152151. }else{
  152152. zCol = "rbu_rowid";
  152153. }
  152154. zType = "INTEGER";
  152155. }else{
  152156. zCol = pIter->azTblCol[iCid];
  152157. zType = pIter->azTblType[iCid];
  152158. }
  152159. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  152160. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  152161. const char *zOrder = (bDesc ? " DESC" : "");
  152162. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  152163. zImpPK, zCom, nBind, zCol, zOrder
  152164. );
  152165. }
  152166. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  152167. zImpCols, zCom, nBind, zCol, zType, zCollate
  152168. );
  152169. zWhere = sqlite3_mprintf(
  152170. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  152171. );
  152172. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  152173. zCom = ", ";
  152174. zAnd = " AND ";
  152175. nBind++;
  152176. }
  152177. rc2 = sqlite3_finalize(pXInfo);
  152178. if( rc==SQLITE_OK ) rc = rc2;
  152179. if( rc!=SQLITE_OK ){
  152180. sqlite3_free(zRet);
  152181. sqlite3_free(zImpCols);
  152182. sqlite3_free(zImpPK);
  152183. sqlite3_free(zWhere);
  152184. zRet = 0;
  152185. zImpCols = 0;
  152186. zImpPK = 0;
  152187. zWhere = 0;
  152188. p->rc = rc;
  152189. }
  152190. *pzImposterCols = zImpCols;
  152191. *pzImposterPk = zImpPK;
  152192. *pzWhere = zWhere;
  152193. *pnBind = nBind;
  152194. return zRet;
  152195. }
  152196. /*
  152197. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  152198. ** paramter is passed "old", return a string of the form:
  152199. **
  152200. ** "old.a, old.b, old.b"
  152201. **
  152202. ** With the column names escaped.
  152203. **
  152204. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  152205. ** the text ", old._rowid_" to the returned value.
  152206. */
  152207. static char *rbuObjIterGetOldlist(
  152208. sqlite3rbu *p,
  152209. RbuObjIter *pIter,
  152210. const char *zObj
  152211. ){
  152212. char *zList = 0;
  152213. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  152214. const char *zS = "";
  152215. int i;
  152216. for(i=0; i<pIter->nTblCol; i++){
  152217. if( pIter->abIndexed[i] ){
  152218. const char *zCol = pIter->azTblCol[i];
  152219. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  152220. }else{
  152221. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  152222. }
  152223. zS = ", ";
  152224. if( zList==0 ){
  152225. p->rc = SQLITE_NOMEM;
  152226. break;
  152227. }
  152228. }
  152229. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  152230. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  152231. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  152232. }
  152233. }
  152234. return zList;
  152235. }
  152236. /*
  152237. ** Return an expression that can be used in a WHERE clause to match the
  152238. ** primary key of the current table. For example, if the table is:
  152239. **
  152240. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  152241. **
  152242. ** Return the string:
  152243. **
  152244. ** "b = ?1 AND c = ?2"
  152245. */
  152246. static char *rbuObjIterGetWhere(
  152247. sqlite3rbu *p,
  152248. RbuObjIter *pIter
  152249. ){
  152250. char *zList = 0;
  152251. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  152252. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  152253. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  152254. const char *zSep = "";
  152255. int i;
  152256. for(i=0; i<pIter->nTblCol; i++){
  152257. if( pIter->abTblPk[i] ){
  152258. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  152259. zSep = " AND ";
  152260. }
  152261. }
  152262. zList = rbuMPrintf(p,
  152263. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  152264. );
  152265. }else{
  152266. const char *zSep = "";
  152267. int i;
  152268. for(i=0; i<pIter->nTblCol; i++){
  152269. if( pIter->abTblPk[i] ){
  152270. const char *zCol = pIter->azTblCol[i];
  152271. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  152272. zSep = " AND ";
  152273. }
  152274. }
  152275. }
  152276. return zList;
  152277. }
  152278. /*
  152279. ** The SELECT statement iterating through the keys for the current object
  152280. ** (p->objiter.pSelect) currently points to a valid row. However, there
  152281. ** is something wrong with the rbu_control value in the rbu_control value
  152282. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  152283. ** of the RBU handle to something reflecting this.
  152284. */
  152285. static void rbuBadControlError(sqlite3rbu *p){
  152286. p->rc = SQLITE_ERROR;
  152287. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  152288. }
  152289. /*
  152290. ** Return a nul-terminated string containing the comma separated list of
  152291. ** assignments that should be included following the "SET" keyword of
  152292. ** an UPDATE statement used to update the table object that the iterator
  152293. ** passed as the second argument currently points to if the rbu_control
  152294. ** column of the data_xxx table entry is set to zMask.
  152295. **
  152296. ** The memory for the returned string is obtained from sqlite3_malloc().
  152297. ** It is the responsibility of the caller to eventually free it using
  152298. ** sqlite3_free().
  152299. **
  152300. ** If an OOM error is encountered when allocating space for the new
  152301. ** string, an error code is left in the rbu handle passed as the first
  152302. ** argument and NULL is returned. Or, if an error has already occurred
  152303. ** when this function is called, NULL is returned immediately, without
  152304. ** attempting the allocation or modifying the stored error code.
  152305. */
  152306. static char *rbuObjIterGetSetlist(
  152307. sqlite3rbu *p,
  152308. RbuObjIter *pIter,
  152309. const char *zMask
  152310. ){
  152311. char *zList = 0;
  152312. if( p->rc==SQLITE_OK ){
  152313. int i;
  152314. if( (int)strlen(zMask)!=pIter->nTblCol ){
  152315. rbuBadControlError(p);
  152316. }else{
  152317. const char *zSep = "";
  152318. for(i=0; i<pIter->nTblCol; i++){
  152319. char c = zMask[pIter->aiSrcOrder[i]];
  152320. if( c=='x' ){
  152321. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  152322. zList, zSep, pIter->azTblCol[i], i+1
  152323. );
  152324. zSep = ", ";
  152325. }
  152326. else if( c=='d' ){
  152327. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  152328. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  152329. );
  152330. zSep = ", ";
  152331. }
  152332. else if( c=='f' ){
  152333. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  152334. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  152335. );
  152336. zSep = ", ";
  152337. }
  152338. }
  152339. }
  152340. }
  152341. return zList;
  152342. }
  152343. /*
  152344. ** Return a nul-terminated string consisting of nByte comma separated
  152345. ** "?" expressions. For example, if nByte is 3, return a pointer to
  152346. ** a buffer containing the string "?,?,?".
  152347. **
  152348. ** The memory for the returned string is obtained from sqlite3_malloc().
  152349. ** It is the responsibility of the caller to eventually free it using
  152350. ** sqlite3_free().
  152351. **
  152352. ** If an OOM error is encountered when allocating space for the new
  152353. ** string, an error code is left in the rbu handle passed as the first
  152354. ** argument and NULL is returned. Or, if an error has already occurred
  152355. ** when this function is called, NULL is returned immediately, without
  152356. ** attempting the allocation or modifying the stored error code.
  152357. */
  152358. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  152359. char *zRet = 0;
  152360. int nByte = nBind*2 + 1;
  152361. zRet = (char*)rbuMalloc(p, nByte);
  152362. if( zRet ){
  152363. int i;
  152364. for(i=0; i<nBind; i++){
  152365. zRet[i*2] = '?';
  152366. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  152367. }
  152368. }
  152369. return zRet;
  152370. }
  152371. /*
  152372. ** The iterator currently points to a table (not index) of type
  152373. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  152374. ** declaration for the corresponding imposter table. For example,
  152375. ** if the iterator points to a table created as:
  152376. **
  152377. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  152378. **
  152379. ** this function returns:
  152380. **
  152381. ** PRIMARY KEY("b", "a" DESC)
  152382. */
  152383. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  152384. char *z = 0;
  152385. assert( pIter->zIdx==0 );
  152386. if( p->rc==SQLITE_OK ){
  152387. const char *zSep = "PRIMARY KEY(";
  152388. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  152389. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  152390. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  152391. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  152392. );
  152393. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  152394. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  152395. if( zOrig && strcmp(zOrig, "pk")==0 ){
  152396. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  152397. if( zIdx ){
  152398. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  152399. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  152400. );
  152401. }
  152402. break;
  152403. }
  152404. }
  152405. rbuFinalize(p, pXList);
  152406. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  152407. if( sqlite3_column_int(pXInfo, 5) ){
  152408. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  152409. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  152410. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  152411. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  152412. zSep = ", ";
  152413. }
  152414. }
  152415. z = rbuMPrintf(p, "%z)", z);
  152416. rbuFinalize(p, pXInfo);
  152417. }
  152418. return z;
  152419. }
  152420. /*
  152421. ** This function creates the second imposter table used when writing to
  152422. ** a table b-tree where the table has an external primary key. If the
  152423. ** iterator passed as the second argument does not currently point to
  152424. ** a table (not index) with an external primary key, this function is a
  152425. ** no-op.
  152426. **
  152427. ** Assuming the iterator does point to a table with an external PK, this
  152428. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  152429. ** used to access that PK index. For example, if the target table is
  152430. ** declared as follows:
  152431. **
  152432. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  152433. **
  152434. ** then the imposter table schema is:
  152435. **
  152436. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  152437. **
  152438. */
  152439. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  152440. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  152441. int tnum = pIter->iPkTnum; /* Root page of PK index */
  152442. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  152443. const char *zIdx = 0; /* Name of PK index */
  152444. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  152445. const char *zComma = "";
  152446. char *zCols = 0; /* Used to build up list of table cols */
  152447. char *zPk = 0; /* Used to build up table PK declaration */
  152448. /* Figure out the name of the primary key index for the current table.
  152449. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  152450. ** zIdx to point to a nul-terminated string containing this name. */
  152451. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  152452. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  152453. );
  152454. if( p->rc==SQLITE_OK ){
  152455. sqlite3_bind_int(pQuery, 1, tnum);
  152456. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  152457. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  152458. }
  152459. }
  152460. if( zIdx ){
  152461. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  152462. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  152463. );
  152464. }
  152465. rbuFinalize(p, pQuery);
  152466. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  152467. int bKey = sqlite3_column_int(pXInfo, 5);
  152468. if( bKey ){
  152469. int iCid = sqlite3_column_int(pXInfo, 1);
  152470. int bDesc = sqlite3_column_int(pXInfo, 3);
  152471. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  152472. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  152473. iCid, pIter->azTblType[iCid], zCollate
  152474. );
  152475. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  152476. zComma = ", ";
  152477. }
  152478. }
  152479. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  152480. rbuFinalize(p, pXInfo);
  152481. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  152482. rbuMPrintfExec(p, p->dbMain,
  152483. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  152484. zCols, zPk
  152485. );
  152486. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  152487. }
  152488. }
  152489. /*
  152490. ** If an error has already occurred when this function is called, it
  152491. ** immediately returns zero (without doing any work). Or, if an error
  152492. ** occurs during the execution of this function, it sets the error code
  152493. ** in the sqlite3rbu object indicated by the first argument and returns
  152494. ** zero.
  152495. **
  152496. ** The iterator passed as the second argument is guaranteed to point to
  152497. ** a table (not an index) when this function is called. This function
  152498. ** attempts to create any imposter table required to write to the main
  152499. ** table b-tree of the table before returning. Non-zero is returned if
  152500. ** an imposter table are created, or zero otherwise.
  152501. **
  152502. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  152503. ** virtual tables are written to directly. The imposter table has the
  152504. ** same schema as the actual target table (less any UNIQUE constraints).
  152505. ** More precisely, the "same schema" means the same columns, types,
  152506. ** collation sequences. For tables that do not have an external PRIMARY
  152507. ** KEY, it also means the same PRIMARY KEY declaration.
  152508. */
  152509. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  152510. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  152511. int tnum = pIter->iTnum;
  152512. const char *zComma = "";
  152513. char *zSql = 0;
  152514. int iCol;
  152515. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  152516. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  152517. const char *zPk = "";
  152518. const char *zCol = pIter->azTblCol[iCol];
  152519. const char *zColl = 0;
  152520. p->rc = sqlite3_table_column_metadata(
  152521. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  152522. );
  152523. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  152524. /* If the target table column is an "INTEGER PRIMARY KEY", add
  152525. ** "PRIMARY KEY" to the imposter table column declaration. */
  152526. zPk = "PRIMARY KEY ";
  152527. }
  152528. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  152529. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  152530. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  152531. );
  152532. zComma = ", ";
  152533. }
  152534. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  152535. char *zPk = rbuWithoutRowidPK(p, pIter);
  152536. if( zPk ){
  152537. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  152538. }
  152539. }
  152540. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  152541. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  152542. pIter->zTbl, zSql,
  152543. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  152544. );
  152545. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  152546. }
  152547. }
  152548. /*
  152549. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  152550. ** Specifically a statement of the form:
  152551. **
  152552. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  152553. **
  152554. ** The number of bound variables is equal to the number of columns in
  152555. ** the target table, plus one (for the rbu_control column), plus one more
  152556. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  152557. ** virtual table.
  152558. */
  152559. static void rbuObjIterPrepareTmpInsert(
  152560. sqlite3rbu *p,
  152561. RbuObjIter *pIter,
  152562. const char *zCollist,
  152563. const char *zRbuRowid
  152564. ){
  152565. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  152566. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  152567. if( zBind ){
  152568. assert( pIter->pTmpInsert==0 );
  152569. p->rc = prepareFreeAndCollectError(
  152570. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  152571. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  152572. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  152573. ));
  152574. }
  152575. }
  152576. static void rbuTmpInsertFunc(
  152577. sqlite3_context *pCtx,
  152578. int nVal,
  152579. sqlite3_value **apVal
  152580. ){
  152581. sqlite3rbu *p = sqlite3_user_data(pCtx);
  152582. int rc = SQLITE_OK;
  152583. int i;
  152584. assert( sqlite3_value_int(apVal[0])!=0
  152585. || p->objiter.eType==RBU_PK_EXTERNAL
  152586. || p->objiter.eType==RBU_PK_NONE
  152587. );
  152588. if( sqlite3_value_int(apVal[0])!=0 ){
  152589. p->nPhaseOneStep += p->objiter.nIndex;
  152590. }
  152591. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  152592. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  152593. }
  152594. if( rc==SQLITE_OK ){
  152595. sqlite3_step(p->objiter.pTmpInsert);
  152596. rc = sqlite3_reset(p->objiter.pTmpInsert);
  152597. }
  152598. if( rc!=SQLITE_OK ){
  152599. sqlite3_result_error_code(pCtx, rc);
  152600. }
  152601. }
  152602. /*
  152603. ** Ensure that the SQLite statement handles required to update the
  152604. ** target database object currently indicated by the iterator passed
  152605. ** as the second argument are available.
  152606. */
  152607. static int rbuObjIterPrepareAll(
  152608. sqlite3rbu *p,
  152609. RbuObjIter *pIter,
  152610. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  152611. ){
  152612. assert( pIter->bCleanup==0 );
  152613. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  152614. const int tnum = pIter->iTnum;
  152615. char *zCollist = 0; /* List of indexed columns */
  152616. char **pz = &p->zErrmsg;
  152617. const char *zIdx = pIter->zIdx;
  152618. char *zLimit = 0;
  152619. if( nOffset ){
  152620. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  152621. if( !zLimit ) p->rc = SQLITE_NOMEM;
  152622. }
  152623. if( zIdx ){
  152624. const char *zTbl = pIter->zTbl;
  152625. char *zImposterCols = 0; /* Columns for imposter table */
  152626. char *zImposterPK = 0; /* Primary key declaration for imposter */
  152627. char *zWhere = 0; /* WHERE clause on PK columns */
  152628. char *zBind = 0;
  152629. int nBind = 0;
  152630. assert( pIter->eType!=RBU_PK_VTAB );
  152631. zCollist = rbuObjIterGetIndexCols(
  152632. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  152633. );
  152634. zBind = rbuObjIterGetBindlist(p, nBind);
  152635. /* Create the imposter table used to write to this index. */
  152636. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  152637. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  152638. rbuMPrintfExec(p, p->dbMain,
  152639. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  152640. zTbl, zImposterCols, zImposterPK
  152641. );
  152642. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  152643. /* Create the statement to insert index entries */
  152644. pIter->nCol = nBind;
  152645. if( p->rc==SQLITE_OK ){
  152646. p->rc = prepareFreeAndCollectError(
  152647. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  152648. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  152649. );
  152650. }
  152651. /* And to delete index entries */
  152652. if( p->rc==SQLITE_OK ){
  152653. p->rc = prepareFreeAndCollectError(
  152654. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  152655. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  152656. );
  152657. }
  152658. /* Create the SELECT statement to read keys in sorted order */
  152659. if( p->rc==SQLITE_OK ){
  152660. char *zSql;
  152661. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  152662. zSql = sqlite3_mprintf(
  152663. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  152664. zCollist, p->zStateDb, pIter->zDataTbl,
  152665. zCollist, zLimit
  152666. );
  152667. }else{
  152668. zSql = sqlite3_mprintf(
  152669. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  152670. "UNION ALL "
  152671. "SELECT %s, rbu_control FROM '%q' "
  152672. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  152673. "ORDER BY %s%s",
  152674. zCollist, p->zStateDb, pIter->zDataTbl,
  152675. zCollist, pIter->zDataTbl,
  152676. zCollist, zLimit
  152677. );
  152678. }
  152679. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  152680. }
  152681. sqlite3_free(zImposterCols);
  152682. sqlite3_free(zImposterPK);
  152683. sqlite3_free(zWhere);
  152684. sqlite3_free(zBind);
  152685. }else{
  152686. int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
  152687. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  152688. const char *zWrite; /* Imposter table name */
  152689. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  152690. char *zWhere = rbuObjIterGetWhere(p, pIter);
  152691. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  152692. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  152693. zCollist = rbuObjIterGetCollist(p, pIter);
  152694. pIter->nCol = pIter->nTblCol;
  152695. /* Create the imposter table or tables (if required). */
  152696. rbuCreateImposterTable(p, pIter);
  152697. rbuCreateImposterTable2(p, pIter);
  152698. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  152699. /* Create the INSERT statement to write to the target PK b-tree */
  152700. if( p->rc==SQLITE_OK ){
  152701. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  152702. sqlite3_mprintf(
  152703. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  152704. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  152705. )
  152706. );
  152707. }
  152708. /* Create the DELETE statement to write to the target PK b-tree */
  152709. if( p->rc==SQLITE_OK ){
  152710. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  152711. sqlite3_mprintf(
  152712. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  152713. )
  152714. );
  152715. }
  152716. if( pIter->abIndexed ){
  152717. const char *zRbuRowid = "";
  152718. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  152719. zRbuRowid = ", rbu_rowid";
  152720. }
  152721. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  152722. rbuMPrintfExec(p, p->dbRbu,
  152723. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  152724. "SELECT *%s FROM '%q' WHERE 0;"
  152725. , p->zStateDb, pIter->zDataTbl
  152726. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  152727. , pIter->zDataTbl
  152728. );
  152729. rbuMPrintfExec(p, p->dbMain,
  152730. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  152731. "BEGIN "
  152732. " SELECT rbu_tmp_insert(3, %s);"
  152733. "END;"
  152734. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  152735. "BEGIN "
  152736. " SELECT rbu_tmp_insert(3, %s);"
  152737. "END;"
  152738. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  152739. "BEGIN "
  152740. " SELECT rbu_tmp_insert(4, %s);"
  152741. "END;",
  152742. zWrite, zTbl, zOldlist,
  152743. zWrite, zTbl, zOldlist,
  152744. zWrite, zTbl, zNewlist
  152745. );
  152746. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  152747. rbuMPrintfExec(p, p->dbMain,
  152748. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  152749. "BEGIN "
  152750. " SELECT rbu_tmp_insert(0, %s);"
  152751. "END;",
  152752. zWrite, zTbl, zNewlist
  152753. );
  152754. }
  152755. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  152756. }
  152757. /* Create the SELECT statement to read keys from data_xxx */
  152758. if( p->rc==SQLITE_OK ){
  152759. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  152760. sqlite3_mprintf(
  152761. "SELECT %s, rbu_control%s FROM '%q'%s",
  152762. zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
  152763. pIter->zDataTbl, zLimit
  152764. )
  152765. );
  152766. }
  152767. sqlite3_free(zWhere);
  152768. sqlite3_free(zOldlist);
  152769. sqlite3_free(zNewlist);
  152770. sqlite3_free(zBindings);
  152771. }
  152772. sqlite3_free(zCollist);
  152773. sqlite3_free(zLimit);
  152774. }
  152775. return p->rc;
  152776. }
  152777. /*
  152778. ** Set output variable *ppStmt to point to an UPDATE statement that may
  152779. ** be used to update the imposter table for the main table b-tree of the
  152780. ** table object that pIter currently points to, assuming that the
  152781. ** rbu_control column of the data_xyz table contains zMask.
  152782. **
  152783. ** If the zMask string does not specify any columns to update, then this
  152784. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  152785. */
  152786. static int rbuGetUpdateStmt(
  152787. sqlite3rbu *p, /* RBU handle */
  152788. RbuObjIter *pIter, /* Object iterator */
  152789. const char *zMask, /* rbu_control value ('x.x.') */
  152790. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  152791. ){
  152792. RbuUpdateStmt **pp;
  152793. RbuUpdateStmt *pUp = 0;
  152794. int nUp = 0;
  152795. /* In case an error occurs */
  152796. *ppStmt = 0;
  152797. /* Search for an existing statement. If one is found, shift it to the front
  152798. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  152799. ** to the number of statements currently in the cache and pUp to the
  152800. ** last object in the list. */
  152801. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  152802. pUp = *pp;
  152803. if( strcmp(pUp->zMask, zMask)==0 ){
  152804. *pp = pUp->pNext;
  152805. pUp->pNext = pIter->pRbuUpdate;
  152806. pIter->pRbuUpdate = pUp;
  152807. *ppStmt = pUp->pUpdate;
  152808. return SQLITE_OK;
  152809. }
  152810. nUp++;
  152811. }
  152812. assert( pUp==0 || pUp->pNext==0 );
  152813. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  152814. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  152815. *pp = 0;
  152816. sqlite3_finalize(pUp->pUpdate);
  152817. pUp->pUpdate = 0;
  152818. }else{
  152819. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  152820. }
  152821. if( pUp ){
  152822. char *zWhere = rbuObjIterGetWhere(p, pIter);
  152823. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  152824. char *zUpdate = 0;
  152825. pUp->zMask = (char*)&pUp[1];
  152826. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  152827. pUp->pNext = pIter->pRbuUpdate;
  152828. pIter->pRbuUpdate = pUp;
  152829. if( zSet ){
  152830. const char *zPrefix = "";
  152831. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  152832. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  152833. zPrefix, pIter->zTbl, zSet, zWhere
  152834. );
  152835. p->rc = prepareFreeAndCollectError(
  152836. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  152837. );
  152838. *ppStmt = pUp->pUpdate;
  152839. }
  152840. sqlite3_free(zWhere);
  152841. sqlite3_free(zSet);
  152842. }
  152843. return p->rc;
  152844. }
  152845. static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
  152846. sqlite3 *db = 0;
  152847. if( p->rc==SQLITE_OK ){
  152848. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  152849. p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
  152850. if( p->rc ){
  152851. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  152852. sqlite3_close(db);
  152853. db = 0;
  152854. }
  152855. }
  152856. return db;
  152857. }
  152858. /*
  152859. ** Open the database handle and attach the RBU database as "rbu". If an
  152860. ** error occurs, leave an error code and message in the RBU handle.
  152861. */
  152862. static void rbuOpenDatabase(sqlite3rbu *p){
  152863. assert( p->rc==SQLITE_OK );
  152864. assert( p->dbMain==0 && p->dbRbu==0 );
  152865. p->eStage = 0;
  152866. p->dbMain = rbuOpenDbhandle(p, p->zTarget);
  152867. p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
  152868. /* If using separate RBU and state databases, attach the state database to
  152869. ** the RBU db handle now. */
  152870. if( p->zState ){
  152871. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  152872. memcpy(p->zStateDb, "stat", 4);
  152873. }else{
  152874. memcpy(p->zStateDb, "main", 4);
  152875. }
  152876. if( p->rc==SQLITE_OK ){
  152877. p->rc = sqlite3_create_function(p->dbMain,
  152878. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  152879. );
  152880. }
  152881. if( p->rc==SQLITE_OK ){
  152882. p->rc = sqlite3_create_function(p->dbMain,
  152883. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  152884. );
  152885. }
  152886. if( p->rc==SQLITE_OK ){
  152887. p->rc = sqlite3_create_function(p->dbRbu,
  152888. "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  152889. );
  152890. }
  152891. if( p->rc==SQLITE_OK ){
  152892. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  152893. }
  152894. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  152895. /* Mark the database file just opened as an RBU target database. If
  152896. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  152897. ** This is an error. */
  152898. if( p->rc==SQLITE_OK ){
  152899. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  152900. }
  152901. if( p->rc==SQLITE_NOTFOUND ){
  152902. p->rc = SQLITE_ERROR;
  152903. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  152904. }
  152905. }
  152906. /*
  152907. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  152908. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  152909. **
  152910. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  152911. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  152912. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  152913. ** three characters, then shorten the suffix on z[] to be the last three
  152914. ** characters of the original suffix.
  152915. **
  152916. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  152917. ** do the suffix shortening regardless of URI parameter.
  152918. **
  152919. ** Examples:
  152920. **
  152921. ** test.db-journal => test.nal
  152922. ** test.db-wal => test.wal
  152923. ** test.db-shm => test.shm
  152924. ** test.db-mj7f3319fa => test.9fa
  152925. */
  152926. static void rbuFileSuffix3(const char *zBase, char *z){
  152927. #ifdef SQLITE_ENABLE_8_3_NAMES
  152928. #if SQLITE_ENABLE_8_3_NAMES<2
  152929. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  152930. #endif
  152931. {
  152932. int i, sz;
  152933. sz = sqlite3Strlen30(z);
  152934. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  152935. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  152936. }
  152937. #endif
  152938. }
  152939. /*
  152940. ** Return the current wal-index header checksum for the target database
  152941. ** as a 64-bit integer.
  152942. **
  152943. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  152944. ** blob starting at byte offset 40.
  152945. */
  152946. static i64 rbuShmChecksum(sqlite3rbu *p){
  152947. i64 iRet = 0;
  152948. if( p->rc==SQLITE_OK ){
  152949. sqlite3_file *pDb = p->pTargetFd->pReal;
  152950. u32 volatile *ptr;
  152951. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  152952. if( p->rc==SQLITE_OK ){
  152953. iRet = ((i64)ptr[10] << 32) + ptr[11];
  152954. }
  152955. }
  152956. return iRet;
  152957. }
  152958. /*
  152959. ** This function is called as part of initializing or reinitializing an
  152960. ** incremental checkpoint.
  152961. **
  152962. ** It populates the sqlite3rbu.aFrame[] array with the set of
  152963. ** (wal frame -> db page) copy operations required to checkpoint the
  152964. ** current wal file, and obtains the set of shm locks required to safely
  152965. ** perform the copy operations directly on the file-system.
  152966. **
  152967. ** If argument pState is not NULL, then the incremental checkpoint is
  152968. ** being resumed. In this case, if the checksum of the wal-index-header
  152969. ** following recovery is not the same as the checksum saved in the RbuState
  152970. ** object, then the rbu handle is set to DONE state. This occurs if some
  152971. ** other client appends a transaction to the wal file in the middle of
  152972. ** an incremental checkpoint.
  152973. */
  152974. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  152975. /* If pState is NULL, then the wal file may not have been opened and
  152976. ** recovered. Running a read-statement here to ensure that doing so
  152977. ** does not interfere with the "capture" process below. */
  152978. if( pState==0 ){
  152979. p->eStage = 0;
  152980. if( p->rc==SQLITE_OK ){
  152981. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  152982. }
  152983. }
  152984. /* Assuming no error has occurred, run a "restart" checkpoint with the
  152985. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  152986. ** special behaviour in the rbu VFS:
  152987. **
  152988. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  152989. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  152990. ** proceed with running a passive checkpoint instead of failing).
  152991. **
  152992. ** * Attempts to read from the *-wal file or write to the database file
  152993. ** do not perform any IO. Instead, the frame/page combinations that
  152994. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  152995. ** array.
  152996. **
  152997. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  152998. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  152999. ** no-ops. These locks will not be released until the connection
  153000. ** is closed.
  153001. **
  153002. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  153003. ** error.
  153004. **
  153005. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  153006. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  153007. ** array populated with a set of (frame -> page) mappings. Because the
  153008. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  153009. ** data from the wal file into the database file according to the
  153010. ** contents of aFrame[].
  153011. */
  153012. if( p->rc==SQLITE_OK ){
  153013. int rc2;
  153014. p->eStage = RBU_STAGE_CAPTURE;
  153015. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  153016. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  153017. }
  153018. if( p->rc==SQLITE_OK ){
  153019. p->eStage = RBU_STAGE_CKPT;
  153020. p->nStep = (pState ? pState->nRow : 0);
  153021. p->aBuf = rbuMalloc(p, p->pgsz);
  153022. p->iWalCksum = rbuShmChecksum(p);
  153023. }
  153024. if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
  153025. p->rc = SQLITE_DONE;
  153026. p->eStage = RBU_STAGE_DONE;
  153027. }
  153028. }
  153029. /*
  153030. ** Called when iAmt bytes are read from offset iOff of the wal file while
  153031. ** the rbu object is in capture mode. Record the frame number of the frame
  153032. ** being read in the aFrame[] array.
  153033. */
  153034. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  153035. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  153036. u32 iFrame;
  153037. if( pRbu->mLock!=mReq ){
  153038. pRbu->rc = SQLITE_BUSY;
  153039. return SQLITE_INTERNAL;
  153040. }
  153041. pRbu->pgsz = iAmt;
  153042. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  153043. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  153044. RbuFrame *aNew;
  153045. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  153046. if( aNew==0 ) return SQLITE_NOMEM;
  153047. pRbu->aFrame = aNew;
  153048. pRbu->nFrameAlloc = nNew;
  153049. }
  153050. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  153051. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  153052. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  153053. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  153054. pRbu->nFrame++;
  153055. return SQLITE_OK;
  153056. }
  153057. /*
  153058. ** Called when a page of data is written to offset iOff of the database
  153059. ** file while the rbu handle is in capture mode. Record the page number
  153060. ** of the page being written in the aFrame[] array.
  153061. */
  153062. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  153063. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  153064. return SQLITE_OK;
  153065. }
  153066. /*
  153067. ** This is called as part of an incremental checkpoint operation. Copy
  153068. ** a single frame of data from the wal file into the database file, as
  153069. ** indicated by the RbuFrame object.
  153070. */
  153071. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  153072. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  153073. sqlite3_file *pDb = p->pTargetFd->pReal;
  153074. i64 iOff;
  153075. assert( p->rc==SQLITE_OK );
  153076. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  153077. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  153078. if( p->rc ) return;
  153079. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  153080. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  153081. }
  153082. /*
  153083. ** Take an EXCLUSIVE lock on the database file.
  153084. */
  153085. static void rbuLockDatabase(sqlite3rbu *p){
  153086. sqlite3_file *pReal = p->pTargetFd->pReal;
  153087. assert( p->rc==SQLITE_OK );
  153088. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  153089. if( p->rc==SQLITE_OK ){
  153090. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  153091. }
  153092. }
  153093. #if defined(_WIN32_WCE)
  153094. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  153095. int nChar;
  153096. LPWSTR zWideFilename;
  153097. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  153098. if( nChar==0 ){
  153099. return 0;
  153100. }
  153101. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  153102. if( zWideFilename==0 ){
  153103. return 0;
  153104. }
  153105. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  153106. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  153107. nChar);
  153108. if( nChar==0 ){
  153109. sqlite3_free(zWideFilename);
  153110. zWideFilename = 0;
  153111. }
  153112. return zWideFilename;
  153113. }
  153114. #endif
  153115. /*
  153116. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  153117. ** on the database file. This proc moves the *-oal file to the *-wal path,
  153118. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  153119. ** If an error occurs, leave an error code and error message in the rbu
  153120. ** handle.
  153121. */
  153122. static void rbuMoveOalFile(sqlite3rbu *p){
  153123. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  153124. char *zWal = sqlite3_mprintf("%s-wal", zBase);
  153125. char *zOal = sqlite3_mprintf("%s-oal", zBase);
  153126. assert( p->eStage==RBU_STAGE_MOVE );
  153127. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  153128. if( zWal==0 || zOal==0 ){
  153129. p->rc = SQLITE_NOMEM;
  153130. }else{
  153131. /* Move the *-oal file to *-wal. At this point connection p->db is
  153132. ** holding a SHARED lock on the target database file (because it is
  153133. ** in WAL mode). So no other connection may be writing the db.
  153134. **
  153135. ** In order to ensure that there are no database readers, an EXCLUSIVE
  153136. ** lock is obtained here before the *-oal is moved to *-wal.
  153137. */
  153138. rbuLockDatabase(p);
  153139. if( p->rc==SQLITE_OK ){
  153140. rbuFileSuffix3(zBase, zWal);
  153141. rbuFileSuffix3(zBase, zOal);
  153142. /* Re-open the databases. */
  153143. rbuObjIterFinalize(&p->objiter);
  153144. sqlite3_close(p->dbMain);
  153145. sqlite3_close(p->dbRbu);
  153146. p->dbMain = 0;
  153147. p->dbRbu = 0;
  153148. #if defined(_WIN32_WCE)
  153149. {
  153150. LPWSTR zWideOal;
  153151. LPWSTR zWideWal;
  153152. zWideOal = rbuWinUtf8ToUnicode(zOal);
  153153. if( zWideOal ){
  153154. zWideWal = rbuWinUtf8ToUnicode(zWal);
  153155. if( zWideWal ){
  153156. if( MoveFileW(zWideOal, zWideWal) ){
  153157. p->rc = SQLITE_OK;
  153158. }else{
  153159. p->rc = SQLITE_IOERR;
  153160. }
  153161. sqlite3_free(zWideWal);
  153162. }else{
  153163. p->rc = SQLITE_IOERR_NOMEM;
  153164. }
  153165. sqlite3_free(zWideOal);
  153166. }else{
  153167. p->rc = SQLITE_IOERR_NOMEM;
  153168. }
  153169. }
  153170. #else
  153171. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  153172. #endif
  153173. if( p->rc==SQLITE_OK ){
  153174. rbuOpenDatabase(p);
  153175. rbuSetupCheckpoint(p, 0);
  153176. }
  153177. }
  153178. }
  153179. sqlite3_free(zWal);
  153180. sqlite3_free(zOal);
  153181. }
  153182. /*
  153183. ** The SELECT statement iterating through the keys for the current object
  153184. ** (p->objiter.pSelect) currently points to a valid row. This function
  153185. ** determines the type of operation requested by this row and returns
  153186. ** one of the following values to indicate the result:
  153187. **
  153188. ** * RBU_INSERT
  153189. ** * RBU_DELETE
  153190. ** * RBU_IDX_DELETE
  153191. ** * RBU_UPDATE
  153192. **
  153193. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  153194. ** point to the text value indicating the columns to update.
  153195. **
  153196. ** If the rbu_control field contains an invalid value, an error code and
  153197. ** message are left in the RBU handle and zero returned.
  153198. */
  153199. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  153200. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  153201. int res = 0; /* Return value */
  153202. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  153203. case SQLITE_INTEGER: {
  153204. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  153205. switch( iVal ){
  153206. case 0: res = RBU_INSERT; break;
  153207. case 1: res = RBU_DELETE; break;
  153208. case 2: res = RBU_REPLACE; break;
  153209. case 3: res = RBU_IDX_DELETE; break;
  153210. case 4: res = RBU_IDX_INSERT; break;
  153211. }
  153212. break;
  153213. }
  153214. case SQLITE_TEXT: {
  153215. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  153216. if( z==0 ){
  153217. p->rc = SQLITE_NOMEM;
  153218. }else{
  153219. *pzMask = (const char*)z;
  153220. }
  153221. res = RBU_UPDATE;
  153222. break;
  153223. }
  153224. default:
  153225. break;
  153226. }
  153227. if( res==0 ){
  153228. rbuBadControlError(p);
  153229. }
  153230. return res;
  153231. }
  153232. #ifdef SQLITE_DEBUG
  153233. /*
  153234. ** Assert that column iCol of statement pStmt is named zName.
  153235. */
  153236. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  153237. const char *zCol = sqlite3_column_name(pStmt, iCol);
  153238. assert( 0==sqlite3_stricmp(zName, zCol) );
  153239. }
  153240. #else
  153241. # define assertColumnName(x,y,z)
  153242. #endif
  153243. /*
  153244. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  153245. ** RBU_IDX_DELETE. This function performs the work of a single
  153246. ** sqlite3rbu_step() call for the type of operation specified by eType.
  153247. */
  153248. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  153249. RbuObjIter *pIter = &p->objiter;
  153250. sqlite3_value *pVal;
  153251. sqlite3_stmt *pWriter;
  153252. int i;
  153253. assert( p->rc==SQLITE_OK );
  153254. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  153255. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  153256. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  153257. );
  153258. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  153259. ** statement below does actually delete a row, nPhaseOneStep will be
  153260. ** incremented by the same amount when SQL function rbu_tmp_insert()
  153261. ** is invoked by the trigger. */
  153262. if( eType==RBU_DELETE ){
  153263. p->nPhaseOneStep -= p->objiter.nIndex;
  153264. }
  153265. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  153266. pWriter = pIter->pDelete;
  153267. }else{
  153268. pWriter = pIter->pInsert;
  153269. }
  153270. for(i=0; i<pIter->nCol; i++){
  153271. /* If this is an INSERT into a table b-tree and the table has an
  153272. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  153273. ** to write a NULL into the IPK column. That is not permitted. */
  153274. if( eType==RBU_INSERT
  153275. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  153276. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  153277. ){
  153278. p->rc = SQLITE_MISMATCH;
  153279. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  153280. return;
  153281. }
  153282. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  153283. continue;
  153284. }
  153285. pVal = sqlite3_column_value(pIter->pSelect, i);
  153286. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  153287. if( p->rc ) return;
  153288. }
  153289. if( pIter->zIdx==0
  153290. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  153291. ){
  153292. /* For a virtual table, or a table with no primary key, the
  153293. ** SELECT statement is:
  153294. **
  153295. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  153296. **
  153297. ** Hence column_value(pIter->nCol+1).
  153298. */
  153299. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  153300. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  153301. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  153302. }
  153303. if( p->rc==SQLITE_OK ){
  153304. sqlite3_step(pWriter);
  153305. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  153306. }
  153307. }
  153308. /*
  153309. ** This function does the work for an sqlite3rbu_step() call.
  153310. **
  153311. ** The object-iterator (p->objiter) currently points to a valid object,
  153312. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  153313. ** input row. Perform whatever processing is required and return.
  153314. **
  153315. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  153316. ** and message is left in the RBU handle and a copy of the error code
  153317. ** returned.
  153318. */
  153319. static int rbuStep(sqlite3rbu *p){
  153320. RbuObjIter *pIter = &p->objiter;
  153321. const char *zMask = 0;
  153322. int eType = rbuStepType(p, &zMask);
  153323. if( eType ){
  153324. assert( eType==RBU_INSERT || eType==RBU_DELETE
  153325. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  153326. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  153327. );
  153328. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  153329. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  153330. rbuBadControlError(p);
  153331. }
  153332. else if( eType==RBU_REPLACE ){
  153333. if( pIter->zIdx==0 ){
  153334. p->nPhaseOneStep += p->objiter.nIndex;
  153335. rbuStepOneOp(p, RBU_DELETE);
  153336. }
  153337. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  153338. }
  153339. else if( eType!=RBU_UPDATE ){
  153340. rbuStepOneOp(p, eType);
  153341. }
  153342. else{
  153343. sqlite3_value *pVal;
  153344. sqlite3_stmt *pUpdate = 0;
  153345. assert( eType==RBU_UPDATE );
  153346. p->nPhaseOneStep -= p->objiter.nIndex;
  153347. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  153348. if( pUpdate ){
  153349. int i;
  153350. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  153351. char c = zMask[pIter->aiSrcOrder[i]];
  153352. pVal = sqlite3_column_value(pIter->pSelect, i);
  153353. if( pIter->abTblPk[i] || c!='.' ){
  153354. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  153355. }
  153356. }
  153357. if( p->rc==SQLITE_OK
  153358. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  153359. ){
  153360. /* Bind the rbu_rowid value to column _rowid_ */
  153361. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  153362. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  153363. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  153364. }
  153365. if( p->rc==SQLITE_OK ){
  153366. sqlite3_step(pUpdate);
  153367. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  153368. }
  153369. }
  153370. }
  153371. }
  153372. return p->rc;
  153373. }
  153374. /*
  153375. ** Increment the schema cookie of the main database opened by p->dbMain.
  153376. */
  153377. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  153378. if( p->rc==SQLITE_OK ){
  153379. int iCookie = 1000000;
  153380. sqlite3_stmt *pStmt;
  153381. p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  153382. "PRAGMA schema_version"
  153383. );
  153384. if( p->rc==SQLITE_OK ){
  153385. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  153386. ** is already a transaction open, so the prepared statement cannot
  153387. ** throw an SQLITE_SCHEMA exception. The only database page the
  153388. ** statement reads is page 1, which is guaranteed to be in the cache.
  153389. ** And no memory allocations are required. */
  153390. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  153391. iCookie = sqlite3_column_int(pStmt, 0);
  153392. }
  153393. rbuFinalize(p, pStmt);
  153394. }
  153395. if( p->rc==SQLITE_OK ){
  153396. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  153397. }
  153398. }
  153399. }
  153400. /*
  153401. ** Update the contents of the rbu_state table within the rbu database. The
  153402. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  153403. ** are determined by inspecting the rbu handle passed as the first argument.
  153404. */
  153405. static void rbuSaveState(sqlite3rbu *p, int eStage){
  153406. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  153407. sqlite3_stmt *pInsert = 0;
  153408. int rc;
  153409. assert( p->zErrmsg==0 );
  153410. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  153411. sqlite3_mprintf(
  153412. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  153413. "(%d, %d), "
  153414. "(%d, %Q), "
  153415. "(%d, %Q), "
  153416. "(%d, %d), "
  153417. "(%d, %d), "
  153418. "(%d, %lld), "
  153419. "(%d, %lld), "
  153420. "(%d, %lld), "
  153421. "(%d, %lld) ",
  153422. p->zStateDb,
  153423. RBU_STATE_STAGE, eStage,
  153424. RBU_STATE_TBL, p->objiter.zTbl,
  153425. RBU_STATE_IDX, p->objiter.zIdx,
  153426. RBU_STATE_ROW, p->nStep,
  153427. RBU_STATE_PROGRESS, p->nProgress,
  153428. RBU_STATE_CKPT, p->iWalCksum,
  153429. RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
  153430. RBU_STATE_OALSZ, p->iOalSz,
  153431. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
  153432. )
  153433. );
  153434. assert( pInsert==0 || rc==SQLITE_OK );
  153435. if( rc==SQLITE_OK ){
  153436. sqlite3_step(pInsert);
  153437. rc = sqlite3_finalize(pInsert);
  153438. }
  153439. if( rc!=SQLITE_OK ) p->rc = rc;
  153440. }
  153441. }
  153442. /*
  153443. ** Step the RBU object.
  153444. */
  153445. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
  153446. if( p ){
  153447. switch( p->eStage ){
  153448. case RBU_STAGE_OAL: {
  153449. RbuObjIter *pIter = &p->objiter;
  153450. while( p->rc==SQLITE_OK && pIter->zTbl ){
  153451. if( pIter->bCleanup ){
  153452. /* Clean up the rbu_tmp_xxx table for the previous table. It
  153453. ** cannot be dropped as there are currently active SQL statements.
  153454. ** But the contents can be deleted. */
  153455. if( pIter->abIndexed ){
  153456. rbuMPrintfExec(p, p->dbRbu,
  153457. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  153458. );
  153459. }
  153460. }else{
  153461. rbuObjIterPrepareAll(p, pIter, 0);
  153462. /* Advance to the next row to process. */
  153463. if( p->rc==SQLITE_OK ){
  153464. int rc = sqlite3_step(pIter->pSelect);
  153465. if( rc==SQLITE_ROW ){
  153466. p->nProgress++;
  153467. p->nStep++;
  153468. return rbuStep(p);
  153469. }
  153470. p->rc = sqlite3_reset(pIter->pSelect);
  153471. p->nStep = 0;
  153472. }
  153473. }
  153474. rbuObjIterNext(p, pIter);
  153475. }
  153476. if( p->rc==SQLITE_OK ){
  153477. assert( pIter->zTbl==0 );
  153478. rbuSaveState(p, RBU_STAGE_MOVE);
  153479. rbuIncrSchemaCookie(p);
  153480. if( p->rc==SQLITE_OK ){
  153481. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  153482. }
  153483. if( p->rc==SQLITE_OK ){
  153484. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  153485. }
  153486. p->eStage = RBU_STAGE_MOVE;
  153487. }
  153488. break;
  153489. }
  153490. case RBU_STAGE_MOVE: {
  153491. if( p->rc==SQLITE_OK ){
  153492. rbuMoveOalFile(p);
  153493. p->nProgress++;
  153494. }
  153495. break;
  153496. }
  153497. case RBU_STAGE_CKPT: {
  153498. if( p->rc==SQLITE_OK ){
  153499. if( p->nStep>=p->nFrame ){
  153500. sqlite3_file *pDb = p->pTargetFd->pReal;
  153501. /* Sync the db file */
  153502. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  153503. /* Update nBackfill */
  153504. if( p->rc==SQLITE_OK ){
  153505. void volatile *ptr;
  153506. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  153507. if( p->rc==SQLITE_OK ){
  153508. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  153509. }
  153510. }
  153511. if( p->rc==SQLITE_OK ){
  153512. p->eStage = RBU_STAGE_DONE;
  153513. p->rc = SQLITE_DONE;
  153514. }
  153515. }else{
  153516. RbuFrame *pFrame = &p->aFrame[p->nStep];
  153517. rbuCheckpointFrame(p, pFrame);
  153518. p->nStep++;
  153519. }
  153520. p->nProgress++;
  153521. }
  153522. break;
  153523. }
  153524. default:
  153525. break;
  153526. }
  153527. return p->rc;
  153528. }else{
  153529. return SQLITE_NOMEM;
  153530. }
  153531. }
  153532. /*
  153533. ** Free an RbuState object allocated by rbuLoadState().
  153534. */
  153535. static void rbuFreeState(RbuState *p){
  153536. if( p ){
  153537. sqlite3_free(p->zTbl);
  153538. sqlite3_free(p->zIdx);
  153539. sqlite3_free(p);
  153540. }
  153541. }
  153542. /*
  153543. ** Allocate an RbuState object and load the contents of the rbu_state
  153544. ** table into it. Return a pointer to the new object. It is the
  153545. ** responsibility of the caller to eventually free the object using
  153546. ** sqlite3_free().
  153547. **
  153548. ** If an error occurs, leave an error code and message in the rbu handle
  153549. ** and return NULL.
  153550. */
  153551. static RbuState *rbuLoadState(sqlite3rbu *p){
  153552. RbuState *pRet = 0;
  153553. sqlite3_stmt *pStmt = 0;
  153554. int rc;
  153555. int rc2;
  153556. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  153557. if( pRet==0 ) return 0;
  153558. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  153559. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  153560. );
  153561. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  153562. switch( sqlite3_column_int(pStmt, 0) ){
  153563. case RBU_STATE_STAGE:
  153564. pRet->eStage = sqlite3_column_int(pStmt, 1);
  153565. if( pRet->eStage!=RBU_STAGE_OAL
  153566. && pRet->eStage!=RBU_STAGE_MOVE
  153567. && pRet->eStage!=RBU_STAGE_CKPT
  153568. ){
  153569. p->rc = SQLITE_CORRUPT;
  153570. }
  153571. break;
  153572. case RBU_STATE_TBL:
  153573. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  153574. break;
  153575. case RBU_STATE_IDX:
  153576. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  153577. break;
  153578. case RBU_STATE_ROW:
  153579. pRet->nRow = sqlite3_column_int(pStmt, 1);
  153580. break;
  153581. case RBU_STATE_PROGRESS:
  153582. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  153583. break;
  153584. case RBU_STATE_CKPT:
  153585. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  153586. break;
  153587. case RBU_STATE_COOKIE:
  153588. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  153589. break;
  153590. case RBU_STATE_OALSZ:
  153591. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  153592. break;
  153593. case RBU_STATE_PHASEONESTEP:
  153594. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  153595. break;
  153596. default:
  153597. rc = SQLITE_CORRUPT;
  153598. break;
  153599. }
  153600. }
  153601. rc2 = sqlite3_finalize(pStmt);
  153602. if( rc==SQLITE_OK ) rc = rc2;
  153603. p->rc = rc;
  153604. return pRet;
  153605. }
  153606. /*
  153607. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  153608. ** otherwise. Either or both argument may be NULL. Two NULL values are
  153609. ** considered equal, and NULL is considered distinct from all other values.
  153610. */
  153611. static int rbuStrCompare(const char *z1, const char *z2){
  153612. if( z1==0 && z2==0 ) return 0;
  153613. if( z1==0 || z2==0 ) return 1;
  153614. return (sqlite3_stricmp(z1, z2)!=0);
  153615. }
  153616. /*
  153617. ** This function is called as part of sqlite3rbu_open() when initializing
  153618. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  153619. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  153620. ** things so that the next call to sqlite3rbu_step() continues on from
  153621. ** where the previous rbu handle left off.
  153622. **
  153623. ** If an error occurs, an error code and error message are left in the
  153624. ** rbu handle passed as the first argument.
  153625. */
  153626. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  153627. assert( p->rc==SQLITE_OK );
  153628. if( pState->zTbl ){
  153629. RbuObjIter *pIter = &p->objiter;
  153630. int rc = SQLITE_OK;
  153631. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  153632. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  153633. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  153634. )){
  153635. rc = rbuObjIterNext(p, pIter);
  153636. }
  153637. if( rc==SQLITE_OK && !pIter->zTbl ){
  153638. rc = SQLITE_ERROR;
  153639. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  153640. }
  153641. if( rc==SQLITE_OK ){
  153642. p->nStep = pState->nRow;
  153643. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  153644. }
  153645. p->rc = rc;
  153646. }
  153647. }
  153648. /*
  153649. ** If there is a "*-oal" file in the file-system corresponding to the
  153650. ** target database in the file-system, delete it. If an error occurs,
  153651. ** leave an error code and error message in the rbu handle.
  153652. */
  153653. static void rbuDeleteOalFile(sqlite3rbu *p){
  153654. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  153655. if( zOal ){
  153656. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  153657. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  153658. pVfs->xDelete(pVfs, zOal, 0);
  153659. sqlite3_free(zOal);
  153660. }
  153661. }
  153662. /*
  153663. ** Allocate a private rbu VFS for the rbu handle passed as the only
  153664. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  153665. ** specified a URI with a vfs=? option in place of a target database
  153666. ** file name.
  153667. */
  153668. static void rbuCreateVfs(sqlite3rbu *p){
  153669. int rnd;
  153670. char zRnd[64];
  153671. assert( p->rc==SQLITE_OK );
  153672. sqlite3_randomness(sizeof(int), (void*)&rnd);
  153673. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  153674. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  153675. if( p->rc==SQLITE_OK ){
  153676. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  153677. assert( pVfs );
  153678. p->zVfsName = pVfs->zName;
  153679. }
  153680. }
  153681. /*
  153682. ** Destroy the private VFS created for the rbu handle passed as the only
  153683. ** argument by an earlier call to rbuCreateVfs().
  153684. */
  153685. static void rbuDeleteVfs(sqlite3rbu *p){
  153686. if( p->zVfsName ){
  153687. sqlite3rbu_destroy_vfs(p->zVfsName);
  153688. p->zVfsName = 0;
  153689. }
  153690. }
  153691. /*
  153692. ** This user-defined SQL function is invoked with a single argument - the
  153693. ** name of a table expected to appear in the target database. It returns
  153694. ** the number of auxilliary indexes on the table.
  153695. */
  153696. static void rbuIndexCntFunc(
  153697. sqlite3_context *pCtx,
  153698. int nVal,
  153699. sqlite3_value **apVal
  153700. ){
  153701. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  153702. sqlite3_stmt *pStmt = 0;
  153703. char *zErrmsg = 0;
  153704. int rc;
  153705. assert( nVal==1 );
  153706. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  153707. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  153708. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  153709. );
  153710. if( rc!=SQLITE_OK ){
  153711. sqlite3_result_error(pCtx, zErrmsg, -1);
  153712. }else{
  153713. int nIndex = 0;
  153714. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  153715. nIndex = sqlite3_column_int(pStmt, 0);
  153716. }
  153717. rc = sqlite3_finalize(pStmt);
  153718. if( rc==SQLITE_OK ){
  153719. sqlite3_result_int(pCtx, nIndex);
  153720. }else{
  153721. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  153722. }
  153723. }
  153724. sqlite3_free(zErrmsg);
  153725. }
  153726. /*
  153727. ** If the RBU database contains the rbu_count table, use it to initialize
  153728. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  153729. ** is assumed to contain the same columns as:
  153730. **
  153731. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  153732. **
  153733. ** There should be one row in the table for each data_xxx table in the
  153734. ** database. The 'tbl' column should contain the name of a data_xxx table,
  153735. ** and the cnt column the number of rows it contains.
  153736. **
  153737. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  153738. ** for all rows in the rbu_count table, where nIndex is the number of
  153739. ** indexes on the corresponding target database table.
  153740. */
  153741. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  153742. if( p->rc==SQLITE_OK ){
  153743. sqlite3_stmt *pStmt = 0;
  153744. int bExists = 0; /* True if rbu_count exists */
  153745. p->nPhaseOneStep = -1;
  153746. p->rc = sqlite3_create_function(p->dbRbu,
  153747. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  153748. );
  153749. /* Check for the rbu_count table. If it does not exist, or if an error
  153750. ** occurs, nPhaseOneStep will be left set to -1. */
  153751. if( p->rc==SQLITE_OK ){
  153752. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  153753. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  153754. );
  153755. }
  153756. if( p->rc==SQLITE_OK ){
  153757. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  153758. bExists = 1;
  153759. }
  153760. p->rc = sqlite3_finalize(pStmt);
  153761. }
  153762. if( p->rc==SQLITE_OK && bExists ){
  153763. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  153764. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  153765. "FROM rbu_count"
  153766. );
  153767. if( p->rc==SQLITE_OK ){
  153768. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  153769. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  153770. }
  153771. p->rc = sqlite3_finalize(pStmt);
  153772. }
  153773. }
  153774. }
  153775. }
  153776. /*
  153777. ** Open and return a new RBU handle.
  153778. */
  153779. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  153780. const char *zTarget,
  153781. const char *zRbu,
  153782. const char *zState
  153783. ){
  153784. sqlite3rbu *p;
  153785. size_t nTarget = strlen(zTarget);
  153786. size_t nRbu = strlen(zRbu);
  153787. size_t nState = zState ? strlen(zState) : 0;
  153788. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
  153789. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  153790. if( p ){
  153791. RbuState *pState = 0;
  153792. /* Create the custom VFS. */
  153793. memset(p, 0, sizeof(sqlite3rbu));
  153794. rbuCreateVfs(p);
  153795. /* Open the target database */
  153796. if( p->rc==SQLITE_OK ){
  153797. p->zTarget = (char*)&p[1];
  153798. memcpy(p->zTarget, zTarget, nTarget+1);
  153799. p->zRbu = &p->zTarget[nTarget+1];
  153800. memcpy(p->zRbu, zRbu, nRbu+1);
  153801. if( zState ){
  153802. p->zState = &p->zRbu[nRbu+1];
  153803. memcpy(p->zState, zState, nState+1);
  153804. }
  153805. rbuOpenDatabase(p);
  153806. }
  153807. /* If it has not already been created, create the rbu_state table */
  153808. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  153809. if( p->rc==SQLITE_OK ){
  153810. pState = rbuLoadState(p);
  153811. assert( pState || p->rc!=SQLITE_OK );
  153812. if( p->rc==SQLITE_OK ){
  153813. if( pState->eStage==0 ){
  153814. rbuDeleteOalFile(p);
  153815. rbuInitPhaseOneSteps(p);
  153816. p->eStage = RBU_STAGE_OAL;
  153817. }else{
  153818. p->eStage = pState->eStage;
  153819. p->nPhaseOneStep = pState->nPhaseOneStep;
  153820. }
  153821. p->nProgress = pState->nProgress;
  153822. p->iOalSz = pState->iOalSz;
  153823. }
  153824. }
  153825. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  153826. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  153827. if( p->eStage==RBU_STAGE_OAL ){
  153828. p->rc = SQLITE_ERROR;
  153829. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  153830. }else if( p->eStage==RBU_STAGE_MOVE ){
  153831. p->eStage = RBU_STAGE_CKPT;
  153832. p->nStep = 0;
  153833. }
  153834. }
  153835. if( p->rc==SQLITE_OK
  153836. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  153837. && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
  153838. ){
  153839. /* At this point (pTargetFd->iCookie) contains the value of the
  153840. ** change-counter cookie (the thing that gets incremented when a
  153841. ** transaction is committed in rollback mode) currently stored on
  153842. ** page 1 of the database file. */
  153843. p->rc = SQLITE_BUSY;
  153844. p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
  153845. }
  153846. if( p->rc==SQLITE_OK ){
  153847. if( p->eStage==RBU_STAGE_OAL ){
  153848. sqlite3 *db = p->dbMain;
  153849. /* Open transactions both databases. The *-oal file is opened or
  153850. ** created at this point. */
  153851. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  153852. if( p->rc==SQLITE_OK ){
  153853. p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  153854. }
  153855. /* Check if the main database is a zipvfs db. If it is, set the upper
  153856. ** level pager to use "journal_mode=off". This prevents it from
  153857. ** generating a large journal using a temp file. */
  153858. if( p->rc==SQLITE_OK ){
  153859. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  153860. if( frc==SQLITE_OK ){
  153861. p->rc = sqlite3_exec(db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  153862. }
  153863. }
  153864. /* Point the object iterator at the first object */
  153865. if( p->rc==SQLITE_OK ){
  153866. p->rc = rbuObjIterFirst(p, &p->objiter);
  153867. }
  153868. /* If the RBU database contains no data_xxx tables, declare the RBU
  153869. ** update finished. */
  153870. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  153871. p->rc = SQLITE_DONE;
  153872. }
  153873. if( p->rc==SQLITE_OK ){
  153874. rbuSetupOal(p, pState);
  153875. }
  153876. }else if( p->eStage==RBU_STAGE_MOVE ){
  153877. /* no-op */
  153878. }else if( p->eStage==RBU_STAGE_CKPT ){
  153879. rbuSetupCheckpoint(p, pState);
  153880. }else if( p->eStage==RBU_STAGE_DONE ){
  153881. p->rc = SQLITE_DONE;
  153882. }else{
  153883. p->rc = SQLITE_CORRUPT;
  153884. }
  153885. }
  153886. rbuFreeState(pState);
  153887. }
  153888. return p;
  153889. }
  153890. /*
  153891. ** Return the database handle used by pRbu.
  153892. */
  153893. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  153894. sqlite3 *db = 0;
  153895. if( pRbu ){
  153896. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  153897. }
  153898. return db;
  153899. }
  153900. /*
  153901. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  153902. ** then edit any error message string so as to remove all occurrences of
  153903. ** the pattern "rbu_imp_[0-9]*".
  153904. */
  153905. static void rbuEditErrmsg(sqlite3rbu *p){
  153906. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  153907. int i;
  153908. size_t nErrmsg = strlen(p->zErrmsg);
  153909. for(i=0; i<(nErrmsg-8); i++){
  153910. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  153911. int nDel = 8;
  153912. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  153913. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  153914. nErrmsg -= nDel;
  153915. }
  153916. }
  153917. }
  153918. }
  153919. /*
  153920. ** Close the RBU handle.
  153921. */
  153922. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  153923. int rc;
  153924. if( p ){
  153925. /* Commit the transaction to the *-oal file. */
  153926. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  153927. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  153928. }
  153929. rbuSaveState(p, p->eStage);
  153930. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  153931. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  153932. }
  153933. /* Close any open statement handles. */
  153934. rbuObjIterFinalize(&p->objiter);
  153935. /* Close the open database handle and VFS object. */
  153936. sqlite3_close(p->dbMain);
  153937. sqlite3_close(p->dbRbu);
  153938. rbuDeleteVfs(p);
  153939. sqlite3_free(p->aBuf);
  153940. sqlite3_free(p->aFrame);
  153941. rbuEditErrmsg(p);
  153942. rc = p->rc;
  153943. *pzErrmsg = p->zErrmsg;
  153944. sqlite3_free(p);
  153945. }else{
  153946. rc = SQLITE_NOMEM;
  153947. *pzErrmsg = 0;
  153948. }
  153949. return rc;
  153950. }
  153951. /*
  153952. ** Return the total number of key-value operations (inserts, deletes or
  153953. ** updates) that have been performed on the target database since the
  153954. ** current RBU update was started.
  153955. */
  153956. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
  153957. return pRbu->nProgress;
  153958. }
  153959. /*
  153960. ** Return permyriadage progress indications for the two main stages of
  153961. ** an RBU update.
  153962. */
  153963. SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  153964. const int MAX_PROGRESS = 10000;
  153965. switch( p->eStage ){
  153966. case RBU_STAGE_OAL:
  153967. if( p->nPhaseOneStep>0 ){
  153968. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  153969. }else{
  153970. *pnOne = -1;
  153971. }
  153972. *pnTwo = 0;
  153973. break;
  153974. case RBU_STAGE_MOVE:
  153975. *pnOne = MAX_PROGRESS;
  153976. *pnTwo = 0;
  153977. break;
  153978. case RBU_STAGE_CKPT:
  153979. *pnOne = MAX_PROGRESS;
  153980. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  153981. break;
  153982. case RBU_STAGE_DONE:
  153983. *pnOne = MAX_PROGRESS;
  153984. *pnTwo = MAX_PROGRESS;
  153985. break;
  153986. default:
  153987. assert( 0 );
  153988. }
  153989. }
  153990. SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
  153991. int rc = p->rc;
  153992. if( rc==SQLITE_DONE ) return SQLITE_OK;
  153993. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  153994. if( p->eStage==RBU_STAGE_OAL ){
  153995. assert( rc!=SQLITE_DONE );
  153996. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  153997. }
  153998. p->rc = rc;
  153999. rbuSaveState(p, p->eStage);
  154000. rc = p->rc;
  154001. if( p->eStage==RBU_STAGE_OAL ){
  154002. assert( rc!=SQLITE_DONE );
  154003. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  154004. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  154005. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  154006. }
  154007. p->rc = rc;
  154008. return rc;
  154009. }
  154010. /**************************************************************************
  154011. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  154012. ** of a standard VFS in the following ways:
  154013. **
  154014. ** 1. Whenever the first page of a main database file is read or
  154015. ** written, the value of the change-counter cookie is stored in
  154016. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  154017. ** database header field is stored in rbu_file.iWriteVer. This ensures
  154018. ** that the values are always trustworthy within an open transaction.
  154019. **
  154020. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  154021. ** member variable of the associated database file descriptor is set
  154022. ** to point to the new file. A mutex protected linked list of all main
  154023. ** db fds opened using a particular RBU VFS is maintained at
  154024. ** rbu_vfs.pMain to facilitate this.
  154025. **
  154026. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  154027. ** object can be marked as the target database of an RBU update. This
  154028. ** turns on the following extra special behaviour:
  154029. **
  154030. ** 3a. If xAccess() is called to check if there exists a *-wal file
  154031. ** associated with an RBU target database currently in RBU_STAGE_OAL
  154032. ** stage (preparing the *-oal file), the following special handling
  154033. ** applies:
  154034. **
  154035. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  154036. ** target database may not be in wal mode already.
  154037. **
  154038. ** * if the *-wal file does not exist, set the output parameter to
  154039. ** non-zero (to tell SQLite that it does exist) anyway.
  154040. **
  154041. ** Then, when xOpen() is called to open the *-wal file associated with
  154042. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  154043. ** file, the rbu vfs opens the corresponding *-oal file instead.
  154044. **
  154045. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  154046. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  154047. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  154048. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  154049. ** because assert() statements in some VFS implementations fail if
  154050. ** xShmLock() is called before xShmMap().
  154051. **
  154052. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  154053. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  154054. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  154055. ** from automatically checkpointing a *-wal (or *-oal) file from within
  154056. ** sqlite3_close().
  154057. **
  154058. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  154059. ** all xWrite() calls on the target database file perform no IO.
  154060. ** Instead the frame and page numbers that would be read and written
  154061. ** are recorded. Additionally, successful attempts to obtain exclusive
  154062. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  154063. ** database file are recorded. xShmLock() calls to unlock the same
  154064. ** locks are no-ops (so that once obtained, these locks are never
  154065. ** relinquished). Finally, calls to xSync() on the target database
  154066. ** file fail with SQLITE_INTERNAL errors.
  154067. */
  154068. static void rbuUnlockShm(rbu_file *p){
  154069. if( p->pRbu ){
  154070. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  154071. int i;
  154072. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  154073. if( (1<<i) & p->pRbu->mLock ){
  154074. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  154075. }
  154076. }
  154077. p->pRbu->mLock = 0;
  154078. }
  154079. }
  154080. /*
  154081. ** Close an rbu file.
  154082. */
  154083. static int rbuVfsClose(sqlite3_file *pFile){
  154084. rbu_file *p = (rbu_file*)pFile;
  154085. int rc;
  154086. int i;
  154087. /* Free the contents of the apShm[] array. And the array itself. */
  154088. for(i=0; i<p->nShm; i++){
  154089. sqlite3_free(p->apShm[i]);
  154090. }
  154091. sqlite3_free(p->apShm);
  154092. p->apShm = 0;
  154093. sqlite3_free(p->zDel);
  154094. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  154095. rbu_file **pp;
  154096. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  154097. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  154098. *pp = p->pMainNext;
  154099. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  154100. rbuUnlockShm(p);
  154101. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  154102. }
  154103. /* Close the underlying file handle */
  154104. rc = p->pReal->pMethods->xClose(p->pReal);
  154105. return rc;
  154106. }
  154107. /*
  154108. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  154109. ** passed as the only argument.
  154110. */
  154111. static u32 rbuGetU32(u8 *aBuf){
  154112. return ((u32)aBuf[0] << 24)
  154113. + ((u32)aBuf[1] << 16)
  154114. + ((u32)aBuf[2] << 8)
  154115. + ((u32)aBuf[3]);
  154116. }
  154117. /*
  154118. ** Read data from an rbuVfs-file.
  154119. */
  154120. static int rbuVfsRead(
  154121. sqlite3_file *pFile,
  154122. void *zBuf,
  154123. int iAmt,
  154124. sqlite_int64 iOfst
  154125. ){
  154126. rbu_file *p = (rbu_file*)pFile;
  154127. sqlite3rbu *pRbu = p->pRbu;
  154128. int rc;
  154129. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  154130. assert( p->openFlags & SQLITE_OPEN_WAL );
  154131. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  154132. }else{
  154133. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  154134. && (p->openFlags & SQLITE_OPEN_WAL)
  154135. && iOfst>=pRbu->iOalSz
  154136. ){
  154137. rc = SQLITE_OK;
  154138. memset(zBuf, 0, iAmt);
  154139. }else{
  154140. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  154141. }
  154142. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  154143. /* These look like magic numbers. But they are stable, as they are part
  154144. ** of the definition of the SQLite file format, which may not change. */
  154145. u8 *pBuf = (u8*)zBuf;
  154146. p->iCookie = rbuGetU32(&pBuf[24]);
  154147. p->iWriteVer = pBuf[19];
  154148. }
  154149. }
  154150. return rc;
  154151. }
  154152. /*
  154153. ** Write data to an rbuVfs-file.
  154154. */
  154155. static int rbuVfsWrite(
  154156. sqlite3_file *pFile,
  154157. const void *zBuf,
  154158. int iAmt,
  154159. sqlite_int64 iOfst
  154160. ){
  154161. rbu_file *p = (rbu_file*)pFile;
  154162. sqlite3rbu *pRbu = p->pRbu;
  154163. int rc;
  154164. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  154165. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  154166. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  154167. }else{
  154168. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  154169. && (p->openFlags & SQLITE_OPEN_WAL)
  154170. && iOfst>=pRbu->iOalSz
  154171. ){
  154172. pRbu->iOalSz = iAmt + iOfst;
  154173. }
  154174. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  154175. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  154176. /* These look like magic numbers. But they are stable, as they are part
  154177. ** of the definition of the SQLite file format, which may not change. */
  154178. u8 *pBuf = (u8*)zBuf;
  154179. p->iCookie = rbuGetU32(&pBuf[24]);
  154180. p->iWriteVer = pBuf[19];
  154181. }
  154182. }
  154183. return rc;
  154184. }
  154185. /*
  154186. ** Truncate an rbuVfs-file.
  154187. */
  154188. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  154189. rbu_file *p = (rbu_file*)pFile;
  154190. return p->pReal->pMethods->xTruncate(p->pReal, size);
  154191. }
  154192. /*
  154193. ** Sync an rbuVfs-file.
  154194. */
  154195. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  154196. rbu_file *p = (rbu_file *)pFile;
  154197. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  154198. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  154199. return SQLITE_INTERNAL;
  154200. }
  154201. return SQLITE_OK;
  154202. }
  154203. return p->pReal->pMethods->xSync(p->pReal, flags);
  154204. }
  154205. /*
  154206. ** Return the current file-size of an rbuVfs-file.
  154207. */
  154208. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  154209. rbu_file *p = (rbu_file *)pFile;
  154210. return p->pReal->pMethods->xFileSize(p->pReal, pSize);
  154211. }
  154212. /*
  154213. ** Lock an rbuVfs-file.
  154214. */
  154215. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  154216. rbu_file *p = (rbu_file*)pFile;
  154217. sqlite3rbu *pRbu = p->pRbu;
  154218. int rc = SQLITE_OK;
  154219. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  154220. if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
  154221. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  154222. ** prevents it from checkpointing the database from sqlite3_close(). */
  154223. rc = SQLITE_BUSY;
  154224. }else{
  154225. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  154226. }
  154227. return rc;
  154228. }
  154229. /*
  154230. ** Unlock an rbuVfs-file.
  154231. */
  154232. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  154233. rbu_file *p = (rbu_file *)pFile;
  154234. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  154235. }
  154236. /*
  154237. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  154238. */
  154239. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  154240. rbu_file *p = (rbu_file *)pFile;
  154241. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  154242. }
  154243. /*
  154244. ** File control method. For custom operations on an rbuVfs-file.
  154245. */
  154246. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  154247. rbu_file *p = (rbu_file *)pFile;
  154248. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  154249. int rc;
  154250. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  154251. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  154252. );
  154253. if( op==SQLITE_FCNTL_RBU ){
  154254. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  154255. /* First try to find another RBU vfs lower down in the vfs stack. If
  154256. ** one is found, this vfs will operate in pass-through mode. The lower
  154257. ** level vfs will do the special RBU handling. */
  154258. rc = xControl(p->pReal, op, pArg);
  154259. if( rc==SQLITE_NOTFOUND ){
  154260. /* Now search for a zipvfs instance lower down in the VFS stack. If
  154261. ** one is found, this is an error. */
  154262. void *dummy = 0;
  154263. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  154264. if( rc==SQLITE_OK ){
  154265. rc = SQLITE_ERROR;
  154266. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  154267. }else if( rc==SQLITE_NOTFOUND ){
  154268. pRbu->pTargetFd = p;
  154269. p->pRbu = pRbu;
  154270. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  154271. rc = SQLITE_OK;
  154272. }
  154273. }
  154274. return rc;
  154275. }
  154276. rc = xControl(p->pReal, op, pArg);
  154277. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  154278. rbu_vfs *pRbuVfs = p->pRbuVfs;
  154279. char *zIn = *(char**)pArg;
  154280. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  154281. *(char**)pArg = zOut;
  154282. if( zOut==0 ) rc = SQLITE_NOMEM;
  154283. }
  154284. return rc;
  154285. }
  154286. /*
  154287. ** Return the sector-size in bytes for an rbuVfs-file.
  154288. */
  154289. static int rbuVfsSectorSize(sqlite3_file *pFile){
  154290. rbu_file *p = (rbu_file *)pFile;
  154291. return p->pReal->pMethods->xSectorSize(p->pReal);
  154292. }
  154293. /*
  154294. ** Return the device characteristic flags supported by an rbuVfs-file.
  154295. */
  154296. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  154297. rbu_file *p = (rbu_file *)pFile;
  154298. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  154299. }
  154300. /*
  154301. ** Take or release a shared-memory lock.
  154302. */
  154303. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  154304. rbu_file *p = (rbu_file*)pFile;
  154305. sqlite3rbu *pRbu = p->pRbu;
  154306. int rc = SQLITE_OK;
  154307. #ifdef SQLITE_AMALGAMATION
  154308. assert( WAL_CKPT_LOCK==1 );
  154309. #endif
  154310. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  154311. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  154312. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  154313. ** taking this lock also prevents any checkpoints from occurring.
  154314. ** todo: really, it's not clear why this might occur, as
  154315. ** wal_autocheckpoint ought to be turned off. */
  154316. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  154317. }else{
  154318. int bCapture = 0;
  154319. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  154320. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  154321. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  154322. ){
  154323. bCapture = 1;
  154324. }
  154325. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  154326. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  154327. if( bCapture && rc==SQLITE_OK ){
  154328. pRbu->mLock |= (1 << ofst);
  154329. }
  154330. }
  154331. }
  154332. return rc;
  154333. }
  154334. /*
  154335. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  154336. */
  154337. static int rbuVfsShmMap(
  154338. sqlite3_file *pFile,
  154339. int iRegion,
  154340. int szRegion,
  154341. int isWrite,
  154342. void volatile **pp
  154343. ){
  154344. rbu_file *p = (rbu_file*)pFile;
  154345. int rc = SQLITE_OK;
  154346. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  154347. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  154348. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  154349. ** instead of a file on disk. */
  154350. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  154351. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  154352. if( iRegion<=p->nShm ){
  154353. int nByte = (iRegion+1) * sizeof(char*);
  154354. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  154355. if( apNew==0 ){
  154356. rc = SQLITE_NOMEM;
  154357. }else{
  154358. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  154359. p->apShm = apNew;
  154360. p->nShm = iRegion+1;
  154361. }
  154362. }
  154363. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  154364. char *pNew = (char*)sqlite3_malloc64(szRegion);
  154365. if( pNew==0 ){
  154366. rc = SQLITE_NOMEM;
  154367. }else{
  154368. memset(pNew, 0, szRegion);
  154369. p->apShm[iRegion] = pNew;
  154370. }
  154371. }
  154372. if( rc==SQLITE_OK ){
  154373. *pp = p->apShm[iRegion];
  154374. }else{
  154375. *pp = 0;
  154376. }
  154377. }else{
  154378. assert( p->apShm==0 );
  154379. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  154380. }
  154381. return rc;
  154382. }
  154383. /*
  154384. ** Memory barrier.
  154385. */
  154386. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  154387. rbu_file *p = (rbu_file *)pFile;
  154388. p->pReal->pMethods->xShmBarrier(p->pReal);
  154389. }
  154390. /*
  154391. ** The xShmUnmap method.
  154392. */
  154393. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  154394. rbu_file *p = (rbu_file*)pFile;
  154395. int rc = SQLITE_OK;
  154396. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  154397. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  154398. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  154399. /* no-op */
  154400. }else{
  154401. /* Release the checkpointer and writer locks */
  154402. rbuUnlockShm(p);
  154403. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  154404. }
  154405. return rc;
  154406. }
  154407. /*
  154408. ** Given that zWal points to a buffer containing a wal file name passed to
  154409. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  154410. ** file-handle opened by the same database connection on the corresponding
  154411. ** database file.
  154412. */
  154413. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  154414. rbu_file *pDb;
  154415. sqlite3_mutex_enter(pRbuVfs->mutex);
  154416. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  154417. sqlite3_mutex_leave(pRbuVfs->mutex);
  154418. return pDb;
  154419. }
  154420. /*
  154421. ** Open an rbu file handle.
  154422. */
  154423. static int rbuVfsOpen(
  154424. sqlite3_vfs *pVfs,
  154425. const char *zName,
  154426. sqlite3_file *pFile,
  154427. int flags,
  154428. int *pOutFlags
  154429. ){
  154430. static sqlite3_io_methods rbuvfs_io_methods = {
  154431. 2, /* iVersion */
  154432. rbuVfsClose, /* xClose */
  154433. rbuVfsRead, /* xRead */
  154434. rbuVfsWrite, /* xWrite */
  154435. rbuVfsTruncate, /* xTruncate */
  154436. rbuVfsSync, /* xSync */
  154437. rbuVfsFileSize, /* xFileSize */
  154438. rbuVfsLock, /* xLock */
  154439. rbuVfsUnlock, /* xUnlock */
  154440. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  154441. rbuVfsFileControl, /* xFileControl */
  154442. rbuVfsSectorSize, /* xSectorSize */
  154443. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  154444. rbuVfsShmMap, /* xShmMap */
  154445. rbuVfsShmLock, /* xShmLock */
  154446. rbuVfsShmBarrier, /* xShmBarrier */
  154447. rbuVfsShmUnmap, /* xShmUnmap */
  154448. 0, 0 /* xFetch, xUnfetch */
  154449. };
  154450. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  154451. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  154452. rbu_file *pFd = (rbu_file *)pFile;
  154453. int rc = SQLITE_OK;
  154454. const char *zOpen = zName;
  154455. memset(pFd, 0, sizeof(rbu_file));
  154456. pFd->pReal = (sqlite3_file*)&pFd[1];
  154457. pFd->pRbuVfs = pRbuVfs;
  154458. pFd->openFlags = flags;
  154459. if( zName ){
  154460. if( flags & SQLITE_OPEN_MAIN_DB ){
  154461. /* A main database has just been opened. The following block sets
  154462. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  154463. ** the name of the *-wal file this db connection will use. SQLite
  154464. ** happens to pass a pointer to this buffer when using xAccess()
  154465. ** or xOpen() to operate on the *-wal file. */
  154466. int n = (int)strlen(zName);
  154467. const char *z = &zName[n];
  154468. if( flags & SQLITE_OPEN_URI ){
  154469. int odd = 0;
  154470. while( 1 ){
  154471. if( z[0]==0 ){
  154472. odd = 1 - odd;
  154473. if( odd && z[1]==0 ) break;
  154474. }
  154475. z++;
  154476. }
  154477. z += 2;
  154478. }else{
  154479. while( *z==0 ) z++;
  154480. }
  154481. z += (n + 8 + 1);
  154482. pFd->zWal = z;
  154483. }
  154484. else if( flags & SQLITE_OPEN_WAL ){
  154485. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  154486. if( pDb ){
  154487. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  154488. /* This call is to open a *-wal file. Intead, open the *-oal. This
  154489. ** code ensures that the string passed to xOpen() is terminated by a
  154490. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  154491. ** parameter from it. */
  154492. size_t nCopy = strlen(zName);
  154493. char *zCopy = sqlite3_malloc64(nCopy+2);
  154494. if( zCopy ){
  154495. memcpy(zCopy, zName, nCopy);
  154496. zCopy[nCopy-3] = 'o';
  154497. zCopy[nCopy] = '\0';
  154498. zCopy[nCopy+1] = '\0';
  154499. zOpen = (const char*)(pFd->zDel = zCopy);
  154500. }else{
  154501. rc = SQLITE_NOMEM;
  154502. }
  154503. pFd->pRbu = pDb->pRbu;
  154504. }
  154505. pDb->pWalFd = pFd;
  154506. }
  154507. }
  154508. }
  154509. if( rc==SQLITE_OK ){
  154510. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
  154511. }
  154512. if( pFd->pReal->pMethods ){
  154513. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  154514. ** pointer and, if the file is a main database file, link it into the
  154515. ** mutex protected linked list of all such files. */
  154516. pFile->pMethods = &rbuvfs_io_methods;
  154517. if( flags & SQLITE_OPEN_MAIN_DB ){
  154518. sqlite3_mutex_enter(pRbuVfs->mutex);
  154519. pFd->pMainNext = pRbuVfs->pMain;
  154520. pRbuVfs->pMain = pFd;
  154521. sqlite3_mutex_leave(pRbuVfs->mutex);
  154522. }
  154523. }else{
  154524. sqlite3_free(pFd->zDel);
  154525. }
  154526. return rc;
  154527. }
  154528. /*
  154529. ** Delete the file located at zPath.
  154530. */
  154531. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  154532. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154533. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  154534. }
  154535. /*
  154536. ** Test for access permissions. Return true if the requested permission
  154537. ** is available, or false otherwise.
  154538. */
  154539. static int rbuVfsAccess(
  154540. sqlite3_vfs *pVfs,
  154541. const char *zPath,
  154542. int flags,
  154543. int *pResOut
  154544. ){
  154545. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  154546. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  154547. int rc;
  154548. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  154549. /* If this call is to check if a *-wal file associated with an RBU target
  154550. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  154551. ** the following special handling is activated:
  154552. **
  154553. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  154554. ** ensures that the RBU extension never tries to update a database
  154555. ** in wal mode, even if the first page of the database file has
  154556. ** been damaged.
  154557. **
  154558. ** b) if the *-wal file does not exist, claim that it does anyway,
  154559. ** causing SQLite to call xOpen() to open it. This call will also
  154560. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  154561. ** file opened instead.
  154562. */
  154563. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  154564. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  154565. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  154566. if( *pResOut ){
  154567. rc = SQLITE_CANTOPEN;
  154568. }else{
  154569. *pResOut = 1;
  154570. }
  154571. }
  154572. }
  154573. return rc;
  154574. }
  154575. /*
  154576. ** Populate buffer zOut with the full canonical pathname corresponding
  154577. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  154578. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  154579. */
  154580. static int rbuVfsFullPathname(
  154581. sqlite3_vfs *pVfs,
  154582. const char *zPath,
  154583. int nOut,
  154584. char *zOut
  154585. ){
  154586. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154587. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  154588. }
  154589. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  154590. /*
  154591. ** Open the dynamic library located at zPath and return a handle.
  154592. */
  154593. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  154594. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154595. return pRealVfs->xDlOpen(pRealVfs, zPath);
  154596. }
  154597. /*
  154598. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  154599. ** utf-8 string describing the most recent error encountered associated
  154600. ** with dynamic libraries.
  154601. */
  154602. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  154603. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154604. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  154605. }
  154606. /*
  154607. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  154608. */
  154609. static void (*rbuVfsDlSym(
  154610. sqlite3_vfs *pVfs,
  154611. void *pArg,
  154612. const char *zSym
  154613. ))(void){
  154614. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154615. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  154616. }
  154617. /*
  154618. ** Close the dynamic library handle pHandle.
  154619. */
  154620. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  154621. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154622. pRealVfs->xDlClose(pRealVfs, pHandle);
  154623. }
  154624. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  154625. /*
  154626. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  154627. ** random data.
  154628. */
  154629. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  154630. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154631. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  154632. }
  154633. /*
  154634. ** Sleep for nMicro microseconds. Return the number of microseconds
  154635. ** actually slept.
  154636. */
  154637. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  154638. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154639. return pRealVfs->xSleep(pRealVfs, nMicro);
  154640. }
  154641. /*
  154642. ** Return the current time as a Julian Day number in *pTimeOut.
  154643. */
  154644. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  154645. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  154646. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  154647. }
  154648. /*
  154649. ** No-op.
  154650. */
  154651. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  154652. return 0;
  154653. }
  154654. /*
  154655. ** Deregister and destroy an RBU vfs created by an earlier call to
  154656. ** sqlite3rbu_create_vfs().
  154657. */
  154658. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
  154659. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  154660. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  154661. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  154662. sqlite3_vfs_unregister(pVfs);
  154663. sqlite3_free(pVfs);
  154664. }
  154665. }
  154666. /*
  154667. ** Create an RBU VFS named zName that accesses the underlying file-system
  154668. ** via existing VFS zParent. The new object is registered as a non-default
  154669. ** VFS with SQLite before returning.
  154670. */
  154671. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  154672. /* Template for VFS */
  154673. static sqlite3_vfs vfs_template = {
  154674. 1, /* iVersion */
  154675. 0, /* szOsFile */
  154676. 0, /* mxPathname */
  154677. 0, /* pNext */
  154678. 0, /* zName */
  154679. 0, /* pAppData */
  154680. rbuVfsOpen, /* xOpen */
  154681. rbuVfsDelete, /* xDelete */
  154682. rbuVfsAccess, /* xAccess */
  154683. rbuVfsFullPathname, /* xFullPathname */
  154684. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  154685. rbuVfsDlOpen, /* xDlOpen */
  154686. rbuVfsDlError, /* xDlError */
  154687. rbuVfsDlSym, /* xDlSym */
  154688. rbuVfsDlClose, /* xDlClose */
  154689. #else
  154690. 0, 0, 0, 0,
  154691. #endif
  154692. rbuVfsRandomness, /* xRandomness */
  154693. rbuVfsSleep, /* xSleep */
  154694. rbuVfsCurrentTime, /* xCurrentTime */
  154695. rbuVfsGetLastError, /* xGetLastError */
  154696. 0, /* xCurrentTimeInt64 (version 2) */
  154697. 0, 0, 0 /* Unimplemented version 3 methods */
  154698. };
  154699. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  154700. int rc = SQLITE_OK;
  154701. size_t nName;
  154702. size_t nByte;
  154703. nName = strlen(zName);
  154704. nByte = sizeof(rbu_vfs) + nName + 1;
  154705. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  154706. if( pNew==0 ){
  154707. rc = SQLITE_NOMEM;
  154708. }else{
  154709. sqlite3_vfs *pParent; /* Parent VFS */
  154710. memset(pNew, 0, nByte);
  154711. pParent = sqlite3_vfs_find(zParent);
  154712. if( pParent==0 ){
  154713. rc = SQLITE_NOTFOUND;
  154714. }else{
  154715. char *zSpace;
  154716. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  154717. pNew->base.mxPathname = pParent->mxPathname;
  154718. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  154719. pNew->pRealVfs = pParent;
  154720. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  154721. memcpy(zSpace, zName, nName);
  154722. /* Allocate the mutex and register the new VFS (not as the default) */
  154723. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  154724. if( pNew->mutex==0 ){
  154725. rc = SQLITE_NOMEM;
  154726. }else{
  154727. rc = sqlite3_vfs_register(&pNew->base, 0);
  154728. }
  154729. }
  154730. if( rc!=SQLITE_OK ){
  154731. sqlite3_mutex_free(pNew->mutex);
  154732. sqlite3_free(pNew);
  154733. }
  154734. }
  154735. return rc;
  154736. }
  154737. /**************************************************************************/
  154738. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  154739. /************** End of sqlite3rbu.c ******************************************/
  154740. /************** Begin file dbstat.c ******************************************/
  154741. /*
  154742. ** 2010 July 12
  154743. **
  154744. ** The author disclaims copyright to this source code. In place of
  154745. ** a legal notice, here is a blessing:
  154746. **
  154747. ** May you do good and not evil.
  154748. ** May you find forgiveness for yourself and forgive others.
  154749. ** May you share freely, never taking more than you give.
  154750. **
  154751. ******************************************************************************
  154752. **
  154753. ** This file contains an implementation of the "dbstat" virtual table.
  154754. **
  154755. ** The dbstat virtual table is used to extract low-level formatting
  154756. ** information from an SQLite database in order to implement the
  154757. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  154758. ** for an example implementation.
  154759. **
  154760. ** Additional information is available on the "dbstat.html" page of the
  154761. ** official SQLite documentation.
  154762. */
  154763. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  154764. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  154765. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  154766. /*
  154767. ** Page paths:
  154768. **
  154769. ** The value of the 'path' column describes the path taken from the
  154770. ** root-node of the b-tree structure to each page. The value of the
  154771. ** root-node path is '/'.
  154772. **
  154773. ** The value of the path for the left-most child page of the root of
  154774. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  154775. ** so the pages to the left have smaller keys than the pages to the right.)
  154776. ** The next to left-most child of the root page is
  154777. ** '/001', and so on, each sibling page identified by a 3-digit hex
  154778. ** value. The children of the 451st left-most sibling have paths such
  154779. ** as '/1c2/000/, '/1c2/001/' etc.
  154780. **
  154781. ** Overflow pages are specified by appending a '+' character and a
  154782. ** six-digit hexadecimal value to the path to the cell they are linked
  154783. ** from. For example, the three overflow pages in a chain linked from
  154784. ** the left-most cell of the 450th child of the root page are identified
  154785. ** by the paths:
  154786. **
  154787. ** '/1c2/000+000000' // First page in overflow chain
  154788. ** '/1c2/000+000001' // Second page in overflow chain
  154789. ** '/1c2/000+000002' // Third page in overflow chain
  154790. **
  154791. ** If the paths are sorted using the BINARY collation sequence, then
  154792. ** the overflow pages associated with a cell will appear earlier in the
  154793. ** sort-order than its child page:
  154794. **
  154795. ** '/1c2/000/' // Left-most child of 451st child of root
  154796. */
  154797. #define VTAB_SCHEMA \
  154798. "CREATE TABLE xx( " \
  154799. " name STRING, /* Name of table or index */" \
  154800. " path INTEGER, /* Path to page from root */" \
  154801. " pageno INTEGER, /* Page number */" \
  154802. " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \
  154803. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  154804. " payload INTEGER, /* Bytes of payload on this page */" \
  154805. " unused INTEGER, /* Bytes of unused space on this page */" \
  154806. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  154807. " pgoffset INTEGER, /* Offset of page in file */" \
  154808. " pgsize INTEGER, /* Size of the page */" \
  154809. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  154810. ");"
  154811. typedef struct StatTable StatTable;
  154812. typedef struct StatCursor StatCursor;
  154813. typedef struct StatPage StatPage;
  154814. typedef struct StatCell StatCell;
  154815. struct StatCell {
  154816. int nLocal; /* Bytes of local payload */
  154817. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  154818. int nOvfl; /* Entries in aOvfl[] */
  154819. u32 *aOvfl; /* Array of overflow page numbers */
  154820. int nLastOvfl; /* Bytes of payload on final overflow page */
  154821. int iOvfl; /* Iterates through aOvfl[] */
  154822. };
  154823. struct StatPage {
  154824. u32 iPgno;
  154825. DbPage *pPg;
  154826. int iCell;
  154827. char *zPath; /* Path to this page */
  154828. /* Variables populated by statDecodePage(): */
  154829. u8 flags; /* Copy of flags byte */
  154830. int nCell; /* Number of cells on page */
  154831. int nUnused; /* Number of unused bytes on page */
  154832. StatCell *aCell; /* Array of parsed cells */
  154833. u32 iRightChildPg; /* Right-child page number (or 0) */
  154834. int nMxPayload; /* Largest payload of any cell on this page */
  154835. };
  154836. struct StatCursor {
  154837. sqlite3_vtab_cursor base;
  154838. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  154839. int isEof; /* After pStmt has returned SQLITE_DONE */
  154840. int iDb; /* Schema used for this query */
  154841. StatPage aPage[32];
  154842. int iPage; /* Current entry in aPage[] */
  154843. /* Values to return. */
  154844. char *zName; /* Value of 'name' column */
  154845. char *zPath; /* Value of 'path' column */
  154846. u32 iPageno; /* Value of 'pageno' column */
  154847. char *zPagetype; /* Value of 'pagetype' column */
  154848. int nCell; /* Value of 'ncell' column */
  154849. int nPayload; /* Value of 'payload' column */
  154850. int nUnused; /* Value of 'unused' column */
  154851. int nMxPayload; /* Value of 'mx_payload' column */
  154852. i64 iOffset; /* Value of 'pgOffset' column */
  154853. int szPage; /* Value of 'pgSize' column */
  154854. };
  154855. struct StatTable {
  154856. sqlite3_vtab base;
  154857. sqlite3 *db;
  154858. int iDb; /* Index of database to analyze */
  154859. };
  154860. #ifndef get2byte
  154861. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  154862. #endif
  154863. /*
  154864. ** Connect to or create a statvfs virtual table.
  154865. */
  154866. static int statConnect(
  154867. sqlite3 *db,
  154868. void *pAux,
  154869. int argc, const char *const*argv,
  154870. sqlite3_vtab **ppVtab,
  154871. char **pzErr
  154872. ){
  154873. StatTable *pTab = 0;
  154874. int rc = SQLITE_OK;
  154875. int iDb;
  154876. if( argc>=4 ){
  154877. Token nm;
  154878. sqlite3TokenInit(&nm, (char*)argv[3]);
  154879. iDb = sqlite3FindDb(db, &nm);
  154880. if( iDb<0 ){
  154881. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  154882. return SQLITE_ERROR;
  154883. }
  154884. }else{
  154885. iDb = 0;
  154886. }
  154887. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  154888. if( rc==SQLITE_OK ){
  154889. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  154890. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  154891. }
  154892. assert( rc==SQLITE_OK || pTab==0 );
  154893. if( rc==SQLITE_OK ){
  154894. memset(pTab, 0, sizeof(StatTable));
  154895. pTab->db = db;
  154896. pTab->iDb = iDb;
  154897. }
  154898. *ppVtab = (sqlite3_vtab*)pTab;
  154899. return rc;
  154900. }
  154901. /*
  154902. ** Disconnect from or destroy a statvfs virtual table.
  154903. */
  154904. static int statDisconnect(sqlite3_vtab *pVtab){
  154905. sqlite3_free(pVtab);
  154906. return SQLITE_OK;
  154907. }
  154908. /*
  154909. ** There is no "best-index". This virtual table always does a linear
  154910. ** scan. However, a schema=? constraint should cause this table to
  154911. ** operate on a different database schema, so check for it.
  154912. **
  154913. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  154914. */
  154915. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  154916. int i;
  154917. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  154918. /* Look for a valid schema=? constraint. If found, change the idxNum to
  154919. ** 1 and request the value of that constraint be sent to xFilter. And
  154920. ** lower the cost estimate to encourage the constrained version to be
  154921. ** used.
  154922. */
  154923. for(i=0; i<pIdxInfo->nConstraint; i++){
  154924. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  154925. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  154926. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  154927. pIdxInfo->idxNum = 1;
  154928. pIdxInfo->estimatedCost = 1.0;
  154929. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  154930. pIdxInfo->aConstraintUsage[i].omit = 1;
  154931. break;
  154932. }
  154933. /* Records are always returned in ascending order of (name, path).
  154934. ** If this will satisfy the client, set the orderByConsumed flag so that
  154935. ** SQLite does not do an external sort.
  154936. */
  154937. if( ( pIdxInfo->nOrderBy==1
  154938. && pIdxInfo->aOrderBy[0].iColumn==0
  154939. && pIdxInfo->aOrderBy[0].desc==0
  154940. ) ||
  154941. ( pIdxInfo->nOrderBy==2
  154942. && pIdxInfo->aOrderBy[0].iColumn==0
  154943. && pIdxInfo->aOrderBy[0].desc==0
  154944. && pIdxInfo->aOrderBy[1].iColumn==1
  154945. && pIdxInfo->aOrderBy[1].desc==0
  154946. )
  154947. ){
  154948. pIdxInfo->orderByConsumed = 1;
  154949. }
  154950. return SQLITE_OK;
  154951. }
  154952. /*
  154953. ** Open a new statvfs cursor.
  154954. */
  154955. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  154956. StatTable *pTab = (StatTable *)pVTab;
  154957. StatCursor *pCsr;
  154958. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  154959. if( pCsr==0 ){
  154960. return SQLITE_NOMEM_BKPT;
  154961. }else{
  154962. memset(pCsr, 0, sizeof(StatCursor));
  154963. pCsr->base.pVtab = pVTab;
  154964. pCsr->iDb = pTab->iDb;
  154965. }
  154966. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  154967. return SQLITE_OK;
  154968. }
  154969. static void statClearPage(StatPage *p){
  154970. int i;
  154971. if( p->aCell ){
  154972. for(i=0; i<p->nCell; i++){
  154973. sqlite3_free(p->aCell[i].aOvfl);
  154974. }
  154975. sqlite3_free(p->aCell);
  154976. }
  154977. sqlite3PagerUnref(p->pPg);
  154978. sqlite3_free(p->zPath);
  154979. memset(p, 0, sizeof(StatPage));
  154980. }
  154981. static void statResetCsr(StatCursor *pCsr){
  154982. int i;
  154983. sqlite3_reset(pCsr->pStmt);
  154984. for(i=0; i<ArraySize(pCsr->aPage); i++){
  154985. statClearPage(&pCsr->aPage[i]);
  154986. }
  154987. pCsr->iPage = 0;
  154988. sqlite3_free(pCsr->zPath);
  154989. pCsr->zPath = 0;
  154990. pCsr->isEof = 0;
  154991. }
  154992. /*
  154993. ** Close a statvfs cursor.
  154994. */
  154995. static int statClose(sqlite3_vtab_cursor *pCursor){
  154996. StatCursor *pCsr = (StatCursor *)pCursor;
  154997. statResetCsr(pCsr);
  154998. sqlite3_finalize(pCsr->pStmt);
  154999. sqlite3_free(pCsr);
  155000. return SQLITE_OK;
  155001. }
  155002. static void getLocalPayload(
  155003. int nUsable, /* Usable bytes per page */
  155004. u8 flags, /* Page flags */
  155005. int nTotal, /* Total record (payload) size */
  155006. int *pnLocal /* OUT: Bytes stored locally */
  155007. ){
  155008. int nLocal;
  155009. int nMinLocal;
  155010. int nMaxLocal;
  155011. if( flags==0x0D ){ /* Table leaf node */
  155012. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  155013. nMaxLocal = nUsable - 35;
  155014. }else{ /* Index interior and leaf nodes */
  155015. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  155016. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  155017. }
  155018. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  155019. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  155020. *pnLocal = nLocal;
  155021. }
  155022. static int statDecodePage(Btree *pBt, StatPage *p){
  155023. int nUnused;
  155024. int iOff;
  155025. int nHdr;
  155026. int isLeaf;
  155027. int szPage;
  155028. u8 *aData = sqlite3PagerGetData(p->pPg);
  155029. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  155030. p->flags = aHdr[0];
  155031. p->nCell = get2byte(&aHdr[3]);
  155032. p->nMxPayload = 0;
  155033. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  155034. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  155035. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  155036. nUnused += (int)aHdr[7];
  155037. iOff = get2byte(&aHdr[1]);
  155038. while( iOff ){
  155039. nUnused += get2byte(&aData[iOff+2]);
  155040. iOff = get2byte(&aData[iOff]);
  155041. }
  155042. p->nUnused = nUnused;
  155043. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  155044. szPage = sqlite3BtreeGetPageSize(pBt);
  155045. if( p->nCell ){
  155046. int i; /* Used to iterate through cells */
  155047. int nUsable; /* Usable bytes per page */
  155048. sqlite3BtreeEnter(pBt);
  155049. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  155050. sqlite3BtreeLeave(pBt);
  155051. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  155052. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  155053. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  155054. for(i=0; i<p->nCell; i++){
  155055. StatCell *pCell = &p->aCell[i];
  155056. iOff = get2byte(&aData[nHdr+i*2]);
  155057. if( !isLeaf ){
  155058. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  155059. iOff += 4;
  155060. }
  155061. if( p->flags==0x05 ){
  155062. /* A table interior node. nPayload==0. */
  155063. }else{
  155064. u32 nPayload; /* Bytes of payload total (local+overflow) */
  155065. int nLocal; /* Bytes of payload stored locally */
  155066. iOff += getVarint32(&aData[iOff], nPayload);
  155067. if( p->flags==0x0D ){
  155068. u64 dummy;
  155069. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  155070. }
  155071. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  155072. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  155073. pCell->nLocal = nLocal;
  155074. assert( nLocal>=0 );
  155075. assert( nPayload>=(u32)nLocal );
  155076. assert( nLocal<=(nUsable-35) );
  155077. if( nPayload>(u32)nLocal ){
  155078. int j;
  155079. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  155080. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  155081. pCell->nOvfl = nOvfl;
  155082. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  155083. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  155084. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  155085. for(j=1; j<nOvfl; j++){
  155086. int rc;
  155087. u32 iPrev = pCell->aOvfl[j-1];
  155088. DbPage *pPg = 0;
  155089. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  155090. if( rc!=SQLITE_OK ){
  155091. assert( pPg==0 );
  155092. return rc;
  155093. }
  155094. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  155095. sqlite3PagerUnref(pPg);
  155096. }
  155097. }
  155098. }
  155099. }
  155100. }
  155101. return SQLITE_OK;
  155102. }
  155103. /*
  155104. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  155105. ** the current value of pCsr->iPageno.
  155106. */
  155107. static void statSizeAndOffset(StatCursor *pCsr){
  155108. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  155109. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  155110. Pager *pPager = sqlite3BtreePager(pBt);
  155111. sqlite3_file *fd;
  155112. sqlite3_int64 x[2];
  155113. /* The default page size and offset */
  155114. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  155115. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  155116. /* If connected to a ZIPVFS backend, override the page size and
  155117. ** offset with actual values obtained from ZIPVFS.
  155118. */
  155119. fd = sqlite3PagerFile(pPager);
  155120. x[0] = pCsr->iPageno;
  155121. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  155122. pCsr->iOffset = x[0];
  155123. pCsr->szPage = (int)x[1];
  155124. }
  155125. }
  155126. /*
  155127. ** Move a statvfs cursor to the next entry in the file.
  155128. */
  155129. static int statNext(sqlite3_vtab_cursor *pCursor){
  155130. int rc;
  155131. int nPayload;
  155132. char *z;
  155133. StatCursor *pCsr = (StatCursor *)pCursor;
  155134. StatTable *pTab = (StatTable *)pCursor->pVtab;
  155135. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  155136. Pager *pPager = sqlite3BtreePager(pBt);
  155137. sqlite3_free(pCsr->zPath);
  155138. pCsr->zPath = 0;
  155139. statNextRestart:
  155140. if( pCsr->aPage[0].pPg==0 ){
  155141. rc = sqlite3_step(pCsr->pStmt);
  155142. if( rc==SQLITE_ROW ){
  155143. int nPage;
  155144. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  155145. sqlite3PagerPagecount(pPager, &nPage);
  155146. if( nPage==0 ){
  155147. pCsr->isEof = 1;
  155148. return sqlite3_reset(pCsr->pStmt);
  155149. }
  155150. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  155151. pCsr->aPage[0].iPgno = iRoot;
  155152. pCsr->aPage[0].iCell = 0;
  155153. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  155154. pCsr->iPage = 0;
  155155. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  155156. }else{
  155157. pCsr->isEof = 1;
  155158. return sqlite3_reset(pCsr->pStmt);
  155159. }
  155160. }else{
  155161. /* Page p itself has already been visited. */
  155162. StatPage *p = &pCsr->aPage[pCsr->iPage];
  155163. while( p->iCell<p->nCell ){
  155164. StatCell *pCell = &p->aCell[p->iCell];
  155165. if( pCell->iOvfl<pCell->nOvfl ){
  155166. int nUsable;
  155167. sqlite3BtreeEnter(pBt);
  155168. nUsable = sqlite3BtreeGetPageSize(pBt) -
  155169. sqlite3BtreeGetReserveNoMutex(pBt);
  155170. sqlite3BtreeLeave(pBt);
  155171. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  155172. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  155173. pCsr->zPagetype = "overflow";
  155174. pCsr->nCell = 0;
  155175. pCsr->nMxPayload = 0;
  155176. pCsr->zPath = z = sqlite3_mprintf(
  155177. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  155178. );
  155179. if( pCell->iOvfl<pCell->nOvfl-1 ){
  155180. pCsr->nUnused = 0;
  155181. pCsr->nPayload = nUsable - 4;
  155182. }else{
  155183. pCsr->nPayload = pCell->nLastOvfl;
  155184. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  155185. }
  155186. pCell->iOvfl++;
  155187. statSizeAndOffset(pCsr);
  155188. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  155189. }
  155190. if( p->iRightChildPg ) break;
  155191. p->iCell++;
  155192. }
  155193. if( !p->iRightChildPg || p->iCell>p->nCell ){
  155194. statClearPage(p);
  155195. if( pCsr->iPage==0 ) return statNext(pCursor);
  155196. pCsr->iPage--;
  155197. goto statNextRestart; /* Tail recursion */
  155198. }
  155199. pCsr->iPage++;
  155200. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  155201. if( p->iCell==p->nCell ){
  155202. p[1].iPgno = p->iRightChildPg;
  155203. }else{
  155204. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  155205. }
  155206. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  155207. p[1].iCell = 0;
  155208. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  155209. p->iCell++;
  155210. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  155211. }
  155212. /* Populate the StatCursor fields with the values to be returned
  155213. ** by the xColumn() and xRowid() methods.
  155214. */
  155215. if( rc==SQLITE_OK ){
  155216. int i;
  155217. StatPage *p = &pCsr->aPage[pCsr->iPage];
  155218. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  155219. pCsr->iPageno = p->iPgno;
  155220. rc = statDecodePage(pBt, p);
  155221. if( rc==SQLITE_OK ){
  155222. statSizeAndOffset(pCsr);
  155223. switch( p->flags ){
  155224. case 0x05: /* table internal */
  155225. case 0x02: /* index internal */
  155226. pCsr->zPagetype = "internal";
  155227. break;
  155228. case 0x0D: /* table leaf */
  155229. case 0x0A: /* index leaf */
  155230. pCsr->zPagetype = "leaf";
  155231. break;
  155232. default:
  155233. pCsr->zPagetype = "corrupted";
  155234. break;
  155235. }
  155236. pCsr->nCell = p->nCell;
  155237. pCsr->nUnused = p->nUnused;
  155238. pCsr->nMxPayload = p->nMxPayload;
  155239. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  155240. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  155241. nPayload = 0;
  155242. for(i=0; i<p->nCell; i++){
  155243. nPayload += p->aCell[i].nLocal;
  155244. }
  155245. pCsr->nPayload = nPayload;
  155246. }
  155247. }
  155248. return rc;
  155249. }
  155250. static int statEof(sqlite3_vtab_cursor *pCursor){
  155251. StatCursor *pCsr = (StatCursor *)pCursor;
  155252. return pCsr->isEof;
  155253. }
  155254. static int statFilter(
  155255. sqlite3_vtab_cursor *pCursor,
  155256. int idxNum, const char *idxStr,
  155257. int argc, sqlite3_value **argv
  155258. ){
  155259. StatCursor *pCsr = (StatCursor *)pCursor;
  155260. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  155261. char *zSql;
  155262. int rc = SQLITE_OK;
  155263. char *zMaster;
  155264. if( idxNum==1 ){
  155265. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  155266. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  155267. if( pCsr->iDb<0 ){
  155268. sqlite3_free(pCursor->pVtab->zErrMsg);
  155269. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  155270. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  155271. }
  155272. }else{
  155273. pCsr->iDb = pTab->iDb;
  155274. }
  155275. statResetCsr(pCsr);
  155276. sqlite3_finalize(pCsr->pStmt);
  155277. pCsr->pStmt = 0;
  155278. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  155279. zSql = sqlite3_mprintf(
  155280. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  155281. " UNION ALL "
  155282. "SELECT name, rootpage, type"
  155283. " FROM \"%w\".%s WHERE rootpage!=0"
  155284. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
  155285. if( zSql==0 ){
  155286. return SQLITE_NOMEM_BKPT;
  155287. }else{
  155288. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  155289. sqlite3_free(zSql);
  155290. }
  155291. if( rc==SQLITE_OK ){
  155292. rc = statNext(pCursor);
  155293. }
  155294. return rc;
  155295. }
  155296. static int statColumn(
  155297. sqlite3_vtab_cursor *pCursor,
  155298. sqlite3_context *ctx,
  155299. int i
  155300. ){
  155301. StatCursor *pCsr = (StatCursor *)pCursor;
  155302. switch( i ){
  155303. case 0: /* name */
  155304. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  155305. break;
  155306. case 1: /* path */
  155307. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  155308. break;
  155309. case 2: /* pageno */
  155310. sqlite3_result_int64(ctx, pCsr->iPageno);
  155311. break;
  155312. case 3: /* pagetype */
  155313. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  155314. break;
  155315. case 4: /* ncell */
  155316. sqlite3_result_int(ctx, pCsr->nCell);
  155317. break;
  155318. case 5: /* payload */
  155319. sqlite3_result_int(ctx, pCsr->nPayload);
  155320. break;
  155321. case 6: /* unused */
  155322. sqlite3_result_int(ctx, pCsr->nUnused);
  155323. break;
  155324. case 7: /* mx_payload */
  155325. sqlite3_result_int(ctx, pCsr->nMxPayload);
  155326. break;
  155327. case 8: /* pgoffset */
  155328. sqlite3_result_int64(ctx, pCsr->iOffset);
  155329. break;
  155330. case 9: /* pgsize */
  155331. sqlite3_result_int(ctx, pCsr->szPage);
  155332. break;
  155333. default: { /* schema */
  155334. sqlite3 *db = sqlite3_context_db_handle(ctx);
  155335. int iDb = pCsr->iDb;
  155336. sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
  155337. break;
  155338. }
  155339. }
  155340. return SQLITE_OK;
  155341. }
  155342. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  155343. StatCursor *pCsr = (StatCursor *)pCursor;
  155344. *pRowid = pCsr->iPageno;
  155345. return SQLITE_OK;
  155346. }
  155347. /*
  155348. ** Invoke this routine to register the "dbstat" virtual table module
  155349. */
  155350. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  155351. static sqlite3_module dbstat_module = {
  155352. 0, /* iVersion */
  155353. statConnect, /* xCreate */
  155354. statConnect, /* xConnect */
  155355. statBestIndex, /* xBestIndex */
  155356. statDisconnect, /* xDisconnect */
  155357. statDisconnect, /* xDestroy */
  155358. statOpen, /* xOpen - open a cursor */
  155359. statClose, /* xClose - close a cursor */
  155360. statFilter, /* xFilter - configure scan constraints */
  155361. statNext, /* xNext - advance a cursor */
  155362. statEof, /* xEof - check for end of scan */
  155363. statColumn, /* xColumn - read data */
  155364. statRowid, /* xRowid - read data */
  155365. 0, /* xUpdate */
  155366. 0, /* xBegin */
  155367. 0, /* xSync */
  155368. 0, /* xCommit */
  155369. 0, /* xRollback */
  155370. 0, /* xFindMethod */
  155371. 0, /* xRename */
  155372. };
  155373. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  155374. }
  155375. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  155376. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  155377. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  155378. /************** End of dbstat.c **********************************************/
  155379. /************** Begin file json1.c *******************************************/
  155380. /*
  155381. ** 2015-08-12
  155382. **
  155383. ** The author disclaims copyright to this source code. In place of
  155384. ** a legal notice, here is a blessing:
  155385. **
  155386. ** May you do good and not evil.
  155387. ** May you find forgiveness for yourself and forgive others.
  155388. ** May you share freely, never taking more than you give.
  155389. **
  155390. ******************************************************************************
  155391. **
  155392. ** This SQLite extension implements JSON functions. The interface is
  155393. ** modeled after MySQL JSON functions:
  155394. **
  155395. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  155396. **
  155397. ** For the time being, all JSON is stored as pure text. (We might add
  155398. ** a JSONB type in the future which stores a binary encoding of JSON in
  155399. ** a BLOB, but there is no support for JSONB in the current implementation.
  155400. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  155401. ** how JSONB might improve on that.)
  155402. */
  155403. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  155404. #if !defined(_SQLITEINT_H_)
  155405. /* #include "sqlite3ext.h" */
  155406. #endif
  155407. SQLITE_EXTENSION_INIT1
  155408. /* #include <assert.h> */
  155409. /* #include <string.h> */
  155410. /* #include <stdlib.h> */
  155411. /* #include <stdarg.h> */
  155412. /* Mark a function parameter as unused, to suppress nuisance compiler
  155413. ** warnings. */
  155414. #ifndef UNUSED_PARAM
  155415. # define UNUSED_PARAM(X) (void)(X)
  155416. #endif
  155417. #ifndef LARGEST_INT64
  155418. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  155419. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  155420. #endif
  155421. /*
  155422. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  155423. ** to pass signed char values.
  155424. */
  155425. #ifdef sqlite3Isdigit
  155426. /* Use the SQLite core versions if this routine is part of the
  155427. ** SQLite amalgamation */
  155428. # define safe_isdigit(x) sqlite3Isdigit(x)
  155429. # define safe_isalnum(x) sqlite3Isalnum(x)
  155430. #else
  155431. /* Use the standard library for separate compilation */
  155432. #include <ctype.h> /* amalgamator: keep */
  155433. # define safe_isdigit(x) isdigit((unsigned char)(x))
  155434. # define safe_isalnum(x) isalnum((unsigned char)(x))
  155435. #endif
  155436. /*
  155437. ** Growing our own isspace() routine this way is twice as fast as
  155438. ** the library isspace() function, resulting in a 7% overall performance
  155439. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  155440. */
  155441. static const char jsonIsSpace[] = {
  155442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  155443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155444. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  155458. };
  155459. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  155460. #ifndef SQLITE_AMALGAMATION
  155461. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  155462. ** but the definitions need to be repeated for separate compilation. */
  155463. typedef sqlite3_uint64 u64;
  155464. typedef unsigned int u32;
  155465. typedef unsigned char u8;
  155466. #endif
  155467. /* Objects */
  155468. typedef struct JsonString JsonString;
  155469. typedef struct JsonNode JsonNode;
  155470. typedef struct JsonParse JsonParse;
  155471. /* An instance of this object represents a JSON string
  155472. ** under construction. Really, this is a generic string accumulator
  155473. ** that can be and is used to create strings other than JSON.
  155474. */
  155475. struct JsonString {
  155476. sqlite3_context *pCtx; /* Function context - put error messages here */
  155477. char *zBuf; /* Append JSON content here */
  155478. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  155479. u64 nUsed; /* Bytes of zBuf[] currently used */
  155480. u8 bStatic; /* True if zBuf is static space */
  155481. u8 bErr; /* True if an error has been encountered */
  155482. char zSpace[100]; /* Initial static space */
  155483. };
  155484. /* JSON type values
  155485. */
  155486. #define JSON_NULL 0
  155487. #define JSON_TRUE 1
  155488. #define JSON_FALSE 2
  155489. #define JSON_INT 3
  155490. #define JSON_REAL 4
  155491. #define JSON_STRING 5
  155492. #define JSON_ARRAY 6
  155493. #define JSON_OBJECT 7
  155494. /* The "subtype" set for JSON values */
  155495. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  155496. /*
  155497. ** Names of the various JSON types:
  155498. */
  155499. static const char * const jsonType[] = {
  155500. "null", "true", "false", "integer", "real", "text", "array", "object"
  155501. };
  155502. /* Bit values for the JsonNode.jnFlag field
  155503. */
  155504. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  155505. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  155506. #define JNODE_REMOVE 0x04 /* Do not output */
  155507. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
  155508. #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
  155509. #define JNODE_LABEL 0x20 /* Is a label of an object */
  155510. /* A single node of parsed JSON
  155511. */
  155512. struct JsonNode {
  155513. u8 eType; /* One of the JSON_ type values */
  155514. u8 jnFlags; /* JNODE flags */
  155515. u8 iVal; /* Replacement value when JNODE_REPLACE */
  155516. u32 n; /* Bytes of content, or number of sub-nodes */
  155517. union {
  155518. const char *zJContent; /* Content for INT, REAL, and STRING */
  155519. u32 iAppend; /* More terms for ARRAY and OBJECT */
  155520. u32 iKey; /* Key for ARRAY objects in json_tree() */
  155521. } u;
  155522. };
  155523. /* A completely parsed JSON string
  155524. */
  155525. struct JsonParse {
  155526. u32 nNode; /* Number of slots of aNode[] used */
  155527. u32 nAlloc; /* Number of slots of aNode[] allocated */
  155528. JsonNode *aNode; /* Array of nodes containing the parse */
  155529. const char *zJson; /* Original JSON string */
  155530. u32 *aUp; /* Index of parent of each node */
  155531. u8 oom; /* Set to true if out of memory */
  155532. u8 nErr; /* Number of errors seen */
  155533. };
  155534. /**************************************************************************
  155535. ** Utility routines for dealing with JsonString objects
  155536. **************************************************************************/
  155537. /* Set the JsonString object to an empty string
  155538. */
  155539. static void jsonZero(JsonString *p){
  155540. p->zBuf = p->zSpace;
  155541. p->nAlloc = sizeof(p->zSpace);
  155542. p->nUsed = 0;
  155543. p->bStatic = 1;
  155544. }
  155545. /* Initialize the JsonString object
  155546. */
  155547. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  155548. p->pCtx = pCtx;
  155549. p->bErr = 0;
  155550. jsonZero(p);
  155551. }
  155552. /* Free all allocated memory and reset the JsonString object back to its
  155553. ** initial state.
  155554. */
  155555. static void jsonReset(JsonString *p){
  155556. if( !p->bStatic ) sqlite3_free(p->zBuf);
  155557. jsonZero(p);
  155558. }
  155559. /* Report an out-of-memory (OOM) condition
  155560. */
  155561. static void jsonOom(JsonString *p){
  155562. p->bErr = 1;
  155563. sqlite3_result_error_nomem(p->pCtx);
  155564. jsonReset(p);
  155565. }
  155566. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  155567. ** Return zero on success. Return non-zero on an OOM error
  155568. */
  155569. static int jsonGrow(JsonString *p, u32 N){
  155570. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  155571. char *zNew;
  155572. if( p->bStatic ){
  155573. if( p->bErr ) return 1;
  155574. zNew = sqlite3_malloc64(nTotal);
  155575. if( zNew==0 ){
  155576. jsonOom(p);
  155577. return SQLITE_NOMEM;
  155578. }
  155579. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  155580. p->zBuf = zNew;
  155581. p->bStatic = 0;
  155582. }else{
  155583. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  155584. if( zNew==0 ){
  155585. jsonOom(p);
  155586. return SQLITE_NOMEM;
  155587. }
  155588. p->zBuf = zNew;
  155589. }
  155590. p->nAlloc = nTotal;
  155591. return SQLITE_OK;
  155592. }
  155593. /* Append N bytes from zIn onto the end of the JsonString string.
  155594. */
  155595. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  155596. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  155597. memcpy(p->zBuf+p->nUsed, zIn, N);
  155598. p->nUsed += N;
  155599. }
  155600. /* Append formatted text (not to exceed N bytes) to the JsonString.
  155601. */
  155602. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  155603. va_list ap;
  155604. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  155605. va_start(ap, zFormat);
  155606. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  155607. va_end(ap);
  155608. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  155609. }
  155610. /* Append a single character
  155611. */
  155612. static void jsonAppendChar(JsonString *p, char c){
  155613. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  155614. p->zBuf[p->nUsed++] = c;
  155615. }
  155616. /* Append a comma separator to the output buffer, if the previous
  155617. ** character is not '[' or '{'.
  155618. */
  155619. static void jsonAppendSeparator(JsonString *p){
  155620. char c;
  155621. if( p->nUsed==0 ) return;
  155622. c = p->zBuf[p->nUsed-1];
  155623. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  155624. }
  155625. /* Append the N-byte string in zIn to the end of the JsonString string
  155626. ** under construction. Enclose the string in "..." and escape
  155627. ** any double-quotes or backslash characters contained within the
  155628. ** string.
  155629. */
  155630. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  155631. u32 i;
  155632. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  155633. p->zBuf[p->nUsed++] = '"';
  155634. for(i=0; i<N; i++){
  155635. unsigned char c = ((unsigned const char*)zIn)[i];
  155636. if( c=='"' || c=='\\' ){
  155637. json_simple_escape:
  155638. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  155639. p->zBuf[p->nUsed++] = '\\';
  155640. }else if( c<=0x1f ){
  155641. static const char aSpecial[] = {
  155642. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  155643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  155644. };
  155645. assert( sizeof(aSpecial)==32 );
  155646. assert( aSpecial['\b']=='b' );
  155647. assert( aSpecial['\f']=='f' );
  155648. assert( aSpecial['\n']=='n' );
  155649. assert( aSpecial['\r']=='r' );
  155650. assert( aSpecial['\t']=='t' );
  155651. if( aSpecial[c] ){
  155652. c = aSpecial[c];
  155653. goto json_simple_escape;
  155654. }
  155655. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  155656. p->zBuf[p->nUsed++] = '\\';
  155657. p->zBuf[p->nUsed++] = 'u';
  155658. p->zBuf[p->nUsed++] = '0';
  155659. p->zBuf[p->nUsed++] = '0';
  155660. p->zBuf[p->nUsed++] = '0' + (c>>4);
  155661. c = "0123456789abcdef"[c&0xf];
  155662. }
  155663. p->zBuf[p->nUsed++] = c;
  155664. }
  155665. p->zBuf[p->nUsed++] = '"';
  155666. assert( p->nUsed<p->nAlloc );
  155667. }
  155668. /*
  155669. ** Append a function parameter value to the JSON string under
  155670. ** construction.
  155671. */
  155672. static void jsonAppendValue(
  155673. JsonString *p, /* Append to this JSON string */
  155674. sqlite3_value *pValue /* Value to append */
  155675. ){
  155676. switch( sqlite3_value_type(pValue) ){
  155677. case SQLITE_NULL: {
  155678. jsonAppendRaw(p, "null", 4);
  155679. break;
  155680. }
  155681. case SQLITE_INTEGER:
  155682. case SQLITE_FLOAT: {
  155683. const char *z = (const char*)sqlite3_value_text(pValue);
  155684. u32 n = (u32)sqlite3_value_bytes(pValue);
  155685. jsonAppendRaw(p, z, n);
  155686. break;
  155687. }
  155688. case SQLITE_TEXT: {
  155689. const char *z = (const char*)sqlite3_value_text(pValue);
  155690. u32 n = (u32)sqlite3_value_bytes(pValue);
  155691. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  155692. jsonAppendRaw(p, z, n);
  155693. }else{
  155694. jsonAppendString(p, z, n);
  155695. }
  155696. break;
  155697. }
  155698. default: {
  155699. if( p->bErr==0 ){
  155700. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  155701. p->bErr = 2;
  155702. jsonReset(p);
  155703. }
  155704. break;
  155705. }
  155706. }
  155707. }
  155708. /* Make the JSON in p the result of the SQL function.
  155709. */
  155710. static void jsonResult(JsonString *p){
  155711. if( p->bErr==0 ){
  155712. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  155713. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  155714. SQLITE_UTF8);
  155715. jsonZero(p);
  155716. }
  155717. assert( p->bStatic );
  155718. }
  155719. /**************************************************************************
  155720. ** Utility routines for dealing with JsonNode and JsonParse objects
  155721. **************************************************************************/
  155722. /*
  155723. ** Return the number of consecutive JsonNode slots need to represent
  155724. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  155725. ** OBJECT types, the number might be larger.
  155726. **
  155727. ** Appended elements are not counted. The value returned is the number
  155728. ** by which the JsonNode counter should increment in order to go to the
  155729. ** next peer value.
  155730. */
  155731. static u32 jsonNodeSize(JsonNode *pNode){
  155732. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  155733. }
  155734. /*
  155735. ** Reclaim all memory allocated by a JsonParse object. But do not
  155736. ** delete the JsonParse object itself.
  155737. */
  155738. static void jsonParseReset(JsonParse *pParse){
  155739. sqlite3_free(pParse->aNode);
  155740. pParse->aNode = 0;
  155741. pParse->nNode = 0;
  155742. pParse->nAlloc = 0;
  155743. sqlite3_free(pParse->aUp);
  155744. pParse->aUp = 0;
  155745. }
  155746. /*
  155747. ** Convert the JsonNode pNode into a pure JSON string and
  155748. ** append to pOut. Subsubstructure is also included. Return
  155749. ** the number of JsonNode objects that are encoded.
  155750. */
  155751. static void jsonRenderNode(
  155752. JsonNode *pNode, /* The node to render */
  155753. JsonString *pOut, /* Write JSON here */
  155754. sqlite3_value **aReplace /* Replacement values */
  155755. ){
  155756. switch( pNode->eType ){
  155757. default: {
  155758. assert( pNode->eType==JSON_NULL );
  155759. jsonAppendRaw(pOut, "null", 4);
  155760. break;
  155761. }
  155762. case JSON_TRUE: {
  155763. jsonAppendRaw(pOut, "true", 4);
  155764. break;
  155765. }
  155766. case JSON_FALSE: {
  155767. jsonAppendRaw(pOut, "false", 5);
  155768. break;
  155769. }
  155770. case JSON_STRING: {
  155771. if( pNode->jnFlags & JNODE_RAW ){
  155772. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  155773. break;
  155774. }
  155775. /* Fall through into the next case */
  155776. }
  155777. case JSON_REAL:
  155778. case JSON_INT: {
  155779. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  155780. break;
  155781. }
  155782. case JSON_ARRAY: {
  155783. u32 j = 1;
  155784. jsonAppendChar(pOut, '[');
  155785. for(;;){
  155786. while( j<=pNode->n ){
  155787. if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
  155788. if( pNode[j].jnFlags & JNODE_REPLACE ){
  155789. jsonAppendSeparator(pOut);
  155790. jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
  155791. }
  155792. }else{
  155793. jsonAppendSeparator(pOut);
  155794. jsonRenderNode(&pNode[j], pOut, aReplace);
  155795. }
  155796. j += jsonNodeSize(&pNode[j]);
  155797. }
  155798. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  155799. pNode = &pNode[pNode->u.iAppend];
  155800. j = 1;
  155801. }
  155802. jsonAppendChar(pOut, ']');
  155803. break;
  155804. }
  155805. case JSON_OBJECT: {
  155806. u32 j = 1;
  155807. jsonAppendChar(pOut, '{');
  155808. for(;;){
  155809. while( j<=pNode->n ){
  155810. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  155811. jsonAppendSeparator(pOut);
  155812. jsonRenderNode(&pNode[j], pOut, aReplace);
  155813. jsonAppendChar(pOut, ':');
  155814. if( pNode[j+1].jnFlags & JNODE_REPLACE ){
  155815. jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
  155816. }else{
  155817. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  155818. }
  155819. }
  155820. j += 1 + jsonNodeSize(&pNode[j+1]);
  155821. }
  155822. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  155823. pNode = &pNode[pNode->u.iAppend];
  155824. j = 1;
  155825. }
  155826. jsonAppendChar(pOut, '}');
  155827. break;
  155828. }
  155829. }
  155830. }
  155831. /*
  155832. ** Return a JsonNode and all its descendents as a JSON string.
  155833. */
  155834. static void jsonReturnJson(
  155835. JsonNode *pNode, /* Node to return */
  155836. sqlite3_context *pCtx, /* Return value for this function */
  155837. sqlite3_value **aReplace /* Array of replacement values */
  155838. ){
  155839. JsonString s;
  155840. jsonInit(&s, pCtx);
  155841. jsonRenderNode(pNode, &s, aReplace);
  155842. jsonResult(&s);
  155843. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  155844. }
  155845. /*
  155846. ** Make the JsonNode the return value of the function.
  155847. */
  155848. static void jsonReturn(
  155849. JsonNode *pNode, /* Node to return */
  155850. sqlite3_context *pCtx, /* Return value for this function */
  155851. sqlite3_value **aReplace /* Array of replacement values */
  155852. ){
  155853. switch( pNode->eType ){
  155854. default: {
  155855. assert( pNode->eType==JSON_NULL );
  155856. sqlite3_result_null(pCtx);
  155857. break;
  155858. }
  155859. case JSON_TRUE: {
  155860. sqlite3_result_int(pCtx, 1);
  155861. break;
  155862. }
  155863. case JSON_FALSE: {
  155864. sqlite3_result_int(pCtx, 0);
  155865. break;
  155866. }
  155867. case JSON_INT: {
  155868. sqlite3_int64 i = 0;
  155869. const char *z = pNode->u.zJContent;
  155870. if( z[0]=='-' ){ z++; }
  155871. while( z[0]>='0' && z[0]<='9' ){
  155872. unsigned v = *(z++) - '0';
  155873. if( i>=LARGEST_INT64/10 ){
  155874. if( i>LARGEST_INT64/10 ) goto int_as_real;
  155875. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  155876. if( v==9 ) goto int_as_real;
  155877. if( v==8 ){
  155878. if( pNode->u.zJContent[0]=='-' ){
  155879. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  155880. goto int_done;
  155881. }else{
  155882. goto int_as_real;
  155883. }
  155884. }
  155885. }
  155886. i = i*10 + v;
  155887. }
  155888. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  155889. sqlite3_result_int64(pCtx, i);
  155890. int_done:
  155891. break;
  155892. int_as_real: /* fall through to real */;
  155893. }
  155894. case JSON_REAL: {
  155895. double r;
  155896. #ifdef SQLITE_AMALGAMATION
  155897. const char *z = pNode->u.zJContent;
  155898. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  155899. #else
  155900. r = strtod(pNode->u.zJContent, 0);
  155901. #endif
  155902. sqlite3_result_double(pCtx, r);
  155903. break;
  155904. }
  155905. case JSON_STRING: {
  155906. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  155907. ** json_insert() and json_replace() and those routines do not
  155908. ** call jsonReturn() */
  155909. if( pNode->jnFlags & JNODE_RAW ){
  155910. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  155911. SQLITE_TRANSIENT);
  155912. }else
  155913. #endif
  155914. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  155915. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  155916. /* JSON formatted without any backslash-escapes */
  155917. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  155918. SQLITE_TRANSIENT);
  155919. }else{
  155920. /* Translate JSON formatted string into raw text */
  155921. u32 i;
  155922. u32 n = pNode->n;
  155923. const char *z = pNode->u.zJContent;
  155924. char *zOut;
  155925. u32 j;
  155926. zOut = sqlite3_malloc( n+1 );
  155927. if( zOut==0 ){
  155928. sqlite3_result_error_nomem(pCtx);
  155929. break;
  155930. }
  155931. for(i=1, j=0; i<n-1; i++){
  155932. char c = z[i];
  155933. if( c!='\\' ){
  155934. zOut[j++] = c;
  155935. }else{
  155936. c = z[++i];
  155937. if( c=='u' ){
  155938. u32 v = 0, k;
  155939. for(k=0; k<4 && i<n-2; i++, k++){
  155940. c = z[i+1];
  155941. if( c>='0' && c<='9' ) v = v*16 + c - '0';
  155942. else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
  155943. else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
  155944. else break;
  155945. }
  155946. if( v==0 ) break;
  155947. if( v<=0x7f ){
  155948. zOut[j++] = (char)v;
  155949. }else if( v<=0x7ff ){
  155950. zOut[j++] = (char)(0xc0 | (v>>6));
  155951. zOut[j++] = 0x80 | (v&0x3f);
  155952. }else{
  155953. zOut[j++] = (char)(0xe0 | (v>>12));
  155954. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  155955. zOut[j++] = 0x80 | (v&0x3f);
  155956. }
  155957. }else{
  155958. if( c=='b' ){
  155959. c = '\b';
  155960. }else if( c=='f' ){
  155961. c = '\f';
  155962. }else if( c=='n' ){
  155963. c = '\n';
  155964. }else if( c=='r' ){
  155965. c = '\r';
  155966. }else if( c=='t' ){
  155967. c = '\t';
  155968. }
  155969. zOut[j++] = c;
  155970. }
  155971. }
  155972. }
  155973. zOut[j] = 0;
  155974. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  155975. }
  155976. break;
  155977. }
  155978. case JSON_ARRAY:
  155979. case JSON_OBJECT: {
  155980. jsonReturnJson(pNode, pCtx, aReplace);
  155981. break;
  155982. }
  155983. }
  155984. }
  155985. /* Forward reference */
  155986. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  155987. /*
  155988. ** A macro to hint to the compiler that a function should not be
  155989. ** inlined.
  155990. */
  155991. #if defined(__GNUC__)
  155992. # define JSON_NOINLINE __attribute__((noinline))
  155993. #elif defined(_MSC_VER) && _MSC_VER>=1310
  155994. # define JSON_NOINLINE __declspec(noinline)
  155995. #else
  155996. # define JSON_NOINLINE
  155997. #endif
  155998. static JSON_NOINLINE int jsonParseAddNodeExpand(
  155999. JsonParse *pParse, /* Append the node to this object */
  156000. u32 eType, /* Node type */
  156001. u32 n, /* Content size or sub-node count */
  156002. const char *zContent /* Content */
  156003. ){
  156004. u32 nNew;
  156005. JsonNode *pNew;
  156006. assert( pParse->nNode>=pParse->nAlloc );
  156007. if( pParse->oom ) return -1;
  156008. nNew = pParse->nAlloc*2 + 10;
  156009. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  156010. if( pNew==0 ){
  156011. pParse->oom = 1;
  156012. return -1;
  156013. }
  156014. pParse->nAlloc = nNew;
  156015. pParse->aNode = pNew;
  156016. assert( pParse->nNode<pParse->nAlloc );
  156017. return jsonParseAddNode(pParse, eType, n, zContent);
  156018. }
  156019. /*
  156020. ** Create a new JsonNode instance based on the arguments and append that
  156021. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  156022. ** new node, or -1 if a memory allocation fails.
  156023. */
  156024. static int jsonParseAddNode(
  156025. JsonParse *pParse, /* Append the node to this object */
  156026. u32 eType, /* Node type */
  156027. u32 n, /* Content size or sub-node count */
  156028. const char *zContent /* Content */
  156029. ){
  156030. JsonNode *p;
  156031. if( pParse->nNode>=pParse->nAlloc ){
  156032. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  156033. }
  156034. p = &pParse->aNode[pParse->nNode];
  156035. p->eType = (u8)eType;
  156036. p->jnFlags = 0;
  156037. p->iVal = 0;
  156038. p->n = n;
  156039. p->u.zJContent = zContent;
  156040. return pParse->nNode++;
  156041. }
  156042. /*
  156043. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  156044. ** index of the first character past the end of the value parsed.
  156045. **
  156046. ** Return negative for a syntax error. Special cases: return -2 if the
  156047. ** first non-whitespace character is '}' and return -3 if the first
  156048. ** non-whitespace character is ']'.
  156049. */
  156050. static int jsonParseValue(JsonParse *pParse, u32 i){
  156051. char c;
  156052. u32 j;
  156053. int iThis;
  156054. int x;
  156055. JsonNode *pNode;
  156056. while( safe_isspace(pParse->zJson[i]) ){ i++; }
  156057. if( (c = pParse->zJson[i])=='{' ){
  156058. /* Parse object */
  156059. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  156060. if( iThis<0 ) return -1;
  156061. for(j=i+1;;j++){
  156062. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  156063. x = jsonParseValue(pParse, j);
  156064. if( x<0 ){
  156065. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  156066. return -1;
  156067. }
  156068. if( pParse->oom ) return -1;
  156069. pNode = &pParse->aNode[pParse->nNode-1];
  156070. if( pNode->eType!=JSON_STRING ) return -1;
  156071. pNode->jnFlags |= JNODE_LABEL;
  156072. j = x;
  156073. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  156074. if( pParse->zJson[j]!=':' ) return -1;
  156075. j++;
  156076. x = jsonParseValue(pParse, j);
  156077. if( x<0 ) return -1;
  156078. j = x;
  156079. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  156080. c = pParse->zJson[j];
  156081. if( c==',' ) continue;
  156082. if( c!='}' ) return -1;
  156083. break;
  156084. }
  156085. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  156086. return j+1;
  156087. }else if( c=='[' ){
  156088. /* Parse array */
  156089. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  156090. if( iThis<0 ) return -1;
  156091. for(j=i+1;;j++){
  156092. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  156093. x = jsonParseValue(pParse, j);
  156094. if( x<0 ){
  156095. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  156096. return -1;
  156097. }
  156098. j = x;
  156099. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  156100. c = pParse->zJson[j];
  156101. if( c==',' ) continue;
  156102. if( c!=']' ) return -1;
  156103. break;
  156104. }
  156105. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  156106. return j+1;
  156107. }else if( c=='"' ){
  156108. /* Parse string */
  156109. u8 jnFlags = 0;
  156110. j = i+1;
  156111. for(;;){
  156112. c = pParse->zJson[j];
  156113. if( c==0 ) return -1;
  156114. if( c=='\\' ){
  156115. c = pParse->zJson[++j];
  156116. if( c==0 ) return -1;
  156117. jnFlags = JNODE_ESCAPE;
  156118. }else if( c=='"' ){
  156119. break;
  156120. }
  156121. j++;
  156122. }
  156123. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
  156124. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  156125. return j+1;
  156126. }else if( c=='n'
  156127. && strncmp(pParse->zJson+i,"null",4)==0
  156128. && !safe_isalnum(pParse->zJson[i+4]) ){
  156129. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  156130. return i+4;
  156131. }else if( c=='t'
  156132. && strncmp(pParse->zJson+i,"true",4)==0
  156133. && !safe_isalnum(pParse->zJson[i+4]) ){
  156134. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  156135. return i+4;
  156136. }else if( c=='f'
  156137. && strncmp(pParse->zJson+i,"false",5)==0
  156138. && !safe_isalnum(pParse->zJson[i+5]) ){
  156139. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  156140. return i+5;
  156141. }else if( c=='-' || (c>='0' && c<='9') ){
  156142. /* Parse number */
  156143. u8 seenDP = 0;
  156144. u8 seenE = 0;
  156145. j = i+1;
  156146. for(;; j++){
  156147. c = pParse->zJson[j];
  156148. if( c>='0' && c<='9' ) continue;
  156149. if( c=='.' ){
  156150. if( pParse->zJson[j-1]=='-' ) return -1;
  156151. if( seenDP ) return -1;
  156152. seenDP = 1;
  156153. continue;
  156154. }
  156155. if( c=='e' || c=='E' ){
  156156. if( pParse->zJson[j-1]<'0' ) return -1;
  156157. if( seenE ) return -1;
  156158. seenDP = seenE = 1;
  156159. c = pParse->zJson[j+1];
  156160. if( c=='+' || c=='-' ){
  156161. j++;
  156162. c = pParse->zJson[j+1];
  156163. }
  156164. if( c<'0' || c>'9' ) return -1;
  156165. continue;
  156166. }
  156167. break;
  156168. }
  156169. if( pParse->zJson[j-1]<'0' ) return -1;
  156170. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  156171. j - i, &pParse->zJson[i]);
  156172. return j;
  156173. }else if( c=='}' ){
  156174. return -2; /* End of {...} */
  156175. }else if( c==']' ){
  156176. return -3; /* End of [...] */
  156177. }else if( c==0 ){
  156178. return 0; /* End of file */
  156179. }else{
  156180. return -1; /* Syntax error */
  156181. }
  156182. }
  156183. /*
  156184. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  156185. ** are any errors. If an error occurs, free all memory associated with
  156186. ** pParse.
  156187. **
  156188. ** pParse is uninitialized when this routine is called.
  156189. */
  156190. static int jsonParse(
  156191. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  156192. sqlite3_context *pCtx, /* Report errors here */
  156193. const char *zJson /* Input JSON text to be parsed */
  156194. ){
  156195. int i;
  156196. memset(pParse, 0, sizeof(*pParse));
  156197. if( zJson==0 ) return 1;
  156198. pParse->zJson = zJson;
  156199. i = jsonParseValue(pParse, 0);
  156200. if( pParse->oom ) i = -1;
  156201. if( i>0 ){
  156202. while( safe_isspace(zJson[i]) ) i++;
  156203. if( zJson[i] ) i = -1;
  156204. }
  156205. if( i<=0 ){
  156206. if( pCtx!=0 ){
  156207. if( pParse->oom ){
  156208. sqlite3_result_error_nomem(pCtx);
  156209. }else{
  156210. sqlite3_result_error(pCtx, "malformed JSON", -1);
  156211. }
  156212. }
  156213. jsonParseReset(pParse);
  156214. return 1;
  156215. }
  156216. return 0;
  156217. }
  156218. /* Mark node i of pParse as being a child of iParent. Call recursively
  156219. ** to fill in all the descendants of node i.
  156220. */
  156221. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  156222. JsonNode *pNode = &pParse->aNode[i];
  156223. u32 j;
  156224. pParse->aUp[i] = iParent;
  156225. switch( pNode->eType ){
  156226. case JSON_ARRAY: {
  156227. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  156228. jsonParseFillInParentage(pParse, i+j, i);
  156229. }
  156230. break;
  156231. }
  156232. case JSON_OBJECT: {
  156233. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  156234. pParse->aUp[i+j] = i;
  156235. jsonParseFillInParentage(pParse, i+j+1, i);
  156236. }
  156237. break;
  156238. }
  156239. default: {
  156240. break;
  156241. }
  156242. }
  156243. }
  156244. /*
  156245. ** Compute the parentage of all nodes in a completed parse.
  156246. */
  156247. static int jsonParseFindParents(JsonParse *pParse){
  156248. u32 *aUp;
  156249. assert( pParse->aUp==0 );
  156250. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  156251. if( aUp==0 ){
  156252. pParse->oom = 1;
  156253. return SQLITE_NOMEM;
  156254. }
  156255. jsonParseFillInParentage(pParse, 0, 0);
  156256. return SQLITE_OK;
  156257. }
  156258. /*
  156259. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  156260. ** a match.
  156261. */
  156262. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  156263. if( pNode->jnFlags & JNODE_RAW ){
  156264. if( pNode->n!=nKey ) return 0;
  156265. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  156266. }else{
  156267. if( pNode->n!=nKey+2 ) return 0;
  156268. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  156269. }
  156270. }
  156271. /* forward declaration */
  156272. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  156273. /*
  156274. ** Search along zPath to find the node specified. Return a pointer
  156275. ** to that node, or NULL if zPath is malformed or if there is no such
  156276. ** node.
  156277. **
  156278. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  156279. ** possible to do so and if no existing node corresponds to zPath. If
  156280. ** new nodes are appended *pApnd is set to 1.
  156281. */
  156282. static JsonNode *jsonLookupStep(
  156283. JsonParse *pParse, /* The JSON to search */
  156284. u32 iRoot, /* Begin the search at this node */
  156285. const char *zPath, /* The path to search */
  156286. int *pApnd, /* Append nodes to complete path if not NULL */
  156287. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  156288. ){
  156289. u32 i, j, nKey;
  156290. const char *zKey;
  156291. JsonNode *pRoot = &pParse->aNode[iRoot];
  156292. if( zPath[0]==0 ) return pRoot;
  156293. if( zPath[0]=='.' ){
  156294. if( pRoot->eType!=JSON_OBJECT ) return 0;
  156295. zPath++;
  156296. if( zPath[0]=='"' ){
  156297. zKey = zPath + 1;
  156298. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  156299. nKey = i-1;
  156300. if( zPath[i] ){
  156301. i++;
  156302. }else{
  156303. *pzErr = zPath;
  156304. return 0;
  156305. }
  156306. }else{
  156307. zKey = zPath;
  156308. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  156309. nKey = i;
  156310. }
  156311. if( nKey==0 ){
  156312. *pzErr = zPath;
  156313. return 0;
  156314. }
  156315. j = 1;
  156316. for(;;){
  156317. while( j<=pRoot->n ){
  156318. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  156319. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  156320. }
  156321. j++;
  156322. j += jsonNodeSize(&pRoot[j]);
  156323. }
  156324. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  156325. iRoot += pRoot->u.iAppend;
  156326. pRoot = &pParse->aNode[iRoot];
  156327. j = 1;
  156328. }
  156329. if( pApnd ){
  156330. u32 iStart, iLabel;
  156331. JsonNode *pNode;
  156332. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  156333. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  156334. zPath += i;
  156335. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  156336. if( pParse->oom ) return 0;
  156337. if( pNode ){
  156338. pRoot = &pParse->aNode[iRoot];
  156339. pRoot->u.iAppend = iStart - iRoot;
  156340. pRoot->jnFlags |= JNODE_APPEND;
  156341. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  156342. }
  156343. return pNode;
  156344. }
  156345. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  156346. if( pRoot->eType!=JSON_ARRAY ) return 0;
  156347. i = 0;
  156348. j = 1;
  156349. while( safe_isdigit(zPath[j]) ){
  156350. i = i*10 + zPath[j] - '0';
  156351. j++;
  156352. }
  156353. if( zPath[j]!=']' ){
  156354. *pzErr = zPath;
  156355. return 0;
  156356. }
  156357. zPath += j + 1;
  156358. j = 1;
  156359. for(;;){
  156360. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  156361. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  156362. j += jsonNodeSize(&pRoot[j]);
  156363. }
  156364. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  156365. iRoot += pRoot->u.iAppend;
  156366. pRoot = &pParse->aNode[iRoot];
  156367. j = 1;
  156368. }
  156369. if( j<=pRoot->n ){
  156370. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  156371. }
  156372. if( i==0 && pApnd ){
  156373. u32 iStart;
  156374. JsonNode *pNode;
  156375. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  156376. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  156377. if( pParse->oom ) return 0;
  156378. if( pNode ){
  156379. pRoot = &pParse->aNode[iRoot];
  156380. pRoot->u.iAppend = iStart - iRoot;
  156381. pRoot->jnFlags |= JNODE_APPEND;
  156382. }
  156383. return pNode;
  156384. }
  156385. }else{
  156386. *pzErr = zPath;
  156387. }
  156388. return 0;
  156389. }
  156390. /*
  156391. ** Append content to pParse that will complete zPath. Return a pointer
  156392. ** to the inserted node, or return NULL if the append fails.
  156393. */
  156394. static JsonNode *jsonLookupAppend(
  156395. JsonParse *pParse, /* Append content to the JSON parse */
  156396. const char *zPath, /* Description of content to append */
  156397. int *pApnd, /* Set this flag to 1 */
  156398. const char **pzErr /* Make this point to any syntax error */
  156399. ){
  156400. *pApnd = 1;
  156401. if( zPath[0]==0 ){
  156402. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  156403. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  156404. }
  156405. if( zPath[0]=='.' ){
  156406. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  156407. }else if( strncmp(zPath,"[0]",3)==0 ){
  156408. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  156409. }else{
  156410. return 0;
  156411. }
  156412. if( pParse->oom ) return 0;
  156413. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  156414. }
  156415. /*
  156416. ** Return the text of a syntax error message on a JSON path. Space is
  156417. ** obtained from sqlite3_malloc().
  156418. */
  156419. static char *jsonPathSyntaxError(const char *zErr){
  156420. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  156421. }
  156422. /*
  156423. ** Do a node lookup using zPath. Return a pointer to the node on success.
  156424. ** Return NULL if not found or if there is an error.
  156425. **
  156426. ** On an error, write an error message into pCtx and increment the
  156427. ** pParse->nErr counter.
  156428. **
  156429. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  156430. ** nodes are appended.
  156431. */
  156432. static JsonNode *jsonLookup(
  156433. JsonParse *pParse, /* The JSON to search */
  156434. const char *zPath, /* The path to search */
  156435. int *pApnd, /* Append nodes to complete path if not NULL */
  156436. sqlite3_context *pCtx /* Report errors here, if not NULL */
  156437. ){
  156438. const char *zErr = 0;
  156439. JsonNode *pNode = 0;
  156440. char *zMsg;
  156441. if( zPath==0 ) return 0;
  156442. if( zPath[0]!='$' ){
  156443. zErr = zPath;
  156444. goto lookup_err;
  156445. }
  156446. zPath++;
  156447. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  156448. if( zErr==0 ) return pNode;
  156449. lookup_err:
  156450. pParse->nErr++;
  156451. assert( zErr!=0 && pCtx!=0 );
  156452. zMsg = jsonPathSyntaxError(zErr);
  156453. if( zMsg ){
  156454. sqlite3_result_error(pCtx, zMsg, -1);
  156455. sqlite3_free(zMsg);
  156456. }else{
  156457. sqlite3_result_error_nomem(pCtx);
  156458. }
  156459. return 0;
  156460. }
  156461. /*
  156462. ** Report the wrong number of arguments for json_insert(), json_replace()
  156463. ** or json_set().
  156464. */
  156465. static void jsonWrongNumArgs(
  156466. sqlite3_context *pCtx,
  156467. const char *zFuncName
  156468. ){
  156469. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  156470. zFuncName);
  156471. sqlite3_result_error(pCtx, zMsg, -1);
  156472. sqlite3_free(zMsg);
  156473. }
  156474. /****************************************************************************
  156475. ** SQL functions used for testing and debugging
  156476. ****************************************************************************/
  156477. #ifdef SQLITE_DEBUG
  156478. /*
  156479. ** The json_parse(JSON) function returns a string which describes
  156480. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  156481. ** well-formed.
  156482. */
  156483. static void jsonParseFunc(
  156484. sqlite3_context *ctx,
  156485. int argc,
  156486. sqlite3_value **argv
  156487. ){
  156488. JsonString s; /* Output string - not real JSON */
  156489. JsonParse x; /* The parse */
  156490. u32 i;
  156491. assert( argc==1 );
  156492. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156493. jsonParseFindParents(&x);
  156494. jsonInit(&s, ctx);
  156495. for(i=0; i<x.nNode; i++){
  156496. const char *zType;
  156497. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  156498. assert( x.aNode[i].eType==JSON_STRING );
  156499. zType = "label";
  156500. }else{
  156501. zType = jsonType[x.aNode[i].eType];
  156502. }
  156503. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  156504. i, zType, x.aNode[i].n, x.aUp[i]);
  156505. if( x.aNode[i].u.zJContent!=0 ){
  156506. jsonAppendRaw(&s, " ", 1);
  156507. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  156508. }
  156509. jsonAppendRaw(&s, "\n", 1);
  156510. }
  156511. jsonParseReset(&x);
  156512. jsonResult(&s);
  156513. }
  156514. /*
  156515. ** The json_test1(JSON) function return true (1) if the input is JSON
  156516. ** text generated by another json function. It returns (0) if the input
  156517. ** is not known to be JSON.
  156518. */
  156519. static void jsonTest1Func(
  156520. sqlite3_context *ctx,
  156521. int argc,
  156522. sqlite3_value **argv
  156523. ){
  156524. UNUSED_PARAM(argc);
  156525. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  156526. }
  156527. #endif /* SQLITE_DEBUG */
  156528. /****************************************************************************
  156529. ** Scalar SQL function implementations
  156530. ****************************************************************************/
  156531. /*
  156532. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  156533. ** array that contains all values given in arguments. Or if any argument
  156534. ** is a BLOB, throw an error.
  156535. */
  156536. static void jsonArrayFunc(
  156537. sqlite3_context *ctx,
  156538. int argc,
  156539. sqlite3_value **argv
  156540. ){
  156541. int i;
  156542. JsonString jx;
  156543. jsonInit(&jx, ctx);
  156544. jsonAppendChar(&jx, '[');
  156545. for(i=0; i<argc; i++){
  156546. jsonAppendSeparator(&jx);
  156547. jsonAppendValue(&jx, argv[i]);
  156548. }
  156549. jsonAppendChar(&jx, ']');
  156550. jsonResult(&jx);
  156551. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  156552. }
  156553. /*
  156554. ** json_array_length(JSON)
  156555. ** json_array_length(JSON, PATH)
  156556. **
  156557. ** Return the number of elements in the top-level JSON array.
  156558. ** Return 0 if the input is not a well-formed JSON array.
  156559. */
  156560. static void jsonArrayLengthFunc(
  156561. sqlite3_context *ctx,
  156562. int argc,
  156563. sqlite3_value **argv
  156564. ){
  156565. JsonParse x; /* The parse */
  156566. sqlite3_int64 n = 0;
  156567. u32 i;
  156568. JsonNode *pNode;
  156569. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156570. assert( x.nNode );
  156571. if( argc==2 ){
  156572. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  156573. pNode = jsonLookup(&x, zPath, 0, ctx);
  156574. }else{
  156575. pNode = x.aNode;
  156576. }
  156577. if( pNode==0 ){
  156578. x.nErr = 1;
  156579. }else if( pNode->eType==JSON_ARRAY ){
  156580. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  156581. for(i=1; i<=pNode->n; n++){
  156582. i += jsonNodeSize(&pNode[i]);
  156583. }
  156584. }
  156585. if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
  156586. jsonParseReset(&x);
  156587. }
  156588. /*
  156589. ** json_extract(JSON, PATH, ...)
  156590. **
  156591. ** Return the element described by PATH. Return NULL if there is no
  156592. ** PATH element. If there are multiple PATHs, then return a JSON array
  156593. ** with the result from each path. Throw an error if the JSON or any PATH
  156594. ** is malformed.
  156595. */
  156596. static void jsonExtractFunc(
  156597. sqlite3_context *ctx,
  156598. int argc,
  156599. sqlite3_value **argv
  156600. ){
  156601. JsonParse x; /* The parse */
  156602. JsonNode *pNode;
  156603. const char *zPath;
  156604. JsonString jx;
  156605. int i;
  156606. if( argc<2 ) return;
  156607. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156608. jsonInit(&jx, ctx);
  156609. jsonAppendChar(&jx, '[');
  156610. for(i=1; i<argc; i++){
  156611. zPath = (const char*)sqlite3_value_text(argv[i]);
  156612. pNode = jsonLookup(&x, zPath, 0, ctx);
  156613. if( x.nErr ) break;
  156614. if( argc>2 ){
  156615. jsonAppendSeparator(&jx);
  156616. if( pNode ){
  156617. jsonRenderNode(pNode, &jx, 0);
  156618. }else{
  156619. jsonAppendRaw(&jx, "null", 4);
  156620. }
  156621. }else if( pNode ){
  156622. jsonReturn(pNode, ctx, 0);
  156623. }
  156624. }
  156625. if( argc>2 && i==argc ){
  156626. jsonAppendChar(&jx, ']');
  156627. jsonResult(&jx);
  156628. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  156629. }
  156630. jsonReset(&jx);
  156631. jsonParseReset(&x);
  156632. }
  156633. /*
  156634. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  156635. ** object that contains all name/value given in arguments. Or if any name
  156636. ** is not a string or if any value is a BLOB, throw an error.
  156637. */
  156638. static void jsonObjectFunc(
  156639. sqlite3_context *ctx,
  156640. int argc,
  156641. sqlite3_value **argv
  156642. ){
  156643. int i;
  156644. JsonString jx;
  156645. const char *z;
  156646. u32 n;
  156647. if( argc&1 ){
  156648. sqlite3_result_error(ctx, "json_object() requires an even number "
  156649. "of arguments", -1);
  156650. return;
  156651. }
  156652. jsonInit(&jx, ctx);
  156653. jsonAppendChar(&jx, '{');
  156654. for(i=0; i<argc; i+=2){
  156655. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  156656. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  156657. jsonReset(&jx);
  156658. return;
  156659. }
  156660. jsonAppendSeparator(&jx);
  156661. z = (const char*)sqlite3_value_text(argv[i]);
  156662. n = (u32)sqlite3_value_bytes(argv[i]);
  156663. jsonAppendString(&jx, z, n);
  156664. jsonAppendChar(&jx, ':');
  156665. jsonAppendValue(&jx, argv[i+1]);
  156666. }
  156667. jsonAppendChar(&jx, '}');
  156668. jsonResult(&jx);
  156669. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  156670. }
  156671. /*
  156672. ** json_remove(JSON, PATH, ...)
  156673. **
  156674. ** Remove the named elements from JSON and return the result. malformed
  156675. ** JSON or PATH arguments result in an error.
  156676. */
  156677. static void jsonRemoveFunc(
  156678. sqlite3_context *ctx,
  156679. int argc,
  156680. sqlite3_value **argv
  156681. ){
  156682. JsonParse x; /* The parse */
  156683. JsonNode *pNode;
  156684. const char *zPath;
  156685. u32 i;
  156686. if( argc<1 ) return;
  156687. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156688. assert( x.nNode );
  156689. for(i=1; i<(u32)argc; i++){
  156690. zPath = (const char*)sqlite3_value_text(argv[i]);
  156691. if( zPath==0 ) goto remove_done;
  156692. pNode = jsonLookup(&x, zPath, 0, ctx);
  156693. if( x.nErr ) goto remove_done;
  156694. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  156695. }
  156696. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  156697. jsonReturnJson(x.aNode, ctx, 0);
  156698. }
  156699. remove_done:
  156700. jsonParseReset(&x);
  156701. }
  156702. /*
  156703. ** json_replace(JSON, PATH, VALUE, ...)
  156704. **
  156705. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  156706. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  156707. */
  156708. static void jsonReplaceFunc(
  156709. sqlite3_context *ctx,
  156710. int argc,
  156711. sqlite3_value **argv
  156712. ){
  156713. JsonParse x; /* The parse */
  156714. JsonNode *pNode;
  156715. const char *zPath;
  156716. u32 i;
  156717. if( argc<1 ) return;
  156718. if( (argc&1)==0 ) {
  156719. jsonWrongNumArgs(ctx, "replace");
  156720. return;
  156721. }
  156722. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156723. assert( x.nNode );
  156724. for(i=1; i<(u32)argc; i+=2){
  156725. zPath = (const char*)sqlite3_value_text(argv[i]);
  156726. pNode = jsonLookup(&x, zPath, 0, ctx);
  156727. if( x.nErr ) goto replace_err;
  156728. if( pNode ){
  156729. pNode->jnFlags |= (u8)JNODE_REPLACE;
  156730. pNode->iVal = (u8)(i+1);
  156731. }
  156732. }
  156733. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  156734. sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
  156735. }else{
  156736. jsonReturnJson(x.aNode, ctx, argv);
  156737. }
  156738. replace_err:
  156739. jsonParseReset(&x);
  156740. }
  156741. /*
  156742. ** json_set(JSON, PATH, VALUE, ...)
  156743. **
  156744. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  156745. ** exist. Overwrite existing values that do exist.
  156746. ** If JSON or PATH is malformed, throw an error.
  156747. **
  156748. ** json_insert(JSON, PATH, VALUE, ...)
  156749. **
  156750. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  156751. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  156752. */
  156753. static void jsonSetFunc(
  156754. sqlite3_context *ctx,
  156755. int argc,
  156756. sqlite3_value **argv
  156757. ){
  156758. JsonParse x; /* The parse */
  156759. JsonNode *pNode;
  156760. const char *zPath;
  156761. u32 i;
  156762. int bApnd;
  156763. int bIsSet = *(int*)sqlite3_user_data(ctx);
  156764. if( argc<1 ) return;
  156765. if( (argc&1)==0 ) {
  156766. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  156767. return;
  156768. }
  156769. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156770. assert( x.nNode );
  156771. for(i=1; i<(u32)argc; i+=2){
  156772. zPath = (const char*)sqlite3_value_text(argv[i]);
  156773. bApnd = 0;
  156774. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  156775. if( x.oom ){
  156776. sqlite3_result_error_nomem(ctx);
  156777. goto jsonSetDone;
  156778. }else if( x.nErr ){
  156779. goto jsonSetDone;
  156780. }else if( pNode && (bApnd || bIsSet) ){
  156781. pNode->jnFlags |= (u8)JNODE_REPLACE;
  156782. pNode->iVal = (u8)(i+1);
  156783. }
  156784. }
  156785. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  156786. sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
  156787. }else{
  156788. jsonReturnJson(x.aNode, ctx, argv);
  156789. }
  156790. jsonSetDone:
  156791. jsonParseReset(&x);
  156792. }
  156793. /*
  156794. ** json_type(JSON)
  156795. ** json_type(JSON, PATH)
  156796. **
  156797. ** Return the top-level "type" of a JSON string. Throw an error if
  156798. ** either the JSON or PATH inputs are not well-formed.
  156799. */
  156800. static void jsonTypeFunc(
  156801. sqlite3_context *ctx,
  156802. int argc,
  156803. sqlite3_value **argv
  156804. ){
  156805. JsonParse x; /* The parse */
  156806. const char *zPath;
  156807. JsonNode *pNode;
  156808. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  156809. assert( x.nNode );
  156810. if( argc==2 ){
  156811. zPath = (const char*)sqlite3_value_text(argv[1]);
  156812. pNode = jsonLookup(&x, zPath, 0, ctx);
  156813. }else{
  156814. pNode = x.aNode;
  156815. }
  156816. if( pNode ){
  156817. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  156818. }
  156819. jsonParseReset(&x);
  156820. }
  156821. /*
  156822. ** json_valid(JSON)
  156823. **
  156824. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  156825. ** Return 0 otherwise.
  156826. */
  156827. static void jsonValidFunc(
  156828. sqlite3_context *ctx,
  156829. int argc,
  156830. sqlite3_value **argv
  156831. ){
  156832. JsonParse x; /* The parse */
  156833. int rc = 0;
  156834. UNUSED_PARAM(argc);
  156835. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  156836. rc = 1;
  156837. }
  156838. jsonParseReset(&x);
  156839. sqlite3_result_int(ctx, rc);
  156840. }
  156841. /****************************************************************************
  156842. ** Aggregate SQL function implementations
  156843. ****************************************************************************/
  156844. /*
  156845. ** json_group_array(VALUE)
  156846. **
  156847. ** Return a JSON array composed of all values in the aggregate.
  156848. */
  156849. static void jsonArrayStep(
  156850. sqlite3_context *ctx,
  156851. int argc,
  156852. sqlite3_value **argv
  156853. ){
  156854. JsonString *pStr;
  156855. UNUSED_PARAM(argc);
  156856. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  156857. if( pStr ){
  156858. if( pStr->zBuf==0 ){
  156859. jsonInit(pStr, ctx);
  156860. jsonAppendChar(pStr, '[');
  156861. }else{
  156862. jsonAppendChar(pStr, ',');
  156863. pStr->pCtx = ctx;
  156864. }
  156865. jsonAppendValue(pStr, argv[0]);
  156866. }
  156867. }
  156868. static void jsonArrayFinal(sqlite3_context *ctx){
  156869. JsonString *pStr;
  156870. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  156871. if( pStr ){
  156872. pStr->pCtx = ctx;
  156873. jsonAppendChar(pStr, ']');
  156874. if( pStr->bErr ){
  156875. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  156876. assert( pStr->bStatic );
  156877. }else{
  156878. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  156879. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  156880. pStr->bStatic = 1;
  156881. }
  156882. }else{
  156883. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  156884. }
  156885. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  156886. }
  156887. /*
  156888. ** json_group_obj(NAME,VALUE)
  156889. **
  156890. ** Return a JSON object composed of all names and values in the aggregate.
  156891. */
  156892. static void jsonObjectStep(
  156893. sqlite3_context *ctx,
  156894. int argc,
  156895. sqlite3_value **argv
  156896. ){
  156897. JsonString *pStr;
  156898. const char *z;
  156899. u32 n;
  156900. UNUSED_PARAM(argc);
  156901. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  156902. if( pStr ){
  156903. if( pStr->zBuf==0 ){
  156904. jsonInit(pStr, ctx);
  156905. jsonAppendChar(pStr, '{');
  156906. }else{
  156907. jsonAppendChar(pStr, ',');
  156908. pStr->pCtx = ctx;
  156909. }
  156910. z = (const char*)sqlite3_value_text(argv[0]);
  156911. n = (u32)sqlite3_value_bytes(argv[0]);
  156912. jsonAppendString(pStr, z, n);
  156913. jsonAppendChar(pStr, ':');
  156914. jsonAppendValue(pStr, argv[1]);
  156915. }
  156916. }
  156917. static void jsonObjectFinal(sqlite3_context *ctx){
  156918. JsonString *pStr;
  156919. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  156920. if( pStr ){
  156921. jsonAppendChar(pStr, '}');
  156922. if( pStr->bErr ){
  156923. if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
  156924. assert( pStr->bStatic );
  156925. }else{
  156926. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  156927. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  156928. pStr->bStatic = 1;
  156929. }
  156930. }else{
  156931. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  156932. }
  156933. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  156934. }
  156935. #ifndef SQLITE_OMIT_VIRTUALTABLE
  156936. /****************************************************************************
  156937. ** The json_each virtual table
  156938. ****************************************************************************/
  156939. typedef struct JsonEachCursor JsonEachCursor;
  156940. struct JsonEachCursor {
  156941. sqlite3_vtab_cursor base; /* Base class - must be first */
  156942. u32 iRowid; /* The rowid */
  156943. u32 iBegin; /* The first node of the scan */
  156944. u32 i; /* Index in sParse.aNode[] of current row */
  156945. u32 iEnd; /* EOF when i equals or exceeds this value */
  156946. u8 eType; /* Type of top-level element */
  156947. u8 bRecursive; /* True for json_tree(). False for json_each() */
  156948. char *zJson; /* Input JSON */
  156949. char *zRoot; /* Path by which to filter zJson */
  156950. JsonParse sParse; /* Parse of the input JSON */
  156951. };
  156952. /* Constructor for the json_each virtual table */
  156953. static int jsonEachConnect(
  156954. sqlite3 *db,
  156955. void *pAux,
  156956. int argc, const char *const*argv,
  156957. sqlite3_vtab **ppVtab,
  156958. char **pzErr
  156959. ){
  156960. sqlite3_vtab *pNew;
  156961. int rc;
  156962. /* Column numbers */
  156963. #define JEACH_KEY 0
  156964. #define JEACH_VALUE 1
  156965. #define JEACH_TYPE 2
  156966. #define JEACH_ATOM 3
  156967. #define JEACH_ID 4
  156968. #define JEACH_PARENT 5
  156969. #define JEACH_FULLKEY 6
  156970. #define JEACH_PATH 7
  156971. #define JEACH_JSON 8
  156972. #define JEACH_ROOT 9
  156973. UNUSED_PARAM(pzErr);
  156974. UNUSED_PARAM(argv);
  156975. UNUSED_PARAM(argc);
  156976. UNUSED_PARAM(pAux);
  156977. rc = sqlite3_declare_vtab(db,
  156978. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  156979. "json HIDDEN,root HIDDEN)");
  156980. if( rc==SQLITE_OK ){
  156981. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  156982. if( pNew==0 ) return SQLITE_NOMEM;
  156983. memset(pNew, 0, sizeof(*pNew));
  156984. }
  156985. return rc;
  156986. }
  156987. /* destructor for json_each virtual table */
  156988. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  156989. sqlite3_free(pVtab);
  156990. return SQLITE_OK;
  156991. }
  156992. /* constructor for a JsonEachCursor object for json_each(). */
  156993. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  156994. JsonEachCursor *pCur;
  156995. UNUSED_PARAM(p);
  156996. pCur = sqlite3_malloc( sizeof(*pCur) );
  156997. if( pCur==0 ) return SQLITE_NOMEM;
  156998. memset(pCur, 0, sizeof(*pCur));
  156999. *ppCursor = &pCur->base;
  157000. return SQLITE_OK;
  157001. }
  157002. /* constructor for a JsonEachCursor object for json_tree(). */
  157003. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  157004. int rc = jsonEachOpenEach(p, ppCursor);
  157005. if( rc==SQLITE_OK ){
  157006. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  157007. pCur->bRecursive = 1;
  157008. }
  157009. return rc;
  157010. }
  157011. /* Reset a JsonEachCursor back to its original state. Free any memory
  157012. ** held. */
  157013. static void jsonEachCursorReset(JsonEachCursor *p){
  157014. sqlite3_free(p->zJson);
  157015. sqlite3_free(p->zRoot);
  157016. jsonParseReset(&p->sParse);
  157017. p->iRowid = 0;
  157018. p->i = 0;
  157019. p->iEnd = 0;
  157020. p->eType = 0;
  157021. p->zJson = 0;
  157022. p->zRoot = 0;
  157023. }
  157024. /* Destructor for a jsonEachCursor object */
  157025. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  157026. JsonEachCursor *p = (JsonEachCursor*)cur;
  157027. jsonEachCursorReset(p);
  157028. sqlite3_free(cur);
  157029. return SQLITE_OK;
  157030. }
  157031. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  157032. ** of the JSON object */
  157033. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  157034. JsonEachCursor *p = (JsonEachCursor*)cur;
  157035. return p->i >= p->iEnd;
  157036. }
  157037. /* Advance the cursor to the next element for json_tree() */
  157038. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  157039. JsonEachCursor *p = (JsonEachCursor*)cur;
  157040. if( p->bRecursive ){
  157041. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  157042. p->i++;
  157043. p->iRowid++;
  157044. if( p->i<p->iEnd ){
  157045. u32 iUp = p->sParse.aUp[p->i];
  157046. JsonNode *pUp = &p->sParse.aNode[iUp];
  157047. p->eType = pUp->eType;
  157048. if( pUp->eType==JSON_ARRAY ){
  157049. if( iUp==p->i-1 ){
  157050. pUp->u.iKey = 0;
  157051. }else{
  157052. pUp->u.iKey++;
  157053. }
  157054. }
  157055. }
  157056. }else{
  157057. switch( p->eType ){
  157058. case JSON_ARRAY: {
  157059. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  157060. p->iRowid++;
  157061. break;
  157062. }
  157063. case JSON_OBJECT: {
  157064. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  157065. p->iRowid++;
  157066. break;
  157067. }
  157068. default: {
  157069. p->i = p->iEnd;
  157070. break;
  157071. }
  157072. }
  157073. }
  157074. return SQLITE_OK;
  157075. }
  157076. /* Append the name of the path for element i to pStr
  157077. */
  157078. static void jsonEachComputePath(
  157079. JsonEachCursor *p, /* The cursor */
  157080. JsonString *pStr, /* Write the path here */
  157081. u32 i /* Path to this element */
  157082. ){
  157083. JsonNode *pNode, *pUp;
  157084. u32 iUp;
  157085. if( i==0 ){
  157086. jsonAppendChar(pStr, '$');
  157087. return;
  157088. }
  157089. iUp = p->sParse.aUp[i];
  157090. jsonEachComputePath(p, pStr, iUp);
  157091. pNode = &p->sParse.aNode[i];
  157092. pUp = &p->sParse.aNode[iUp];
  157093. if( pUp->eType==JSON_ARRAY ){
  157094. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  157095. }else{
  157096. assert( pUp->eType==JSON_OBJECT );
  157097. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  157098. assert( pNode->eType==JSON_STRING );
  157099. assert( pNode->jnFlags & JNODE_LABEL );
  157100. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  157101. }
  157102. }
  157103. /* Return the value of a column */
  157104. static int jsonEachColumn(
  157105. sqlite3_vtab_cursor *cur, /* The cursor */
  157106. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  157107. int i /* Which column to return */
  157108. ){
  157109. JsonEachCursor *p = (JsonEachCursor*)cur;
  157110. JsonNode *pThis = &p->sParse.aNode[p->i];
  157111. switch( i ){
  157112. case JEACH_KEY: {
  157113. if( p->i==0 ) break;
  157114. if( p->eType==JSON_OBJECT ){
  157115. jsonReturn(pThis, ctx, 0);
  157116. }else if( p->eType==JSON_ARRAY ){
  157117. u32 iKey;
  157118. if( p->bRecursive ){
  157119. if( p->iRowid==0 ) break;
  157120. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  157121. }else{
  157122. iKey = p->iRowid;
  157123. }
  157124. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  157125. }
  157126. break;
  157127. }
  157128. case JEACH_VALUE: {
  157129. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  157130. jsonReturn(pThis, ctx, 0);
  157131. break;
  157132. }
  157133. case JEACH_TYPE: {
  157134. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  157135. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  157136. break;
  157137. }
  157138. case JEACH_ATOM: {
  157139. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  157140. if( pThis->eType>=JSON_ARRAY ) break;
  157141. jsonReturn(pThis, ctx, 0);
  157142. break;
  157143. }
  157144. case JEACH_ID: {
  157145. sqlite3_result_int64(ctx,
  157146. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  157147. break;
  157148. }
  157149. case JEACH_PARENT: {
  157150. if( p->i>p->iBegin && p->bRecursive ){
  157151. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  157152. }
  157153. break;
  157154. }
  157155. case JEACH_FULLKEY: {
  157156. JsonString x;
  157157. jsonInit(&x, ctx);
  157158. if( p->bRecursive ){
  157159. jsonEachComputePath(p, &x, p->i);
  157160. }else{
  157161. if( p->zRoot ){
  157162. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  157163. }else{
  157164. jsonAppendChar(&x, '$');
  157165. }
  157166. if( p->eType==JSON_ARRAY ){
  157167. jsonPrintf(30, &x, "[%d]", p->iRowid);
  157168. }else{
  157169. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  157170. }
  157171. }
  157172. jsonResult(&x);
  157173. break;
  157174. }
  157175. case JEACH_PATH: {
  157176. if( p->bRecursive ){
  157177. JsonString x;
  157178. jsonInit(&x, ctx);
  157179. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  157180. jsonResult(&x);
  157181. break;
  157182. }
  157183. /* For json_each() path and root are the same so fall through
  157184. ** into the root case */
  157185. }
  157186. case JEACH_ROOT: {
  157187. const char *zRoot = p->zRoot;
  157188. if( zRoot==0 ) zRoot = "$";
  157189. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  157190. break;
  157191. }
  157192. case JEACH_JSON: {
  157193. assert( i==JEACH_JSON );
  157194. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  157195. break;
  157196. }
  157197. }
  157198. return SQLITE_OK;
  157199. }
  157200. /* Return the current rowid value */
  157201. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  157202. JsonEachCursor *p = (JsonEachCursor*)cur;
  157203. *pRowid = p->iRowid;
  157204. return SQLITE_OK;
  157205. }
  157206. /* The query strategy is to look for an equality constraint on the json
  157207. ** column. Without such a constraint, the table cannot operate. idxNum is
  157208. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  157209. ** and 0 otherwise.
  157210. */
  157211. static int jsonEachBestIndex(
  157212. sqlite3_vtab *tab,
  157213. sqlite3_index_info *pIdxInfo
  157214. ){
  157215. int i;
  157216. int jsonIdx = -1;
  157217. int rootIdx = -1;
  157218. const struct sqlite3_index_constraint *pConstraint;
  157219. UNUSED_PARAM(tab);
  157220. pConstraint = pIdxInfo->aConstraint;
  157221. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  157222. if( pConstraint->usable==0 ) continue;
  157223. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  157224. switch( pConstraint->iColumn ){
  157225. case JEACH_JSON: jsonIdx = i; break;
  157226. case JEACH_ROOT: rootIdx = i; break;
  157227. default: /* no-op */ break;
  157228. }
  157229. }
  157230. if( jsonIdx<0 ){
  157231. pIdxInfo->idxNum = 0;
  157232. pIdxInfo->estimatedCost = 1e99;
  157233. }else{
  157234. pIdxInfo->estimatedCost = 1.0;
  157235. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  157236. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  157237. if( rootIdx<0 ){
  157238. pIdxInfo->idxNum = 1;
  157239. }else{
  157240. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  157241. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  157242. pIdxInfo->idxNum = 3;
  157243. }
  157244. }
  157245. return SQLITE_OK;
  157246. }
  157247. /* Start a search on a new JSON string */
  157248. static int jsonEachFilter(
  157249. sqlite3_vtab_cursor *cur,
  157250. int idxNum, const char *idxStr,
  157251. int argc, sqlite3_value **argv
  157252. ){
  157253. JsonEachCursor *p = (JsonEachCursor*)cur;
  157254. const char *z;
  157255. const char *zRoot = 0;
  157256. sqlite3_int64 n;
  157257. UNUSED_PARAM(idxStr);
  157258. UNUSED_PARAM(argc);
  157259. jsonEachCursorReset(p);
  157260. if( idxNum==0 ) return SQLITE_OK;
  157261. z = (const char*)sqlite3_value_text(argv[0]);
  157262. if( z==0 ) return SQLITE_OK;
  157263. n = sqlite3_value_bytes(argv[0]);
  157264. p->zJson = sqlite3_malloc64( n+1 );
  157265. if( p->zJson==0 ) return SQLITE_NOMEM;
  157266. memcpy(p->zJson, z, (size_t)n+1);
  157267. if( jsonParse(&p->sParse, 0, p->zJson) ){
  157268. int rc = SQLITE_NOMEM;
  157269. if( p->sParse.oom==0 ){
  157270. sqlite3_free(cur->pVtab->zErrMsg);
  157271. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  157272. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  157273. }
  157274. jsonEachCursorReset(p);
  157275. return rc;
  157276. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  157277. jsonEachCursorReset(p);
  157278. return SQLITE_NOMEM;
  157279. }else{
  157280. JsonNode *pNode = 0;
  157281. if( idxNum==3 ){
  157282. const char *zErr = 0;
  157283. zRoot = (const char*)sqlite3_value_text(argv[1]);
  157284. if( zRoot==0 ) return SQLITE_OK;
  157285. n = sqlite3_value_bytes(argv[1]);
  157286. p->zRoot = sqlite3_malloc64( n+1 );
  157287. if( p->zRoot==0 ) return SQLITE_NOMEM;
  157288. memcpy(p->zRoot, zRoot, (size_t)n+1);
  157289. if( zRoot[0]!='$' ){
  157290. zErr = zRoot;
  157291. }else{
  157292. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  157293. }
  157294. if( zErr ){
  157295. sqlite3_free(cur->pVtab->zErrMsg);
  157296. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  157297. jsonEachCursorReset(p);
  157298. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  157299. }else if( pNode==0 ){
  157300. return SQLITE_OK;
  157301. }
  157302. }else{
  157303. pNode = p->sParse.aNode;
  157304. }
  157305. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  157306. p->eType = pNode->eType;
  157307. if( p->eType>=JSON_ARRAY ){
  157308. pNode->u.iKey = 0;
  157309. p->iEnd = p->i + pNode->n + 1;
  157310. if( p->bRecursive ){
  157311. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  157312. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  157313. p->i--;
  157314. }
  157315. }else{
  157316. p->i++;
  157317. }
  157318. }else{
  157319. p->iEnd = p->i+1;
  157320. }
  157321. }
  157322. return SQLITE_OK;
  157323. }
  157324. /* The methods of the json_each virtual table */
  157325. static sqlite3_module jsonEachModule = {
  157326. 0, /* iVersion */
  157327. 0, /* xCreate */
  157328. jsonEachConnect, /* xConnect */
  157329. jsonEachBestIndex, /* xBestIndex */
  157330. jsonEachDisconnect, /* xDisconnect */
  157331. 0, /* xDestroy */
  157332. jsonEachOpenEach, /* xOpen - open a cursor */
  157333. jsonEachClose, /* xClose - close a cursor */
  157334. jsonEachFilter, /* xFilter - configure scan constraints */
  157335. jsonEachNext, /* xNext - advance a cursor */
  157336. jsonEachEof, /* xEof - check for end of scan */
  157337. jsonEachColumn, /* xColumn - read data */
  157338. jsonEachRowid, /* xRowid - read data */
  157339. 0, /* xUpdate */
  157340. 0, /* xBegin */
  157341. 0, /* xSync */
  157342. 0, /* xCommit */
  157343. 0, /* xRollback */
  157344. 0, /* xFindMethod */
  157345. 0, /* xRename */
  157346. 0, /* xSavepoint */
  157347. 0, /* xRelease */
  157348. 0 /* xRollbackTo */
  157349. };
  157350. /* The methods of the json_tree virtual table. */
  157351. static sqlite3_module jsonTreeModule = {
  157352. 0, /* iVersion */
  157353. 0, /* xCreate */
  157354. jsonEachConnect, /* xConnect */
  157355. jsonEachBestIndex, /* xBestIndex */
  157356. jsonEachDisconnect, /* xDisconnect */
  157357. 0, /* xDestroy */
  157358. jsonEachOpenTree, /* xOpen - open a cursor */
  157359. jsonEachClose, /* xClose - close a cursor */
  157360. jsonEachFilter, /* xFilter - configure scan constraints */
  157361. jsonEachNext, /* xNext - advance a cursor */
  157362. jsonEachEof, /* xEof - check for end of scan */
  157363. jsonEachColumn, /* xColumn - read data */
  157364. jsonEachRowid, /* xRowid - read data */
  157365. 0, /* xUpdate */
  157366. 0, /* xBegin */
  157367. 0, /* xSync */
  157368. 0, /* xCommit */
  157369. 0, /* xRollback */
  157370. 0, /* xFindMethod */
  157371. 0, /* xRename */
  157372. 0, /* xSavepoint */
  157373. 0, /* xRelease */
  157374. 0 /* xRollbackTo */
  157375. };
  157376. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  157377. /****************************************************************************
  157378. ** The following routines are the only publically visible identifiers in this
  157379. ** file. Call the following routines in order to register the various SQL
  157380. ** functions and the virtual table implemented by this file.
  157381. ****************************************************************************/
  157382. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  157383. int rc = SQLITE_OK;
  157384. unsigned int i;
  157385. static const struct {
  157386. const char *zName;
  157387. int nArg;
  157388. int flag;
  157389. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  157390. } aFunc[] = {
  157391. { "json", 1, 0, jsonRemoveFunc },
  157392. { "json_array", -1, 0, jsonArrayFunc },
  157393. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  157394. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  157395. { "json_extract", -1, 0, jsonExtractFunc },
  157396. { "json_insert", -1, 0, jsonSetFunc },
  157397. { "json_object", -1, 0, jsonObjectFunc },
  157398. { "json_remove", -1, 0, jsonRemoveFunc },
  157399. { "json_replace", -1, 0, jsonReplaceFunc },
  157400. { "json_set", -1, 1, jsonSetFunc },
  157401. { "json_type", 1, 0, jsonTypeFunc },
  157402. { "json_type", 2, 0, jsonTypeFunc },
  157403. { "json_valid", 1, 0, jsonValidFunc },
  157404. #if SQLITE_DEBUG
  157405. /* DEBUG and TESTING functions */
  157406. { "json_parse", 1, 0, jsonParseFunc },
  157407. { "json_test1", 1, 0, jsonTest1Func },
  157408. #endif
  157409. };
  157410. static const struct {
  157411. const char *zName;
  157412. int nArg;
  157413. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  157414. void (*xFinal)(sqlite3_context*);
  157415. } aAgg[] = {
  157416. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  157417. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  157418. };
  157419. #ifndef SQLITE_OMIT_VIRTUALTABLE
  157420. static const struct {
  157421. const char *zName;
  157422. sqlite3_module *pModule;
  157423. } aMod[] = {
  157424. { "json_each", &jsonEachModule },
  157425. { "json_tree", &jsonTreeModule },
  157426. };
  157427. #endif
  157428. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  157429. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  157430. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  157431. (void*)&aFunc[i].flag,
  157432. aFunc[i].xFunc, 0, 0);
  157433. }
  157434. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  157435. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  157436. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  157437. 0, aAgg[i].xStep, aAgg[i].xFinal);
  157438. }
  157439. #ifndef SQLITE_OMIT_VIRTUALTABLE
  157440. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  157441. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  157442. }
  157443. #endif
  157444. return rc;
  157445. }
  157446. #ifndef SQLITE_CORE
  157447. #ifdef _WIN32
  157448. __declspec(dllexport)
  157449. #endif
  157450. SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
  157451. sqlite3 *db,
  157452. char **pzErrMsg,
  157453. const sqlite3_api_routines *pApi
  157454. ){
  157455. SQLITE_EXTENSION_INIT2(pApi);
  157456. (void)pzErrMsg; /* Unused parameter */
  157457. return sqlite3Json1Init(db);
  157458. }
  157459. #endif
  157460. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  157461. /************** End of json1.c ***********************************************/
  157462. /************** Begin file fts5.c ********************************************/
  157463. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  157464. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  157465. # define NDEBUG 1
  157466. #endif
  157467. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  157468. # undef NDEBUG
  157469. #endif
  157470. /*
  157471. ** 2014 May 31
  157472. **
  157473. ** The author disclaims copyright to this source code. In place of
  157474. ** a legal notice, here is a blessing:
  157475. **
  157476. ** May you do good and not evil.
  157477. ** May you find forgiveness for yourself and forgive others.
  157478. ** May you share freely, never taking more than you give.
  157479. **
  157480. ******************************************************************************
  157481. **
  157482. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  157483. ** FTS5 may be extended with:
  157484. **
  157485. ** * custom tokenizers, and
  157486. ** * custom auxiliary functions.
  157487. */
  157488. #ifndef _FTS5_H
  157489. #define _FTS5_H
  157490. /* #include "sqlite3.h" */
  157491. #if 0
  157492. extern "C" {
  157493. #endif
  157494. /*************************************************************************
  157495. ** CUSTOM AUXILIARY FUNCTIONS
  157496. **
  157497. ** Virtual table implementations may overload SQL functions by implementing
  157498. ** the sqlite3_module.xFindFunction() method.
  157499. */
  157500. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  157501. typedef struct Fts5Context Fts5Context;
  157502. typedef struct Fts5PhraseIter Fts5PhraseIter;
  157503. typedef void (*fts5_extension_function)(
  157504. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  157505. Fts5Context *pFts, /* First arg to pass to pApi functions */
  157506. sqlite3_context *pCtx, /* Context for returning result/error */
  157507. int nVal, /* Number of values in apVal[] array */
  157508. sqlite3_value **apVal /* Array of trailing arguments */
  157509. );
  157510. struct Fts5PhraseIter {
  157511. const unsigned char *a;
  157512. const unsigned char *b;
  157513. };
  157514. /*
  157515. ** EXTENSION API FUNCTIONS
  157516. **
  157517. ** xUserData(pFts):
  157518. ** Return a copy of the context pointer the extension function was
  157519. ** registered with.
  157520. **
  157521. ** xColumnTotalSize(pFts, iCol, pnToken):
  157522. ** If parameter iCol is less than zero, set output variable *pnToken
  157523. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  157524. ** non-negative but less than the number of columns in the table, return
  157525. ** the total number of tokens in column iCol, considering all rows in
  157526. ** the FTS5 table.
  157527. **
  157528. ** If parameter iCol is greater than or equal to the number of columns
  157529. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  157530. ** an OOM condition or IO error), an appropriate SQLite error code is
  157531. ** returned.
  157532. **
  157533. ** xColumnCount(pFts):
  157534. ** Return the number of columns in the table.
  157535. **
  157536. ** xColumnSize(pFts, iCol, pnToken):
  157537. ** If parameter iCol is less than zero, set output variable *pnToken
  157538. ** to the total number of tokens in the current row. Or, if iCol is
  157539. ** non-negative but less than the number of columns in the table, set
  157540. ** *pnToken to the number of tokens in column iCol of the current row.
  157541. **
  157542. ** If parameter iCol is greater than or equal to the number of columns
  157543. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  157544. ** an OOM condition or IO error), an appropriate SQLite error code is
  157545. ** returned.
  157546. **
  157547. ** This function may be quite inefficient if used with an FTS5 table
  157548. ** created with the "columnsize=0" option.
  157549. **
  157550. ** xColumnText:
  157551. ** This function attempts to retrieve the text of column iCol of the
  157552. ** current document. If successful, (*pz) is set to point to a buffer
  157553. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  157554. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  157555. ** if an error occurs, an SQLite error code is returned and the final values
  157556. ** of (*pz) and (*pn) are undefined.
  157557. **
  157558. ** xPhraseCount:
  157559. ** Returns the number of phrases in the current query expression.
  157560. **
  157561. ** xPhraseSize:
  157562. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  157563. ** are numbered starting from zero.
  157564. **
  157565. ** xInstCount:
  157566. ** Set *pnInst to the total number of occurrences of all phrases within
  157567. ** the query within the current row. Return SQLITE_OK if successful, or
  157568. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  157569. **
  157570. ** This API can be quite slow if used with an FTS5 table created with the
  157571. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  157572. ** with either "detail=none" or "detail=column" and "content=" option
  157573. ** (i.e. if it is a contentless table), then this API always returns 0.
  157574. **
  157575. ** xInst:
  157576. ** Query for the details of phrase match iIdx within the current row.
  157577. ** Phrase matches are numbered starting from zero, so the iIdx argument
  157578. ** should be greater than or equal to zero and smaller than the value
  157579. ** output by xInstCount().
  157580. **
  157581. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  157582. ** to the column in which it occurs and *piOff the token offset of the
  157583. ** first token of the phrase. The exception is if the table was created
  157584. ** with the offsets=0 option specified. In this case *piOff is always
  157585. ** set to -1.
  157586. **
  157587. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  157588. ** if an error occurs.
  157589. **
  157590. ** This API can be quite slow if used with an FTS5 table created with the
  157591. ** "detail=none" or "detail=column" option.
  157592. **
  157593. ** xRowid:
  157594. ** Returns the rowid of the current row.
  157595. **
  157596. ** xTokenize:
  157597. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  157598. **
  157599. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  157600. ** This API function is used to query the FTS table for phrase iPhrase
  157601. ** of the current query. Specifically, a query equivalent to:
  157602. **
  157603. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  157604. **
  157605. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  157606. ** current query is executed. For each row visited, the callback function
  157607. ** passed as the fourth argument is invoked. The context and API objects
  157608. ** passed to the callback function may be used to access the properties of
  157609. ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
  157610. ** passed as the third argument to pUserData.
  157611. **
  157612. ** If the callback function returns any value other than SQLITE_OK, the
  157613. ** query is abandoned and the xQueryPhrase function returns immediately.
  157614. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  157615. ** Otherwise, the error code is propagated upwards.
  157616. **
  157617. ** If the query runs to completion without incident, SQLITE_OK is returned.
  157618. ** Or, if some error occurs before the query completes or is aborted by
  157619. ** the callback, an SQLite error code is returned.
  157620. **
  157621. **
  157622. ** xSetAuxdata(pFts5, pAux, xDelete)
  157623. **
  157624. ** Save the pointer passed as the second argument as the extension functions
  157625. ** "auxiliary data". The pointer may then be retrieved by the current or any
  157626. ** future invocation of the same fts5 extension function made as part of
  157627. ** of the same MATCH query using the xGetAuxdata() API.
  157628. **
  157629. ** Each extension function is allocated a single auxiliary data slot for
  157630. ** each FTS query (MATCH expression). If the extension function is invoked
  157631. ** more than once for a single FTS query, then all invocations share a
  157632. ** single auxiliary data context.
  157633. **
  157634. ** If there is already an auxiliary data pointer when this function is
  157635. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  157636. ** was specified along with the original pointer, it is invoked at this
  157637. ** point.
  157638. **
  157639. ** The xDelete callback, if one is specified, is also invoked on the
  157640. ** auxiliary data pointer after the FTS5 query has finished.
  157641. **
  157642. ** If an error (e.g. an OOM condition) occurs within this function, an
  157643. ** the auxiliary data is set to NULL and an error code returned. If the
  157644. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  157645. ** pointer before returning.
  157646. **
  157647. **
  157648. ** xGetAuxdata(pFts5, bClear)
  157649. **
  157650. ** Returns the current auxiliary data pointer for the fts5 extension
  157651. ** function. See the xSetAuxdata() method for details.
  157652. **
  157653. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  157654. ** (set to NULL) before this function returns. In this case the xDelete,
  157655. ** if any, is not invoked.
  157656. **
  157657. **
  157658. ** xRowCount(pFts5, pnRow)
  157659. **
  157660. ** This function is used to retrieve the total number of rows in the table.
  157661. ** In other words, the same value that would be returned by:
  157662. **
  157663. ** SELECT count(*) FROM ftstable;
  157664. **
  157665. ** xPhraseFirst()
  157666. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  157667. ** method, to iterate through all instances of a single query phrase within
  157668. ** the current row. This is the same information as is accessible via the
  157669. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  157670. ** to use, this API may be faster under some circumstances. To iterate
  157671. ** through instances of phrase iPhrase, use the following code:
  157672. **
  157673. ** Fts5PhraseIter iter;
  157674. ** int iCol, iOff;
  157675. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  157676. ** iCol>=0;
  157677. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  157678. ** ){
  157679. ** // An instance of phrase iPhrase at offset iOff of column iCol
  157680. ** }
  157681. **
  157682. ** The Fts5PhraseIter structure is defined above. Applications should not
  157683. ** modify this structure directly - it should only be used as shown above
  157684. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  157685. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  157686. **
  157687. ** This API can be quite slow if used with an FTS5 table created with the
  157688. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  157689. ** with either "detail=none" or "detail=column" and "content=" option
  157690. ** (i.e. if it is a contentless table), then this API always iterates
  157691. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  157692. **
  157693. ** xPhraseNext()
  157694. ** See xPhraseFirst above.
  157695. **
  157696. ** xPhraseFirstColumn()
  157697. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  157698. ** and xPhraseNext() APIs described above. The difference is that instead
  157699. ** of iterating through all instances of a phrase in the current row, these
  157700. ** APIs are used to iterate through the set of columns in the current row
  157701. ** that contain one or more instances of a specified phrase. For example:
  157702. **
  157703. ** Fts5PhraseIter iter;
  157704. ** int iCol;
  157705. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  157706. ** iCol>=0;
  157707. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  157708. ** ){
  157709. ** // Column iCol contains at least one instance of phrase iPhrase
  157710. ** }
  157711. **
  157712. ** This API can be quite slow if used with an FTS5 table created with the
  157713. ** "detail=none" option. If the FTS5 table is created with either
  157714. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  157715. ** then this API always iterates through an empty set (all calls to
  157716. ** xPhraseFirstColumn() set iCol to -1).
  157717. **
  157718. ** The information accessed using this API and its companion
  157719. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  157720. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  157721. ** significantly more efficient than those alternatives when used with
  157722. ** "detail=column" tables.
  157723. **
  157724. ** xPhraseNextColumn()
  157725. ** See xPhraseFirstColumn above.
  157726. */
  157727. struct Fts5ExtensionApi {
  157728. int iVersion; /* Currently always set to 3 */
  157729. void *(*xUserData)(Fts5Context*);
  157730. int (*xColumnCount)(Fts5Context*);
  157731. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  157732. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  157733. int (*xTokenize)(Fts5Context*,
  157734. const char *pText, int nText, /* Text to tokenize */
  157735. void *pCtx, /* Context passed to xToken() */
  157736. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  157737. );
  157738. int (*xPhraseCount)(Fts5Context*);
  157739. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  157740. int (*xInstCount)(Fts5Context*, int *pnInst);
  157741. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  157742. sqlite3_int64 (*xRowid)(Fts5Context*);
  157743. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  157744. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  157745. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  157746. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  157747. );
  157748. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  157749. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  157750. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  157751. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  157752. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  157753. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  157754. };
  157755. /*
  157756. ** CUSTOM AUXILIARY FUNCTIONS
  157757. *************************************************************************/
  157758. /*************************************************************************
  157759. ** CUSTOM TOKENIZERS
  157760. **
  157761. ** Applications may also register custom tokenizer types. A tokenizer
  157762. ** is registered by providing fts5 with a populated instance of the
  157763. ** following structure. All structure methods must be defined, setting
  157764. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  157765. ** behaviour. The structure methods are expected to function as follows:
  157766. **
  157767. ** xCreate:
  157768. ** This function is used to allocate and inititalize a tokenizer instance.
  157769. ** A tokenizer instance is required to actually tokenize text.
  157770. **
  157771. ** The first argument passed to this function is a copy of the (void*)
  157772. ** pointer provided by the application when the fts5_tokenizer object
  157773. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  157774. ** The second and third arguments are an array of nul-terminated strings
  157775. ** containing the tokenizer arguments, if any, specified following the
  157776. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  157777. ** to create the FTS5 table.
  157778. **
  157779. ** The final argument is an output variable. If successful, (*ppOut)
  157780. ** should be set to point to the new tokenizer handle and SQLITE_OK
  157781. ** returned. If an error occurs, some value other than SQLITE_OK should
  157782. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  157783. ** is undefined.
  157784. **
  157785. ** xDelete:
  157786. ** This function is invoked to delete a tokenizer handle previously
  157787. ** allocated using xCreate(). Fts5 guarantees that this function will
  157788. ** be invoked exactly once for each successful call to xCreate().
  157789. **
  157790. ** xTokenize:
  157791. ** This function is expected to tokenize the nText byte string indicated
  157792. ** by argument pText. pText may or may not be nul-terminated. The first
  157793. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  157794. ** returned by an earlier call to xCreate().
  157795. **
  157796. ** The second argument indicates the reason that FTS5 is requesting
  157797. ** tokenization of the supplied text. This is always one of the following
  157798. ** four values:
  157799. **
  157800. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  157801. ** or removed from the FTS table. The tokenizer is being invoked to
  157802. ** determine the set of tokens to add to (or delete from) the
  157803. ** FTS index.
  157804. **
  157805. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  157806. ** against the FTS index. The tokenizer is being called to tokenize
  157807. ** a bareword or quoted string specified as part of the query.
  157808. **
  157809. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  157810. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  157811. ** followed by a "*" character, indicating that the last token
  157812. ** returned by the tokenizer will be treated as a token prefix.
  157813. **
  157814. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  157815. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  157816. ** function. Or an fts5_api.xColumnSize() request made by the same
  157817. ** on a columnsize=0 database.
  157818. ** </ul>
  157819. **
  157820. ** For each token in the input string, the supplied callback xToken() must
  157821. ** be invoked. The first argument to it should be a copy of the pointer
  157822. ** passed as the second argument to xTokenize(). The third and fourth
  157823. ** arguments are a pointer to a buffer containing the token text, and the
  157824. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  157825. ** of the first byte of and first byte immediately following the text from
  157826. ** which the token is derived within the input.
  157827. **
  157828. ** The second argument passed to the xToken() callback ("tflags") should
  157829. ** normally be set to 0. The exception is if the tokenizer supports
  157830. ** synonyms. In this case see the discussion below for details.
  157831. **
  157832. ** FTS5 assumes the xToken() callback is invoked for each token in the
  157833. ** order that they occur within the input text.
  157834. **
  157835. ** If an xToken() callback returns any value other than SQLITE_OK, then
  157836. ** the tokenization should be abandoned and the xTokenize() method should
  157837. ** immediately return a copy of the xToken() return value. Or, if the
  157838. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  157839. ** if an error occurs with the xTokenize() implementation itself, it
  157840. ** may abandon the tokenization and return any error code other than
  157841. ** SQLITE_OK or SQLITE_DONE.
  157842. **
  157843. ** SYNONYM SUPPORT
  157844. **
  157845. ** Custom tokenizers may also support synonyms. Consider a case in which a
  157846. ** user wishes to query for a phrase such as "first place". Using the
  157847. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  157848. ** of "first place" within the document set, but not alternative forms
  157849. ** such as "1st place". In some applications, it would be better to match
  157850. ** all instances of "first place" or "1st place" regardless of which form
  157851. ** the user specified in the MATCH query text.
  157852. **
  157853. ** There are several ways to approach this in FTS5:
  157854. **
  157855. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  157856. ** In the above example, this means that the tokenizer returns the
  157857. ** same token for inputs "first" and "1st". Say that token is in
  157858. ** fact "first", so that when the user inserts the document "I won
  157859. ** 1st place" entries are added to the index for tokens "i", "won",
  157860. ** "first" and "place". If the user then queries for '1st + place',
  157861. ** the tokenizer substitutes "first" for "1st" and the query works
  157862. ** as expected.
  157863. **
  157864. ** <li> By adding multiple synonyms for a single term to the FTS index.
  157865. ** In this case, when tokenizing query text, the tokenizer may
  157866. ** provide multiple synonyms for a single term within the document.
  157867. ** FTS5 then queries the index for each synonym individually. For
  157868. ** example, faced with the query:
  157869. **
  157870. ** <codeblock>
  157871. ** ... MATCH 'first place'</codeblock>
  157872. **
  157873. ** the tokenizer offers both "1st" and "first" as synonyms for the
  157874. ** first token in the MATCH query and FTS5 effectively runs a query
  157875. ** similar to:
  157876. **
  157877. ** <codeblock>
  157878. ** ... MATCH '(first OR 1st) place'</codeblock>
  157879. **
  157880. ** except that, for the purposes of auxiliary functions, the query
  157881. ** still appears to contain just two phrases - "(first OR 1st)"
  157882. ** being treated as a single phrase.
  157883. **
  157884. ** <li> By adding multiple synonyms for a single term to the FTS index.
  157885. ** Using this method, when tokenizing document text, the tokenizer
  157886. ** provides multiple synonyms for each token. So that when a
  157887. ** document such as "I won first place" is tokenized, entries are
  157888. ** added to the FTS index for "i", "won", "first", "1st" and
  157889. ** "place".
  157890. **
  157891. ** This way, even if the tokenizer does not provide synonyms
  157892. ** when tokenizing query text (it should not - to do would be
  157893. ** inefficient), it doesn't matter if the user queries for
  157894. ** 'first + place' or '1st + place', as there are entires in the
  157895. ** FTS index corresponding to both forms of the first token.
  157896. ** </ol>
  157897. **
  157898. ** Whether it is parsing document or query text, any call to xToken that
  157899. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  157900. ** is considered to supply a synonym for the previous token. For example,
  157901. ** when parsing the document "I won first place", a tokenizer that supports
  157902. ** synonyms would call xToken() 5 times, as follows:
  157903. **
  157904. ** <codeblock>
  157905. ** xToken(pCtx, 0, "i", 1, 0, 1);
  157906. ** xToken(pCtx, 0, "won", 3, 2, 5);
  157907. ** xToken(pCtx, 0, "first", 5, 6, 11);
  157908. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  157909. ** xToken(pCtx, 0, "place", 5, 12, 17);
  157910. **</codeblock>
  157911. **
  157912. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  157913. ** xToken() is called. Multiple synonyms may be specified for a single token
  157914. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  157915. ** There is no limit to the number of synonyms that may be provided for a
  157916. ** single token.
  157917. **
  157918. ** In many cases, method (1) above is the best approach. It does not add
  157919. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  157920. ** so it is efficient in terms of disk space and query speed. However, it
  157921. ** does not support prefix queries very well. If, as suggested above, the
  157922. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  157923. **
  157924. ** <codeblock>
  157925. ** ... MATCH '1s*'</codeblock>
  157926. **
  157927. ** will not match documents that contain the token "1st" (as the tokenizer
  157928. ** will probably not map "1s" to any prefix of "first").
  157929. **
  157930. ** For full prefix support, method (3) may be preferred. In this case,
  157931. ** because the index contains entries for both "first" and "1st", prefix
  157932. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  157933. ** extra entries are added to the FTS index, this method uses more space
  157934. ** within the database.
  157935. **
  157936. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  157937. ** a query such as '1s*' will match documents that contain the literal
  157938. ** token "1st", but not "first" (assuming the tokenizer is not able to
  157939. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  157940. ** will match against "1st" and "first". This method does not require
  157941. ** extra disk space, as no extra entries are added to the FTS index.
  157942. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  157943. ** as separate queries of the FTS index are required for each synonym.
  157944. **
  157945. ** When using methods (2) or (3), it is important that the tokenizer only
  157946. ** provide synonyms when tokenizing document text (method (2)) or query
  157947. ** text (method (3)), not both. Doing so will not cause any errors, but is
  157948. ** inefficient.
  157949. */
  157950. typedef struct Fts5Tokenizer Fts5Tokenizer;
  157951. typedef struct fts5_tokenizer fts5_tokenizer;
  157952. struct fts5_tokenizer {
  157953. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  157954. void (*xDelete)(Fts5Tokenizer*);
  157955. int (*xTokenize)(Fts5Tokenizer*,
  157956. void *pCtx,
  157957. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  157958. const char *pText, int nText,
  157959. int (*xToken)(
  157960. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  157961. int tflags, /* Mask of FTS5_TOKEN_* flags */
  157962. const char *pToken, /* Pointer to buffer containing token */
  157963. int nToken, /* Size of token in bytes */
  157964. int iStart, /* Byte offset of token within input text */
  157965. int iEnd /* Byte offset of end of token within input text */
  157966. )
  157967. );
  157968. };
  157969. /* Flags that may be passed as the third argument to xTokenize() */
  157970. #define FTS5_TOKENIZE_QUERY 0x0001
  157971. #define FTS5_TOKENIZE_PREFIX 0x0002
  157972. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  157973. #define FTS5_TOKENIZE_AUX 0x0008
  157974. /* Flags that may be passed by the tokenizer implementation back to FTS5
  157975. ** as the third argument to the supplied xToken callback. */
  157976. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  157977. /*
  157978. ** END OF CUSTOM TOKENIZERS
  157979. *************************************************************************/
  157980. /*************************************************************************
  157981. ** FTS5 EXTENSION REGISTRATION API
  157982. */
  157983. typedef struct fts5_api fts5_api;
  157984. struct fts5_api {
  157985. int iVersion; /* Currently always set to 2 */
  157986. /* Create a new tokenizer */
  157987. int (*xCreateTokenizer)(
  157988. fts5_api *pApi,
  157989. const char *zName,
  157990. void *pContext,
  157991. fts5_tokenizer *pTokenizer,
  157992. void (*xDestroy)(void*)
  157993. );
  157994. /* Find an existing tokenizer */
  157995. int (*xFindTokenizer)(
  157996. fts5_api *pApi,
  157997. const char *zName,
  157998. void **ppContext,
  157999. fts5_tokenizer *pTokenizer
  158000. );
  158001. /* Create a new auxiliary function */
  158002. int (*xCreateFunction)(
  158003. fts5_api *pApi,
  158004. const char *zName,
  158005. void *pContext,
  158006. fts5_extension_function xFunction,
  158007. void (*xDestroy)(void*)
  158008. );
  158009. };
  158010. /*
  158011. ** END OF REGISTRATION API
  158012. *************************************************************************/
  158013. #if 0
  158014. } /* end of the 'extern "C"' block */
  158015. #endif
  158016. #endif /* _FTS5_H */
  158017. /*
  158018. ** 2014 May 31
  158019. **
  158020. ** The author disclaims copyright to this source code. In place of
  158021. ** a legal notice, here is a blessing:
  158022. **
  158023. ** May you do good and not evil.
  158024. ** May you find forgiveness for yourself and forgive others.
  158025. ** May you share freely, never taking more than you give.
  158026. **
  158027. ******************************************************************************
  158028. **
  158029. */
  158030. #ifndef _FTS5INT_H
  158031. #define _FTS5INT_H
  158032. /* #include "fts5.h" */
  158033. /* #include "sqlite3ext.h" */
  158034. SQLITE_EXTENSION_INIT1
  158035. /* #include <string.h> */
  158036. /* #include <assert.h> */
  158037. #ifndef SQLITE_AMALGAMATION
  158038. typedef unsigned char u8;
  158039. typedef unsigned int u32;
  158040. typedef unsigned short u16;
  158041. typedef short i16;
  158042. typedef sqlite3_int64 i64;
  158043. typedef sqlite3_uint64 u64;
  158044. #define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  158045. #define testcase(x)
  158046. #define ALWAYS(x) 1
  158047. #define NEVER(x) 0
  158048. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  158049. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  158050. /*
  158051. ** Constants for the largest and smallest possible 64-bit signed integers.
  158052. */
  158053. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  158054. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  158055. #endif
  158056. /* Truncate very long tokens to this many bytes. Hard limit is
  158057. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  158058. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  158059. #define FTS5_MAX_TOKEN_SIZE 32768
  158060. /*
  158061. ** Maximum number of prefix indexes on single FTS5 table. This must be
  158062. ** less than 32. If it is set to anything large than that, an #error
  158063. ** directive in fts5_index.c will cause the build to fail.
  158064. */
  158065. #define FTS5_MAX_PREFIX_INDEXES 31
  158066. #define FTS5_DEFAULT_NEARDIST 10
  158067. #define FTS5_DEFAULT_RANK "bm25"
  158068. /* Name of rank and rowid columns */
  158069. #define FTS5_RANK_NAME "rank"
  158070. #define FTS5_ROWID_NAME "rowid"
  158071. #ifdef SQLITE_DEBUG
  158072. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  158073. static int sqlite3Fts5Corrupt(void);
  158074. #else
  158075. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  158076. #endif
  158077. /*
  158078. ** The assert_nc() macro is similar to the assert() macro, except that it
  158079. ** is used for assert() conditions that are true only if it can be
  158080. ** guranteed that the database is not corrupt.
  158081. */
  158082. #ifdef SQLITE_DEBUG
  158083. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  158084. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  158085. #else
  158086. # define assert_nc(x) assert(x)
  158087. #endif
  158088. /* Mark a function parameter as unused, to suppress nuisance compiler
  158089. ** warnings. */
  158090. #ifndef UNUSED_PARAM
  158091. # define UNUSED_PARAM(X) (void)(X)
  158092. #endif
  158093. #ifndef UNUSED_PARAM2
  158094. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  158095. #endif
  158096. typedef struct Fts5Global Fts5Global;
  158097. typedef struct Fts5Colset Fts5Colset;
  158098. /* If a NEAR() clump or phrase may only match a specific set of columns,
  158099. ** then an object of the following type is used to record the set of columns.
  158100. ** Each entry in the aiCol[] array is a column that may be matched.
  158101. **
  158102. ** This object is used by fts5_expr.c and fts5_index.c.
  158103. */
  158104. struct Fts5Colset {
  158105. int nCol;
  158106. int aiCol[1];
  158107. };
  158108. /**************************************************************************
  158109. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  158110. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  158111. */
  158112. typedef struct Fts5Config Fts5Config;
  158113. /*
  158114. ** An instance of the following structure encodes all information that can
  158115. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  158116. **
  158117. ** And all information loaded from the %_config table.
  158118. **
  158119. ** nAutomerge:
  158120. ** The minimum number of segments that an auto-merge operation should
  158121. ** attempt to merge together. A value of 1 sets the object to use the
  158122. ** compile time default. Zero disables auto-merge altogether.
  158123. **
  158124. ** zContent:
  158125. **
  158126. ** zContentRowid:
  158127. ** The value of the content_rowid= option, if one was specified. Or
  158128. ** the string "rowid" otherwise. This text is not quoted - if it is
  158129. ** used as part of an SQL statement it needs to be quoted appropriately.
  158130. **
  158131. ** zContentExprlist:
  158132. **
  158133. ** pzErrmsg:
  158134. ** This exists in order to allow the fts5_index.c module to return a
  158135. ** decent error message if it encounters a file-format version it does
  158136. ** not understand.
  158137. **
  158138. ** bColumnsize:
  158139. ** True if the %_docsize table is created.
  158140. **
  158141. ** bPrefixIndex:
  158142. ** This is only used for debugging. If set to false, any prefix indexes
  158143. ** are ignored. This value is configured using:
  158144. **
  158145. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  158146. **
  158147. */
  158148. struct Fts5Config {
  158149. sqlite3 *db; /* Database handle */
  158150. char *zDb; /* Database holding FTS index (e.g. "main") */
  158151. char *zName; /* Name of FTS index */
  158152. int nCol; /* Number of columns */
  158153. char **azCol; /* Column names */
  158154. u8 *abUnindexed; /* True for unindexed columns */
  158155. int nPrefix; /* Number of prefix indexes */
  158156. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  158157. int eContent; /* An FTS5_CONTENT value */
  158158. char *zContent; /* content table */
  158159. char *zContentRowid; /* "content_rowid=" option value */
  158160. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  158161. int eDetail; /* FTS5_DETAIL_XXX value */
  158162. char *zContentExprlist;
  158163. Fts5Tokenizer *pTok;
  158164. fts5_tokenizer *pTokApi;
  158165. /* Values loaded from the %_config table */
  158166. int iCookie; /* Incremented when %_config is modified */
  158167. int pgsz; /* Approximate page size used in %_data */
  158168. int nAutomerge; /* 'automerge' setting */
  158169. int nCrisisMerge; /* Maximum allowed segments per level */
  158170. int nUsermerge; /* 'usermerge' setting */
  158171. int nHashSize; /* Bytes of memory for in-memory hash */
  158172. char *zRank; /* Name of rank function */
  158173. char *zRankArgs; /* Arguments to rank function */
  158174. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  158175. char **pzErrmsg;
  158176. #ifdef SQLITE_DEBUG
  158177. int bPrefixIndex; /* True to use prefix-indexes */
  158178. #endif
  158179. };
  158180. /* Current expected value of %_config table 'version' field */
  158181. #define FTS5_CURRENT_VERSION 4
  158182. #define FTS5_CONTENT_NORMAL 0
  158183. #define FTS5_CONTENT_NONE 1
  158184. #define FTS5_CONTENT_EXTERNAL 2
  158185. #define FTS5_DETAIL_FULL 0
  158186. #define FTS5_DETAIL_NONE 1
  158187. #define FTS5_DETAIL_COLUMNS 2
  158188. static int sqlite3Fts5ConfigParse(
  158189. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  158190. );
  158191. static void sqlite3Fts5ConfigFree(Fts5Config*);
  158192. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  158193. static int sqlite3Fts5Tokenize(
  158194. Fts5Config *pConfig, /* FTS5 Configuration object */
  158195. int flags, /* FTS5_TOKENIZE_* flags */
  158196. const char *pText, int nText, /* Text to tokenize */
  158197. void *pCtx, /* Context passed to xToken() */
  158198. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  158199. );
  158200. static void sqlite3Fts5Dequote(char *z);
  158201. /* Load the contents of the %_config table */
  158202. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  158203. /* Set the value of a single config attribute */
  158204. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  158205. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  158206. /*
  158207. ** End of interface to code in fts5_config.c.
  158208. **************************************************************************/
  158209. /**************************************************************************
  158210. ** Interface to code in fts5_buffer.c.
  158211. */
  158212. /*
  158213. ** Buffer object for the incremental building of string data.
  158214. */
  158215. typedef struct Fts5Buffer Fts5Buffer;
  158216. struct Fts5Buffer {
  158217. u8 *p;
  158218. int n;
  158219. int nSpace;
  158220. };
  158221. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  158222. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  158223. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  158224. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  158225. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  158226. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  158227. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  158228. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  158229. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  158230. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  158231. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  158232. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  158233. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  158234. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  158235. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  158236. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  158237. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  158238. )
  158239. /* Write and decode big-endian 32-bit integer values */
  158240. static void sqlite3Fts5Put32(u8*, int);
  158241. static int sqlite3Fts5Get32(const u8*);
  158242. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  158243. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  158244. typedef struct Fts5PoslistReader Fts5PoslistReader;
  158245. struct Fts5PoslistReader {
  158246. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  158247. const u8 *a; /* Position list to iterate through */
  158248. int n; /* Size of buffer at a[] in bytes */
  158249. int i; /* Current offset in a[] */
  158250. u8 bFlag; /* For client use (any custom purpose) */
  158251. /* Output variables */
  158252. u8 bEof; /* Set to true at EOF */
  158253. i64 iPos; /* (iCol<<32) + iPos */
  158254. };
  158255. static int sqlite3Fts5PoslistReaderInit(
  158256. const u8 *a, int n, /* Poslist buffer to iterate through */
  158257. Fts5PoslistReader *pIter /* Iterator object to initialize */
  158258. );
  158259. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  158260. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  158261. struct Fts5PoslistWriter {
  158262. i64 iPrev;
  158263. };
  158264. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  158265. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  158266. static int sqlite3Fts5PoslistNext64(
  158267. const u8 *a, int n, /* Buffer containing poslist */
  158268. int *pi, /* IN/OUT: Offset within a[] */
  158269. i64 *piOff /* IN/OUT: Current offset */
  158270. );
  158271. /* Malloc utility */
  158272. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  158273. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  158274. /* Character set tests (like isspace(), isalpha() etc.) */
  158275. static int sqlite3Fts5IsBareword(char t);
  158276. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  158277. typedef struct Fts5Termset Fts5Termset;
  158278. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  158279. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  158280. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  158281. /*
  158282. ** End of interface to code in fts5_buffer.c.
  158283. **************************************************************************/
  158284. /**************************************************************************
  158285. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  158286. ** to access the data stored in the %_data table.
  158287. */
  158288. typedef struct Fts5Index Fts5Index;
  158289. typedef struct Fts5IndexIter Fts5IndexIter;
  158290. struct Fts5IndexIter {
  158291. i64 iRowid;
  158292. const u8 *pData;
  158293. int nData;
  158294. u8 bEof;
  158295. };
  158296. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  158297. /*
  158298. ** Values used as part of the flags argument passed to IndexQuery().
  158299. */
  158300. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  158301. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  158302. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  158303. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  158304. /* The following are used internally by the fts5_index.c module. They are
  158305. ** defined here only to make it easier to avoid clashes with the flags
  158306. ** above. */
  158307. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  158308. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  158309. /*
  158310. ** Create/destroy an Fts5Index object.
  158311. */
  158312. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  158313. static int sqlite3Fts5IndexClose(Fts5Index *p);
  158314. /*
  158315. ** Return a simple checksum value based on the arguments.
  158316. */
  158317. static u64 sqlite3Fts5IndexEntryCksum(
  158318. i64 iRowid,
  158319. int iCol,
  158320. int iPos,
  158321. int iIdx,
  158322. const char *pTerm,
  158323. int nTerm
  158324. );
  158325. /*
  158326. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  158327. ** size. Return the number of bytes in the nChar character prefix of the
  158328. ** buffer, or 0 if there are less than nChar characters in total.
  158329. */
  158330. static int sqlite3Fts5IndexCharlenToBytelen(
  158331. const char *p,
  158332. int nByte,
  158333. int nChar
  158334. );
  158335. /*
  158336. ** Open a new iterator to iterate though all rowids that match the
  158337. ** specified token or token prefix.
  158338. */
  158339. static int sqlite3Fts5IndexQuery(
  158340. Fts5Index *p, /* FTS index to query */
  158341. const char *pToken, int nToken, /* Token (or prefix) to query for */
  158342. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  158343. Fts5Colset *pColset, /* Match these columns only */
  158344. Fts5IndexIter **ppIter /* OUT: New iterator object */
  158345. );
  158346. /*
  158347. ** The various operations on open token or token prefix iterators opened
  158348. ** using sqlite3Fts5IndexQuery().
  158349. */
  158350. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  158351. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  158352. /*
  158353. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  158354. */
  158355. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  158356. /*
  158357. ** This interface is used by the fts5vocab module.
  158358. */
  158359. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  158360. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  158361. /*
  158362. ** Insert or remove data to or from the index. Each time a document is
  158363. ** added to or removed from the index, this function is called one or more
  158364. ** times.
  158365. **
  158366. ** For an insert, it must be called once for each token in the new document.
  158367. ** If the operation is a delete, it must be called (at least) once for each
  158368. ** unique token in the document with an iCol value less than zero. The iPos
  158369. ** argument is ignored for a delete.
  158370. */
  158371. static int sqlite3Fts5IndexWrite(
  158372. Fts5Index *p, /* Index to write to */
  158373. int iCol, /* Column token appears in (-ve -> delete) */
  158374. int iPos, /* Position of token within column */
  158375. const char *pToken, int nToken /* Token to add or remove to or from index */
  158376. );
  158377. /*
  158378. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  158379. ** document iDocid.
  158380. */
  158381. static int sqlite3Fts5IndexBeginWrite(
  158382. Fts5Index *p, /* Index to write to */
  158383. int bDelete, /* True if current operation is a delete */
  158384. i64 iDocid /* Docid to add or remove data from */
  158385. );
  158386. /*
  158387. ** Flush any data stored in the in-memory hash tables to the database.
  158388. ** If the bCommit flag is true, also close any open blob handles.
  158389. */
  158390. static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
  158391. /*
  158392. ** Discard any data stored in the in-memory hash tables. Do not write it
  158393. ** to the database. Additionally, assume that the contents of the %_data
  158394. ** table may have changed on disk. So any in-memory caches of %_data
  158395. ** records must be invalidated.
  158396. */
  158397. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  158398. /*
  158399. ** Get or set the "averages" values.
  158400. */
  158401. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  158402. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  158403. /*
  158404. ** Functions called by the storage module as part of integrity-check.
  158405. */
  158406. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  158407. /*
  158408. ** Called during virtual module initialization to register UDF
  158409. ** fts5_decode() with SQLite
  158410. */
  158411. static int sqlite3Fts5IndexInit(sqlite3*);
  158412. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  158413. /*
  158414. ** Return the total number of entries read from the %_data table by
  158415. ** this connection since it was created.
  158416. */
  158417. static int sqlite3Fts5IndexReads(Fts5Index *p);
  158418. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  158419. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  158420. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  158421. static int sqlite3Fts5IndexReset(Fts5Index *p);
  158422. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  158423. /*
  158424. ** End of interface to code in fts5_index.c.
  158425. **************************************************************************/
  158426. /**************************************************************************
  158427. ** Interface to code in fts5_varint.c.
  158428. */
  158429. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  158430. static int sqlite3Fts5GetVarintLen(u32 iVal);
  158431. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  158432. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  158433. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  158434. #define fts5GetVarint sqlite3Fts5GetVarint
  158435. #define fts5FastGetVarint32(a, iOff, nVal) { \
  158436. nVal = (a)[iOff++]; \
  158437. if( nVal & 0x80 ){ \
  158438. iOff--; \
  158439. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  158440. } \
  158441. }
  158442. /*
  158443. ** End of interface to code in fts5_varint.c.
  158444. **************************************************************************/
  158445. /**************************************************************************
  158446. ** Interface to code in fts5.c.
  158447. */
  158448. static int sqlite3Fts5GetTokenizer(
  158449. Fts5Global*,
  158450. const char **azArg,
  158451. int nArg,
  158452. Fts5Tokenizer**,
  158453. fts5_tokenizer**,
  158454. char **pzErr
  158455. );
  158456. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  158457. /*
  158458. ** End of interface to code in fts5.c.
  158459. **************************************************************************/
  158460. /**************************************************************************
  158461. ** Interface to code in fts5_hash.c.
  158462. */
  158463. typedef struct Fts5Hash Fts5Hash;
  158464. /*
  158465. ** Create a hash table, free a hash table.
  158466. */
  158467. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  158468. static void sqlite3Fts5HashFree(Fts5Hash*);
  158469. static int sqlite3Fts5HashWrite(
  158470. Fts5Hash*,
  158471. i64 iRowid, /* Rowid for this entry */
  158472. int iCol, /* Column token appears in (-ve -> delete) */
  158473. int iPos, /* Position of token within column */
  158474. char bByte,
  158475. const char *pToken, int nToken /* Token to add or remove to or from index */
  158476. );
  158477. /*
  158478. ** Empty (but do not delete) a hash table.
  158479. */
  158480. static void sqlite3Fts5HashClear(Fts5Hash*);
  158481. static int sqlite3Fts5HashQuery(
  158482. Fts5Hash*, /* Hash table to query */
  158483. const char *pTerm, int nTerm, /* Query term */
  158484. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  158485. int *pnDoclist /* OUT: Size of doclist in bytes */
  158486. );
  158487. static int sqlite3Fts5HashScanInit(
  158488. Fts5Hash*, /* Hash table to query */
  158489. const char *pTerm, int nTerm /* Query prefix */
  158490. );
  158491. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  158492. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  158493. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  158494. const char **pzTerm, /* OUT: term (nul-terminated) */
  158495. const u8 **ppDoclist, /* OUT: pointer to doclist */
  158496. int *pnDoclist /* OUT: size of doclist in bytes */
  158497. );
  158498. /*
  158499. ** End of interface to code in fts5_hash.c.
  158500. **************************************************************************/
  158501. /**************************************************************************
  158502. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  158503. ** code to access the data stored in the %_content and %_docsize tables.
  158504. */
  158505. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  158506. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  158507. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  158508. typedef struct Fts5Storage Fts5Storage;
  158509. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  158510. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  158511. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  158512. static int sqlite3Fts5DropAll(Fts5Config*);
  158513. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  158514. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  158515. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  158516. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  158517. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  158518. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  158519. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  158520. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  158521. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  158522. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  158523. static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
  158524. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  158525. static int sqlite3Fts5StorageConfigValue(
  158526. Fts5Storage *p, const char*, sqlite3_value*, int
  158527. );
  158528. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  158529. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  158530. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  158531. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  158532. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  158533. /*
  158534. ** End of interface to code in fts5_storage.c.
  158535. **************************************************************************/
  158536. /**************************************************************************
  158537. ** Interface to code in fts5_expr.c.
  158538. */
  158539. typedef struct Fts5Expr Fts5Expr;
  158540. typedef struct Fts5ExprNode Fts5ExprNode;
  158541. typedef struct Fts5Parse Fts5Parse;
  158542. typedef struct Fts5Token Fts5Token;
  158543. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  158544. typedef struct Fts5ExprNearset Fts5ExprNearset;
  158545. struct Fts5Token {
  158546. const char *p; /* Token text (not NULL terminated) */
  158547. int n; /* Size of buffer p in bytes */
  158548. };
  158549. /* Parse a MATCH expression. */
  158550. static int sqlite3Fts5ExprNew(
  158551. Fts5Config *pConfig,
  158552. const char *zExpr,
  158553. Fts5Expr **ppNew,
  158554. char **pzErr
  158555. );
  158556. /*
  158557. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  158558. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  158559. ** rc = sqlite3Fts5ExprNext(pExpr)
  158560. ** ){
  158561. ** // The document with rowid iRowid matches the expression!
  158562. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  158563. ** }
  158564. */
  158565. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  158566. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  158567. static int sqlite3Fts5ExprEof(Fts5Expr*);
  158568. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  158569. static void sqlite3Fts5ExprFree(Fts5Expr*);
  158570. /* Called during startup to register a UDF with SQLite */
  158571. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  158572. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  158573. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  158574. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  158575. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  158576. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  158577. static int sqlite3Fts5ExprPopulatePoslists(
  158578. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  158579. );
  158580. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  158581. static void sqlite3Fts5ExprClearEof(Fts5Expr*);
  158582. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  158583. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  158584. /*******************************************
  158585. ** The fts5_expr.c API above this point is used by the other hand-written
  158586. ** C code in this module. The interfaces below this point are called by
  158587. ** the parser code in fts5parse.y. */
  158588. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  158589. static Fts5ExprNode *sqlite3Fts5ParseNode(
  158590. Fts5Parse *pParse,
  158591. int eType,
  158592. Fts5ExprNode *pLeft,
  158593. Fts5ExprNode *pRight,
  158594. Fts5ExprNearset *pNear
  158595. );
  158596. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  158597. Fts5Parse *pParse,
  158598. Fts5ExprNode *pLeft,
  158599. Fts5ExprNode *pRight
  158600. );
  158601. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  158602. Fts5Parse *pParse,
  158603. Fts5ExprPhrase *pPhrase,
  158604. Fts5Token *pToken,
  158605. int bPrefix
  158606. );
  158607. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  158608. Fts5Parse*,
  158609. Fts5ExprNearset*,
  158610. Fts5ExprPhrase*
  158611. );
  158612. static Fts5Colset *sqlite3Fts5ParseColset(
  158613. Fts5Parse*,
  158614. Fts5Colset*,
  158615. Fts5Token *
  158616. );
  158617. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  158618. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  158619. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  158620. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  158621. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
  158622. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  158623. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  158624. /*
  158625. ** End of interface to code in fts5_expr.c.
  158626. **************************************************************************/
  158627. /**************************************************************************
  158628. ** Interface to code in fts5_aux.c.
  158629. */
  158630. static int sqlite3Fts5AuxInit(fts5_api*);
  158631. /*
  158632. ** End of interface to code in fts5_aux.c.
  158633. **************************************************************************/
  158634. /**************************************************************************
  158635. ** Interface to code in fts5_tokenizer.c.
  158636. */
  158637. static int sqlite3Fts5TokenizerInit(fts5_api*);
  158638. /*
  158639. ** End of interface to code in fts5_tokenizer.c.
  158640. **************************************************************************/
  158641. /**************************************************************************
  158642. ** Interface to code in fts5_vocab.c.
  158643. */
  158644. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  158645. /*
  158646. ** End of interface to code in fts5_vocab.c.
  158647. **************************************************************************/
  158648. /**************************************************************************
  158649. ** Interface to automatically generated code in fts5_unicode2.c.
  158650. */
  158651. static int sqlite3Fts5UnicodeIsalnum(int c);
  158652. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  158653. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  158654. /*
  158655. ** End of interface to code in fts5_unicode2.c.
  158656. **************************************************************************/
  158657. #endif
  158658. #define FTS5_OR 1
  158659. #define FTS5_AND 2
  158660. #define FTS5_NOT 3
  158661. #define FTS5_TERM 4
  158662. #define FTS5_COLON 5
  158663. #define FTS5_LP 6
  158664. #define FTS5_RP 7
  158665. #define FTS5_LCP 8
  158666. #define FTS5_RCP 9
  158667. #define FTS5_STRING 10
  158668. #define FTS5_COMMA 11
  158669. #define FTS5_PLUS 12
  158670. #define FTS5_STAR 13
  158671. /*
  158672. ** 2000-05-29
  158673. **
  158674. ** The author disclaims copyright to this source code. In place of
  158675. ** a legal notice, here is a blessing:
  158676. **
  158677. ** May you do good and not evil.
  158678. ** May you find forgiveness for yourself and forgive others.
  158679. ** May you share freely, never taking more than you give.
  158680. **
  158681. *************************************************************************
  158682. ** Driver template for the LEMON parser generator.
  158683. **
  158684. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  158685. ** this template to construct a parser. The "lemon" program inserts text
  158686. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  158687. ** interstitial "-" characters) contained in this template is changed into
  158688. ** the value of the %name directive from the grammar. Otherwise, the content
  158689. ** of this template is copied straight through into the generate parser
  158690. ** source file.
  158691. **
  158692. ** The following is the concatenation of all %include directives from the
  158693. ** input grammar file:
  158694. */
  158695. /* #include <stdio.h> */
  158696. /************ Begin %include sections from the grammar ************************/
  158697. /* #include "fts5Int.h" */
  158698. /* #include "fts5parse.h" */
  158699. /*
  158700. ** Disable all error recovery processing in the parser push-down
  158701. ** automaton.
  158702. */
  158703. #define fts5YYNOERRORRECOVERY 1
  158704. /*
  158705. ** Make fts5yytestcase() the same as testcase()
  158706. */
  158707. #define fts5yytestcase(X) testcase(X)
  158708. /*
  158709. ** Indicate that sqlite3ParserFree() will never be called with a null
  158710. ** pointer.
  158711. */
  158712. #define fts5YYPARSEFREENOTNULL 1
  158713. /*
  158714. ** Alternative datatype for the argument to the malloc() routine passed
  158715. ** into sqlite3ParserAlloc(). The default is size_t.
  158716. */
  158717. #define fts5YYMALLOCARGTYPE u64
  158718. /**************** End of %include directives **********************************/
  158719. /* These constants specify the various numeric values for terminal symbols
  158720. ** in a format understandable to "makeheaders". This section is blank unless
  158721. ** "lemon" is run with the "-m" command-line option.
  158722. ***************** Begin makeheaders token definitions *************************/
  158723. /**************** End makeheaders token definitions ***************************/
  158724. /* The next sections is a series of control #defines.
  158725. ** various aspects of the generated parser.
  158726. ** fts5YYCODETYPE is the data type used to store the integer codes
  158727. ** that represent terminal and non-terminal symbols.
  158728. ** "unsigned char" is used if there are fewer than
  158729. ** 256 symbols. Larger types otherwise.
  158730. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  158731. ** any terminal or nonterminal symbol.
  158732. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  158733. ** (also known as: "terminal symbols") have fall-back
  158734. ** values which should be used if the original symbol
  158735. ** would not parse. This permits keywords to sometimes
  158736. ** be used as identifiers, for example.
  158737. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  158738. ** that indicate what to do in response to the next
  158739. ** token.
  158740. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  158741. ** symbols. Background: A "minor type" is a semantic
  158742. ** value associated with a terminal or non-terminal
  158743. ** symbols. For example, for an "ID" terminal symbol,
  158744. ** the minor type might be the name of the identifier.
  158745. ** Each non-terminal can have a different minor type.
  158746. ** Terminal symbols all have the same minor type, though.
  158747. ** This macros defines the minor type for terminal
  158748. ** symbols.
  158749. ** fts5YYMINORTYPE is the data type used for all minor types.
  158750. ** This is typically a union of many types, one of
  158751. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  158752. ** for terminal symbols is called "fts5yy0".
  158753. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  158754. ** zero the stack is dynamically sized using realloc()
  158755. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  158756. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  158757. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  158758. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  158759. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  158760. ** defined, then do no error processing.
  158761. ** fts5YYNSTATE the combined number of states.
  158762. ** fts5YYNRULE the number of rules in the grammar
  158763. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  158764. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  158765. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  158766. ** fts5YY_MIN_REDUCE Maximum value for reduce actions
  158767. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  158768. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  158769. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  158770. */
  158771. #ifndef INTERFACE
  158772. # define INTERFACE 1
  158773. #endif
  158774. /************* Begin control #defines *****************************************/
  158775. #define fts5YYCODETYPE unsigned char
  158776. #define fts5YYNOCODE 27
  158777. #define fts5YYACTIONTYPE unsigned char
  158778. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  158779. typedef union {
  158780. int fts5yyinit;
  158781. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  158782. Fts5Colset* fts5yy3;
  158783. Fts5ExprPhrase* fts5yy11;
  158784. Fts5ExprNode* fts5yy18;
  158785. int fts5yy20;
  158786. Fts5ExprNearset* fts5yy26;
  158787. } fts5YYMINORTYPE;
  158788. #ifndef fts5YYSTACKDEPTH
  158789. #define fts5YYSTACKDEPTH 100
  158790. #endif
  158791. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  158792. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  158793. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  158794. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  158795. #define fts5YYNSTATE 26
  158796. #define fts5YYNRULE 24
  158797. #define fts5YY_MAX_SHIFT 25
  158798. #define fts5YY_MIN_SHIFTREDUCE 40
  158799. #define fts5YY_MAX_SHIFTREDUCE 63
  158800. #define fts5YY_MIN_REDUCE 64
  158801. #define fts5YY_MAX_REDUCE 87
  158802. #define fts5YY_ERROR_ACTION 88
  158803. #define fts5YY_ACCEPT_ACTION 89
  158804. #define fts5YY_NO_ACTION 90
  158805. /************* End control #defines *******************************************/
  158806. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  158807. ** otherwise.
  158808. **
  158809. ** Applications can choose to define fts5yytestcase() in the %include section
  158810. ** to a macro that can assist in verifying code coverage. For production
  158811. ** code the fts5yytestcase() macro should be turned off. But it is useful
  158812. ** for testing.
  158813. */
  158814. #ifndef fts5yytestcase
  158815. # define fts5yytestcase(X)
  158816. #endif
  158817. /* Next are the tables used to determine what action to take based on the
  158818. ** current state and lookahead token. These tables are used to implement
  158819. ** functions that take a state number and lookahead value and return an
  158820. ** action integer.
  158821. **
  158822. ** Suppose the action integer is N. Then the action is determined as
  158823. ** follows
  158824. **
  158825. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  158826. ** token onto the stack and goto state N.
  158827. **
  158828. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  158829. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  158830. **
  158831. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  158832. ** and fts5YY_MAX_REDUCE
  158833. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  158834. **
  158835. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  158836. **
  158837. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  158838. ** slots in the fts5yy_action[] table.
  158839. **
  158840. ** The action table is constructed as a single large table named fts5yy_action[].
  158841. ** Given state S and lookahead X, the action is computed as
  158842. **
  158843. ** fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  158844. **
  158845. ** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
  158846. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
  158847. ** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
  158848. ** and that fts5yy_default[S] should be used instead.
  158849. **
  158850. ** The formula above is for computing the action when the lookahead is
  158851. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  158852. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  158853. ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
  158854. ** fts5YY_SHIFT_USE_DFLT.
  158855. **
  158856. ** The following are the tables generated in this section:
  158857. **
  158858. ** fts5yy_action[] A single table containing all actions.
  158859. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  158860. ** fts5yy_action. Used to detect hash collisions.
  158861. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  158862. ** shifting terminals.
  158863. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  158864. ** shifting non-terminals after a reduce.
  158865. ** fts5yy_default[] Default action for each state.
  158866. **
  158867. *********** Begin parsing tables **********************************************/
  158868. #define fts5YY_ACTTAB_COUNT (78)
  158869. static const fts5YYACTIONTYPE fts5yy_action[] = {
  158870. /* 0 */ 89, 15, 46, 5, 48, 24, 12, 19, 23, 14,
  158871. /* 10 */ 46, 5, 48, 24, 20, 21, 23, 43, 46, 5,
  158872. /* 20 */ 48, 24, 6, 18, 23, 17, 46, 5, 48, 24,
  158873. /* 30 */ 75, 7, 23, 25, 46, 5, 48, 24, 62, 47,
  158874. /* 40 */ 23, 48, 24, 7, 11, 23, 9, 3, 4, 2,
  158875. /* 50 */ 62, 50, 52, 44, 64, 3, 4, 2, 49, 4,
  158876. /* 60 */ 2, 1, 23, 11, 16, 9, 12, 2, 10, 61,
  158877. /* 70 */ 53, 59, 62, 60, 22, 13, 55, 8,
  158878. };
  158879. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  158880. /* 0 */ 15, 16, 17, 18, 19, 20, 10, 11, 23, 16,
  158881. /* 10 */ 17, 18, 19, 20, 23, 24, 23, 16, 17, 18,
  158882. /* 20 */ 19, 20, 22, 23, 23, 16, 17, 18, 19, 20,
  158883. /* 30 */ 5, 6, 23, 16, 17, 18, 19, 20, 13, 17,
  158884. /* 40 */ 23, 19, 20, 6, 8, 23, 10, 1, 2, 3,
  158885. /* 50 */ 13, 9, 10, 7, 0, 1, 2, 3, 19, 2,
  158886. /* 60 */ 3, 6, 23, 8, 21, 10, 10, 3, 10, 25,
  158887. /* 70 */ 10, 10, 13, 25, 12, 10, 7, 5,
  158888. };
  158889. #define fts5YY_SHIFT_USE_DFLT (-5)
  158890. #define fts5YY_SHIFT_COUNT (25)
  158891. #define fts5YY_SHIFT_MIN (-4)
  158892. #define fts5YY_SHIFT_MAX (72)
  158893. static const signed char fts5yy_shift_ofst[] = {
  158894. /* 0 */ 55, 55, 55, 55, 55, 36, -4, 56, 58, 25,
  158895. /* 10 */ 37, 60, 59, 59, 46, 54, 42, 57, 62, 61,
  158896. /* 20 */ 62, 69, 65, 62, 72, 64,
  158897. };
  158898. #define fts5YY_REDUCE_USE_DFLT (-16)
  158899. #define fts5YY_REDUCE_COUNT (13)
  158900. #define fts5YY_REDUCE_MIN (-15)
  158901. #define fts5YY_REDUCE_MAX (48)
  158902. static const signed char fts5yy_reduce_ofst[] = {
  158903. /* 0 */ -15, -7, 1, 9, 17, 22, -9, 0, 39, 44,
  158904. /* 10 */ 44, 43, 44, 48,
  158905. };
  158906. static const fts5YYACTIONTYPE fts5yy_default[] = {
  158907. /* 0 */ 88, 88, 88, 88, 88, 69, 82, 88, 88, 87,
  158908. /* 10 */ 87, 88, 87, 87, 88, 88, 88, 66, 80, 88,
  158909. /* 20 */ 81, 88, 88, 78, 88, 65,
  158910. };
  158911. /********** End of lemon-generated parsing tables *****************************/
  158912. /* The next table maps tokens (terminal symbols) into fallback tokens.
  158913. ** If a construct like the following:
  158914. **
  158915. ** %fallback ID X Y Z.
  158916. **
  158917. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  158918. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  158919. ** but it does not parse, the type of the token is changed to ID and
  158920. ** the parse is retried before an error is thrown.
  158921. **
  158922. ** This feature can be used, for example, to cause some keywords in a language
  158923. ** to revert to identifiers if they keyword does not apply in the context where
  158924. ** it appears.
  158925. */
  158926. #ifdef fts5YYFALLBACK
  158927. static const fts5YYCODETYPE fts5yyFallback[] = {
  158928. };
  158929. #endif /* fts5YYFALLBACK */
  158930. /* The following structure represents a single element of the
  158931. ** parser's stack. Information stored includes:
  158932. **
  158933. ** + The state number for the parser at this level of the stack.
  158934. **
  158935. ** + The value of the token stored at this level of the stack.
  158936. ** (In other words, the "major" token.)
  158937. **
  158938. ** + The semantic value stored at this level of the stack. This is
  158939. ** the information used by the action routines in the grammar.
  158940. ** It is sometimes called the "minor" token.
  158941. **
  158942. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  158943. ** actually contains the reduce action for the second half of the
  158944. ** SHIFTREDUCE.
  158945. */
  158946. struct fts5yyStackEntry {
  158947. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  158948. fts5YYCODETYPE major; /* The major token value. This is the code
  158949. ** number for the token at this stack level */
  158950. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  158951. ** is the value of the token */
  158952. };
  158953. typedef struct fts5yyStackEntry fts5yyStackEntry;
  158954. /* The state of the parser is completely contained in an instance of
  158955. ** the following structure */
  158956. struct fts5yyParser {
  158957. int fts5yyidx; /* Index of top element in stack */
  158958. #ifdef fts5YYTRACKMAXSTACKDEPTH
  158959. int fts5yyidxMax; /* Maximum value of fts5yyidx */
  158960. #endif
  158961. #ifndef fts5YYNOERRORRECOVERY
  158962. int fts5yyerrcnt; /* Shifts left before out of the error */
  158963. #endif
  158964. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  158965. #if fts5YYSTACKDEPTH<=0
  158966. int fts5yystksz; /* Current side of the stack */
  158967. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  158968. #else
  158969. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  158970. #endif
  158971. };
  158972. typedef struct fts5yyParser fts5yyParser;
  158973. #ifndef NDEBUG
  158974. /* #include <stdio.h> */
  158975. static FILE *fts5yyTraceFILE = 0;
  158976. static char *fts5yyTracePrompt = 0;
  158977. #endif /* NDEBUG */
  158978. #ifndef NDEBUG
  158979. /*
  158980. ** Turn parser tracing on by giving a stream to which to write the trace
  158981. ** and a prompt to preface each trace message. Tracing is turned off
  158982. ** by making either argument NULL
  158983. **
  158984. ** Inputs:
  158985. ** <ul>
  158986. ** <li> A FILE* to which trace output should be written.
  158987. ** If NULL, then tracing is turned off.
  158988. ** <li> A prefix string written at the beginning of every
  158989. ** line of trace output. If NULL, then tracing is
  158990. ** turned off.
  158991. ** </ul>
  158992. **
  158993. ** Outputs:
  158994. ** None.
  158995. */
  158996. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  158997. fts5yyTraceFILE = TraceFILE;
  158998. fts5yyTracePrompt = zTracePrompt;
  158999. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  159000. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  159001. }
  159002. #endif /* NDEBUG */
  159003. #ifndef NDEBUG
  159004. /* For tracing shifts, the names of all terminals and nonterminals
  159005. ** are required. The following table supplies these names */
  159006. static const char *const fts5yyTokenName[] = {
  159007. "$", "OR", "AND", "NOT",
  159008. "TERM", "COLON", "LP", "RP",
  159009. "LCP", "RCP", "STRING", "COMMA",
  159010. "PLUS", "STAR", "error", "input",
  159011. "expr", "cnearset", "exprlist", "nearset",
  159012. "colset", "colsetlist", "nearphrases", "phrase",
  159013. "neardist_opt", "star_opt",
  159014. };
  159015. #endif /* NDEBUG */
  159016. #ifndef NDEBUG
  159017. /* For tracing reduce actions, the names of all rules are required.
  159018. */
  159019. static const char *const fts5yyRuleName[] = {
  159020. /* 0 */ "input ::= expr",
  159021. /* 1 */ "expr ::= expr AND expr",
  159022. /* 2 */ "expr ::= expr OR expr",
  159023. /* 3 */ "expr ::= expr NOT expr",
  159024. /* 4 */ "expr ::= LP expr RP",
  159025. /* 5 */ "expr ::= exprlist",
  159026. /* 6 */ "exprlist ::= cnearset",
  159027. /* 7 */ "exprlist ::= exprlist cnearset",
  159028. /* 8 */ "cnearset ::= nearset",
  159029. /* 9 */ "cnearset ::= colset COLON nearset",
  159030. /* 10 */ "colset ::= LCP colsetlist RCP",
  159031. /* 11 */ "colset ::= STRING",
  159032. /* 12 */ "colsetlist ::= colsetlist STRING",
  159033. /* 13 */ "colsetlist ::= STRING",
  159034. /* 14 */ "nearset ::= phrase",
  159035. /* 15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  159036. /* 16 */ "nearphrases ::= phrase",
  159037. /* 17 */ "nearphrases ::= nearphrases phrase",
  159038. /* 18 */ "neardist_opt ::=",
  159039. /* 19 */ "neardist_opt ::= COMMA STRING",
  159040. /* 20 */ "phrase ::= phrase PLUS STRING star_opt",
  159041. /* 21 */ "phrase ::= STRING star_opt",
  159042. /* 22 */ "star_opt ::= STAR",
  159043. /* 23 */ "star_opt ::=",
  159044. };
  159045. #endif /* NDEBUG */
  159046. #if fts5YYSTACKDEPTH<=0
  159047. /*
  159048. ** Try to increase the size of the parser stack.
  159049. */
  159050. static void fts5yyGrowStack(fts5yyParser *p){
  159051. int newSize;
  159052. fts5yyStackEntry *pNew;
  159053. newSize = p->fts5yystksz*2 + 100;
  159054. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  159055. if( pNew ){
  159056. p->fts5yystack = pNew;
  159057. p->fts5yystksz = newSize;
  159058. #ifndef NDEBUG
  159059. if( fts5yyTraceFILE ){
  159060. fprintf(fts5yyTraceFILE,"%sStack grows to %d entries!\n",
  159061. fts5yyTracePrompt, p->fts5yystksz);
  159062. }
  159063. #endif
  159064. }
  159065. }
  159066. #endif
  159067. /* Datatype of the argument to the memory allocated passed as the
  159068. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  159069. ** putting an appropriate #define in the %include section of the input
  159070. ** grammar.
  159071. */
  159072. #ifndef fts5YYMALLOCARGTYPE
  159073. # define fts5YYMALLOCARGTYPE size_t
  159074. #endif
  159075. /*
  159076. ** This function allocates a new parser.
  159077. ** The only argument is a pointer to a function which works like
  159078. ** malloc.
  159079. **
  159080. ** Inputs:
  159081. ** A pointer to the function used to allocate memory.
  159082. **
  159083. ** Outputs:
  159084. ** A pointer to a parser. This pointer is used in subsequent calls
  159085. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  159086. */
  159087. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
  159088. fts5yyParser *pParser;
  159089. pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  159090. if( pParser ){
  159091. pParser->fts5yyidx = -1;
  159092. #ifdef fts5YYTRACKMAXSTACKDEPTH
  159093. pParser->fts5yyidxMax = 0;
  159094. #endif
  159095. #if fts5YYSTACKDEPTH<=0
  159096. pParser->fts5yystack = NULL;
  159097. pParser->fts5yystksz = 0;
  159098. fts5yyGrowStack(pParser);
  159099. #endif
  159100. }
  159101. return pParser;
  159102. }
  159103. /* The following function deletes the "minor type" or semantic value
  159104. ** associated with a symbol. The symbol can be either a terminal
  159105. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  159106. ** a pointer to the value to be deleted. The code used to do the
  159107. ** deletions is derived from the %destructor and/or %token_destructor
  159108. ** directives of the input grammar.
  159109. */
  159110. static void fts5yy_destructor(
  159111. fts5yyParser *fts5yypParser, /* The parser */
  159112. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  159113. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  159114. ){
  159115. sqlite3Fts5ParserARG_FETCH;
  159116. switch( fts5yymajor ){
  159117. /* Here is inserted the actions which take place when a
  159118. ** terminal or non-terminal is destroyed. This can happen
  159119. ** when the symbol is popped from the stack during a
  159120. ** reduce or during error processing or when a parser is
  159121. ** being destroyed before it is finished parsing.
  159122. **
  159123. ** Note: during a reduce, the only symbols destroyed are those
  159124. ** which appear on the RHS of the rule, but which are *not* used
  159125. ** inside the C code.
  159126. */
  159127. /********* Begin destructor definitions ***************************************/
  159128. case 15: /* input */
  159129. {
  159130. (void)pParse;
  159131. }
  159132. break;
  159133. case 16: /* expr */
  159134. case 17: /* cnearset */
  159135. case 18: /* exprlist */
  159136. {
  159137. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
  159138. }
  159139. break;
  159140. case 19: /* nearset */
  159141. case 22: /* nearphrases */
  159142. {
  159143. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
  159144. }
  159145. break;
  159146. case 20: /* colset */
  159147. case 21: /* colsetlist */
  159148. {
  159149. sqlite3_free((fts5yypminor->fts5yy3));
  159150. }
  159151. break;
  159152. case 23: /* phrase */
  159153. {
  159154. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
  159155. }
  159156. break;
  159157. /********* End destructor definitions *****************************************/
  159158. default: break; /* If no destructor action specified: do nothing */
  159159. }
  159160. }
  159161. /*
  159162. ** Pop the parser's stack once.
  159163. **
  159164. ** If there is a destructor routine associated with the token which
  159165. ** is popped from the stack, then call it.
  159166. */
  159167. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  159168. fts5yyStackEntry *fts5yytos;
  159169. assert( pParser->fts5yyidx>=0 );
  159170. fts5yytos = &pParser->fts5yystack[pParser->fts5yyidx--];
  159171. #ifndef NDEBUG
  159172. if( fts5yyTraceFILE ){
  159173. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  159174. fts5yyTracePrompt,
  159175. fts5yyTokenName[fts5yytos->major]);
  159176. }
  159177. #endif
  159178. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  159179. }
  159180. /*
  159181. ** Deallocate and destroy a parser. Destructors are called for
  159182. ** all stack elements before shutting the parser down.
  159183. **
  159184. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  159185. ** is defined in a %include section of the input grammar) then it is
  159186. ** assumed that the input pointer is never NULL.
  159187. */
  159188. static void sqlite3Fts5ParserFree(
  159189. void *p, /* The parser to be deleted */
  159190. void (*freeProc)(void*) /* Function used to reclaim memory */
  159191. ){
  159192. fts5yyParser *pParser = (fts5yyParser*)p;
  159193. #ifndef fts5YYPARSEFREENEVERNULL
  159194. if( pParser==0 ) return;
  159195. #endif
  159196. while( pParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(pParser);
  159197. #if fts5YYSTACKDEPTH<=0
  159198. free(pParser->fts5yystack);
  159199. #endif
  159200. (*freeProc)((void*)pParser);
  159201. }
  159202. /*
  159203. ** Return the peak depth of the stack for a parser.
  159204. */
  159205. #ifdef fts5YYTRACKMAXSTACKDEPTH
  159206. static int sqlite3Fts5ParserStackPeak(void *p){
  159207. fts5yyParser *pParser = (fts5yyParser*)p;
  159208. return pParser->fts5yyidxMax;
  159209. }
  159210. #endif
  159211. /*
  159212. ** Find the appropriate action for a parser given the terminal
  159213. ** look-ahead token iLookAhead.
  159214. */
  159215. static unsigned int fts5yy_find_shift_action(
  159216. fts5yyParser *pParser, /* The parser */
  159217. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  159218. ){
  159219. int i;
  159220. int stateno = pParser->fts5yystack[pParser->fts5yyidx].stateno;
  159221. if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
  159222. assert( stateno <= fts5YY_SHIFT_COUNT );
  159223. do{
  159224. i = fts5yy_shift_ofst[stateno];
  159225. if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
  159226. assert( iLookAhead!=fts5YYNOCODE );
  159227. i += iLookAhead;
  159228. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  159229. if( iLookAhead>0 ){
  159230. #ifdef fts5YYFALLBACK
  159231. fts5YYCODETYPE iFallback; /* Fallback token */
  159232. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  159233. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  159234. #ifndef NDEBUG
  159235. if( fts5yyTraceFILE ){
  159236. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  159237. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  159238. }
  159239. #endif
  159240. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  159241. iLookAhead = iFallback;
  159242. continue;
  159243. }
  159244. #endif
  159245. #ifdef fts5YYWILDCARD
  159246. {
  159247. int j = i - iLookAhead + fts5YYWILDCARD;
  159248. if(
  159249. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  159250. j>=0 &&
  159251. #endif
  159252. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  159253. j<fts5YY_ACTTAB_COUNT &&
  159254. #endif
  159255. fts5yy_lookahead[j]==fts5YYWILDCARD
  159256. ){
  159257. #ifndef NDEBUG
  159258. if( fts5yyTraceFILE ){
  159259. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  159260. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  159261. fts5yyTokenName[fts5YYWILDCARD]);
  159262. }
  159263. #endif /* NDEBUG */
  159264. return fts5yy_action[j];
  159265. }
  159266. }
  159267. #endif /* fts5YYWILDCARD */
  159268. }
  159269. return fts5yy_default[stateno];
  159270. }else{
  159271. return fts5yy_action[i];
  159272. }
  159273. }while(1);
  159274. }
  159275. /*
  159276. ** Find the appropriate action for a parser given the non-terminal
  159277. ** look-ahead token iLookAhead.
  159278. */
  159279. static int fts5yy_find_reduce_action(
  159280. int stateno, /* Current state number */
  159281. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  159282. ){
  159283. int i;
  159284. #ifdef fts5YYERRORSYMBOL
  159285. if( stateno>fts5YY_REDUCE_COUNT ){
  159286. return fts5yy_default[stateno];
  159287. }
  159288. #else
  159289. assert( stateno<=fts5YY_REDUCE_COUNT );
  159290. #endif
  159291. i = fts5yy_reduce_ofst[stateno];
  159292. assert( i!=fts5YY_REDUCE_USE_DFLT );
  159293. assert( iLookAhead!=fts5YYNOCODE );
  159294. i += iLookAhead;
  159295. #ifdef fts5YYERRORSYMBOL
  159296. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  159297. return fts5yy_default[stateno];
  159298. }
  159299. #else
  159300. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  159301. assert( fts5yy_lookahead[i]==iLookAhead );
  159302. #endif
  159303. return fts5yy_action[i];
  159304. }
  159305. /*
  159306. ** The following routine is called if the stack overflows.
  159307. */
  159308. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  159309. sqlite3Fts5ParserARG_FETCH;
  159310. fts5yypParser->fts5yyidx--;
  159311. #ifndef NDEBUG
  159312. if( fts5yyTraceFILE ){
  159313. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  159314. }
  159315. #endif
  159316. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  159317. /* Here code is inserted which will execute if the parser
  159318. ** stack every overflows */
  159319. /******** Begin %stack_overflow code ******************************************/
  159320. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  159321. /******** End %stack_overflow code ********************************************/
  159322. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  159323. }
  159324. /*
  159325. ** Print tracing information for a SHIFT action
  159326. */
  159327. #ifndef NDEBUG
  159328. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
  159329. if( fts5yyTraceFILE ){
  159330. if( fts5yyNewState<fts5YYNSTATE ){
  159331. fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
  159332. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major],
  159333. fts5yyNewState);
  159334. }else{
  159335. fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
  159336. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major]);
  159337. }
  159338. }
  159339. }
  159340. #else
  159341. # define fts5yyTraceShift(X,Y)
  159342. #endif
  159343. /*
  159344. ** Perform a shift action.
  159345. */
  159346. static void fts5yy_shift(
  159347. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  159348. int fts5yyNewState, /* The new state to shift in */
  159349. int fts5yyMajor, /* The major token to shift in */
  159350. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  159351. ){
  159352. fts5yyStackEntry *fts5yytos;
  159353. fts5yypParser->fts5yyidx++;
  159354. #ifdef fts5YYTRACKMAXSTACKDEPTH
  159355. if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
  159356. fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
  159357. }
  159358. #endif
  159359. #if fts5YYSTACKDEPTH>0
  159360. if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH ){
  159361. fts5yyStackOverflow(fts5yypParser);
  159362. return;
  159363. }
  159364. #else
  159365. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
  159366. fts5yyGrowStack(fts5yypParser);
  159367. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
  159368. fts5yyStackOverflow(fts5yypParser);
  159369. return;
  159370. }
  159371. }
  159372. #endif
  159373. fts5yytos = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
  159374. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  159375. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  159376. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  159377. fts5yyTraceShift(fts5yypParser, fts5yyNewState);
  159378. }
  159379. /* The following table contains information about every rule that
  159380. ** is used during the reduce.
  159381. */
  159382. static const struct {
  159383. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  159384. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  159385. } fts5yyRuleInfo[] = {
  159386. { 15, 1 },
  159387. { 16, 3 },
  159388. { 16, 3 },
  159389. { 16, 3 },
  159390. { 16, 3 },
  159391. { 16, 1 },
  159392. { 18, 1 },
  159393. { 18, 2 },
  159394. { 17, 1 },
  159395. { 17, 3 },
  159396. { 20, 3 },
  159397. { 20, 1 },
  159398. { 21, 2 },
  159399. { 21, 1 },
  159400. { 19, 1 },
  159401. { 19, 5 },
  159402. { 22, 1 },
  159403. { 22, 2 },
  159404. { 24, 0 },
  159405. { 24, 2 },
  159406. { 23, 4 },
  159407. { 23, 2 },
  159408. { 25, 1 },
  159409. { 25, 0 },
  159410. };
  159411. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  159412. /*
  159413. ** Perform a reduce action and the shift that must immediately
  159414. ** follow the reduce.
  159415. */
  159416. static void fts5yy_reduce(
  159417. fts5yyParser *fts5yypParser, /* The parser */
  159418. unsigned int fts5yyruleno /* Number of the rule by which to reduce */
  159419. ){
  159420. int fts5yygoto; /* The next state */
  159421. int fts5yyact; /* The next action */
  159422. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  159423. int fts5yysize; /* Amount to pop the stack */
  159424. sqlite3Fts5ParserARG_FETCH;
  159425. fts5yymsp = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
  159426. #ifndef NDEBUG
  159427. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  159428. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  159429. fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
  159430. fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
  159431. }
  159432. #endif /* NDEBUG */
  159433. /* Check that the stack is large enough to grow by a single entry
  159434. ** if the RHS of the rule is empty. This ensures that there is room
  159435. ** enough on the stack to push the LHS value */
  159436. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  159437. #ifdef fts5YYTRACKMAXSTACKDEPTH
  159438. if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
  159439. fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
  159440. }
  159441. #endif
  159442. #if fts5YYSTACKDEPTH>0
  159443. if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH-1 ){
  159444. fts5yyStackOverflow(fts5yypParser);
  159445. return;
  159446. }
  159447. #else
  159448. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz-1 ){
  159449. fts5yyGrowStack(fts5yypParser);
  159450. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz-1 ){
  159451. fts5yyStackOverflow(fts5yypParser);
  159452. return;
  159453. }
  159454. }
  159455. #endif
  159456. }
  159457. switch( fts5yyruleno ){
  159458. /* Beginning here are the reduction cases. A typical example
  159459. ** follows:
  159460. ** case 0:
  159461. ** #line <lineno> <grammarfile>
  159462. ** { ... } // User supplied code
  159463. ** #line <lineno> <thisfile>
  159464. ** break;
  159465. */
  159466. /********** Begin reduce actions **********************************************/
  159467. fts5YYMINORTYPE fts5yylhsminor;
  159468. case 0: /* input ::= expr */
  159469. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
  159470. break;
  159471. case 1: /* expr ::= expr AND expr */
  159472. {
  159473. fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  159474. }
  159475. fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159476. break;
  159477. case 2: /* expr ::= expr OR expr */
  159478. {
  159479. fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  159480. }
  159481. fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159482. break;
  159483. case 3: /* expr ::= expr NOT expr */
  159484. {
  159485. fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  159486. }
  159487. fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159488. break;
  159489. case 4: /* expr ::= LP expr RP */
  159490. {fts5yymsp[-2].minor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
  159491. break;
  159492. case 5: /* expr ::= exprlist */
  159493. case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
  159494. {fts5yylhsminor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
  159495. fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159496. break;
  159497. case 7: /* exprlist ::= exprlist cnearset */
  159498. {
  159499. fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18);
  159500. }
  159501. fts5yymsp[-1].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159502. break;
  159503. case 8: /* cnearset ::= nearset */
  159504. {
  159505. fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
  159506. }
  159507. fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159508. break;
  159509. case 9: /* cnearset ::= colset COLON nearset */
  159510. {
  159511. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
  159512. fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
  159513. }
  159514. fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
  159515. break;
  159516. case 10: /* colset ::= LCP colsetlist RCP */
  159517. { fts5yymsp[-2].minor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
  159518. break;
  159519. case 11: /* colset ::= STRING */
  159520. {
  159521. fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  159522. }
  159523. fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
  159524. break;
  159525. case 12: /* colsetlist ::= colsetlist STRING */
  159526. {
  159527. fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
  159528. fts5yymsp[-1].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
  159529. break;
  159530. case 13: /* colsetlist ::= STRING */
  159531. {
  159532. fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  159533. }
  159534. fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
  159535. break;
  159536. case 14: /* nearset ::= phrase */
  159537. { fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
  159538. fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
  159539. break;
  159540. case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  159541. {
  159542. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  159543. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
  159544. fts5yylhsminor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
  159545. }
  159546. fts5yymsp[-4].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
  159547. break;
  159548. case 16: /* nearphrases ::= phrase */
  159549. {
  159550. fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
  159551. }
  159552. fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
  159553. break;
  159554. case 17: /* nearphrases ::= nearphrases phrase */
  159555. {
  159556. fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
  159557. }
  159558. fts5yymsp[-1].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
  159559. break;
  159560. case 18: /* neardist_opt ::= */
  159561. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  159562. break;
  159563. case 19: /* neardist_opt ::= COMMA STRING */
  159564. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  159565. break;
  159566. case 20: /* phrase ::= phrase PLUS STRING star_opt */
  159567. {
  159568. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
  159569. }
  159570. fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  159571. break;
  159572. case 21: /* phrase ::= STRING star_opt */
  159573. {
  159574. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
  159575. }
  159576. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  159577. break;
  159578. case 22: /* star_opt ::= STAR */
  159579. { fts5yymsp[0].minor.fts5yy20 = 1; }
  159580. break;
  159581. case 23: /* star_opt ::= */
  159582. { fts5yymsp[1].minor.fts5yy20 = 0; }
  159583. break;
  159584. default:
  159585. break;
  159586. /********** End reduce actions ************************************************/
  159587. };
  159588. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  159589. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  159590. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  159591. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  159592. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  159593. if( fts5yyact>fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  159594. fts5yypParser->fts5yyidx -= fts5yysize - 1;
  159595. fts5yymsp -= fts5yysize-1;
  159596. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  159597. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  159598. fts5yyTraceShift(fts5yypParser, fts5yyact);
  159599. }else{
  159600. assert( fts5yyact == fts5YY_ACCEPT_ACTION );
  159601. fts5yypParser->fts5yyidx -= fts5yysize;
  159602. fts5yy_accept(fts5yypParser);
  159603. }
  159604. }
  159605. /*
  159606. ** The following code executes when the parse fails
  159607. */
  159608. #ifndef fts5YYNOERRORRECOVERY
  159609. static void fts5yy_parse_failed(
  159610. fts5yyParser *fts5yypParser /* The parser */
  159611. ){
  159612. sqlite3Fts5ParserARG_FETCH;
  159613. #ifndef NDEBUG
  159614. if( fts5yyTraceFILE ){
  159615. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  159616. }
  159617. #endif
  159618. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  159619. /* Here code is inserted which will be executed whenever the
  159620. ** parser fails */
  159621. /************ Begin %parse_failure code ***************************************/
  159622. /************ End %parse_failure code *****************************************/
  159623. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  159624. }
  159625. #endif /* fts5YYNOERRORRECOVERY */
  159626. /*
  159627. ** The following code executes when a syntax error first occurs.
  159628. */
  159629. static void fts5yy_syntax_error(
  159630. fts5yyParser *fts5yypParser, /* The parser */
  159631. int fts5yymajor, /* The major type of the error token */
  159632. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  159633. ){
  159634. sqlite3Fts5ParserARG_FETCH;
  159635. #define FTS5TOKEN fts5yyminor
  159636. /************ Begin %syntax_error code ****************************************/
  159637. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  159638. sqlite3Fts5ParseError(
  159639. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  159640. );
  159641. /************ End %syntax_error code ******************************************/
  159642. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  159643. }
  159644. /*
  159645. ** The following is executed when the parser accepts
  159646. */
  159647. static void fts5yy_accept(
  159648. fts5yyParser *fts5yypParser /* The parser */
  159649. ){
  159650. sqlite3Fts5ParserARG_FETCH;
  159651. #ifndef NDEBUG
  159652. if( fts5yyTraceFILE ){
  159653. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  159654. }
  159655. #endif
  159656. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  159657. /* Here code is inserted which will be executed whenever the
  159658. ** parser accepts */
  159659. /*********** Begin %parse_accept code *****************************************/
  159660. /*********** End %parse_accept code *******************************************/
  159661. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  159662. }
  159663. /* The main parser program.
  159664. ** The first argument is a pointer to a structure obtained from
  159665. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  159666. ** The second argument is the major token number. The third is
  159667. ** the minor token. The fourth optional argument is whatever the
  159668. ** user wants (and specified in the grammar) and is available for
  159669. ** use by the action routines.
  159670. **
  159671. ** Inputs:
  159672. ** <ul>
  159673. ** <li> A pointer to the parser (an opaque structure.)
  159674. ** <li> The major token number.
  159675. ** <li> The minor token number.
  159676. ** <li> An option argument of a grammar-specified type.
  159677. ** </ul>
  159678. **
  159679. ** Outputs:
  159680. ** None.
  159681. */
  159682. static void sqlite3Fts5Parser(
  159683. void *fts5yyp, /* The parser */
  159684. int fts5yymajor, /* The major token code number */
  159685. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  159686. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  159687. ){
  159688. fts5YYMINORTYPE fts5yyminorunion;
  159689. unsigned int fts5yyact; /* The parser action. */
  159690. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  159691. int fts5yyendofinput; /* True if we are at the end of input */
  159692. #endif
  159693. #ifdef fts5YYERRORSYMBOL
  159694. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  159695. #endif
  159696. fts5yyParser *fts5yypParser; /* The parser */
  159697. /* (re)initialize the parser, if necessary */
  159698. fts5yypParser = (fts5yyParser*)fts5yyp;
  159699. if( fts5yypParser->fts5yyidx<0 ){
  159700. #if fts5YYSTACKDEPTH<=0
  159701. if( fts5yypParser->fts5yystksz <=0 ){
  159702. fts5yyStackOverflow(fts5yypParser);
  159703. return;
  159704. }
  159705. #endif
  159706. fts5yypParser->fts5yyidx = 0;
  159707. #ifndef fts5YYNOERRORRECOVERY
  159708. fts5yypParser->fts5yyerrcnt = -1;
  159709. #endif
  159710. fts5yypParser->fts5yystack[0].stateno = 0;
  159711. fts5yypParser->fts5yystack[0].major = 0;
  159712. #ifndef NDEBUG
  159713. if( fts5yyTraceFILE ){
  159714. fprintf(fts5yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
  159715. fts5yyTracePrompt);
  159716. }
  159717. #endif
  159718. }
  159719. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  159720. fts5yyendofinput = (fts5yymajor==0);
  159721. #endif
  159722. sqlite3Fts5ParserARG_STORE;
  159723. #ifndef NDEBUG
  159724. if( fts5yyTraceFILE ){
  159725. fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  159726. }
  159727. #endif
  159728. do{
  159729. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  159730. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  159731. if( fts5yyact > fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  159732. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
  159733. #ifndef fts5YYNOERRORRECOVERY
  159734. fts5yypParser->fts5yyerrcnt--;
  159735. #endif
  159736. fts5yymajor = fts5YYNOCODE;
  159737. }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
  159738. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
  159739. }else{
  159740. assert( fts5yyact == fts5YY_ERROR_ACTION );
  159741. fts5yyminorunion.fts5yy0 = fts5yyminor;
  159742. #ifdef fts5YYERRORSYMBOL
  159743. int fts5yymx;
  159744. #endif
  159745. #ifndef NDEBUG
  159746. if( fts5yyTraceFILE ){
  159747. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  159748. }
  159749. #endif
  159750. #ifdef fts5YYERRORSYMBOL
  159751. /* A syntax error has occurred.
  159752. ** The response to an error depends upon whether or not the
  159753. ** grammar defines an error token "ERROR".
  159754. **
  159755. ** This is what we do if the grammar does define ERROR:
  159756. **
  159757. ** * Call the %syntax_error function.
  159758. **
  159759. ** * Begin popping the stack until we enter a state where
  159760. ** it is legal to shift the error symbol, then shift
  159761. ** the error symbol.
  159762. **
  159763. ** * Set the error count to three.
  159764. **
  159765. ** * Begin accepting and shifting new tokens. No new error
  159766. ** processing will occur until three tokens have been
  159767. ** shifted successfully.
  159768. **
  159769. */
  159770. if( fts5yypParser->fts5yyerrcnt<0 ){
  159771. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  159772. }
  159773. fts5yymx = fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major;
  159774. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  159775. #ifndef NDEBUG
  159776. if( fts5yyTraceFILE ){
  159777. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  159778. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  159779. }
  159780. #endif
  159781. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  159782. fts5yymajor = fts5YYNOCODE;
  159783. }else{
  159784. while(
  159785. fts5yypParser->fts5yyidx >= 0 &&
  159786. fts5yymx != fts5YYERRORSYMBOL &&
  159787. (fts5yyact = fts5yy_find_reduce_action(
  159788. fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].stateno,
  159789. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  159790. ){
  159791. fts5yy_pop_parser_stack(fts5yypParser);
  159792. }
  159793. if( fts5yypParser->fts5yyidx < 0 || fts5yymajor==0 ){
  159794. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  159795. fts5yy_parse_failed(fts5yypParser);
  159796. fts5yymajor = fts5YYNOCODE;
  159797. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  159798. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  159799. }
  159800. }
  159801. fts5yypParser->fts5yyerrcnt = 3;
  159802. fts5yyerrorhit = 1;
  159803. #elif defined(fts5YYNOERRORRECOVERY)
  159804. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  159805. ** do any kind of error recovery. Instead, simply invoke the syntax
  159806. ** error routine and continue going as if nothing had happened.
  159807. **
  159808. ** Applications can set this macro (for example inside %include) if
  159809. ** they intend to abandon the parse upon the first syntax error seen.
  159810. */
  159811. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  159812. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  159813. fts5yymajor = fts5YYNOCODE;
  159814. #else /* fts5YYERRORSYMBOL is not defined */
  159815. /* This is what we do if the grammar does not define ERROR:
  159816. **
  159817. ** * Report an error message, and throw away the input token.
  159818. **
  159819. ** * If the input token is $, then fail the parse.
  159820. **
  159821. ** As before, subsequent error messages are suppressed until
  159822. ** three input tokens have been successfully shifted.
  159823. */
  159824. if( fts5yypParser->fts5yyerrcnt<=0 ){
  159825. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  159826. }
  159827. fts5yypParser->fts5yyerrcnt = 3;
  159828. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  159829. if( fts5yyendofinput ){
  159830. fts5yy_parse_failed(fts5yypParser);
  159831. }
  159832. fts5yymajor = fts5YYNOCODE;
  159833. #endif
  159834. }
  159835. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yyidx>=0 );
  159836. #ifndef NDEBUG
  159837. if( fts5yyTraceFILE ){
  159838. int i;
  159839. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  159840. for(i=1; i<=fts5yypParser->fts5yyidx; i++)
  159841. fprintf(fts5yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
  159842. fts5yyTokenName[fts5yypParser->fts5yystack[i].major]);
  159843. fprintf(fts5yyTraceFILE,"]\n");
  159844. }
  159845. #endif
  159846. return;
  159847. }
  159848. /*
  159849. ** 2014 May 31
  159850. **
  159851. ** The author disclaims copyright to this source code. In place of
  159852. ** a legal notice, here is a blessing:
  159853. **
  159854. ** May you do good and not evil.
  159855. ** May you find forgiveness for yourself and forgive others.
  159856. ** May you share freely, never taking more than you give.
  159857. **
  159858. ******************************************************************************
  159859. */
  159860. /* #include "fts5Int.h" */
  159861. #include <math.h> /* amalgamator: keep */
  159862. /*
  159863. ** Object used to iterate through all "coalesced phrase instances" in
  159864. ** a single column of the current row. If the phrase instances in the
  159865. ** column being considered do not overlap, this object simply iterates
  159866. ** through them. Or, if they do overlap (share one or more tokens in
  159867. ** common), each set of overlapping instances is treated as a single
  159868. ** match. See documentation for the highlight() auxiliary function for
  159869. ** details.
  159870. **
  159871. ** Usage is:
  159872. **
  159873. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  159874. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  159875. ** rc = fts5CInstIterNext(&iter)
  159876. ** ){
  159877. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  159878. ** }
  159879. **
  159880. */
  159881. typedef struct CInstIter CInstIter;
  159882. struct CInstIter {
  159883. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  159884. Fts5Context *pFts; /* First arg to pass to pApi functions */
  159885. int iCol; /* Column to search */
  159886. int iInst; /* Next phrase instance index */
  159887. int nInst; /* Total number of phrase instances */
  159888. /* Output variables */
  159889. int iStart; /* First token in coalesced phrase instance */
  159890. int iEnd; /* Last token in coalesced phrase instance */
  159891. };
  159892. /*
  159893. ** Advance the iterator to the next coalesced phrase instance. Return
  159894. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  159895. */
  159896. static int fts5CInstIterNext(CInstIter *pIter){
  159897. int rc = SQLITE_OK;
  159898. pIter->iStart = -1;
  159899. pIter->iEnd = -1;
  159900. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  159901. int ip; int ic; int io;
  159902. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  159903. if( rc==SQLITE_OK ){
  159904. if( ic==pIter->iCol ){
  159905. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  159906. if( pIter->iStart<0 ){
  159907. pIter->iStart = io;
  159908. pIter->iEnd = iEnd;
  159909. }else if( io<=pIter->iEnd ){
  159910. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  159911. }else{
  159912. break;
  159913. }
  159914. }
  159915. pIter->iInst++;
  159916. }
  159917. }
  159918. return rc;
  159919. }
  159920. /*
  159921. ** Initialize the iterator object indicated by the final parameter to
  159922. ** iterate through coalesced phrase instances in column iCol.
  159923. */
  159924. static int fts5CInstIterInit(
  159925. const Fts5ExtensionApi *pApi,
  159926. Fts5Context *pFts,
  159927. int iCol,
  159928. CInstIter *pIter
  159929. ){
  159930. int rc;
  159931. memset(pIter, 0, sizeof(CInstIter));
  159932. pIter->pApi = pApi;
  159933. pIter->pFts = pFts;
  159934. pIter->iCol = iCol;
  159935. rc = pApi->xInstCount(pFts, &pIter->nInst);
  159936. if( rc==SQLITE_OK ){
  159937. rc = fts5CInstIterNext(pIter);
  159938. }
  159939. return rc;
  159940. }
  159941. /*************************************************************************
  159942. ** Start of highlight() implementation.
  159943. */
  159944. typedef struct HighlightContext HighlightContext;
  159945. struct HighlightContext {
  159946. CInstIter iter; /* Coalesced Instance Iterator */
  159947. int iPos; /* Current token offset in zIn[] */
  159948. int iRangeStart; /* First token to include */
  159949. int iRangeEnd; /* If non-zero, last token to include */
  159950. const char *zOpen; /* Opening highlight */
  159951. const char *zClose; /* Closing highlight */
  159952. const char *zIn; /* Input text */
  159953. int nIn; /* Size of input text in bytes */
  159954. int iOff; /* Current offset within zIn[] */
  159955. char *zOut; /* Output value */
  159956. };
  159957. /*
  159958. ** Append text to the HighlightContext output string - p->zOut. Argument
  159959. ** z points to a buffer containing n bytes of text to append. If n is
  159960. ** negative, everything up until the first '\0' is appended to the output.
  159961. **
  159962. ** If *pRc is set to any value other than SQLITE_OK when this function is
  159963. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  159964. ** *pRc is set to an error code before returning.
  159965. */
  159966. static void fts5HighlightAppend(
  159967. int *pRc,
  159968. HighlightContext *p,
  159969. const char *z, int n
  159970. ){
  159971. if( *pRc==SQLITE_OK ){
  159972. if( n<0 ) n = (int)strlen(z);
  159973. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  159974. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  159975. }
  159976. }
  159977. /*
  159978. ** Tokenizer callback used by implementation of highlight() function.
  159979. */
  159980. static int fts5HighlightCb(
  159981. void *pContext, /* Pointer to HighlightContext object */
  159982. int tflags, /* Mask of FTS5_TOKEN_* flags */
  159983. const char *pToken, /* Buffer containing token */
  159984. int nToken, /* Size of token in bytes */
  159985. int iStartOff, /* Start offset of token */
  159986. int iEndOff /* End offset of token */
  159987. ){
  159988. HighlightContext *p = (HighlightContext*)pContext;
  159989. int rc = SQLITE_OK;
  159990. int iPos;
  159991. UNUSED_PARAM2(pToken, nToken);
  159992. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  159993. iPos = p->iPos++;
  159994. if( p->iRangeEnd>0 ){
  159995. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  159996. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  159997. }
  159998. if( iPos==p->iter.iStart ){
  159999. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  160000. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  160001. p->iOff = iStartOff;
  160002. }
  160003. if( iPos==p->iter.iEnd ){
  160004. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  160005. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  160006. }
  160007. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  160008. fts5HighlightAppend(&rc, p, p->zClose, -1);
  160009. p->iOff = iEndOff;
  160010. if( rc==SQLITE_OK ){
  160011. rc = fts5CInstIterNext(&p->iter);
  160012. }
  160013. }
  160014. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  160015. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  160016. p->iOff = iEndOff;
  160017. if( iPos<p->iter.iEnd ){
  160018. fts5HighlightAppend(&rc, p, p->zClose, -1);
  160019. }
  160020. }
  160021. return rc;
  160022. }
  160023. /*
  160024. ** Implementation of highlight() function.
  160025. */
  160026. static void fts5HighlightFunction(
  160027. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  160028. Fts5Context *pFts, /* First arg to pass to pApi functions */
  160029. sqlite3_context *pCtx, /* Context for returning result/error */
  160030. int nVal, /* Number of values in apVal[] array */
  160031. sqlite3_value **apVal /* Array of trailing arguments */
  160032. ){
  160033. HighlightContext ctx;
  160034. int rc;
  160035. int iCol;
  160036. if( nVal!=3 ){
  160037. const char *zErr = "wrong number of arguments to function highlight()";
  160038. sqlite3_result_error(pCtx, zErr, -1);
  160039. return;
  160040. }
  160041. iCol = sqlite3_value_int(apVal[0]);
  160042. memset(&ctx, 0, sizeof(HighlightContext));
  160043. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  160044. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  160045. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  160046. if( ctx.zIn ){
  160047. if( rc==SQLITE_OK ){
  160048. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  160049. }
  160050. if( rc==SQLITE_OK ){
  160051. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  160052. }
  160053. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  160054. if( rc==SQLITE_OK ){
  160055. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  160056. }
  160057. sqlite3_free(ctx.zOut);
  160058. }
  160059. if( rc!=SQLITE_OK ){
  160060. sqlite3_result_error_code(pCtx, rc);
  160061. }
  160062. }
  160063. /*
  160064. ** End of highlight() implementation.
  160065. **************************************************************************/
  160066. /*
  160067. ** Implementation of snippet() function.
  160068. */
  160069. static void fts5SnippetFunction(
  160070. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  160071. Fts5Context *pFts, /* First arg to pass to pApi functions */
  160072. sqlite3_context *pCtx, /* Context for returning result/error */
  160073. int nVal, /* Number of values in apVal[] array */
  160074. sqlite3_value **apVal /* Array of trailing arguments */
  160075. ){
  160076. HighlightContext ctx;
  160077. int rc = SQLITE_OK; /* Return code */
  160078. int iCol; /* 1st argument to snippet() */
  160079. const char *zEllips; /* 4th argument to snippet() */
  160080. int nToken; /* 5th argument to snippet() */
  160081. int nInst = 0; /* Number of instance matches this row */
  160082. int i; /* Used to iterate through instances */
  160083. int nPhrase; /* Number of phrases in query */
  160084. unsigned char *aSeen; /* Array of "seen instance" flags */
  160085. int iBestCol; /* Column containing best snippet */
  160086. int iBestStart = 0; /* First token of best snippet */
  160087. int iBestLast; /* Last token of best snippet */
  160088. int nBestScore = 0; /* Score of best snippet */
  160089. int nColSize = 0; /* Total size of iBestCol in tokens */
  160090. if( nVal!=5 ){
  160091. const char *zErr = "wrong number of arguments to function snippet()";
  160092. sqlite3_result_error(pCtx, zErr, -1);
  160093. return;
  160094. }
  160095. memset(&ctx, 0, sizeof(HighlightContext));
  160096. iCol = sqlite3_value_int(apVal[0]);
  160097. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  160098. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  160099. zEllips = (const char*)sqlite3_value_text(apVal[3]);
  160100. nToken = sqlite3_value_int(apVal[4]);
  160101. iBestLast = nToken-1;
  160102. iBestCol = (iCol>=0 ? iCol : 0);
  160103. nPhrase = pApi->xPhraseCount(pFts);
  160104. aSeen = sqlite3_malloc(nPhrase);
  160105. if( aSeen==0 ){
  160106. rc = SQLITE_NOMEM;
  160107. }
  160108. if( rc==SQLITE_OK ){
  160109. rc = pApi->xInstCount(pFts, &nInst);
  160110. }
  160111. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  160112. int ip, iSnippetCol, iStart;
  160113. memset(aSeen, 0, nPhrase);
  160114. rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
  160115. if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
  160116. int nScore = 1000;
  160117. int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
  160118. int j;
  160119. aSeen[ip] = 1;
  160120. for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
  160121. int ic; int io; int iFinal;
  160122. rc = pApi->xInst(pFts, j, &ip, &ic, &io);
  160123. iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
  160124. if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
  160125. nScore += aSeen[ip] ? 1000 : 1;
  160126. aSeen[ip] = 1;
  160127. if( iFinal>iLast ) iLast = iFinal;
  160128. }
  160129. }
  160130. if( rc==SQLITE_OK && nScore>nBestScore ){
  160131. iBestCol = iSnippetCol;
  160132. iBestStart = iStart;
  160133. iBestLast = iLast;
  160134. nBestScore = nScore;
  160135. }
  160136. }
  160137. }
  160138. if( rc==SQLITE_OK ){
  160139. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  160140. }
  160141. if( rc==SQLITE_OK ){
  160142. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  160143. }
  160144. if( ctx.zIn ){
  160145. if( rc==SQLITE_OK ){
  160146. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  160147. }
  160148. if( (iBestStart+nToken-1)>iBestLast ){
  160149. iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
  160150. }
  160151. if( iBestStart+nToken>nColSize ){
  160152. iBestStart = nColSize - nToken;
  160153. }
  160154. if( iBestStart<0 ) iBestStart = 0;
  160155. ctx.iRangeStart = iBestStart;
  160156. ctx.iRangeEnd = iBestStart + nToken - 1;
  160157. if( iBestStart>0 ){
  160158. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  160159. }
  160160. if( rc==SQLITE_OK ){
  160161. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  160162. }
  160163. if( ctx.iRangeEnd>=(nColSize-1) ){
  160164. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  160165. }else{
  160166. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  160167. }
  160168. if( rc==SQLITE_OK ){
  160169. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  160170. }else{
  160171. sqlite3_result_error_code(pCtx, rc);
  160172. }
  160173. sqlite3_free(ctx.zOut);
  160174. }
  160175. sqlite3_free(aSeen);
  160176. }
  160177. /************************************************************************/
  160178. /*
  160179. ** The first time the bm25() function is called for a query, an instance
  160180. ** of the following structure is allocated and populated.
  160181. */
  160182. typedef struct Fts5Bm25Data Fts5Bm25Data;
  160183. struct Fts5Bm25Data {
  160184. int nPhrase; /* Number of phrases in query */
  160185. double avgdl; /* Average number of tokens in each row */
  160186. double *aIDF; /* IDF for each phrase */
  160187. double *aFreq; /* Array used to calculate phrase freq. */
  160188. };
  160189. /*
  160190. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  160191. ** table matched by each individual phrase within the query.
  160192. */
  160193. static int fts5CountCb(
  160194. const Fts5ExtensionApi *pApi,
  160195. Fts5Context *pFts,
  160196. void *pUserData /* Pointer to sqlite3_int64 variable */
  160197. ){
  160198. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  160199. UNUSED_PARAM2(pApi, pFts);
  160200. (*pn)++;
  160201. return SQLITE_OK;
  160202. }
  160203. /*
  160204. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  160205. ** If the object has not already been allocated, allocate and populate it
  160206. ** now.
  160207. */
  160208. static int fts5Bm25GetData(
  160209. const Fts5ExtensionApi *pApi,
  160210. Fts5Context *pFts,
  160211. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  160212. ){
  160213. int rc = SQLITE_OK; /* Return code */
  160214. Fts5Bm25Data *p; /* Object to return */
  160215. p = pApi->xGetAuxdata(pFts, 0);
  160216. if( p==0 ){
  160217. int nPhrase; /* Number of phrases in query */
  160218. sqlite3_int64 nRow = 0; /* Number of rows in table */
  160219. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  160220. int nByte; /* Bytes of space to allocate */
  160221. int i;
  160222. /* Allocate the Fts5Bm25Data object */
  160223. nPhrase = pApi->xPhraseCount(pFts);
  160224. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  160225. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  160226. if( p==0 ){
  160227. rc = SQLITE_NOMEM;
  160228. }else{
  160229. memset(p, 0, nByte);
  160230. p->nPhrase = nPhrase;
  160231. p->aIDF = (double*)&p[1];
  160232. p->aFreq = &p->aIDF[nPhrase];
  160233. }
  160234. /* Calculate the average document length for this FTS5 table */
  160235. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  160236. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  160237. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  160238. /* Calculate an IDF for each phrase in the query */
  160239. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  160240. sqlite3_int64 nHit = 0;
  160241. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  160242. if( rc==SQLITE_OK ){
  160243. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  160244. ** This is done using the standard BM25 formula as found on wikipedia:
  160245. **
  160246. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  160247. **
  160248. ** where "N" is the total number of documents in the set and nHit
  160249. ** is the number that contain at least one instance of the phrase
  160250. ** under consideration.
  160251. **
  160252. ** The problem with this is that if (N < 2*nHit), the IDF is
  160253. ** negative. Which is undesirable. So the mimimum allowable IDF is
  160254. ** (1e-6) - roughly the same as a term that appears in just over
  160255. ** half of set of 5,000,000 documents. */
  160256. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  160257. if( idf<=0.0 ) idf = 1e-6;
  160258. p->aIDF[i] = idf;
  160259. }
  160260. }
  160261. if( rc!=SQLITE_OK ){
  160262. sqlite3_free(p);
  160263. }else{
  160264. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  160265. }
  160266. if( rc!=SQLITE_OK ) p = 0;
  160267. }
  160268. *ppData = p;
  160269. return rc;
  160270. }
  160271. /*
  160272. ** Implementation of bm25() function.
  160273. */
  160274. static void fts5Bm25Function(
  160275. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  160276. Fts5Context *pFts, /* First arg to pass to pApi functions */
  160277. sqlite3_context *pCtx, /* Context for returning result/error */
  160278. int nVal, /* Number of values in apVal[] array */
  160279. sqlite3_value **apVal /* Array of trailing arguments */
  160280. ){
  160281. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  160282. const double b = 0.75; /* Constant "b" from BM25 formula */
  160283. int rc = SQLITE_OK; /* Error code */
  160284. double score = 0.0; /* SQL function return value */
  160285. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  160286. int i; /* Iterator variable */
  160287. int nInst = 0; /* Value returned by xInstCount() */
  160288. double D = 0.0; /* Total number of tokens in row */
  160289. double *aFreq = 0; /* Array of phrase freq. for current row */
  160290. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  160291. ** for each phrase in the query for the current row. */
  160292. rc = fts5Bm25GetData(pApi, pFts, &pData);
  160293. if( rc==SQLITE_OK ){
  160294. aFreq = pData->aFreq;
  160295. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  160296. rc = pApi->xInstCount(pFts, &nInst);
  160297. }
  160298. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  160299. int ip; int ic; int io;
  160300. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  160301. if( rc==SQLITE_OK ){
  160302. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  160303. aFreq[ip] += w;
  160304. }
  160305. }
  160306. /* Figure out the total size of the current row in tokens. */
  160307. if( rc==SQLITE_OK ){
  160308. int nTok;
  160309. rc = pApi->xColumnSize(pFts, -1, &nTok);
  160310. D = (double)nTok;
  160311. }
  160312. /* Determine the BM25 score for the current row. */
  160313. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  160314. score += pData->aIDF[i] * (
  160315. ( aFreq[i] * (k1 + 1.0) ) /
  160316. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  160317. );
  160318. }
  160319. /* If no error has occurred, return the calculated score. Otherwise,
  160320. ** throw an SQL exception. */
  160321. if( rc==SQLITE_OK ){
  160322. sqlite3_result_double(pCtx, -1.0 * score);
  160323. }else{
  160324. sqlite3_result_error_code(pCtx, rc);
  160325. }
  160326. }
  160327. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  160328. struct Builtin {
  160329. const char *zFunc; /* Function name (nul-terminated) */
  160330. void *pUserData; /* User-data pointer */
  160331. fts5_extension_function xFunc;/* Callback function */
  160332. void (*xDestroy)(void*); /* Destructor function */
  160333. } aBuiltin [] = {
  160334. { "snippet", 0, fts5SnippetFunction, 0 },
  160335. { "highlight", 0, fts5HighlightFunction, 0 },
  160336. { "bm25", 0, fts5Bm25Function, 0 },
  160337. };
  160338. int rc = SQLITE_OK; /* Return code */
  160339. int i; /* To iterate through builtin functions */
  160340. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  160341. rc = pApi->xCreateFunction(pApi,
  160342. aBuiltin[i].zFunc,
  160343. aBuiltin[i].pUserData,
  160344. aBuiltin[i].xFunc,
  160345. aBuiltin[i].xDestroy
  160346. );
  160347. }
  160348. return rc;
  160349. }
  160350. /*
  160351. ** 2014 May 31
  160352. **
  160353. ** The author disclaims copyright to this source code. In place of
  160354. ** a legal notice, here is a blessing:
  160355. **
  160356. ** May you do good and not evil.
  160357. ** May you find forgiveness for yourself and forgive others.
  160358. ** May you share freely, never taking more than you give.
  160359. **
  160360. ******************************************************************************
  160361. */
  160362. /* #include "fts5Int.h" */
  160363. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  160364. if( (u32)pBuf->nSpace<nByte ){
  160365. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  160366. u8 *pNew;
  160367. while( nNew<nByte ){
  160368. nNew = nNew * 2;
  160369. }
  160370. pNew = sqlite3_realloc(pBuf->p, nNew);
  160371. if( pNew==0 ){
  160372. *pRc = SQLITE_NOMEM;
  160373. return 1;
  160374. }else{
  160375. pBuf->nSpace = nNew;
  160376. pBuf->p = pNew;
  160377. }
  160378. }
  160379. return 0;
  160380. }
  160381. /*
  160382. ** Encode value iVal as an SQLite varint and append it to the buffer object
  160383. ** pBuf. If an OOM error occurs, set the error code in p.
  160384. */
  160385. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  160386. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  160387. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  160388. }
  160389. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  160390. aBuf[0] = (iVal>>24) & 0x00FF;
  160391. aBuf[1] = (iVal>>16) & 0x00FF;
  160392. aBuf[2] = (iVal>> 8) & 0x00FF;
  160393. aBuf[3] = (iVal>> 0) & 0x00FF;
  160394. }
  160395. static int sqlite3Fts5Get32(const u8 *aBuf){
  160396. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  160397. }
  160398. /*
  160399. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  160400. ** the error code in p. If an error has already occurred when this function
  160401. ** is called, it is a no-op.
  160402. */
  160403. static void sqlite3Fts5BufferAppendBlob(
  160404. int *pRc,
  160405. Fts5Buffer *pBuf,
  160406. u32 nData,
  160407. const u8 *pData
  160408. ){
  160409. assert_nc( *pRc || nData>=0 );
  160410. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  160411. memcpy(&pBuf->p[pBuf->n], pData, nData);
  160412. pBuf->n += nData;
  160413. }
  160414. /*
  160415. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  160416. ** ensures that the byte following the buffer data is set to 0x00, even
  160417. ** though this byte is not included in the pBuf->n count.
  160418. */
  160419. static void sqlite3Fts5BufferAppendString(
  160420. int *pRc,
  160421. Fts5Buffer *pBuf,
  160422. const char *zStr
  160423. ){
  160424. int nStr = (int)strlen(zStr);
  160425. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  160426. pBuf->n--;
  160427. }
  160428. /*
  160429. ** Argument zFmt is a printf() style format string. This function performs
  160430. ** the printf() style processing, then appends the results to buffer pBuf.
  160431. **
  160432. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  160433. ** following the buffer data is set to 0x00, even though this byte is not
  160434. ** included in the pBuf->n count.
  160435. */
  160436. static void sqlite3Fts5BufferAppendPrintf(
  160437. int *pRc,
  160438. Fts5Buffer *pBuf,
  160439. char *zFmt, ...
  160440. ){
  160441. if( *pRc==SQLITE_OK ){
  160442. char *zTmp;
  160443. va_list ap;
  160444. va_start(ap, zFmt);
  160445. zTmp = sqlite3_vmprintf(zFmt, ap);
  160446. va_end(ap);
  160447. if( zTmp==0 ){
  160448. *pRc = SQLITE_NOMEM;
  160449. }else{
  160450. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  160451. sqlite3_free(zTmp);
  160452. }
  160453. }
  160454. }
  160455. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  160456. char *zRet = 0;
  160457. if( *pRc==SQLITE_OK ){
  160458. va_list ap;
  160459. va_start(ap, zFmt);
  160460. zRet = sqlite3_vmprintf(zFmt, ap);
  160461. va_end(ap);
  160462. if( zRet==0 ){
  160463. *pRc = SQLITE_NOMEM;
  160464. }
  160465. }
  160466. return zRet;
  160467. }
  160468. /*
  160469. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  160470. */
  160471. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  160472. sqlite3_free(pBuf->p);
  160473. memset(pBuf, 0, sizeof(Fts5Buffer));
  160474. }
  160475. /*
  160476. ** Zero the contents of the buffer object. But do not free the associated
  160477. ** memory allocation.
  160478. */
  160479. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  160480. pBuf->n = 0;
  160481. }
  160482. /*
  160483. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  160484. ** the error code in p. If an error has already occurred when this function
  160485. ** is called, it is a no-op.
  160486. */
  160487. static void sqlite3Fts5BufferSet(
  160488. int *pRc,
  160489. Fts5Buffer *pBuf,
  160490. int nData,
  160491. const u8 *pData
  160492. ){
  160493. pBuf->n = 0;
  160494. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  160495. }
  160496. static int sqlite3Fts5PoslistNext64(
  160497. const u8 *a, int n, /* Buffer containing poslist */
  160498. int *pi, /* IN/OUT: Offset within a[] */
  160499. i64 *piOff /* IN/OUT: Current offset */
  160500. ){
  160501. int i = *pi;
  160502. if( i>=n ){
  160503. /* EOF */
  160504. *piOff = -1;
  160505. return 1;
  160506. }else{
  160507. i64 iOff = *piOff;
  160508. int iVal;
  160509. fts5FastGetVarint32(a, i, iVal);
  160510. if( iVal==1 ){
  160511. fts5FastGetVarint32(a, i, iVal);
  160512. iOff = ((i64)iVal) << 32;
  160513. fts5FastGetVarint32(a, i, iVal);
  160514. }
  160515. *piOff = iOff + (iVal-2);
  160516. *pi = i;
  160517. return 0;
  160518. }
  160519. }
  160520. /*
  160521. ** Advance the iterator object passed as the only argument. Return true
  160522. ** if the iterator reaches EOF, or false otherwise.
  160523. */
  160524. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  160525. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  160526. pIter->bEof = 1;
  160527. }
  160528. return pIter->bEof;
  160529. }
  160530. static int sqlite3Fts5PoslistReaderInit(
  160531. const u8 *a, int n, /* Poslist buffer to iterate through */
  160532. Fts5PoslistReader *pIter /* Iterator object to initialize */
  160533. ){
  160534. memset(pIter, 0, sizeof(*pIter));
  160535. pIter->a = a;
  160536. pIter->n = n;
  160537. sqlite3Fts5PoslistReaderNext(pIter);
  160538. return pIter->bEof;
  160539. }
  160540. /*
  160541. ** Append position iPos to the position list being accumulated in buffer
  160542. ** pBuf, which must be already be large enough to hold the new data.
  160543. ** The previous position written to this list is *piPrev. *piPrev is set
  160544. ** to iPos before returning.
  160545. */
  160546. static void sqlite3Fts5PoslistSafeAppend(
  160547. Fts5Buffer *pBuf,
  160548. i64 *piPrev,
  160549. i64 iPos
  160550. ){
  160551. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  160552. if( (iPos & colmask) != (*piPrev & colmask) ){
  160553. pBuf->p[pBuf->n++] = 1;
  160554. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  160555. *piPrev = (iPos & colmask);
  160556. }
  160557. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  160558. *piPrev = iPos;
  160559. }
  160560. static int sqlite3Fts5PoslistWriterAppend(
  160561. Fts5Buffer *pBuf,
  160562. Fts5PoslistWriter *pWriter,
  160563. i64 iPos
  160564. ){
  160565. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  160566. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  160567. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  160568. return SQLITE_OK;
  160569. }
  160570. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  160571. void *pRet = 0;
  160572. if( *pRc==SQLITE_OK ){
  160573. pRet = sqlite3_malloc(nByte);
  160574. if( pRet==0 && nByte>0 ){
  160575. *pRc = SQLITE_NOMEM;
  160576. }else{
  160577. memset(pRet, 0, nByte);
  160578. }
  160579. }
  160580. return pRet;
  160581. }
  160582. /*
  160583. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  160584. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  160585. ** the length of the string is determined using strlen().
  160586. **
  160587. ** It is the responsibility of the caller to eventually free the returned
  160588. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  160589. */
  160590. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  160591. char *zRet = 0;
  160592. if( *pRc==SQLITE_OK ){
  160593. if( nIn<0 ){
  160594. nIn = (int)strlen(pIn);
  160595. }
  160596. zRet = (char*)sqlite3_malloc(nIn+1);
  160597. if( zRet ){
  160598. memcpy(zRet, pIn, nIn);
  160599. zRet[nIn] = '\0';
  160600. }else{
  160601. *pRc = SQLITE_NOMEM;
  160602. }
  160603. }
  160604. return zRet;
  160605. }
  160606. /*
  160607. ** Return true if character 't' may be part of an FTS5 bareword, or false
  160608. ** otherwise. Characters that may be part of barewords:
  160609. **
  160610. ** * All non-ASCII characters,
  160611. ** * The 52 upper and lower case ASCII characters, and
  160612. ** * The 10 integer ASCII characters.
  160613. ** * The underscore character "_" (0x5F).
  160614. ** * The unicode "subsitute" character (0x1A).
  160615. */
  160616. static int sqlite3Fts5IsBareword(char t){
  160617. u8 aBareword[128] = {
  160618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  160619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  160620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  160621. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  160622. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  160623. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  160624. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  160625. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  160626. };
  160627. return (t & 0x80) || aBareword[(int)t];
  160628. }
  160629. /*************************************************************************
  160630. */
  160631. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  160632. struct Fts5TermsetEntry {
  160633. char *pTerm;
  160634. int nTerm;
  160635. int iIdx; /* Index (main or aPrefix[] entry) */
  160636. Fts5TermsetEntry *pNext;
  160637. };
  160638. struct Fts5Termset {
  160639. Fts5TermsetEntry *apHash[512];
  160640. };
  160641. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  160642. int rc = SQLITE_OK;
  160643. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  160644. return rc;
  160645. }
  160646. static int sqlite3Fts5TermsetAdd(
  160647. Fts5Termset *p,
  160648. int iIdx,
  160649. const char *pTerm, int nTerm,
  160650. int *pbPresent
  160651. ){
  160652. int rc = SQLITE_OK;
  160653. *pbPresent = 0;
  160654. if( p ){
  160655. int i;
  160656. u32 hash = 13;
  160657. Fts5TermsetEntry *pEntry;
  160658. /* Calculate a hash value for this term. This is the same hash checksum
  160659. ** used by the fts5_hash.c module. This is not important for correct
  160660. ** operation of the module, but is necessary to ensure that some tests
  160661. ** designed to produce hash table collisions really do work. */
  160662. for(i=nTerm-1; i>=0; i--){
  160663. hash = (hash << 3) ^ hash ^ pTerm[i];
  160664. }
  160665. hash = (hash << 3) ^ hash ^ iIdx;
  160666. hash = hash % ArraySize(p->apHash);
  160667. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  160668. if( pEntry->iIdx==iIdx
  160669. && pEntry->nTerm==nTerm
  160670. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  160671. ){
  160672. *pbPresent = 1;
  160673. break;
  160674. }
  160675. }
  160676. if( pEntry==0 ){
  160677. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  160678. if( pEntry ){
  160679. pEntry->pTerm = (char*)&pEntry[1];
  160680. pEntry->nTerm = nTerm;
  160681. pEntry->iIdx = iIdx;
  160682. memcpy(pEntry->pTerm, pTerm, nTerm);
  160683. pEntry->pNext = p->apHash[hash];
  160684. p->apHash[hash] = pEntry;
  160685. }
  160686. }
  160687. }
  160688. return rc;
  160689. }
  160690. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  160691. if( p ){
  160692. u32 i;
  160693. for(i=0; i<ArraySize(p->apHash); i++){
  160694. Fts5TermsetEntry *pEntry = p->apHash[i];
  160695. while( pEntry ){
  160696. Fts5TermsetEntry *pDel = pEntry;
  160697. pEntry = pEntry->pNext;
  160698. sqlite3_free(pDel);
  160699. }
  160700. }
  160701. sqlite3_free(p);
  160702. }
  160703. }
  160704. /*
  160705. ** 2014 Jun 09
  160706. **
  160707. ** The author disclaims copyright to this source code. In place of
  160708. ** a legal notice, here is a blessing:
  160709. **
  160710. ** May you do good and not evil.
  160711. ** May you find forgiveness for yourself and forgive others.
  160712. ** May you share freely, never taking more than you give.
  160713. **
  160714. ******************************************************************************
  160715. **
  160716. ** This is an SQLite module implementing full-text search.
  160717. */
  160718. /* #include "fts5Int.h" */
  160719. #define FTS5_DEFAULT_PAGE_SIZE 4050
  160720. #define FTS5_DEFAULT_AUTOMERGE 4
  160721. #define FTS5_DEFAULT_USERMERGE 4
  160722. #define FTS5_DEFAULT_CRISISMERGE 16
  160723. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  160724. /* Maximum allowed page size */
  160725. #define FTS5_MAX_PAGE_SIZE (128*1024)
  160726. static int fts5_iswhitespace(char x){
  160727. return (x==' ');
  160728. }
  160729. static int fts5_isopenquote(char x){
  160730. return (x=='"' || x=='\'' || x=='[' || x=='`');
  160731. }
  160732. /*
  160733. ** Argument pIn points to a character that is part of a nul-terminated
  160734. ** string. Return a pointer to the first character following *pIn in
  160735. ** the string that is not a white-space character.
  160736. */
  160737. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  160738. const char *p = pIn;
  160739. if( p ){
  160740. while( fts5_iswhitespace(*p) ){ p++; }
  160741. }
  160742. return p;
  160743. }
  160744. /*
  160745. ** Argument pIn points to a character that is part of a nul-terminated
  160746. ** string. Return a pointer to the first character following *pIn in
  160747. ** the string that is not a "bareword" character.
  160748. */
  160749. static const char *fts5ConfigSkipBareword(const char *pIn){
  160750. const char *p = pIn;
  160751. while ( sqlite3Fts5IsBareword(*p) ) p++;
  160752. if( p==pIn ) p = 0;
  160753. return p;
  160754. }
  160755. static int fts5_isdigit(char a){
  160756. return (a>='0' && a<='9');
  160757. }
  160758. static const char *fts5ConfigSkipLiteral(const char *pIn){
  160759. const char *p = pIn;
  160760. switch( *p ){
  160761. case 'n': case 'N':
  160762. if( sqlite3_strnicmp("null", p, 4)==0 ){
  160763. p = &p[4];
  160764. }else{
  160765. p = 0;
  160766. }
  160767. break;
  160768. case 'x': case 'X':
  160769. p++;
  160770. if( *p=='\'' ){
  160771. p++;
  160772. while( (*p>='a' && *p<='f')
  160773. || (*p>='A' && *p<='F')
  160774. || (*p>='0' && *p<='9')
  160775. ){
  160776. p++;
  160777. }
  160778. if( *p=='\'' && 0==((p-pIn)%2) ){
  160779. p++;
  160780. }else{
  160781. p = 0;
  160782. }
  160783. }else{
  160784. p = 0;
  160785. }
  160786. break;
  160787. case '\'':
  160788. p++;
  160789. while( p ){
  160790. if( *p=='\'' ){
  160791. p++;
  160792. if( *p!='\'' ) break;
  160793. }
  160794. p++;
  160795. if( *p==0 ) p = 0;
  160796. }
  160797. break;
  160798. default:
  160799. /* maybe a number */
  160800. if( *p=='+' || *p=='-' ) p++;
  160801. while( fts5_isdigit(*p) ) p++;
  160802. /* At this point, if the literal was an integer, the parse is
  160803. ** finished. Or, if it is a floating point value, it may continue
  160804. ** with either a decimal point or an 'E' character. */
  160805. if( *p=='.' && fts5_isdigit(p[1]) ){
  160806. p += 2;
  160807. while( fts5_isdigit(*p) ) p++;
  160808. }
  160809. if( p==pIn ) p = 0;
  160810. break;
  160811. }
  160812. return p;
  160813. }
  160814. /*
  160815. ** The first character of the string pointed to by argument z is guaranteed
  160816. ** to be an open-quote character (see function fts5_isopenquote()).
  160817. **
  160818. ** This function searches for the corresponding close-quote character within
  160819. ** the string and, if found, dequotes the string in place and adds a new
  160820. ** nul-terminator byte.
  160821. **
  160822. ** If the close-quote is found, the value returned is the byte offset of
  160823. ** the character immediately following it. Or, if the close-quote is not
  160824. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  160825. ** undefined state.
  160826. */
  160827. static int fts5Dequote(char *z){
  160828. char q;
  160829. int iIn = 1;
  160830. int iOut = 0;
  160831. q = z[0];
  160832. /* Set stack variable q to the close-quote character */
  160833. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  160834. if( q=='[' ) q = ']';
  160835. while( ALWAYS(z[iIn]) ){
  160836. if( z[iIn]==q ){
  160837. if( z[iIn+1]!=q ){
  160838. /* Character iIn was the close quote. */
  160839. iIn++;
  160840. break;
  160841. }else{
  160842. /* Character iIn and iIn+1 form an escaped quote character. Skip
  160843. ** the input cursor past both and copy a single quote character
  160844. ** to the output buffer. */
  160845. iIn += 2;
  160846. z[iOut++] = q;
  160847. }
  160848. }else{
  160849. z[iOut++] = z[iIn++];
  160850. }
  160851. }
  160852. z[iOut] = '\0';
  160853. return iIn;
  160854. }
  160855. /*
  160856. ** Convert an SQL-style quoted string into a normal string by removing
  160857. ** the quote characters. The conversion is done in-place. If the
  160858. ** input does not begin with a quote character, then this routine
  160859. ** is a no-op.
  160860. **
  160861. ** Examples:
  160862. **
  160863. ** "abc" becomes abc
  160864. ** 'xyz' becomes xyz
  160865. ** [pqr] becomes pqr
  160866. ** `mno` becomes mno
  160867. */
  160868. static void sqlite3Fts5Dequote(char *z){
  160869. char quote; /* Quote character (if any ) */
  160870. assert( 0==fts5_iswhitespace(z[0]) );
  160871. quote = z[0];
  160872. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  160873. fts5Dequote(z);
  160874. }
  160875. }
  160876. struct Fts5Enum {
  160877. const char *zName;
  160878. int eVal;
  160879. };
  160880. typedef struct Fts5Enum Fts5Enum;
  160881. static int fts5ConfigSetEnum(
  160882. const Fts5Enum *aEnum,
  160883. const char *zEnum,
  160884. int *peVal
  160885. ){
  160886. int nEnum = (int)strlen(zEnum);
  160887. int i;
  160888. int iVal = -1;
  160889. for(i=0; aEnum[i].zName; i++){
  160890. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  160891. if( iVal>=0 ) return SQLITE_ERROR;
  160892. iVal = aEnum[i].eVal;
  160893. }
  160894. }
  160895. *peVal = iVal;
  160896. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  160897. }
  160898. /*
  160899. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  160900. ** configuration object pConfig as appropriate.
  160901. **
  160902. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  160903. ** an error occurs, an SQLite error code is returned and an error message
  160904. ** may be left in *pzErr. It is the responsibility of the caller to
  160905. ** eventually free any such error message using sqlite3_free().
  160906. */
  160907. static int fts5ConfigParseSpecial(
  160908. Fts5Global *pGlobal,
  160909. Fts5Config *pConfig, /* Configuration object to update */
  160910. const char *zCmd, /* Special command to parse */
  160911. const char *zArg, /* Argument to parse */
  160912. char **pzErr /* OUT: Error message */
  160913. ){
  160914. int rc = SQLITE_OK;
  160915. int nCmd = (int)strlen(zCmd);
  160916. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  160917. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  160918. const char *p;
  160919. int bFirst = 1;
  160920. if( pConfig->aPrefix==0 ){
  160921. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  160922. if( rc ) return rc;
  160923. }
  160924. p = zArg;
  160925. while( 1 ){
  160926. int nPre = 0;
  160927. while( p[0]==' ' ) p++;
  160928. if( bFirst==0 && p[0]==',' ){
  160929. p++;
  160930. while( p[0]==' ' ) p++;
  160931. }else if( p[0]=='\0' ){
  160932. break;
  160933. }
  160934. if( p[0]<'0' || p[0]>'9' ){
  160935. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  160936. rc = SQLITE_ERROR;
  160937. break;
  160938. }
  160939. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  160940. *pzErr = sqlite3_mprintf(
  160941. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  160942. );
  160943. rc = SQLITE_ERROR;
  160944. break;
  160945. }
  160946. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  160947. nPre = nPre*10 + (p[0] - '0');
  160948. p++;
  160949. }
  160950. if( nPre<=0 || nPre>=1000 ){
  160951. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  160952. rc = SQLITE_ERROR;
  160953. break;
  160954. }
  160955. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  160956. pConfig->nPrefix++;
  160957. bFirst = 0;
  160958. }
  160959. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  160960. return rc;
  160961. }
  160962. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  160963. const char *p = (const char*)zArg;
  160964. int nArg = (int)strlen(zArg) + 1;
  160965. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  160966. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  160967. char *pSpace = pDel;
  160968. if( azArg && pSpace ){
  160969. if( pConfig->pTok ){
  160970. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  160971. rc = SQLITE_ERROR;
  160972. }else{
  160973. for(nArg=0; p && *p; nArg++){
  160974. const char *p2 = fts5ConfigSkipWhitespace(p);
  160975. if( *p2=='\'' ){
  160976. p = fts5ConfigSkipLiteral(p2);
  160977. }else{
  160978. p = fts5ConfigSkipBareword(p2);
  160979. }
  160980. if( p ){
  160981. memcpy(pSpace, p2, p-p2);
  160982. azArg[nArg] = pSpace;
  160983. sqlite3Fts5Dequote(pSpace);
  160984. pSpace += (p - p2) + 1;
  160985. p = fts5ConfigSkipWhitespace(p);
  160986. }
  160987. }
  160988. if( p==0 ){
  160989. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  160990. rc = SQLITE_ERROR;
  160991. }else{
  160992. rc = sqlite3Fts5GetTokenizer(pGlobal,
  160993. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  160994. pzErr
  160995. );
  160996. }
  160997. }
  160998. }
  160999. sqlite3_free(azArg);
  161000. sqlite3_free(pDel);
  161001. return rc;
  161002. }
  161003. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  161004. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  161005. *pzErr = sqlite3_mprintf("multiple content=... directives");
  161006. rc = SQLITE_ERROR;
  161007. }else{
  161008. if( zArg[0] ){
  161009. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  161010. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  161011. }else{
  161012. pConfig->eContent = FTS5_CONTENT_NONE;
  161013. }
  161014. }
  161015. return rc;
  161016. }
  161017. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  161018. if( pConfig->zContentRowid ){
  161019. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  161020. rc = SQLITE_ERROR;
  161021. }else{
  161022. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  161023. }
  161024. return rc;
  161025. }
  161026. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  161027. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  161028. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  161029. rc = SQLITE_ERROR;
  161030. }else{
  161031. pConfig->bColumnsize = (zArg[0]=='1');
  161032. }
  161033. return rc;
  161034. }
  161035. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  161036. const Fts5Enum aDetail[] = {
  161037. { "none", FTS5_DETAIL_NONE },
  161038. { "full", FTS5_DETAIL_FULL },
  161039. { "columns", FTS5_DETAIL_COLUMNS },
  161040. { 0, 0 }
  161041. };
  161042. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  161043. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  161044. }
  161045. return rc;
  161046. }
  161047. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  161048. return SQLITE_ERROR;
  161049. }
  161050. /*
  161051. ** Allocate an instance of the default tokenizer ("simple") at
  161052. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  161053. ** code if an error occurs.
  161054. */
  161055. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  161056. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  161057. return sqlite3Fts5GetTokenizer(
  161058. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  161059. );
  161060. }
  161061. /*
  161062. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  161063. ** Return a pointer to the character immediately following the last in
  161064. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  161065. ** to find close-quote character).
  161066. **
  161067. ** Before returning, set pzOut to point to a new buffer containing a
  161068. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  161069. ** quoted, *pbQuoted is also set to 1 before returning.
  161070. **
  161071. ** If *pRc is other than SQLITE_OK when this function is called, it is
  161072. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  161073. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  161074. ** set if a parse error (failed to find close quote) occurs.
  161075. */
  161076. static const char *fts5ConfigGobbleWord(
  161077. int *pRc, /* IN/OUT: Error code */
  161078. const char *zIn, /* Buffer to gobble string/bareword from */
  161079. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  161080. int *pbQuoted /* OUT: Set to true if dequoting required */
  161081. ){
  161082. const char *zRet = 0;
  161083. int nIn = (int)strlen(zIn);
  161084. char *zOut = sqlite3_malloc(nIn+1);
  161085. assert( *pRc==SQLITE_OK );
  161086. *pbQuoted = 0;
  161087. *pzOut = 0;
  161088. if( zOut==0 ){
  161089. *pRc = SQLITE_NOMEM;
  161090. }else{
  161091. memcpy(zOut, zIn, nIn+1);
  161092. if( fts5_isopenquote(zOut[0]) ){
  161093. int ii = fts5Dequote(zOut);
  161094. zRet = &zIn[ii];
  161095. *pbQuoted = 1;
  161096. }else{
  161097. zRet = fts5ConfigSkipBareword(zIn);
  161098. if( zRet ){
  161099. zOut[zRet-zIn] = '\0';
  161100. }
  161101. }
  161102. }
  161103. if( zRet==0 ){
  161104. sqlite3_free(zOut);
  161105. }else{
  161106. *pzOut = zOut;
  161107. }
  161108. return zRet;
  161109. }
  161110. static int fts5ConfigParseColumn(
  161111. Fts5Config *p,
  161112. char *zCol,
  161113. char *zArg,
  161114. char **pzErr
  161115. ){
  161116. int rc = SQLITE_OK;
  161117. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  161118. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  161119. ){
  161120. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  161121. rc = SQLITE_ERROR;
  161122. }else if( zArg ){
  161123. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  161124. p->abUnindexed[p->nCol] = 1;
  161125. }else{
  161126. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  161127. rc = SQLITE_ERROR;
  161128. }
  161129. }
  161130. p->azCol[p->nCol++] = zCol;
  161131. return rc;
  161132. }
  161133. /*
  161134. ** Populate the Fts5Config.zContentExprlist string.
  161135. */
  161136. static int fts5ConfigMakeExprlist(Fts5Config *p){
  161137. int i;
  161138. int rc = SQLITE_OK;
  161139. Fts5Buffer buf = {0, 0, 0};
  161140. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  161141. if( p->eContent!=FTS5_CONTENT_NONE ){
  161142. for(i=0; i<p->nCol; i++){
  161143. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  161144. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  161145. }else{
  161146. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  161147. }
  161148. }
  161149. }
  161150. assert( p->zContentExprlist==0 );
  161151. p->zContentExprlist = (char*)buf.p;
  161152. return rc;
  161153. }
  161154. /*
  161155. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  161156. ** or xConnect method of the virtual table. This function attempts to
  161157. ** allocate an instance of Fts5Config containing the results of parsing
  161158. ** those arguments.
  161159. **
  161160. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  161161. ** new Fts5Config object. If an error occurs, an SQLite error code is
  161162. ** returned, *ppOut is set to NULL and an error message may be left in
  161163. ** *pzErr. It is the responsibility of the caller to eventually free any
  161164. ** such error message using sqlite3_free().
  161165. */
  161166. static int sqlite3Fts5ConfigParse(
  161167. Fts5Global *pGlobal,
  161168. sqlite3 *db,
  161169. int nArg, /* Number of arguments */
  161170. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  161171. Fts5Config **ppOut, /* OUT: Results of parse */
  161172. char **pzErr /* OUT: Error message */
  161173. ){
  161174. int rc = SQLITE_OK; /* Return code */
  161175. Fts5Config *pRet; /* New object to return */
  161176. int i;
  161177. int nByte;
  161178. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  161179. if( pRet==0 ) return SQLITE_NOMEM;
  161180. memset(pRet, 0, sizeof(Fts5Config));
  161181. pRet->db = db;
  161182. pRet->iCookie = -1;
  161183. nByte = nArg * (sizeof(char*) + sizeof(u8));
  161184. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  161185. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  161186. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  161187. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  161188. pRet->bColumnsize = 1;
  161189. pRet->eDetail = FTS5_DETAIL_FULL;
  161190. #ifdef SQLITE_DEBUG
  161191. pRet->bPrefixIndex = 1;
  161192. #endif
  161193. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  161194. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  161195. rc = SQLITE_ERROR;
  161196. }
  161197. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  161198. const char *zOrig = azArg[i];
  161199. const char *z;
  161200. char *zOne = 0;
  161201. char *zTwo = 0;
  161202. int bOption = 0;
  161203. int bMustBeCol = 0;
  161204. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  161205. z = fts5ConfigSkipWhitespace(z);
  161206. if( z && *z=='=' ){
  161207. bOption = 1;
  161208. z++;
  161209. if( bMustBeCol ) z = 0;
  161210. }
  161211. z = fts5ConfigSkipWhitespace(z);
  161212. if( z && z[0] ){
  161213. int bDummy;
  161214. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  161215. if( z && z[0] ) z = 0;
  161216. }
  161217. if( rc==SQLITE_OK ){
  161218. if( z==0 ){
  161219. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  161220. rc = SQLITE_ERROR;
  161221. }else{
  161222. if( bOption ){
  161223. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  161224. }else{
  161225. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  161226. zOne = 0;
  161227. }
  161228. }
  161229. }
  161230. sqlite3_free(zOne);
  161231. sqlite3_free(zTwo);
  161232. }
  161233. /* If a tokenizer= option was successfully parsed, the tokenizer has
  161234. ** already been allocated. Otherwise, allocate an instance of the default
  161235. ** tokenizer (unicode61) now. */
  161236. if( rc==SQLITE_OK && pRet->pTok==0 ){
  161237. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  161238. }
  161239. /* If no zContent option was specified, fill in the default values. */
  161240. if( rc==SQLITE_OK && pRet->zContent==0 ){
  161241. const char *zTail = 0;
  161242. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  161243. || pRet->eContent==FTS5_CONTENT_NONE
  161244. );
  161245. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  161246. zTail = "content";
  161247. }else if( pRet->bColumnsize ){
  161248. zTail = "docsize";
  161249. }
  161250. if( zTail ){
  161251. pRet->zContent = sqlite3Fts5Mprintf(
  161252. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  161253. );
  161254. }
  161255. }
  161256. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  161257. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  161258. }
  161259. /* Formulate the zContentExprlist text */
  161260. if( rc==SQLITE_OK ){
  161261. rc = fts5ConfigMakeExprlist(pRet);
  161262. }
  161263. if( rc!=SQLITE_OK ){
  161264. sqlite3Fts5ConfigFree(pRet);
  161265. *ppOut = 0;
  161266. }
  161267. return rc;
  161268. }
  161269. /*
  161270. ** Free the configuration object passed as the only argument.
  161271. */
  161272. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  161273. if( pConfig ){
  161274. int i;
  161275. if( pConfig->pTok ){
  161276. pConfig->pTokApi->xDelete(pConfig->pTok);
  161277. }
  161278. sqlite3_free(pConfig->zDb);
  161279. sqlite3_free(pConfig->zName);
  161280. for(i=0; i<pConfig->nCol; i++){
  161281. sqlite3_free(pConfig->azCol[i]);
  161282. }
  161283. sqlite3_free(pConfig->azCol);
  161284. sqlite3_free(pConfig->aPrefix);
  161285. sqlite3_free(pConfig->zRank);
  161286. sqlite3_free(pConfig->zRankArgs);
  161287. sqlite3_free(pConfig->zContent);
  161288. sqlite3_free(pConfig->zContentRowid);
  161289. sqlite3_free(pConfig->zContentExprlist);
  161290. sqlite3_free(pConfig);
  161291. }
  161292. }
  161293. /*
  161294. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  161295. ** object passed as the only argument. Return SQLITE_OK if successful, or
  161296. ** an SQLite error code if an error occurs.
  161297. */
  161298. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  161299. int i;
  161300. int rc = SQLITE_OK;
  161301. char *zSql;
  161302. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  161303. for(i=0; zSql && i<pConfig->nCol; i++){
  161304. const char *zSep = (i==0?"":", ");
  161305. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  161306. }
  161307. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  161308. zSql, pConfig->zName, FTS5_RANK_NAME
  161309. );
  161310. assert( zSql || rc==SQLITE_NOMEM );
  161311. if( zSql ){
  161312. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  161313. sqlite3_free(zSql);
  161314. }
  161315. return rc;
  161316. }
  161317. /*
  161318. ** Tokenize the text passed via the second and third arguments.
  161319. **
  161320. ** The callback is invoked once for each token in the input text. The
  161321. ** arguments passed to it are, in order:
  161322. **
  161323. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  161324. ** const char *pToken // Pointer to buffer containing token
  161325. ** int nToken // Size of token in bytes
  161326. ** int iStart // Byte offset of start of token within input text
  161327. ** int iEnd // Byte offset of end of token within input text
  161328. ** int iPos // Position of token in input (first token is 0)
  161329. **
  161330. ** If the callback returns a non-zero value the tokenization is abandoned
  161331. ** and no further callbacks are issued.
  161332. **
  161333. ** This function returns SQLITE_OK if successful or an SQLite error code
  161334. ** if an error occurs. If the tokenization was abandoned early because
  161335. ** the callback returned SQLITE_DONE, this is not an error and this function
  161336. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  161337. ** because the callback returned another non-zero value, it is assumed
  161338. ** to be an SQLite error code and returned to the caller.
  161339. */
  161340. static int sqlite3Fts5Tokenize(
  161341. Fts5Config *pConfig, /* FTS5 Configuration object */
  161342. int flags, /* FTS5_TOKENIZE_* flags */
  161343. const char *pText, int nText, /* Text to tokenize */
  161344. void *pCtx, /* Context passed to xToken() */
  161345. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  161346. ){
  161347. if( pText==0 ) return SQLITE_OK;
  161348. return pConfig->pTokApi->xTokenize(
  161349. pConfig->pTok, pCtx, flags, pText, nText, xToken
  161350. );
  161351. }
  161352. /*
  161353. ** Argument pIn points to the first character in what is expected to be
  161354. ** a comma-separated list of SQL literals followed by a ')' character.
  161355. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  161356. ** NULL to indicate a parse error.
  161357. */
  161358. static const char *fts5ConfigSkipArgs(const char *pIn){
  161359. const char *p = pIn;
  161360. while( 1 ){
  161361. p = fts5ConfigSkipWhitespace(p);
  161362. p = fts5ConfigSkipLiteral(p);
  161363. p = fts5ConfigSkipWhitespace(p);
  161364. if( p==0 || *p==')' ) break;
  161365. if( *p!=',' ){
  161366. p = 0;
  161367. break;
  161368. }
  161369. p++;
  161370. }
  161371. return p;
  161372. }
  161373. /*
  161374. ** Parameter zIn contains a rank() function specification. The format of
  161375. ** this is:
  161376. **
  161377. ** + Bareword (function name)
  161378. ** + Open parenthesis - "("
  161379. ** + Zero or more SQL literals in a comma separated list
  161380. ** + Close parenthesis - ")"
  161381. */
  161382. static int sqlite3Fts5ConfigParseRank(
  161383. const char *zIn, /* Input string */
  161384. char **pzRank, /* OUT: Rank function name */
  161385. char **pzRankArgs /* OUT: Rank function arguments */
  161386. ){
  161387. const char *p = zIn;
  161388. const char *pRank;
  161389. char *zRank = 0;
  161390. char *zRankArgs = 0;
  161391. int rc = SQLITE_OK;
  161392. *pzRank = 0;
  161393. *pzRankArgs = 0;
  161394. if( p==0 ){
  161395. rc = SQLITE_ERROR;
  161396. }else{
  161397. p = fts5ConfigSkipWhitespace(p);
  161398. pRank = p;
  161399. p = fts5ConfigSkipBareword(p);
  161400. if( p ){
  161401. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  161402. if( zRank ) memcpy(zRank, pRank, p-pRank);
  161403. }else{
  161404. rc = SQLITE_ERROR;
  161405. }
  161406. if( rc==SQLITE_OK ){
  161407. p = fts5ConfigSkipWhitespace(p);
  161408. if( *p!='(' ) rc = SQLITE_ERROR;
  161409. p++;
  161410. }
  161411. if( rc==SQLITE_OK ){
  161412. const char *pArgs;
  161413. p = fts5ConfigSkipWhitespace(p);
  161414. pArgs = p;
  161415. if( *p!=')' ){
  161416. p = fts5ConfigSkipArgs(p);
  161417. if( p==0 ){
  161418. rc = SQLITE_ERROR;
  161419. }else{
  161420. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  161421. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  161422. }
  161423. }
  161424. }
  161425. }
  161426. if( rc!=SQLITE_OK ){
  161427. sqlite3_free(zRank);
  161428. assert( zRankArgs==0 );
  161429. }else{
  161430. *pzRank = zRank;
  161431. *pzRankArgs = zRankArgs;
  161432. }
  161433. return rc;
  161434. }
  161435. static int sqlite3Fts5ConfigSetValue(
  161436. Fts5Config *pConfig,
  161437. const char *zKey,
  161438. sqlite3_value *pVal,
  161439. int *pbBadkey
  161440. ){
  161441. int rc = SQLITE_OK;
  161442. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  161443. int pgsz = 0;
  161444. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  161445. pgsz = sqlite3_value_int(pVal);
  161446. }
  161447. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  161448. *pbBadkey = 1;
  161449. }else{
  161450. pConfig->pgsz = pgsz;
  161451. }
  161452. }
  161453. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  161454. int nHashSize = -1;
  161455. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  161456. nHashSize = sqlite3_value_int(pVal);
  161457. }
  161458. if( nHashSize<=0 ){
  161459. *pbBadkey = 1;
  161460. }else{
  161461. pConfig->nHashSize = nHashSize;
  161462. }
  161463. }
  161464. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  161465. int nAutomerge = -1;
  161466. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  161467. nAutomerge = sqlite3_value_int(pVal);
  161468. }
  161469. if( nAutomerge<0 || nAutomerge>64 ){
  161470. *pbBadkey = 1;
  161471. }else{
  161472. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  161473. pConfig->nAutomerge = nAutomerge;
  161474. }
  161475. }
  161476. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  161477. int nUsermerge = -1;
  161478. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  161479. nUsermerge = sqlite3_value_int(pVal);
  161480. }
  161481. if( nUsermerge<2 || nUsermerge>16 ){
  161482. *pbBadkey = 1;
  161483. }else{
  161484. pConfig->nUsermerge = nUsermerge;
  161485. }
  161486. }
  161487. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  161488. int nCrisisMerge = -1;
  161489. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  161490. nCrisisMerge = sqlite3_value_int(pVal);
  161491. }
  161492. if( nCrisisMerge<0 ){
  161493. *pbBadkey = 1;
  161494. }else{
  161495. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  161496. pConfig->nCrisisMerge = nCrisisMerge;
  161497. }
  161498. }
  161499. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  161500. const char *zIn = (const char*)sqlite3_value_text(pVal);
  161501. char *zRank;
  161502. char *zRankArgs;
  161503. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  161504. if( rc==SQLITE_OK ){
  161505. sqlite3_free(pConfig->zRank);
  161506. sqlite3_free(pConfig->zRankArgs);
  161507. pConfig->zRank = zRank;
  161508. pConfig->zRankArgs = zRankArgs;
  161509. }else if( rc==SQLITE_ERROR ){
  161510. rc = SQLITE_OK;
  161511. *pbBadkey = 1;
  161512. }
  161513. }else{
  161514. *pbBadkey = 1;
  161515. }
  161516. return rc;
  161517. }
  161518. /*
  161519. ** Load the contents of the %_config table into memory.
  161520. */
  161521. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  161522. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  161523. char *zSql;
  161524. sqlite3_stmt *p = 0;
  161525. int rc = SQLITE_OK;
  161526. int iVersion = 0;
  161527. /* Set default values */
  161528. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  161529. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  161530. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  161531. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  161532. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  161533. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  161534. if( zSql ){
  161535. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  161536. sqlite3_free(zSql);
  161537. }
  161538. assert( rc==SQLITE_OK || p==0 );
  161539. if( rc==SQLITE_OK ){
  161540. while( SQLITE_ROW==sqlite3_step(p) ){
  161541. const char *zK = (const char*)sqlite3_column_text(p, 0);
  161542. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  161543. if( 0==sqlite3_stricmp(zK, "version") ){
  161544. iVersion = sqlite3_value_int(pVal);
  161545. }else{
  161546. int bDummy = 0;
  161547. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  161548. }
  161549. }
  161550. rc = sqlite3_finalize(p);
  161551. }
  161552. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  161553. rc = SQLITE_ERROR;
  161554. if( pConfig->pzErrmsg ){
  161555. assert( 0==*pConfig->pzErrmsg );
  161556. *pConfig->pzErrmsg = sqlite3_mprintf(
  161557. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  161558. iVersion, FTS5_CURRENT_VERSION
  161559. );
  161560. }
  161561. }
  161562. if( rc==SQLITE_OK ){
  161563. pConfig->iCookie = iCookie;
  161564. }
  161565. return rc;
  161566. }
  161567. /*
  161568. ** 2014 May 31
  161569. **
  161570. ** The author disclaims copyright to this source code. In place of
  161571. ** a legal notice, here is a blessing:
  161572. **
  161573. ** May you do good and not evil.
  161574. ** May you find forgiveness for yourself and forgive others.
  161575. ** May you share freely, never taking more than you give.
  161576. **
  161577. ******************************************************************************
  161578. **
  161579. */
  161580. /* #include "fts5Int.h" */
  161581. /* #include "fts5parse.h" */
  161582. /*
  161583. ** All token types in the generated fts5parse.h file are greater than 0.
  161584. */
  161585. #define FTS5_EOF 0
  161586. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  161587. typedef struct Fts5ExprTerm Fts5ExprTerm;
  161588. /*
  161589. ** Functions generated by lemon from fts5parse.y.
  161590. */
  161591. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  161592. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  161593. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  161594. #ifndef NDEBUG
  161595. /* #include <stdio.h> */
  161596. static void sqlite3Fts5ParserTrace(FILE*, char*);
  161597. #endif
  161598. struct Fts5Expr {
  161599. Fts5Index *pIndex;
  161600. Fts5Config *pConfig;
  161601. Fts5ExprNode *pRoot;
  161602. int bDesc; /* Iterate in descending rowid order */
  161603. int nPhrase; /* Number of phrases in expression */
  161604. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  161605. };
  161606. /*
  161607. ** eType:
  161608. ** Expression node type. Always one of:
  161609. **
  161610. ** FTS5_AND (nChild, apChild valid)
  161611. ** FTS5_OR (nChild, apChild valid)
  161612. ** FTS5_NOT (nChild, apChild valid)
  161613. ** FTS5_STRING (pNear valid)
  161614. ** FTS5_TERM (pNear valid)
  161615. */
  161616. struct Fts5ExprNode {
  161617. int eType; /* Node type */
  161618. int bEof; /* True at EOF */
  161619. int bNomatch; /* True if entry is not a match */
  161620. /* Next method for this node. */
  161621. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  161622. i64 iRowid; /* Current rowid */
  161623. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  161624. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  161625. ** AND or OR nodes, it contains 2 or more entries. */
  161626. int nChild; /* Number of child nodes */
  161627. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  161628. };
  161629. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  161630. /*
  161631. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  161632. ** used as if it has the same signature as the xNext() methods themselves.
  161633. */
  161634. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  161635. /*
  161636. ** An instance of the following structure represents a single search term
  161637. ** or term prefix.
  161638. */
  161639. struct Fts5ExprTerm {
  161640. int bPrefix; /* True for a prefix term */
  161641. char *zTerm; /* nul-terminated term */
  161642. Fts5IndexIter *pIter; /* Iterator for this term */
  161643. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  161644. };
  161645. /*
  161646. ** A phrase. One or more terms that must appear in a contiguous sequence
  161647. ** within a document for it to match.
  161648. */
  161649. struct Fts5ExprPhrase {
  161650. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  161651. Fts5Buffer poslist; /* Current position list */
  161652. int nTerm; /* Number of entries in aTerm[] */
  161653. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  161654. };
  161655. /*
  161656. ** One or more phrases that must appear within a certain token distance of
  161657. ** each other within each matching document.
  161658. */
  161659. struct Fts5ExprNearset {
  161660. int nNear; /* NEAR parameter */
  161661. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  161662. int nPhrase; /* Number of entries in aPhrase[] array */
  161663. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  161664. };
  161665. /*
  161666. ** Parse context.
  161667. */
  161668. struct Fts5Parse {
  161669. Fts5Config *pConfig;
  161670. char *zErr;
  161671. int rc;
  161672. int nPhrase; /* Size of apPhrase array */
  161673. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  161674. Fts5ExprNode *pExpr; /* Result of a successful parse */
  161675. };
  161676. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  161677. va_list ap;
  161678. va_start(ap, zFmt);
  161679. if( pParse->rc==SQLITE_OK ){
  161680. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  161681. pParse->rc = SQLITE_ERROR;
  161682. }
  161683. va_end(ap);
  161684. }
  161685. static int fts5ExprIsspace(char t){
  161686. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  161687. }
  161688. /*
  161689. ** Read the first token from the nul-terminated string at *pz.
  161690. */
  161691. static int fts5ExprGetToken(
  161692. Fts5Parse *pParse,
  161693. const char **pz, /* IN/OUT: Pointer into buffer */
  161694. Fts5Token *pToken
  161695. ){
  161696. const char *z = *pz;
  161697. int tok;
  161698. /* Skip past any whitespace */
  161699. while( fts5ExprIsspace(*z) ) z++;
  161700. pToken->p = z;
  161701. pToken->n = 1;
  161702. switch( *z ){
  161703. case '(': tok = FTS5_LP; break;
  161704. case ')': tok = FTS5_RP; break;
  161705. case '{': tok = FTS5_LCP; break;
  161706. case '}': tok = FTS5_RCP; break;
  161707. case ':': tok = FTS5_COLON; break;
  161708. case ',': tok = FTS5_COMMA; break;
  161709. case '+': tok = FTS5_PLUS; break;
  161710. case '*': tok = FTS5_STAR; break;
  161711. case '\0': tok = FTS5_EOF; break;
  161712. case '"': {
  161713. const char *z2;
  161714. tok = FTS5_STRING;
  161715. for(z2=&z[1]; 1; z2++){
  161716. if( z2[0]=='"' ){
  161717. z2++;
  161718. if( z2[0]!='"' ) break;
  161719. }
  161720. if( z2[0]=='\0' ){
  161721. sqlite3Fts5ParseError(pParse, "unterminated string");
  161722. return FTS5_EOF;
  161723. }
  161724. }
  161725. pToken->n = (z2 - z);
  161726. break;
  161727. }
  161728. default: {
  161729. const char *z2;
  161730. if( sqlite3Fts5IsBareword(z[0])==0 ){
  161731. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  161732. return FTS5_EOF;
  161733. }
  161734. tok = FTS5_STRING;
  161735. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  161736. pToken->n = (z2 - z);
  161737. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  161738. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  161739. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  161740. break;
  161741. }
  161742. }
  161743. *pz = &pToken->p[pToken->n];
  161744. return tok;
  161745. }
  161746. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  161747. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  161748. static int sqlite3Fts5ExprNew(
  161749. Fts5Config *pConfig, /* FTS5 Configuration */
  161750. const char *zExpr, /* Expression text */
  161751. Fts5Expr **ppNew,
  161752. char **pzErr
  161753. ){
  161754. Fts5Parse sParse;
  161755. Fts5Token token;
  161756. const char *z = zExpr;
  161757. int t; /* Next token type */
  161758. void *pEngine;
  161759. Fts5Expr *pNew;
  161760. *ppNew = 0;
  161761. *pzErr = 0;
  161762. memset(&sParse, 0, sizeof(sParse));
  161763. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  161764. if( pEngine==0 ){ return SQLITE_NOMEM; }
  161765. sParse.pConfig = pConfig;
  161766. do {
  161767. t = fts5ExprGetToken(&sParse, &z, &token);
  161768. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  161769. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  161770. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  161771. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  161772. if( sParse.rc==SQLITE_OK ){
  161773. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  161774. if( pNew==0 ){
  161775. sParse.rc = SQLITE_NOMEM;
  161776. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  161777. }else{
  161778. if( !sParse.pExpr ){
  161779. const int nByte = sizeof(Fts5ExprNode);
  161780. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  161781. if( pNew->pRoot ){
  161782. pNew->pRoot->bEof = 1;
  161783. }
  161784. }else{
  161785. pNew->pRoot = sParse.pExpr;
  161786. }
  161787. pNew->pIndex = 0;
  161788. pNew->pConfig = pConfig;
  161789. pNew->apExprPhrase = sParse.apPhrase;
  161790. pNew->nPhrase = sParse.nPhrase;
  161791. sParse.apPhrase = 0;
  161792. }
  161793. }else{
  161794. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  161795. }
  161796. sqlite3_free(sParse.apPhrase);
  161797. *pzErr = sParse.zErr;
  161798. return sParse.rc;
  161799. }
  161800. /*
  161801. ** Free the expression node object passed as the only argument.
  161802. */
  161803. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  161804. if( p ){
  161805. int i;
  161806. for(i=0; i<p->nChild; i++){
  161807. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  161808. }
  161809. sqlite3Fts5ParseNearsetFree(p->pNear);
  161810. sqlite3_free(p);
  161811. }
  161812. }
  161813. /*
  161814. ** Free the expression object passed as the only argument.
  161815. */
  161816. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  161817. if( p ){
  161818. sqlite3Fts5ParseNodeFree(p->pRoot);
  161819. sqlite3_free(p->apExprPhrase);
  161820. sqlite3_free(p);
  161821. }
  161822. }
  161823. /*
  161824. ** Argument pTerm must be a synonym iterator. Return the current rowid
  161825. ** that it points to.
  161826. */
  161827. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  161828. i64 iRet = 0;
  161829. int bRetValid = 0;
  161830. Fts5ExprTerm *p;
  161831. assert( pTerm->pSynonym );
  161832. assert( bDesc==0 || bDesc==1 );
  161833. for(p=pTerm; p; p=p->pSynonym){
  161834. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  161835. i64 iRowid = p->pIter->iRowid;
  161836. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  161837. iRet = iRowid;
  161838. bRetValid = 1;
  161839. }
  161840. }
  161841. }
  161842. if( pbEof && bRetValid==0 ) *pbEof = 1;
  161843. return iRet;
  161844. }
  161845. /*
  161846. ** Argument pTerm must be a synonym iterator.
  161847. */
  161848. static int fts5ExprSynonymList(
  161849. Fts5ExprTerm *pTerm,
  161850. i64 iRowid,
  161851. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  161852. u8 **pa, int *pn
  161853. ){
  161854. Fts5PoslistReader aStatic[4];
  161855. Fts5PoslistReader *aIter = aStatic;
  161856. int nIter = 0;
  161857. int nAlloc = 4;
  161858. int rc = SQLITE_OK;
  161859. Fts5ExprTerm *p;
  161860. assert( pTerm->pSynonym );
  161861. for(p=pTerm; p; p=p->pSynonym){
  161862. Fts5IndexIter *pIter = p->pIter;
  161863. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  161864. if( pIter->nData==0 ) continue;
  161865. if( nIter==nAlloc ){
  161866. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  161867. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  161868. if( aNew==0 ){
  161869. rc = SQLITE_NOMEM;
  161870. goto synonym_poslist_out;
  161871. }
  161872. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  161873. nAlloc = nAlloc*2;
  161874. if( aIter!=aStatic ) sqlite3_free(aIter);
  161875. aIter = aNew;
  161876. }
  161877. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  161878. assert( aIter[nIter].bEof==0 );
  161879. nIter++;
  161880. }
  161881. }
  161882. if( nIter==1 ){
  161883. *pa = (u8*)aIter[0].a;
  161884. *pn = aIter[0].n;
  161885. }else{
  161886. Fts5PoslistWriter writer = {0};
  161887. i64 iPrev = -1;
  161888. fts5BufferZero(pBuf);
  161889. while( 1 ){
  161890. int i;
  161891. i64 iMin = FTS5_LARGEST_INT64;
  161892. for(i=0; i<nIter; i++){
  161893. if( aIter[i].bEof==0 ){
  161894. if( aIter[i].iPos==iPrev ){
  161895. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  161896. }
  161897. if( aIter[i].iPos<iMin ){
  161898. iMin = aIter[i].iPos;
  161899. }
  161900. }
  161901. }
  161902. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  161903. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  161904. iPrev = iMin;
  161905. }
  161906. if( rc==SQLITE_OK ){
  161907. *pa = pBuf->p;
  161908. *pn = pBuf->n;
  161909. }
  161910. }
  161911. synonym_poslist_out:
  161912. if( aIter!=aStatic ) sqlite3_free(aIter);
  161913. return rc;
  161914. }
  161915. /*
  161916. ** All individual term iterators in pPhrase are guaranteed to be valid and
  161917. ** pointing to the same rowid when this function is called. This function
  161918. ** checks if the current rowid really is a match, and if so populates
  161919. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  161920. ** is set to true if this is really a match, or false otherwise.
  161921. **
  161922. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  161923. ** otherwise. It is not considered an error code if the current rowid is
  161924. ** not a match.
  161925. */
  161926. static int fts5ExprPhraseIsMatch(
  161927. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  161928. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  161929. int *pbMatch /* OUT: Set to true if really a match */
  161930. ){
  161931. Fts5PoslistWriter writer = {0};
  161932. Fts5PoslistReader aStatic[4];
  161933. Fts5PoslistReader *aIter = aStatic;
  161934. int i;
  161935. int rc = SQLITE_OK;
  161936. fts5BufferZero(&pPhrase->poslist);
  161937. /* If the aStatic[] array is not large enough, allocate a large array
  161938. ** using sqlite3_malloc(). This approach could be improved upon. */
  161939. if( pPhrase->nTerm>ArraySize(aStatic) ){
  161940. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  161941. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  161942. if( !aIter ) return SQLITE_NOMEM;
  161943. }
  161944. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  161945. /* Initialize a term iterator for each term in the phrase */
  161946. for(i=0; i<pPhrase->nTerm; i++){
  161947. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  161948. int n = 0;
  161949. int bFlag = 0;
  161950. u8 *a = 0;
  161951. if( pTerm->pSynonym ){
  161952. Fts5Buffer buf = {0, 0, 0};
  161953. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  161954. if( rc ){
  161955. sqlite3_free(a);
  161956. goto ismatch_out;
  161957. }
  161958. if( a==buf.p ) bFlag = 1;
  161959. }else{
  161960. a = (u8*)pTerm->pIter->pData;
  161961. n = pTerm->pIter->nData;
  161962. }
  161963. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  161964. aIter[i].bFlag = (u8)bFlag;
  161965. if( aIter[i].bEof ) goto ismatch_out;
  161966. }
  161967. while( 1 ){
  161968. int bMatch;
  161969. i64 iPos = aIter[0].iPos;
  161970. do {
  161971. bMatch = 1;
  161972. for(i=0; i<pPhrase->nTerm; i++){
  161973. Fts5PoslistReader *pPos = &aIter[i];
  161974. i64 iAdj = iPos + i;
  161975. if( pPos->iPos!=iAdj ){
  161976. bMatch = 0;
  161977. while( pPos->iPos<iAdj ){
  161978. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  161979. }
  161980. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  161981. }
  161982. }
  161983. }while( bMatch==0 );
  161984. /* Append position iPos to the output */
  161985. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  161986. if( rc!=SQLITE_OK ) goto ismatch_out;
  161987. for(i=0; i<pPhrase->nTerm; i++){
  161988. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  161989. }
  161990. }
  161991. ismatch_out:
  161992. *pbMatch = (pPhrase->poslist.n>0);
  161993. for(i=0; i<pPhrase->nTerm; i++){
  161994. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  161995. }
  161996. if( aIter!=aStatic ) sqlite3_free(aIter);
  161997. return rc;
  161998. }
  161999. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  162000. struct Fts5LookaheadReader {
  162001. const u8 *a; /* Buffer containing position list */
  162002. int n; /* Size of buffer a[] in bytes */
  162003. int i; /* Current offset in position list */
  162004. i64 iPos; /* Current position */
  162005. i64 iLookahead; /* Next position */
  162006. };
  162007. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  162008. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  162009. p->iPos = p->iLookahead;
  162010. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  162011. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  162012. }
  162013. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  162014. }
  162015. static int fts5LookaheadReaderInit(
  162016. const u8 *a, int n, /* Buffer to read position list from */
  162017. Fts5LookaheadReader *p /* Iterator object to initialize */
  162018. ){
  162019. memset(p, 0, sizeof(Fts5LookaheadReader));
  162020. p->a = a;
  162021. p->n = n;
  162022. fts5LookaheadReaderNext(p);
  162023. return fts5LookaheadReaderNext(p);
  162024. }
  162025. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  162026. struct Fts5NearTrimmer {
  162027. Fts5LookaheadReader reader; /* Input iterator */
  162028. Fts5PoslistWriter writer; /* Writer context */
  162029. Fts5Buffer *pOut; /* Output poslist */
  162030. };
  162031. /*
  162032. ** The near-set object passed as the first argument contains more than
  162033. ** one phrase. All phrases currently point to the same row. The
  162034. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  162035. ** tests if the current row contains instances of each phrase sufficiently
  162036. ** close together to meet the NEAR constraint. Non-zero is returned if it
  162037. ** does, or zero otherwise.
  162038. **
  162039. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  162040. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  162041. ** occurs within this function (*pRc) is set accordingly before returning.
  162042. ** The return value is undefined in both these cases.
  162043. **
  162044. ** If no error occurs and non-zero (a match) is returned, the position-list
  162045. ** of each phrase object is edited to contain only those entries that
  162046. ** meet the constraint before returning.
  162047. */
  162048. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  162049. Fts5NearTrimmer aStatic[4];
  162050. Fts5NearTrimmer *a = aStatic;
  162051. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  162052. int i;
  162053. int rc = *pRc;
  162054. int bMatch;
  162055. assert( pNear->nPhrase>1 );
  162056. /* If the aStatic[] array is not large enough, allocate a large array
  162057. ** using sqlite3_malloc(). This approach could be improved upon. */
  162058. if( pNear->nPhrase>ArraySize(aStatic) ){
  162059. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  162060. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  162061. }else{
  162062. memset(aStatic, 0, sizeof(aStatic));
  162063. }
  162064. if( rc!=SQLITE_OK ){
  162065. *pRc = rc;
  162066. return 0;
  162067. }
  162068. /* Initialize a lookahead iterator for each phrase. After passing the
  162069. ** buffer and buffer size to the lookaside-reader init function, zero
  162070. ** the phrase poslist buffer. The new poslist for the phrase (containing
  162071. ** the same entries as the original with some entries removed on account
  162072. ** of the NEAR constraint) is written over the original even as it is
  162073. ** being read. This is safe as the entries for the new poslist are a
  162074. ** subset of the old, so it is not possible for data yet to be read to
  162075. ** be overwritten. */
  162076. for(i=0; i<pNear->nPhrase; i++){
  162077. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  162078. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  162079. pPoslist->n = 0;
  162080. a[i].pOut = pPoslist;
  162081. }
  162082. while( 1 ){
  162083. int iAdv;
  162084. i64 iMin;
  162085. i64 iMax;
  162086. /* This block advances the phrase iterators until they point to a set of
  162087. ** entries that together comprise a match. */
  162088. iMax = a[0].reader.iPos;
  162089. do {
  162090. bMatch = 1;
  162091. for(i=0; i<pNear->nPhrase; i++){
  162092. Fts5LookaheadReader *pPos = &a[i].reader;
  162093. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  162094. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  162095. bMatch = 0;
  162096. while( pPos->iPos<iMin ){
  162097. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  162098. }
  162099. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  162100. }
  162101. }
  162102. }while( bMatch==0 );
  162103. /* Add an entry to each output position list */
  162104. for(i=0; i<pNear->nPhrase; i++){
  162105. i64 iPos = a[i].reader.iPos;
  162106. Fts5PoslistWriter *pWriter = &a[i].writer;
  162107. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  162108. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  162109. }
  162110. }
  162111. iAdv = 0;
  162112. iMin = a[0].reader.iLookahead;
  162113. for(i=0; i<pNear->nPhrase; i++){
  162114. if( a[i].reader.iLookahead < iMin ){
  162115. iMin = a[i].reader.iLookahead;
  162116. iAdv = i;
  162117. }
  162118. }
  162119. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  162120. }
  162121. ismatch_out: {
  162122. int bRet = a[0].pOut->n>0;
  162123. *pRc = rc;
  162124. if( a!=aStatic ) sqlite3_free(a);
  162125. return bRet;
  162126. }
  162127. }
  162128. /*
  162129. ** Advance iterator pIter until it points to a value equal to or laster
  162130. ** than the initial value of *piLast. If this means the iterator points
  162131. ** to a value laster than *piLast, update *piLast to the new lastest value.
  162132. **
  162133. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  162134. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  162135. ** are set, return a non-zero value. Otherwise, return zero.
  162136. */
  162137. static int fts5ExprAdvanceto(
  162138. Fts5IndexIter *pIter, /* Iterator to advance */
  162139. int bDesc, /* True if iterator is "rowid DESC" */
  162140. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  162141. int *pRc, /* OUT: Error code */
  162142. int *pbEof /* OUT: Set to true if EOF */
  162143. ){
  162144. i64 iLast = *piLast;
  162145. i64 iRowid;
  162146. iRowid = pIter->iRowid;
  162147. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  162148. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  162149. if( rc || sqlite3Fts5IterEof(pIter) ){
  162150. *pRc = rc;
  162151. *pbEof = 1;
  162152. return 1;
  162153. }
  162154. iRowid = pIter->iRowid;
  162155. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  162156. }
  162157. *piLast = iRowid;
  162158. return 0;
  162159. }
  162160. static int fts5ExprSynonymAdvanceto(
  162161. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  162162. int bDesc, /* True if iterator is "rowid DESC" */
  162163. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  162164. int *pRc /* OUT: Error code */
  162165. ){
  162166. int rc = SQLITE_OK;
  162167. i64 iLast = *piLast;
  162168. Fts5ExprTerm *p;
  162169. int bEof = 0;
  162170. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  162171. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  162172. i64 iRowid = p->pIter->iRowid;
  162173. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  162174. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  162175. }
  162176. }
  162177. }
  162178. if( rc!=SQLITE_OK ){
  162179. *pRc = rc;
  162180. bEof = 1;
  162181. }else{
  162182. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  162183. }
  162184. return bEof;
  162185. }
  162186. static int fts5ExprNearTest(
  162187. int *pRc,
  162188. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  162189. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  162190. ){
  162191. Fts5ExprNearset *pNear = pNode->pNear;
  162192. int rc = *pRc;
  162193. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  162194. Fts5ExprTerm *pTerm;
  162195. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  162196. pPhrase->poslist.n = 0;
  162197. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  162198. Fts5IndexIter *pIter = pTerm->pIter;
  162199. if( sqlite3Fts5IterEof(pIter)==0 ){
  162200. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  162201. pPhrase->poslist.n = 1;
  162202. }
  162203. }
  162204. }
  162205. return pPhrase->poslist.n;
  162206. }else{
  162207. int i;
  162208. /* Check that each phrase in the nearset matches the current row.
  162209. ** Populate the pPhrase->poslist buffers at the same time. If any
  162210. ** phrase is not a match, break out of the loop early. */
  162211. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  162212. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  162213. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
  162214. int bMatch = 0;
  162215. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  162216. if( bMatch==0 ) break;
  162217. }else{
  162218. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  162219. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  162220. }
  162221. }
  162222. *pRc = rc;
  162223. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  162224. return 1;
  162225. }
  162226. return 0;
  162227. }
  162228. }
  162229. /*
  162230. ** Initialize all term iterators in the pNear object. If any term is found
  162231. ** to match no documents at all, return immediately without initializing any
  162232. ** further iterators.
  162233. */
  162234. static int fts5ExprNearInitAll(
  162235. Fts5Expr *pExpr,
  162236. Fts5ExprNode *pNode
  162237. ){
  162238. Fts5ExprNearset *pNear = pNode->pNear;
  162239. int i, j;
  162240. int rc = SQLITE_OK;
  162241. assert( pNode->bNomatch==0 );
  162242. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  162243. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  162244. for(j=0; j<pPhrase->nTerm; j++){
  162245. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  162246. Fts5ExprTerm *p;
  162247. int bEof = 1;
  162248. for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
  162249. if( p->pIter ){
  162250. sqlite3Fts5IterClose(p->pIter);
  162251. p->pIter = 0;
  162252. }
  162253. rc = sqlite3Fts5IndexQuery(
  162254. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  162255. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  162256. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  162257. pNear->pColset,
  162258. &p->pIter
  162259. );
  162260. assert( rc==SQLITE_OK || p->pIter==0 );
  162261. if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
  162262. bEof = 0;
  162263. }
  162264. }
  162265. if( bEof ){
  162266. pNode->bEof = 1;
  162267. return rc;
  162268. }
  162269. }
  162270. }
  162271. return rc;
  162272. }
  162273. /*
  162274. ** If pExpr is an ASC iterator, this function returns a value with the
  162275. ** same sign as:
  162276. **
  162277. ** (iLhs - iRhs)
  162278. **
  162279. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  162280. **
  162281. ** (iRhs - iLhs)
  162282. */
  162283. static int fts5RowidCmp(
  162284. Fts5Expr *pExpr,
  162285. i64 iLhs,
  162286. i64 iRhs
  162287. ){
  162288. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  162289. if( pExpr->bDesc==0 ){
  162290. if( iLhs<iRhs ) return -1;
  162291. return (iLhs > iRhs);
  162292. }else{
  162293. if( iLhs>iRhs ) return -1;
  162294. return (iLhs < iRhs);
  162295. }
  162296. }
  162297. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  162298. int i;
  162299. pNode->bEof = 1;
  162300. pNode->bNomatch = 0;
  162301. for(i=0; i<pNode->nChild; i++){
  162302. fts5ExprSetEof(pNode->apChild[i]);
  162303. }
  162304. }
  162305. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  162306. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  162307. Fts5ExprNearset *pNear = pNode->pNear;
  162308. int i;
  162309. for(i=0; i<pNear->nPhrase; i++){
  162310. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  162311. pPhrase->poslist.n = 0;
  162312. }
  162313. }else{
  162314. int i;
  162315. for(i=0; i<pNode->nChild; i++){
  162316. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  162317. }
  162318. }
  162319. }
  162320. /*
  162321. ** Compare the values currently indicated by the two nodes as follows:
  162322. **
  162323. ** res = (*p1) - (*p2)
  162324. **
  162325. ** Nodes that point to values that come later in the iteration order are
  162326. ** considered to be larger. Nodes at EOF are the largest of all.
  162327. **
  162328. ** This means that if the iteration order is ASC, then numerically larger
  162329. ** rowids are considered larger. Or if it is the default DESC, numerically
  162330. ** smaller rowids are larger.
  162331. */
  162332. static int fts5NodeCompare(
  162333. Fts5Expr *pExpr,
  162334. Fts5ExprNode *p1,
  162335. Fts5ExprNode *p2
  162336. ){
  162337. if( p2->bEof ) return -1;
  162338. if( p1->bEof ) return +1;
  162339. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  162340. }
  162341. /*
  162342. ** All individual term iterators in pNear are guaranteed to be valid when
  162343. ** this function is called. This function checks if all term iterators
  162344. ** point to the same rowid, and if not, advances them until they do.
  162345. ** If an EOF is reached before this happens, *pbEof is set to true before
  162346. ** returning.
  162347. **
  162348. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  162349. ** otherwise. It is not considered an error code if an iterator reaches
  162350. ** EOF.
  162351. */
  162352. static int fts5ExprNodeTest_STRING(
  162353. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  162354. Fts5ExprNode *pNode
  162355. ){
  162356. Fts5ExprNearset *pNear = pNode->pNear;
  162357. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  162358. int rc = SQLITE_OK;
  162359. i64 iLast; /* Lastest rowid any iterator points to */
  162360. int i, j; /* Phrase and token index, respectively */
  162361. int bMatch; /* True if all terms are at the same rowid */
  162362. const int bDesc = pExpr->bDesc;
  162363. /* Check that this node should not be FTS5_TERM */
  162364. assert( pNear->nPhrase>1
  162365. || pNear->apPhrase[0]->nTerm>1
  162366. || pNear->apPhrase[0]->aTerm[0].pSynonym
  162367. );
  162368. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  162369. ** iterator skips through rowids in the default ascending order, this means
  162370. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  162371. ** means the minimum rowid. */
  162372. if( pLeft->aTerm[0].pSynonym ){
  162373. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  162374. }else{
  162375. iLast = pLeft->aTerm[0].pIter->iRowid;
  162376. }
  162377. do {
  162378. bMatch = 1;
  162379. for(i=0; i<pNear->nPhrase; i++){
  162380. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  162381. for(j=0; j<pPhrase->nTerm; j++){
  162382. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  162383. if( pTerm->pSynonym ){
  162384. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  162385. if( iRowid==iLast ) continue;
  162386. bMatch = 0;
  162387. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  162388. pNode->bNomatch = 0;
  162389. pNode->bEof = 1;
  162390. return rc;
  162391. }
  162392. }else{
  162393. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  162394. if( pIter->iRowid==iLast ) continue;
  162395. bMatch = 0;
  162396. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  162397. return rc;
  162398. }
  162399. }
  162400. }
  162401. }
  162402. }while( bMatch==0 );
  162403. pNode->iRowid = iLast;
  162404. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  162405. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  162406. return rc;
  162407. }
  162408. /*
  162409. ** Advance the first term iterator in the first phrase of pNear. Set output
  162410. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  162411. **
  162412. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  162413. ** occurs.
  162414. */
  162415. static int fts5ExprNodeNext_STRING(
  162416. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  162417. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  162418. int bFromValid,
  162419. i64 iFrom
  162420. ){
  162421. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  162422. int rc = SQLITE_OK;
  162423. pNode->bNomatch = 0;
  162424. if( pTerm->pSynonym ){
  162425. int bEof = 1;
  162426. Fts5ExprTerm *p;
  162427. /* Find the firstest rowid any synonym points to. */
  162428. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  162429. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  162430. ** is valid - each iterator that points to a rowid before iFrom. */
  162431. for(p=pTerm; p; p=p->pSynonym){
  162432. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  162433. i64 ii = p->pIter->iRowid;
  162434. if( ii==iRowid
  162435. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  162436. ){
  162437. if( bFromValid ){
  162438. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  162439. }else{
  162440. rc = sqlite3Fts5IterNext(p->pIter);
  162441. }
  162442. if( rc!=SQLITE_OK ) break;
  162443. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  162444. bEof = 0;
  162445. }
  162446. }else{
  162447. bEof = 0;
  162448. }
  162449. }
  162450. }
  162451. /* Set the EOF flag if either all synonym iterators are at EOF or an
  162452. ** error has occurred. */
  162453. pNode->bEof = (rc || bEof);
  162454. }else{
  162455. Fts5IndexIter *pIter = pTerm->pIter;
  162456. assert( Fts5NodeIsString(pNode) );
  162457. if( bFromValid ){
  162458. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  162459. }else{
  162460. rc = sqlite3Fts5IterNext(pIter);
  162461. }
  162462. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  162463. }
  162464. if( pNode->bEof==0 ){
  162465. assert( rc==SQLITE_OK );
  162466. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  162467. }
  162468. return rc;
  162469. }
  162470. static int fts5ExprNodeTest_TERM(
  162471. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  162472. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  162473. ){
  162474. /* As this "NEAR" object is actually a single phrase that consists
  162475. ** of a single term only, grab pointers into the poslist managed by the
  162476. ** fts5_index.c iterator object. This is much faster than synthesizing
  162477. ** a new poslist the way we have to for more complicated phrase or NEAR
  162478. ** expressions. */
  162479. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  162480. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  162481. assert( pNode->eType==FTS5_TERM );
  162482. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  162483. assert( pPhrase->aTerm[0].pSynonym==0 );
  162484. pPhrase->poslist.n = pIter->nData;
  162485. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  162486. pPhrase->poslist.p = (u8*)pIter->pData;
  162487. }
  162488. pNode->iRowid = pIter->iRowid;
  162489. pNode->bNomatch = (pPhrase->poslist.n==0);
  162490. return SQLITE_OK;
  162491. }
  162492. /*
  162493. ** xNext() method for a node of type FTS5_TERM.
  162494. */
  162495. static int fts5ExprNodeNext_TERM(
  162496. Fts5Expr *pExpr,
  162497. Fts5ExprNode *pNode,
  162498. int bFromValid,
  162499. i64 iFrom
  162500. ){
  162501. int rc;
  162502. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  162503. assert( pNode->bEof==0 );
  162504. if( bFromValid ){
  162505. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  162506. }else{
  162507. rc = sqlite3Fts5IterNext(pIter);
  162508. }
  162509. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  162510. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  162511. }else{
  162512. pNode->bEof = 1;
  162513. pNode->bNomatch = 0;
  162514. }
  162515. return rc;
  162516. }
  162517. static void fts5ExprNodeTest_OR(
  162518. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  162519. Fts5ExprNode *pNode /* Expression node to test */
  162520. ){
  162521. Fts5ExprNode *pNext = pNode->apChild[0];
  162522. int i;
  162523. for(i=1; i<pNode->nChild; i++){
  162524. Fts5ExprNode *pChild = pNode->apChild[i];
  162525. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  162526. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  162527. pNext = pChild;
  162528. }
  162529. }
  162530. pNode->iRowid = pNext->iRowid;
  162531. pNode->bEof = pNext->bEof;
  162532. pNode->bNomatch = pNext->bNomatch;
  162533. }
  162534. static int fts5ExprNodeNext_OR(
  162535. Fts5Expr *pExpr,
  162536. Fts5ExprNode *pNode,
  162537. int bFromValid,
  162538. i64 iFrom
  162539. ){
  162540. int i;
  162541. i64 iLast = pNode->iRowid;
  162542. for(i=0; i<pNode->nChild; i++){
  162543. Fts5ExprNode *p1 = pNode->apChild[i];
  162544. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  162545. if( p1->bEof==0 ){
  162546. if( (p1->iRowid==iLast)
  162547. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  162548. ){
  162549. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  162550. if( rc!=SQLITE_OK ) return rc;
  162551. }
  162552. }
  162553. }
  162554. fts5ExprNodeTest_OR(pExpr, pNode);
  162555. return SQLITE_OK;
  162556. }
  162557. /*
  162558. ** Argument pNode is an FTS5_AND node.
  162559. */
  162560. static int fts5ExprNodeTest_AND(
  162561. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  162562. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  162563. ){
  162564. int iChild;
  162565. i64 iLast = pAnd->iRowid;
  162566. int rc = SQLITE_OK;
  162567. int bMatch;
  162568. assert( pAnd->bEof==0 );
  162569. do {
  162570. pAnd->bNomatch = 0;
  162571. bMatch = 1;
  162572. for(iChild=0; iChild<pAnd->nChild; iChild++){
  162573. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  162574. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  162575. if( cmp>0 ){
  162576. /* Advance pChild until it points to iLast or laster */
  162577. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  162578. if( rc!=SQLITE_OK ) return rc;
  162579. }
  162580. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  162581. ** the child node is guaranteed to have advanced at least as far as
  162582. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  162583. ** new lastest rowid seen so far. */
  162584. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  162585. if( pChild->bEof ){
  162586. fts5ExprSetEof(pAnd);
  162587. bMatch = 1;
  162588. break;
  162589. }else if( iLast!=pChild->iRowid ){
  162590. bMatch = 0;
  162591. iLast = pChild->iRowid;
  162592. }
  162593. if( pChild->bNomatch ){
  162594. pAnd->bNomatch = 1;
  162595. }
  162596. }
  162597. }while( bMatch==0 );
  162598. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  162599. fts5ExprNodeZeroPoslist(pAnd);
  162600. }
  162601. pAnd->iRowid = iLast;
  162602. return SQLITE_OK;
  162603. }
  162604. static int fts5ExprNodeNext_AND(
  162605. Fts5Expr *pExpr,
  162606. Fts5ExprNode *pNode,
  162607. int bFromValid,
  162608. i64 iFrom
  162609. ){
  162610. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  162611. if( rc==SQLITE_OK ){
  162612. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  162613. }
  162614. return rc;
  162615. }
  162616. static int fts5ExprNodeTest_NOT(
  162617. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  162618. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  162619. ){
  162620. int rc = SQLITE_OK;
  162621. Fts5ExprNode *p1 = pNode->apChild[0];
  162622. Fts5ExprNode *p2 = pNode->apChild[1];
  162623. assert( pNode->nChild==2 );
  162624. while( rc==SQLITE_OK && p1->bEof==0 ){
  162625. int cmp = fts5NodeCompare(pExpr, p1, p2);
  162626. if( cmp>0 ){
  162627. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  162628. cmp = fts5NodeCompare(pExpr, p1, p2);
  162629. }
  162630. assert( rc!=SQLITE_OK || cmp<=0 );
  162631. if( cmp || p2->bNomatch ) break;
  162632. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  162633. }
  162634. pNode->bEof = p1->bEof;
  162635. pNode->bNomatch = p1->bNomatch;
  162636. pNode->iRowid = p1->iRowid;
  162637. if( p1->bEof ){
  162638. fts5ExprNodeZeroPoslist(p2);
  162639. }
  162640. return rc;
  162641. }
  162642. static int fts5ExprNodeNext_NOT(
  162643. Fts5Expr *pExpr,
  162644. Fts5ExprNode *pNode,
  162645. int bFromValid,
  162646. i64 iFrom
  162647. ){
  162648. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  162649. if( rc==SQLITE_OK ){
  162650. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  162651. }
  162652. return rc;
  162653. }
  162654. /*
  162655. ** If pNode currently points to a match, this function returns SQLITE_OK
  162656. ** without modifying it. Otherwise, pNode is advanced until it does point
  162657. ** to a match or EOF is reached.
  162658. */
  162659. static int fts5ExprNodeTest(
  162660. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  162661. Fts5ExprNode *pNode /* Expression node to test */
  162662. ){
  162663. int rc = SQLITE_OK;
  162664. if( pNode->bEof==0 ){
  162665. switch( pNode->eType ){
  162666. case FTS5_STRING: {
  162667. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  162668. break;
  162669. }
  162670. case FTS5_TERM: {
  162671. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  162672. break;
  162673. }
  162674. case FTS5_AND: {
  162675. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  162676. break;
  162677. }
  162678. case FTS5_OR: {
  162679. fts5ExprNodeTest_OR(pExpr, pNode);
  162680. break;
  162681. }
  162682. default: assert( pNode->eType==FTS5_NOT ); {
  162683. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  162684. break;
  162685. }
  162686. }
  162687. }
  162688. return rc;
  162689. }
  162690. /*
  162691. ** Set node pNode, which is part of expression pExpr, to point to the first
  162692. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  162693. **
  162694. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  162695. ** It is not an error if there are no matches.
  162696. */
  162697. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  162698. int rc = SQLITE_OK;
  162699. pNode->bEof = 0;
  162700. pNode->bNomatch = 0;
  162701. if( Fts5NodeIsString(pNode) ){
  162702. /* Initialize all term iterators in the NEAR object. */
  162703. rc = fts5ExprNearInitAll(pExpr, pNode);
  162704. }else if( pNode->xNext==0 ){
  162705. pNode->bEof = 1;
  162706. }else{
  162707. int i;
  162708. int nEof = 0;
  162709. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  162710. Fts5ExprNode *pChild = pNode->apChild[i];
  162711. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  162712. assert( pChild->bEof==0 || pChild->bEof==1 );
  162713. nEof += pChild->bEof;
  162714. }
  162715. pNode->iRowid = pNode->apChild[0]->iRowid;
  162716. switch( pNode->eType ){
  162717. case FTS5_AND:
  162718. if( nEof>0 ) fts5ExprSetEof(pNode);
  162719. break;
  162720. case FTS5_OR:
  162721. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  162722. break;
  162723. default:
  162724. assert( pNode->eType==FTS5_NOT );
  162725. pNode->bEof = pNode->apChild[0]->bEof;
  162726. break;
  162727. }
  162728. }
  162729. if( rc==SQLITE_OK ){
  162730. rc = fts5ExprNodeTest(pExpr, pNode);
  162731. }
  162732. return rc;
  162733. }
  162734. /*
  162735. ** Begin iterating through the set of documents in index pIdx matched by
  162736. ** the MATCH expression passed as the first argument. If the "bDesc"
  162737. ** parameter is passed a non-zero value, iteration is in descending rowid
  162738. ** order. Or, if it is zero, in ascending order.
  162739. **
  162740. ** If iterating in ascending rowid order (bDesc==0), the first document
  162741. ** visited is that with the smallest rowid that is larger than or equal
  162742. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  162743. ** then the first document visited must have a rowid smaller than or
  162744. ** equal to iFirst.
  162745. **
  162746. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  162747. ** is not considered an error if the query does not match any documents.
  162748. */
  162749. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  162750. Fts5ExprNode *pRoot = p->pRoot;
  162751. int rc; /* Return code */
  162752. p->pIndex = pIdx;
  162753. p->bDesc = bDesc;
  162754. rc = fts5ExprNodeFirst(p, pRoot);
  162755. /* If not at EOF but the current rowid occurs earlier than iFirst in
  162756. ** the iteration order, move to document iFirst or later. */
  162757. if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
  162758. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  162759. }
  162760. /* If the iterator is not at a real match, skip forward until it is. */
  162761. while( pRoot->bNomatch ){
  162762. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  162763. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  162764. }
  162765. return rc;
  162766. }
  162767. /*
  162768. ** Move to the next document
  162769. **
  162770. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  162771. ** is not considered an error if the query does not match any documents.
  162772. */
  162773. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  162774. int rc;
  162775. Fts5ExprNode *pRoot = p->pRoot;
  162776. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  162777. do {
  162778. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  162779. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  162780. }while( pRoot->bNomatch );
  162781. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  162782. pRoot->bEof = 1;
  162783. }
  162784. return rc;
  162785. }
  162786. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  162787. return p->pRoot->bEof;
  162788. }
  162789. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  162790. return p->pRoot->iRowid;
  162791. }
  162792. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  162793. int rc = SQLITE_OK;
  162794. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  162795. return rc;
  162796. }
  162797. /*
  162798. ** Free the phrase object passed as the only argument.
  162799. */
  162800. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  162801. if( pPhrase ){
  162802. int i;
  162803. for(i=0; i<pPhrase->nTerm; i++){
  162804. Fts5ExprTerm *pSyn;
  162805. Fts5ExprTerm *pNext;
  162806. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  162807. sqlite3_free(pTerm->zTerm);
  162808. sqlite3Fts5IterClose(pTerm->pIter);
  162809. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  162810. pNext = pSyn->pSynonym;
  162811. sqlite3Fts5IterClose(pSyn->pIter);
  162812. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  162813. sqlite3_free(pSyn);
  162814. }
  162815. }
  162816. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  162817. sqlite3_free(pPhrase);
  162818. }
  162819. }
  162820. /*
  162821. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  162822. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  162823. ** appended to it and the results returned.
  162824. **
  162825. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  162826. ** NULL returned.
  162827. */
  162828. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  162829. Fts5Parse *pParse, /* Parse context */
  162830. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  162831. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  162832. ){
  162833. const int SZALLOC = 8;
  162834. Fts5ExprNearset *pRet = 0;
  162835. if( pParse->rc==SQLITE_OK ){
  162836. if( pPhrase==0 ){
  162837. return pNear;
  162838. }
  162839. if( pNear==0 ){
  162840. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  162841. pRet = sqlite3_malloc(nByte);
  162842. if( pRet==0 ){
  162843. pParse->rc = SQLITE_NOMEM;
  162844. }else{
  162845. memset(pRet, 0, nByte);
  162846. }
  162847. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  162848. int nNew = pNear->nPhrase + SZALLOC;
  162849. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  162850. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  162851. if( pRet==0 ){
  162852. pParse->rc = SQLITE_NOMEM;
  162853. }
  162854. }else{
  162855. pRet = pNear;
  162856. }
  162857. }
  162858. if( pRet==0 ){
  162859. assert( pParse->rc!=SQLITE_OK );
  162860. sqlite3Fts5ParseNearsetFree(pNear);
  162861. sqlite3Fts5ParsePhraseFree(pPhrase);
  162862. }else{
  162863. if( pRet->nPhrase>0 ){
  162864. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  162865. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  162866. if( pPhrase->nTerm==0 ){
  162867. fts5ExprPhraseFree(pPhrase);
  162868. pRet->nPhrase--;
  162869. pParse->nPhrase--;
  162870. pPhrase = pLast;
  162871. }else if( pLast->nTerm==0 ){
  162872. fts5ExprPhraseFree(pLast);
  162873. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  162874. pParse->nPhrase--;
  162875. pRet->nPhrase--;
  162876. }
  162877. }
  162878. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  162879. }
  162880. return pRet;
  162881. }
  162882. typedef struct TokenCtx TokenCtx;
  162883. struct TokenCtx {
  162884. Fts5ExprPhrase *pPhrase;
  162885. int rc;
  162886. };
  162887. /*
  162888. ** Callback for tokenizing terms used by ParseTerm().
  162889. */
  162890. static int fts5ParseTokenize(
  162891. void *pContext, /* Pointer to Fts5InsertCtx object */
  162892. int tflags, /* Mask of FTS5_TOKEN_* flags */
  162893. const char *pToken, /* Buffer containing token */
  162894. int nToken, /* Size of token in bytes */
  162895. int iUnused1, /* Start offset of token */
  162896. int iUnused2 /* End offset of token */
  162897. ){
  162898. int rc = SQLITE_OK;
  162899. const int SZALLOC = 8;
  162900. TokenCtx *pCtx = (TokenCtx*)pContext;
  162901. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  162902. UNUSED_PARAM2(iUnused1, iUnused2);
  162903. /* If an error has already occurred, this is a no-op */
  162904. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  162905. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  162906. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  162907. Fts5ExprTerm *pSyn;
  162908. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  162909. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  162910. if( pSyn==0 ){
  162911. rc = SQLITE_NOMEM;
  162912. }else{
  162913. memset(pSyn, 0, nByte);
  162914. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  162915. memcpy(pSyn->zTerm, pToken, nToken);
  162916. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  162917. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  162918. }
  162919. }else{
  162920. Fts5ExprTerm *pTerm;
  162921. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  162922. Fts5ExprPhrase *pNew;
  162923. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  162924. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  162925. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  162926. );
  162927. if( pNew==0 ){
  162928. rc = SQLITE_NOMEM;
  162929. }else{
  162930. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  162931. pCtx->pPhrase = pPhrase = pNew;
  162932. pNew->nTerm = nNew - SZALLOC;
  162933. }
  162934. }
  162935. if( rc==SQLITE_OK ){
  162936. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  162937. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  162938. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  162939. }
  162940. }
  162941. pCtx->rc = rc;
  162942. return rc;
  162943. }
  162944. /*
  162945. ** Free the phrase object passed as the only argument.
  162946. */
  162947. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  162948. fts5ExprPhraseFree(pPhrase);
  162949. }
  162950. /*
  162951. ** Free the phrase object passed as the second argument.
  162952. */
  162953. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  162954. if( pNear ){
  162955. int i;
  162956. for(i=0; i<pNear->nPhrase; i++){
  162957. fts5ExprPhraseFree(pNear->apPhrase[i]);
  162958. }
  162959. sqlite3_free(pNear->pColset);
  162960. sqlite3_free(pNear);
  162961. }
  162962. }
  162963. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  162964. assert( pParse->pExpr==0 );
  162965. pParse->pExpr = p;
  162966. }
  162967. /*
  162968. ** This function is called by the parser to process a string token. The
  162969. ** string may or may not be quoted. In any case it is tokenized and a
  162970. ** phrase object consisting of all tokens returned.
  162971. */
  162972. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  162973. Fts5Parse *pParse, /* Parse context */
  162974. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  162975. Fts5Token *pToken, /* String to tokenize */
  162976. int bPrefix /* True if there is a trailing "*" */
  162977. ){
  162978. Fts5Config *pConfig = pParse->pConfig;
  162979. TokenCtx sCtx; /* Context object passed to callback */
  162980. int rc; /* Tokenize return code */
  162981. char *z = 0;
  162982. memset(&sCtx, 0, sizeof(TokenCtx));
  162983. sCtx.pPhrase = pAppend;
  162984. rc = fts5ParseStringFromToken(pToken, &z);
  162985. if( rc==SQLITE_OK ){
  162986. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
  162987. int n;
  162988. sqlite3Fts5Dequote(z);
  162989. n = (int)strlen(z);
  162990. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  162991. }
  162992. sqlite3_free(z);
  162993. if( rc || (rc = sCtx.rc) ){
  162994. pParse->rc = rc;
  162995. fts5ExprPhraseFree(sCtx.pPhrase);
  162996. sCtx.pPhrase = 0;
  162997. }else{
  162998. if( pAppend==0 ){
  162999. if( (pParse->nPhrase % 8)==0 ){
  163000. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  163001. Fts5ExprPhrase **apNew;
  163002. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  163003. if( apNew==0 ){
  163004. pParse->rc = SQLITE_NOMEM;
  163005. fts5ExprPhraseFree(sCtx.pPhrase);
  163006. return 0;
  163007. }
  163008. pParse->apPhrase = apNew;
  163009. }
  163010. pParse->nPhrase++;
  163011. }
  163012. if( sCtx.pPhrase==0 ){
  163013. /* This happens when parsing a token or quoted phrase that contains
  163014. ** no token characters at all. (e.g ... MATCH '""'). */
  163015. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  163016. }else if( sCtx.pPhrase->nTerm ){
  163017. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
  163018. }
  163019. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  163020. }
  163021. return sCtx.pPhrase;
  163022. }
  163023. /*
  163024. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  163025. ** expression passed as the second argument.
  163026. */
  163027. static int sqlite3Fts5ExprClonePhrase(
  163028. Fts5Expr *pExpr,
  163029. int iPhrase,
  163030. Fts5Expr **ppNew
  163031. ){
  163032. int rc = SQLITE_OK; /* Return code */
  163033. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  163034. int i; /* Used to iterate through phrase terms */
  163035. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  163036. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  163037. pOrig = pExpr->apExprPhrase[iPhrase];
  163038. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  163039. if( rc==SQLITE_OK ){
  163040. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  163041. sizeof(Fts5ExprPhrase*));
  163042. }
  163043. if( rc==SQLITE_OK ){
  163044. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  163045. sizeof(Fts5ExprNode));
  163046. }
  163047. if( rc==SQLITE_OK ){
  163048. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  163049. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  163050. }
  163051. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  163052. int tflags = 0;
  163053. Fts5ExprTerm *p;
  163054. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  163055. const char *zTerm = p->zTerm;
  163056. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  163057. 0, 0);
  163058. tflags = FTS5_TOKEN_COLOCATED;
  163059. }
  163060. if( rc==SQLITE_OK ){
  163061. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  163062. }
  163063. }
  163064. if( rc==SQLITE_OK ){
  163065. /* All the allocations succeeded. Put the expression object together. */
  163066. pNew->pIndex = pExpr->pIndex;
  163067. pNew->pConfig = pExpr->pConfig;
  163068. pNew->nPhrase = 1;
  163069. pNew->apExprPhrase[0] = sCtx.pPhrase;
  163070. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  163071. pNew->pRoot->pNear->nPhrase = 1;
  163072. sCtx.pPhrase->pNode = pNew->pRoot;
  163073. if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
  163074. pNew->pRoot->eType = FTS5_TERM;
  163075. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  163076. }else{
  163077. pNew->pRoot->eType = FTS5_STRING;
  163078. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  163079. }
  163080. }else{
  163081. sqlite3Fts5ExprFree(pNew);
  163082. fts5ExprPhraseFree(sCtx.pPhrase);
  163083. pNew = 0;
  163084. }
  163085. *ppNew = pNew;
  163086. return rc;
  163087. }
  163088. /*
  163089. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  163090. ** is expected. If token pTok does not contain "NEAR", store an error
  163091. ** in the pParse object.
  163092. */
  163093. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  163094. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  163095. sqlite3Fts5ParseError(
  163096. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  163097. );
  163098. }
  163099. }
  163100. static void sqlite3Fts5ParseSetDistance(
  163101. Fts5Parse *pParse,
  163102. Fts5ExprNearset *pNear,
  163103. Fts5Token *p
  163104. ){
  163105. if( pNear ){
  163106. int nNear = 0;
  163107. int i;
  163108. if( p->n ){
  163109. for(i=0; i<p->n; i++){
  163110. char c = (char)p->p[i];
  163111. if( c<'0' || c>'9' ){
  163112. sqlite3Fts5ParseError(
  163113. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  163114. );
  163115. return;
  163116. }
  163117. nNear = nNear * 10 + (p->p[i] - '0');
  163118. }
  163119. }else{
  163120. nNear = FTS5_DEFAULT_NEARDIST;
  163121. }
  163122. pNear->nNear = nNear;
  163123. }
  163124. }
  163125. /*
  163126. ** The second argument passed to this function may be NULL, or it may be
  163127. ** an existing Fts5Colset object. This function returns a pointer to
  163128. ** a new colset object containing the contents of (p) with new value column
  163129. ** number iCol appended.
  163130. **
  163131. ** If an OOM error occurs, store an error code in pParse and return NULL.
  163132. ** The old colset object (if any) is not freed in this case.
  163133. */
  163134. static Fts5Colset *fts5ParseColset(
  163135. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  163136. Fts5Colset *p, /* Existing colset object */
  163137. int iCol /* New column to add to colset object */
  163138. ){
  163139. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  163140. Fts5Colset *pNew; /* New colset object to return */
  163141. assert( pParse->rc==SQLITE_OK );
  163142. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  163143. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  163144. if( pNew==0 ){
  163145. pParse->rc = SQLITE_NOMEM;
  163146. }else{
  163147. int *aiCol = pNew->aiCol;
  163148. int i, j;
  163149. for(i=0; i<nCol; i++){
  163150. if( aiCol[i]==iCol ) return pNew;
  163151. if( aiCol[i]>iCol ) break;
  163152. }
  163153. for(j=nCol; j>i; j--){
  163154. aiCol[j] = aiCol[j-1];
  163155. }
  163156. aiCol[i] = iCol;
  163157. pNew->nCol = nCol+1;
  163158. #ifndef NDEBUG
  163159. /* Check that the array is in order and contains no duplicate entries. */
  163160. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  163161. #endif
  163162. }
  163163. return pNew;
  163164. }
  163165. static Fts5Colset *sqlite3Fts5ParseColset(
  163166. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  163167. Fts5Colset *pColset, /* Existing colset object */
  163168. Fts5Token *p
  163169. ){
  163170. Fts5Colset *pRet = 0;
  163171. int iCol;
  163172. char *z; /* Dequoted copy of token p */
  163173. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  163174. if( pParse->rc==SQLITE_OK ){
  163175. Fts5Config *pConfig = pParse->pConfig;
  163176. sqlite3Fts5Dequote(z);
  163177. for(iCol=0; iCol<pConfig->nCol; iCol++){
  163178. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  163179. }
  163180. if( iCol==pConfig->nCol ){
  163181. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  163182. }else{
  163183. pRet = fts5ParseColset(pParse, pColset, iCol);
  163184. }
  163185. sqlite3_free(z);
  163186. }
  163187. if( pRet==0 ){
  163188. assert( pParse->rc!=SQLITE_OK );
  163189. sqlite3_free(pColset);
  163190. }
  163191. return pRet;
  163192. }
  163193. static void sqlite3Fts5ParseSetColset(
  163194. Fts5Parse *pParse,
  163195. Fts5ExprNearset *pNear,
  163196. Fts5Colset *pColset
  163197. ){
  163198. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  163199. pParse->rc = SQLITE_ERROR;
  163200. pParse->zErr = sqlite3_mprintf(
  163201. "fts5: column queries are not supported (detail=none)"
  163202. );
  163203. sqlite3_free(pColset);
  163204. return;
  163205. }
  163206. if( pNear ){
  163207. pNear->pColset = pColset;
  163208. }else{
  163209. sqlite3_free(pColset);
  163210. }
  163211. }
  163212. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  163213. switch( pNode->eType ){
  163214. case FTS5_STRING: {
  163215. Fts5ExprNearset *pNear = pNode->pNear;
  163216. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  163217. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  163218. ){
  163219. pNode->eType = FTS5_TERM;
  163220. pNode->xNext = fts5ExprNodeNext_TERM;
  163221. }else{
  163222. pNode->xNext = fts5ExprNodeNext_STRING;
  163223. }
  163224. break;
  163225. };
  163226. case FTS5_OR: {
  163227. pNode->xNext = fts5ExprNodeNext_OR;
  163228. break;
  163229. };
  163230. case FTS5_AND: {
  163231. pNode->xNext = fts5ExprNodeNext_AND;
  163232. break;
  163233. };
  163234. default: assert( pNode->eType==FTS5_NOT ); {
  163235. pNode->xNext = fts5ExprNodeNext_NOT;
  163236. break;
  163237. };
  163238. }
  163239. }
  163240. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  163241. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  163242. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  163243. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  163244. p->nChild += pSub->nChild;
  163245. sqlite3_free(pSub);
  163246. }else{
  163247. p->apChild[p->nChild++] = pSub;
  163248. }
  163249. }
  163250. /*
  163251. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  163252. ** OOM error), leave an error code in pParse and return NULL.
  163253. */
  163254. static Fts5ExprNode *sqlite3Fts5ParseNode(
  163255. Fts5Parse *pParse, /* Parse context */
  163256. int eType, /* FTS5_STRING, AND, OR or NOT */
  163257. Fts5ExprNode *pLeft, /* Left hand child expression */
  163258. Fts5ExprNode *pRight, /* Right hand child expression */
  163259. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  163260. ){
  163261. Fts5ExprNode *pRet = 0;
  163262. if( pParse->rc==SQLITE_OK ){
  163263. int nChild = 0; /* Number of children of returned node */
  163264. int nByte; /* Bytes of space to allocate for this node */
  163265. assert( (eType!=FTS5_STRING && !pNear)
  163266. || (eType==FTS5_STRING && !pLeft && !pRight)
  163267. );
  163268. if( eType==FTS5_STRING && pNear==0 ) return 0;
  163269. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  163270. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  163271. if( eType==FTS5_NOT ){
  163272. nChild = 2;
  163273. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  163274. nChild = 2;
  163275. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  163276. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  163277. }
  163278. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  163279. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  163280. if( pRet ){
  163281. pRet->eType = eType;
  163282. pRet->pNear = pNear;
  163283. fts5ExprAssignXNext(pRet);
  163284. if( eType==FTS5_STRING ){
  163285. int iPhrase;
  163286. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  163287. pNear->apPhrase[iPhrase]->pNode = pRet;
  163288. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  163289. pRet->xNext = 0;
  163290. pRet->eType = FTS5_EOF;
  163291. }
  163292. }
  163293. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
  163294. && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
  163295. ){
  163296. assert( pParse->rc==SQLITE_OK );
  163297. pParse->rc = SQLITE_ERROR;
  163298. assert( pParse->zErr==0 );
  163299. pParse->zErr = sqlite3_mprintf(
  163300. "fts5: %s queries are not supported (detail!=full)",
  163301. pNear->nPhrase==1 ? "phrase": "NEAR"
  163302. );
  163303. sqlite3_free(pRet);
  163304. pRet = 0;
  163305. }
  163306. }else{
  163307. fts5ExprAddChildren(pRet, pLeft);
  163308. fts5ExprAddChildren(pRet, pRight);
  163309. }
  163310. }
  163311. }
  163312. if( pRet==0 ){
  163313. assert( pParse->rc!=SQLITE_OK );
  163314. sqlite3Fts5ParseNodeFree(pLeft);
  163315. sqlite3Fts5ParseNodeFree(pRight);
  163316. sqlite3Fts5ParseNearsetFree(pNear);
  163317. }
  163318. return pRet;
  163319. }
  163320. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  163321. Fts5Parse *pParse, /* Parse context */
  163322. Fts5ExprNode *pLeft, /* Left hand child expression */
  163323. Fts5ExprNode *pRight /* Right hand child expression */
  163324. ){
  163325. Fts5ExprNode *pRet = 0;
  163326. Fts5ExprNode *pPrev;
  163327. if( pParse->rc ){
  163328. sqlite3Fts5ParseNodeFree(pLeft);
  163329. sqlite3Fts5ParseNodeFree(pRight);
  163330. }else{
  163331. assert( pLeft->eType==FTS5_STRING
  163332. || pLeft->eType==FTS5_TERM
  163333. || pLeft->eType==FTS5_EOF
  163334. || pLeft->eType==FTS5_AND
  163335. );
  163336. assert( pRight->eType==FTS5_STRING
  163337. || pRight->eType==FTS5_TERM
  163338. || pRight->eType==FTS5_EOF
  163339. );
  163340. if( pLeft->eType==FTS5_AND ){
  163341. pPrev = pLeft->apChild[pLeft->nChild-1];
  163342. }else{
  163343. pPrev = pLeft;
  163344. }
  163345. assert( pPrev->eType==FTS5_STRING
  163346. || pPrev->eType==FTS5_TERM
  163347. || pPrev->eType==FTS5_EOF
  163348. );
  163349. if( pRight->eType==FTS5_EOF ){
  163350. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  163351. sqlite3Fts5ParseNodeFree(pRight);
  163352. pRet = pLeft;
  163353. pParse->nPhrase--;
  163354. }
  163355. else if( pPrev->eType==FTS5_EOF ){
  163356. Fts5ExprPhrase **ap;
  163357. if( pPrev==pLeft ){
  163358. pRet = pRight;
  163359. }else{
  163360. pLeft->apChild[pLeft->nChild-1] = pRight;
  163361. pRet = pLeft;
  163362. }
  163363. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  163364. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  163365. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  163366. pParse->nPhrase--;
  163367. sqlite3Fts5ParseNodeFree(pPrev);
  163368. }
  163369. else{
  163370. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  163371. }
  163372. }
  163373. return pRet;
  163374. }
  163375. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  163376. int nByte = 0;
  163377. Fts5ExprTerm *p;
  163378. char *zQuoted;
  163379. /* Determine the maximum amount of space required. */
  163380. for(p=pTerm; p; p=p->pSynonym){
  163381. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  163382. }
  163383. zQuoted = sqlite3_malloc(nByte);
  163384. if( zQuoted ){
  163385. int i = 0;
  163386. for(p=pTerm; p; p=p->pSynonym){
  163387. char *zIn = p->zTerm;
  163388. zQuoted[i++] = '"';
  163389. while( *zIn ){
  163390. if( *zIn=='"' ) zQuoted[i++] = '"';
  163391. zQuoted[i++] = *zIn++;
  163392. }
  163393. zQuoted[i++] = '"';
  163394. if( p->pSynonym ) zQuoted[i++] = '|';
  163395. }
  163396. if( pTerm->bPrefix ){
  163397. zQuoted[i++] = ' ';
  163398. zQuoted[i++] = '*';
  163399. }
  163400. zQuoted[i++] = '\0';
  163401. }
  163402. return zQuoted;
  163403. }
  163404. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  163405. char *zNew;
  163406. va_list ap;
  163407. va_start(ap, zFmt);
  163408. zNew = sqlite3_vmprintf(zFmt, ap);
  163409. va_end(ap);
  163410. if( zApp && zNew ){
  163411. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  163412. sqlite3_free(zNew);
  163413. zNew = zNew2;
  163414. }
  163415. sqlite3_free(zApp);
  163416. return zNew;
  163417. }
  163418. /*
  163419. ** Compose a tcl-readable representation of expression pExpr. Return a
  163420. ** pointer to a buffer containing that representation. It is the
  163421. ** responsibility of the caller to at some point free the buffer using
  163422. ** sqlite3_free().
  163423. */
  163424. static char *fts5ExprPrintTcl(
  163425. Fts5Config *pConfig,
  163426. const char *zNearsetCmd,
  163427. Fts5ExprNode *pExpr
  163428. ){
  163429. char *zRet = 0;
  163430. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  163431. Fts5ExprNearset *pNear = pExpr->pNear;
  163432. int i;
  163433. int iTerm;
  163434. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  163435. if( zRet==0 ) return 0;
  163436. if( pNear->pColset ){
  163437. int *aiCol = pNear->pColset->aiCol;
  163438. int nCol = pNear->pColset->nCol;
  163439. if( nCol==1 ){
  163440. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  163441. }else{
  163442. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  163443. for(i=1; i<pNear->pColset->nCol; i++){
  163444. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  163445. }
  163446. zRet = fts5PrintfAppend(zRet, "} ");
  163447. }
  163448. if( zRet==0 ) return 0;
  163449. }
  163450. if( pNear->nPhrase>1 ){
  163451. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  163452. if( zRet==0 ) return 0;
  163453. }
  163454. zRet = fts5PrintfAppend(zRet, "--");
  163455. if( zRet==0 ) return 0;
  163456. for(i=0; i<pNear->nPhrase; i++){
  163457. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  163458. zRet = fts5PrintfAppend(zRet, " {");
  163459. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  163460. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  163461. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  163462. if( pPhrase->aTerm[iTerm].bPrefix ){
  163463. zRet = fts5PrintfAppend(zRet, "*");
  163464. }
  163465. }
  163466. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  163467. if( zRet==0 ) return 0;
  163468. }
  163469. }else{
  163470. char const *zOp = 0;
  163471. int i;
  163472. switch( pExpr->eType ){
  163473. case FTS5_AND: zOp = "AND"; break;
  163474. case FTS5_NOT: zOp = "NOT"; break;
  163475. default:
  163476. assert( pExpr->eType==FTS5_OR );
  163477. zOp = "OR";
  163478. break;
  163479. }
  163480. zRet = sqlite3_mprintf("%s", zOp);
  163481. for(i=0; zRet && i<pExpr->nChild; i++){
  163482. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  163483. if( !z ){
  163484. sqlite3_free(zRet);
  163485. zRet = 0;
  163486. }else{
  163487. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  163488. }
  163489. }
  163490. }
  163491. return zRet;
  163492. }
  163493. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  163494. char *zRet = 0;
  163495. if( pExpr->eType==0 ){
  163496. return sqlite3_mprintf("\"\"");
  163497. }else
  163498. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  163499. Fts5ExprNearset *pNear = pExpr->pNear;
  163500. int i;
  163501. int iTerm;
  163502. if( pNear->pColset ){
  163503. int iCol = pNear->pColset->aiCol[0];
  163504. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  163505. if( zRet==0 ) return 0;
  163506. }
  163507. if( pNear->nPhrase>1 ){
  163508. zRet = fts5PrintfAppend(zRet, "NEAR(");
  163509. if( zRet==0 ) return 0;
  163510. }
  163511. for(i=0; i<pNear->nPhrase; i++){
  163512. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  163513. if( i!=0 ){
  163514. zRet = fts5PrintfAppend(zRet, " ");
  163515. if( zRet==0 ) return 0;
  163516. }
  163517. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  163518. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  163519. if( zTerm ){
  163520. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  163521. sqlite3_free(zTerm);
  163522. }
  163523. if( zTerm==0 || zRet==0 ){
  163524. sqlite3_free(zRet);
  163525. return 0;
  163526. }
  163527. }
  163528. }
  163529. if( pNear->nPhrase>1 ){
  163530. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  163531. if( zRet==0 ) return 0;
  163532. }
  163533. }else{
  163534. char const *zOp = 0;
  163535. int i;
  163536. switch( pExpr->eType ){
  163537. case FTS5_AND: zOp = " AND "; break;
  163538. case FTS5_NOT: zOp = " NOT "; break;
  163539. default:
  163540. assert( pExpr->eType==FTS5_OR );
  163541. zOp = " OR ";
  163542. break;
  163543. }
  163544. for(i=0; i<pExpr->nChild; i++){
  163545. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  163546. if( z==0 ){
  163547. sqlite3_free(zRet);
  163548. zRet = 0;
  163549. }else{
  163550. int e = pExpr->apChild[i]->eType;
  163551. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  163552. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  163553. (i==0 ? "" : zOp),
  163554. (b?"(":""), z, (b?")":"")
  163555. );
  163556. }
  163557. if( zRet==0 ) break;
  163558. }
  163559. }
  163560. return zRet;
  163561. }
  163562. /*
  163563. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  163564. ** and fts5_expr_tcl() (bTcl!=0).
  163565. */
  163566. static void fts5ExprFunction(
  163567. sqlite3_context *pCtx, /* Function call context */
  163568. int nArg, /* Number of args */
  163569. sqlite3_value **apVal, /* Function arguments */
  163570. int bTcl
  163571. ){
  163572. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  163573. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  163574. const char *zExpr = 0;
  163575. char *zErr = 0;
  163576. Fts5Expr *pExpr = 0;
  163577. int rc;
  163578. int i;
  163579. const char **azConfig; /* Array of arguments for Fts5Config */
  163580. const char *zNearsetCmd = "nearset";
  163581. int nConfig; /* Size of azConfig[] */
  163582. Fts5Config *pConfig = 0;
  163583. int iArg = 1;
  163584. if( nArg<1 ){
  163585. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  163586. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  163587. );
  163588. sqlite3_result_error(pCtx, zErr, -1);
  163589. sqlite3_free(zErr);
  163590. return;
  163591. }
  163592. if( bTcl && nArg>1 ){
  163593. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  163594. iArg = 2;
  163595. }
  163596. nConfig = 3 + (nArg-iArg);
  163597. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  163598. if( azConfig==0 ){
  163599. sqlite3_result_error_nomem(pCtx);
  163600. return;
  163601. }
  163602. azConfig[0] = 0;
  163603. azConfig[1] = "main";
  163604. azConfig[2] = "tbl";
  163605. for(i=3; iArg<nArg; iArg++){
  163606. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  163607. }
  163608. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  163609. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  163610. if( rc==SQLITE_OK ){
  163611. rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
  163612. }
  163613. if( rc==SQLITE_OK ){
  163614. char *zText;
  163615. if( pExpr->pRoot->xNext==0 ){
  163616. zText = sqlite3_mprintf("");
  163617. }else if( bTcl ){
  163618. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  163619. }else{
  163620. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  163621. }
  163622. if( zText==0 ){
  163623. rc = SQLITE_NOMEM;
  163624. }else{
  163625. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  163626. sqlite3_free(zText);
  163627. }
  163628. }
  163629. if( rc!=SQLITE_OK ){
  163630. if( zErr ){
  163631. sqlite3_result_error(pCtx, zErr, -1);
  163632. sqlite3_free(zErr);
  163633. }else{
  163634. sqlite3_result_error_code(pCtx, rc);
  163635. }
  163636. }
  163637. sqlite3_free((void *)azConfig);
  163638. sqlite3Fts5ConfigFree(pConfig);
  163639. sqlite3Fts5ExprFree(pExpr);
  163640. }
  163641. static void fts5ExprFunctionHr(
  163642. sqlite3_context *pCtx, /* Function call context */
  163643. int nArg, /* Number of args */
  163644. sqlite3_value **apVal /* Function arguments */
  163645. ){
  163646. fts5ExprFunction(pCtx, nArg, apVal, 0);
  163647. }
  163648. static void fts5ExprFunctionTcl(
  163649. sqlite3_context *pCtx, /* Function call context */
  163650. int nArg, /* Number of args */
  163651. sqlite3_value **apVal /* Function arguments */
  163652. ){
  163653. fts5ExprFunction(pCtx, nArg, apVal, 1);
  163654. }
  163655. /*
  163656. ** The implementation of an SQLite user-defined-function that accepts a
  163657. ** single integer as an argument. If the integer is an alpha-numeric
  163658. ** unicode code point, 1 is returned. Otherwise 0.
  163659. */
  163660. static void fts5ExprIsAlnum(
  163661. sqlite3_context *pCtx, /* Function call context */
  163662. int nArg, /* Number of args */
  163663. sqlite3_value **apVal /* Function arguments */
  163664. ){
  163665. int iCode;
  163666. if( nArg!=1 ){
  163667. sqlite3_result_error(pCtx,
  163668. "wrong number of arguments to function fts5_isalnum", -1
  163669. );
  163670. return;
  163671. }
  163672. iCode = sqlite3_value_int(apVal[0]);
  163673. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  163674. }
  163675. static void fts5ExprFold(
  163676. sqlite3_context *pCtx, /* Function call context */
  163677. int nArg, /* Number of args */
  163678. sqlite3_value **apVal /* Function arguments */
  163679. ){
  163680. if( nArg!=1 && nArg!=2 ){
  163681. sqlite3_result_error(pCtx,
  163682. "wrong number of arguments to function fts5_fold", -1
  163683. );
  163684. }else{
  163685. int iCode;
  163686. int bRemoveDiacritics = 0;
  163687. iCode = sqlite3_value_int(apVal[0]);
  163688. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  163689. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  163690. }
  163691. }
  163692. /*
  163693. ** This is called during initialization to register the fts5_expr() scalar
  163694. ** UDF with the SQLite handle passed as the only argument.
  163695. */
  163696. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  163697. struct Fts5ExprFunc {
  163698. const char *z;
  163699. void (*x)(sqlite3_context*,int,sqlite3_value**);
  163700. } aFunc[] = {
  163701. { "fts5_expr", fts5ExprFunctionHr },
  163702. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  163703. { "fts5_isalnum", fts5ExprIsAlnum },
  163704. { "fts5_fold", fts5ExprFold },
  163705. };
  163706. int i;
  163707. int rc = SQLITE_OK;
  163708. void *pCtx = (void*)pGlobal;
  163709. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  163710. struct Fts5ExprFunc *p = &aFunc[i];
  163711. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  163712. }
  163713. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  163714. #ifndef NDEBUG
  163715. (void)sqlite3Fts5ParserTrace;
  163716. #endif
  163717. return rc;
  163718. }
  163719. /*
  163720. ** Return the number of phrases in expression pExpr.
  163721. */
  163722. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  163723. return (pExpr ? pExpr->nPhrase : 0);
  163724. }
  163725. /*
  163726. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  163727. */
  163728. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  163729. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  163730. return pExpr->apExprPhrase[iPhrase]->nTerm;
  163731. }
  163732. /*
  163733. ** This function is used to access the current position list for phrase
  163734. ** iPhrase.
  163735. */
  163736. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  163737. int nRet;
  163738. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  163739. Fts5ExprNode *pNode = pPhrase->pNode;
  163740. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  163741. *pa = pPhrase->poslist.p;
  163742. nRet = pPhrase->poslist.n;
  163743. }else{
  163744. *pa = 0;
  163745. nRet = 0;
  163746. }
  163747. return nRet;
  163748. }
  163749. struct Fts5PoslistPopulator {
  163750. Fts5PoslistWriter writer;
  163751. int bOk; /* True if ok to populate */
  163752. int bMiss;
  163753. };
  163754. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  163755. Fts5PoslistPopulator *pRet;
  163756. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  163757. if( pRet ){
  163758. int i;
  163759. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  163760. for(i=0; i<pExpr->nPhrase; i++){
  163761. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  163762. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  163763. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  163764. if( bLive &&
  163765. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  163766. ){
  163767. pRet[i].bMiss = 1;
  163768. }else{
  163769. pBuf->n = 0;
  163770. }
  163771. }
  163772. }
  163773. return pRet;
  163774. }
  163775. struct Fts5ExprCtx {
  163776. Fts5Expr *pExpr;
  163777. Fts5PoslistPopulator *aPopulator;
  163778. i64 iOff;
  163779. };
  163780. typedef struct Fts5ExprCtx Fts5ExprCtx;
  163781. /*
  163782. ** TODO: Make this more efficient!
  163783. */
  163784. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  163785. int i;
  163786. for(i=0; i<pColset->nCol; i++){
  163787. if( pColset->aiCol[i]==iCol ) return 1;
  163788. }
  163789. return 0;
  163790. }
  163791. static int fts5ExprPopulatePoslistsCb(
  163792. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  163793. int tflags, /* Mask of FTS5_TOKEN_* flags */
  163794. const char *pToken, /* Pointer to buffer containing token */
  163795. int nToken, /* Size of token in bytes */
  163796. int iUnused1, /* Byte offset of token within input text */
  163797. int iUnused2 /* Byte offset of end of token within input text */
  163798. ){
  163799. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  163800. Fts5Expr *pExpr = p->pExpr;
  163801. int i;
  163802. UNUSED_PARAM2(iUnused1, iUnused2);
  163803. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  163804. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  163805. for(i=0; i<pExpr->nPhrase; i++){
  163806. Fts5ExprTerm *pTerm;
  163807. if( p->aPopulator[i].bOk==0 ) continue;
  163808. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  163809. int nTerm = (int)strlen(pTerm->zTerm);
  163810. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  163811. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  163812. ){
  163813. int rc = sqlite3Fts5PoslistWriterAppend(
  163814. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  163815. );
  163816. if( rc ) return rc;
  163817. break;
  163818. }
  163819. }
  163820. }
  163821. return SQLITE_OK;
  163822. }
  163823. static int sqlite3Fts5ExprPopulatePoslists(
  163824. Fts5Config *pConfig,
  163825. Fts5Expr *pExpr,
  163826. Fts5PoslistPopulator *aPopulator,
  163827. int iCol,
  163828. const char *z, int n
  163829. ){
  163830. int i;
  163831. Fts5ExprCtx sCtx;
  163832. sCtx.pExpr = pExpr;
  163833. sCtx.aPopulator = aPopulator;
  163834. sCtx.iOff = (((i64)iCol) << 32) - 1;
  163835. for(i=0; i<pExpr->nPhrase; i++){
  163836. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  163837. Fts5Colset *pColset = pNode->pNear->pColset;
  163838. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  163839. || aPopulator[i].bMiss
  163840. ){
  163841. aPopulator[i].bOk = 0;
  163842. }else{
  163843. aPopulator[i].bOk = 1;
  163844. }
  163845. }
  163846. return sqlite3Fts5Tokenize(pConfig,
  163847. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  163848. );
  163849. }
  163850. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  163851. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  163852. pNode->pNear->apPhrase[0]->poslist.n = 0;
  163853. }else{
  163854. int i;
  163855. for(i=0; i<pNode->nChild; i++){
  163856. fts5ExprClearPoslists(pNode->apChild[i]);
  163857. }
  163858. }
  163859. }
  163860. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  163861. pNode->iRowid = iRowid;
  163862. pNode->bEof = 0;
  163863. switch( pNode->eType ){
  163864. case FTS5_TERM:
  163865. case FTS5_STRING:
  163866. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  163867. case FTS5_AND: {
  163868. int i;
  163869. for(i=0; i<pNode->nChild; i++){
  163870. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  163871. fts5ExprClearPoslists(pNode);
  163872. return 0;
  163873. }
  163874. }
  163875. break;
  163876. }
  163877. case FTS5_OR: {
  163878. int i;
  163879. int bRet = 0;
  163880. for(i=0; i<pNode->nChild; i++){
  163881. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  163882. bRet = 1;
  163883. }
  163884. }
  163885. return bRet;
  163886. }
  163887. default: {
  163888. assert( pNode->eType==FTS5_NOT );
  163889. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  163890. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  163891. ){
  163892. fts5ExprClearPoslists(pNode);
  163893. return 0;
  163894. }
  163895. break;
  163896. }
  163897. }
  163898. return 1;
  163899. }
  163900. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  163901. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  163902. }
  163903. static void fts5ExprClearEof(Fts5ExprNode *pNode){
  163904. int i;
  163905. for(i=0; i<pNode->nChild; i++){
  163906. fts5ExprClearEof(pNode->apChild[i]);
  163907. }
  163908. pNode->bEof = 0;
  163909. }
  163910. static void sqlite3Fts5ExprClearEof(Fts5Expr *pExpr){
  163911. fts5ExprClearEof(pExpr->pRoot);
  163912. }
  163913. /*
  163914. ** This function is only called for detail=columns tables.
  163915. */
  163916. static int sqlite3Fts5ExprPhraseCollist(
  163917. Fts5Expr *pExpr,
  163918. int iPhrase,
  163919. const u8 **ppCollist,
  163920. int *pnCollist
  163921. ){
  163922. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  163923. Fts5ExprNode *pNode = pPhrase->pNode;
  163924. int rc = SQLITE_OK;
  163925. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  163926. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  163927. if( pNode->bEof==0
  163928. && pNode->iRowid==pExpr->pRoot->iRowid
  163929. && pPhrase->poslist.n>0
  163930. ){
  163931. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  163932. if( pTerm->pSynonym ){
  163933. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  163934. rc = fts5ExprSynonymList(
  163935. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  163936. );
  163937. }else{
  163938. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  163939. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  163940. }
  163941. }else{
  163942. *ppCollist = 0;
  163943. *pnCollist = 0;
  163944. }
  163945. return rc;
  163946. }
  163947. /*
  163948. ** 2014 August 11
  163949. **
  163950. ** The author disclaims copyright to this source code. In place of
  163951. ** a legal notice, here is a blessing:
  163952. **
  163953. ** May you do good and not evil.
  163954. ** May you find forgiveness for yourself and forgive others.
  163955. ** May you share freely, never taking more than you give.
  163956. **
  163957. ******************************************************************************
  163958. **
  163959. */
  163960. /* #include "fts5Int.h" */
  163961. typedef struct Fts5HashEntry Fts5HashEntry;
  163962. /*
  163963. ** This file contains the implementation of an in-memory hash table used
  163964. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  163965. ** segment.
  163966. */
  163967. struct Fts5Hash {
  163968. int eDetail; /* Copy of Fts5Config.eDetail */
  163969. int *pnByte; /* Pointer to bytes counter */
  163970. int nEntry; /* Number of entries currently in hash */
  163971. int nSlot; /* Size of aSlot[] array */
  163972. Fts5HashEntry *pScan; /* Current ordered scan item */
  163973. Fts5HashEntry **aSlot; /* Array of hash slots */
  163974. };
  163975. /*
  163976. ** Each entry in the hash table is represented by an object of the
  163977. ** following type. Each object, its key (zKey[]) and its current data
  163978. ** are stored in a single memory allocation. The position list data
  163979. ** immediately follows the key data in memory.
  163980. **
  163981. ** The data that follows the key is in a similar, but not identical format
  163982. ** to the doclist data stored in the database. It is:
  163983. **
  163984. ** * Rowid, as a varint
  163985. ** * Position list, without 0x00 terminator.
  163986. ** * Size of previous position list and rowid, as a 4 byte
  163987. ** big-endian integer.
  163988. **
  163989. ** iRowidOff:
  163990. ** Offset of last rowid written to data area. Relative to first byte of
  163991. ** structure.
  163992. **
  163993. ** nData:
  163994. ** Bytes of data written since iRowidOff.
  163995. */
  163996. struct Fts5HashEntry {
  163997. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  163998. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  163999. int nAlloc; /* Total size of allocation */
  164000. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  164001. int nData; /* Total bytes of data (incl. structure) */
  164002. int nKey; /* Length of zKey[] in bytes */
  164003. u8 bDel; /* Set delete-flag @ iSzPoslist */
  164004. u8 bContent; /* Set content-flag (detail=none mode) */
  164005. i16 iCol; /* Column of last value written */
  164006. int iPos; /* Position of last value written */
  164007. i64 iRowid; /* Rowid of last value written */
  164008. char zKey[8]; /* Nul-terminated entry key */
  164009. };
  164010. /*
  164011. ** Size of Fts5HashEntry without the zKey[] array.
  164012. */
  164013. #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
  164014. /*
  164015. ** Allocate a new hash table.
  164016. */
  164017. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  164018. int rc = SQLITE_OK;
  164019. Fts5Hash *pNew;
  164020. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  164021. if( pNew==0 ){
  164022. rc = SQLITE_NOMEM;
  164023. }else{
  164024. int nByte;
  164025. memset(pNew, 0, sizeof(Fts5Hash));
  164026. pNew->pnByte = pnByte;
  164027. pNew->eDetail = pConfig->eDetail;
  164028. pNew->nSlot = 1024;
  164029. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  164030. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  164031. if( pNew->aSlot==0 ){
  164032. sqlite3_free(pNew);
  164033. *ppNew = 0;
  164034. rc = SQLITE_NOMEM;
  164035. }else{
  164036. memset(pNew->aSlot, 0, nByte);
  164037. }
  164038. }
  164039. return rc;
  164040. }
  164041. /*
  164042. ** Free a hash table object.
  164043. */
  164044. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  164045. if( pHash ){
  164046. sqlite3Fts5HashClear(pHash);
  164047. sqlite3_free(pHash->aSlot);
  164048. sqlite3_free(pHash);
  164049. }
  164050. }
  164051. /*
  164052. ** Empty (but do not delete) a hash table.
  164053. */
  164054. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  164055. int i;
  164056. for(i=0; i<pHash->nSlot; i++){
  164057. Fts5HashEntry *pNext;
  164058. Fts5HashEntry *pSlot;
  164059. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  164060. pNext = pSlot->pHashNext;
  164061. sqlite3_free(pSlot);
  164062. }
  164063. }
  164064. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  164065. pHash->nEntry = 0;
  164066. }
  164067. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  164068. int i;
  164069. unsigned int h = 13;
  164070. for(i=n-1; i>=0; i--){
  164071. h = (h << 3) ^ h ^ p[i];
  164072. }
  164073. return (h % nSlot);
  164074. }
  164075. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  164076. int i;
  164077. unsigned int h = 13;
  164078. for(i=n-1; i>=0; i--){
  164079. h = (h << 3) ^ h ^ p[i];
  164080. }
  164081. h = (h << 3) ^ h ^ b;
  164082. return (h % nSlot);
  164083. }
  164084. /*
  164085. ** Resize the hash table by doubling the number of slots.
  164086. */
  164087. static int fts5HashResize(Fts5Hash *pHash){
  164088. int nNew = pHash->nSlot*2;
  164089. int i;
  164090. Fts5HashEntry **apNew;
  164091. Fts5HashEntry **apOld = pHash->aSlot;
  164092. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  164093. if( !apNew ) return SQLITE_NOMEM;
  164094. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  164095. for(i=0; i<pHash->nSlot; i++){
  164096. while( apOld[i] ){
  164097. int iHash;
  164098. Fts5HashEntry *p = apOld[i];
  164099. apOld[i] = p->pHashNext;
  164100. iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
  164101. p->pHashNext = apNew[iHash];
  164102. apNew[iHash] = p;
  164103. }
  164104. }
  164105. sqlite3_free(apOld);
  164106. pHash->nSlot = nNew;
  164107. pHash->aSlot = apNew;
  164108. return SQLITE_OK;
  164109. }
  164110. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  164111. if( p->iSzPoslist ){
  164112. u8 *pPtr = (u8*)p;
  164113. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  164114. assert( p->nData==p->iSzPoslist );
  164115. if( p->bDel ){
  164116. pPtr[p->nData++] = 0x00;
  164117. if( p->bContent ){
  164118. pPtr[p->nData++] = 0x00;
  164119. }
  164120. }
  164121. }else{
  164122. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  164123. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  164124. assert( p->bDel==0 || p->bDel==1 );
  164125. if( nPos<=127 ){
  164126. pPtr[p->iSzPoslist] = (u8)nPos;
  164127. }else{
  164128. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  164129. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  164130. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  164131. p->nData += (nByte-1);
  164132. }
  164133. }
  164134. p->iSzPoslist = 0;
  164135. p->bDel = 0;
  164136. p->bContent = 0;
  164137. }
  164138. }
  164139. /*
  164140. ** Add an entry to the in-memory hash table. The key is the concatenation
  164141. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  164142. **
  164143. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  164144. **
  164145. ** Or, if iCol is negative, then the value is a delete marker.
  164146. */
  164147. static int sqlite3Fts5HashWrite(
  164148. Fts5Hash *pHash,
  164149. i64 iRowid, /* Rowid for this entry */
  164150. int iCol, /* Column token appears in (-ve -> delete) */
  164151. int iPos, /* Position of token within column */
  164152. char bByte, /* First byte of token */
  164153. const char *pToken, int nToken /* Token to add or remove to or from index */
  164154. ){
  164155. unsigned int iHash;
  164156. Fts5HashEntry *p;
  164157. u8 *pPtr;
  164158. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  164159. int bNew; /* If non-delete entry should be written */
  164160. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  164161. /* Attempt to locate an existing hash entry */
  164162. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  164163. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  164164. if( p->zKey[0]==bByte
  164165. && p->nKey==nToken
  164166. && memcmp(&p->zKey[1], pToken, nToken)==0
  164167. ){
  164168. break;
  164169. }
  164170. }
  164171. /* If an existing hash entry cannot be found, create a new one. */
  164172. if( p==0 ){
  164173. /* Figure out how much space to allocate */
  164174. int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
  164175. if( nByte<128 ) nByte = 128;
  164176. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  164177. if( (pHash->nEntry*2)>=pHash->nSlot ){
  164178. int rc = fts5HashResize(pHash);
  164179. if( rc!=SQLITE_OK ) return rc;
  164180. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  164181. }
  164182. /* Allocate new Fts5HashEntry and add it to the hash table. */
  164183. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  164184. if( !p ) return SQLITE_NOMEM;
  164185. memset(p, 0, FTS5_HASHENTRYSIZE);
  164186. p->nAlloc = nByte;
  164187. p->zKey[0] = bByte;
  164188. memcpy(&p->zKey[1], pToken, nToken);
  164189. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
  164190. p->nKey = nToken;
  164191. p->zKey[nToken+1] = '\0';
  164192. p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
  164193. p->pHashNext = pHash->aSlot[iHash];
  164194. pHash->aSlot[iHash] = p;
  164195. pHash->nEntry++;
  164196. /* Add the first rowid field to the hash-entry */
  164197. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  164198. p->iRowid = iRowid;
  164199. p->iSzPoslist = p->nData;
  164200. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  164201. p->nData += 1;
  164202. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  164203. }
  164204. nIncr += p->nData;
  164205. }else{
  164206. /* Appending to an existing hash-entry. Check that there is enough
  164207. ** space to append the largest possible new entry. Worst case scenario
  164208. ** is:
  164209. **
  164210. ** + 9 bytes for a new rowid,
  164211. ** + 4 byte reserved for the "poslist size" varint.
  164212. ** + 1 byte for a "new column" byte,
  164213. ** + 3 bytes for a new column number (16-bit max) as a varint,
  164214. ** + 5 bytes for the new position offset (32-bit max).
  164215. */
  164216. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  164217. int nNew = p->nAlloc * 2;
  164218. Fts5HashEntry *pNew;
  164219. Fts5HashEntry **pp;
  164220. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  164221. if( pNew==0 ) return SQLITE_NOMEM;
  164222. pNew->nAlloc = nNew;
  164223. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  164224. *pp = pNew;
  164225. p = pNew;
  164226. }
  164227. nIncr -= p->nData;
  164228. }
  164229. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  164230. pPtr = (u8*)p;
  164231. /* If this is a new rowid, append the 4-byte size field for the previous
  164232. ** entry, and the new rowid for this entry. */
  164233. if( iRowid!=p->iRowid ){
  164234. fts5HashAddPoslistSize(pHash, p);
  164235. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  164236. p->iRowid = iRowid;
  164237. bNew = 1;
  164238. p->iSzPoslist = p->nData;
  164239. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  164240. p->nData += 1;
  164241. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  164242. p->iPos = 0;
  164243. }
  164244. }
  164245. if( iCol>=0 ){
  164246. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  164247. p->bContent = 1;
  164248. }else{
  164249. /* Append a new column value, if necessary */
  164250. assert( iCol>=p->iCol );
  164251. if( iCol!=p->iCol ){
  164252. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  164253. pPtr[p->nData++] = 0x01;
  164254. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  164255. p->iCol = iCol;
  164256. p->iPos = 0;
  164257. }else{
  164258. bNew = 1;
  164259. p->iCol = iPos = iCol;
  164260. }
  164261. }
  164262. /* Append the new position offset, if necessary */
  164263. if( bNew ){
  164264. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  164265. p->iPos = iPos;
  164266. }
  164267. }
  164268. }else{
  164269. /* This is a delete. Set the delete flag. */
  164270. p->bDel = 1;
  164271. }
  164272. nIncr += p->nData;
  164273. *pHash->pnByte += nIncr;
  164274. return SQLITE_OK;
  164275. }
  164276. /*
  164277. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  164278. ** each sorted in key order. This function merges the two lists into a
  164279. ** single list and returns a pointer to its first element.
  164280. */
  164281. static Fts5HashEntry *fts5HashEntryMerge(
  164282. Fts5HashEntry *pLeft,
  164283. Fts5HashEntry *pRight
  164284. ){
  164285. Fts5HashEntry *p1 = pLeft;
  164286. Fts5HashEntry *p2 = pRight;
  164287. Fts5HashEntry *pRet = 0;
  164288. Fts5HashEntry **ppOut = &pRet;
  164289. while( p1 || p2 ){
  164290. if( p1==0 ){
  164291. *ppOut = p2;
  164292. p2 = 0;
  164293. }else if( p2==0 ){
  164294. *ppOut = p1;
  164295. p1 = 0;
  164296. }else{
  164297. int i = 0;
  164298. while( p1->zKey[i]==p2->zKey[i] ) i++;
  164299. if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
  164300. /* p2 is smaller */
  164301. *ppOut = p2;
  164302. ppOut = &p2->pScanNext;
  164303. p2 = p2->pScanNext;
  164304. }else{
  164305. /* p1 is smaller */
  164306. *ppOut = p1;
  164307. ppOut = &p1->pScanNext;
  164308. p1 = p1->pScanNext;
  164309. }
  164310. *ppOut = 0;
  164311. }
  164312. }
  164313. return pRet;
  164314. }
  164315. /*
  164316. ** Extract all tokens from hash table iHash and link them into a list
  164317. ** in sorted order. The hash table is cleared before returning. It is
  164318. ** the responsibility of the caller to free the elements of the returned
  164319. ** list.
  164320. */
  164321. static int fts5HashEntrySort(
  164322. Fts5Hash *pHash,
  164323. const char *pTerm, int nTerm, /* Query prefix, if any */
  164324. Fts5HashEntry **ppSorted
  164325. ){
  164326. const int nMergeSlot = 32;
  164327. Fts5HashEntry **ap;
  164328. Fts5HashEntry *pList;
  164329. int iSlot;
  164330. int i;
  164331. *ppSorted = 0;
  164332. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  164333. if( !ap ) return SQLITE_NOMEM;
  164334. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  164335. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  164336. Fts5HashEntry *pIter;
  164337. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  164338. if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
  164339. Fts5HashEntry *pEntry = pIter;
  164340. pEntry->pScanNext = 0;
  164341. for(i=0; ap[i]; i++){
  164342. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  164343. ap[i] = 0;
  164344. }
  164345. ap[i] = pEntry;
  164346. }
  164347. }
  164348. }
  164349. pList = 0;
  164350. for(i=0; i<nMergeSlot; i++){
  164351. pList = fts5HashEntryMerge(pList, ap[i]);
  164352. }
  164353. pHash->nEntry = 0;
  164354. sqlite3_free(ap);
  164355. *ppSorted = pList;
  164356. return SQLITE_OK;
  164357. }
  164358. /*
  164359. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  164360. */
  164361. static int sqlite3Fts5HashQuery(
  164362. Fts5Hash *pHash, /* Hash table to query */
  164363. const char *pTerm, int nTerm, /* Query term */
  164364. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  164365. int *pnDoclist /* OUT: Size of doclist in bytes */
  164366. ){
  164367. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  164368. Fts5HashEntry *p;
  164369. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  164370. if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
  164371. }
  164372. if( p ){
  164373. fts5HashAddPoslistSize(pHash, p);
  164374. *ppDoclist = (const u8*)&p->zKey[nTerm+1];
  164375. *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
  164376. }else{
  164377. *ppDoclist = 0;
  164378. *pnDoclist = 0;
  164379. }
  164380. return SQLITE_OK;
  164381. }
  164382. static int sqlite3Fts5HashScanInit(
  164383. Fts5Hash *p, /* Hash table to query */
  164384. const char *pTerm, int nTerm /* Query prefix */
  164385. ){
  164386. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  164387. }
  164388. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  164389. assert( !sqlite3Fts5HashScanEof(p) );
  164390. p->pScan = p->pScan->pScanNext;
  164391. }
  164392. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  164393. return (p->pScan==0);
  164394. }
  164395. static void sqlite3Fts5HashScanEntry(
  164396. Fts5Hash *pHash,
  164397. const char **pzTerm, /* OUT: term (nul-terminated) */
  164398. const u8 **ppDoclist, /* OUT: pointer to doclist */
  164399. int *pnDoclist /* OUT: size of doclist in bytes */
  164400. ){
  164401. Fts5HashEntry *p;
  164402. if( (p = pHash->pScan) ){
  164403. int nTerm = (int)strlen(p->zKey);
  164404. fts5HashAddPoslistSize(pHash, p);
  164405. *pzTerm = p->zKey;
  164406. *ppDoclist = (const u8*)&p->zKey[nTerm+1];
  164407. *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
  164408. }else{
  164409. *pzTerm = 0;
  164410. *ppDoclist = 0;
  164411. *pnDoclist = 0;
  164412. }
  164413. }
  164414. /*
  164415. ** 2014 May 31
  164416. **
  164417. ** The author disclaims copyright to this source code. In place of
  164418. ** a legal notice, here is a blessing:
  164419. **
  164420. ** May you do good and not evil.
  164421. ** May you find forgiveness for yourself and forgive others.
  164422. ** May you share freely, never taking more than you give.
  164423. **
  164424. ******************************************************************************
  164425. **
  164426. ** Low level access to the FTS index stored in the database file. The
  164427. ** routines in this file file implement all read and write access to the
  164428. ** %_data table. Other parts of the system access this functionality via
  164429. ** the interface defined in fts5Int.h.
  164430. */
  164431. /* #include "fts5Int.h" */
  164432. /*
  164433. ** Overview:
  164434. **
  164435. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  164436. ** As well as the main term index, there may be up to 31 prefix indexes.
  164437. ** The format is similar to FTS3/4, except that:
  164438. **
  164439. ** * all segment b-tree leaf data is stored in fixed size page records
  164440. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  164441. ** taken to ensure it is possible to iterate in either direction through
  164442. ** the entries in a doclist, or to seek to a specific entry within a
  164443. ** doclist, without loading it into memory.
  164444. **
  164445. ** * large doclists that span many pages have associated "doclist index"
  164446. ** records that contain a copy of the first rowid on each page spanned by
  164447. ** the doclist. This is used to speed up seek operations, and merges of
  164448. ** large doclists with very small doclists.
  164449. **
  164450. ** * extra fields in the "structure record" record the state of ongoing
  164451. ** incremental merge operations.
  164452. **
  164453. */
  164454. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  164455. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  164456. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  164457. #define FTS5_MAIN_PREFIX '0'
  164458. #if FTS5_MAX_PREFIX_INDEXES > 31
  164459. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  164460. #endif
  164461. /*
  164462. ** Details:
  164463. **
  164464. ** The %_data table managed by this module,
  164465. **
  164466. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  164467. **
  164468. ** , contains the following 5 types of records. See the comments surrounding
  164469. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  164470. ** assigned to each fo them.
  164471. **
  164472. ** 1. Structure Records:
  164473. **
  164474. ** The set of segments that make up an index - the index structure - are
  164475. ** recorded in a single record within the %_data table. The record consists
  164476. ** of a single 32-bit configuration cookie value followed by a list of
  164477. ** SQLite varints. If the FTS table features more than one index (because
  164478. ** there are one or more prefix indexes), it is guaranteed that all share
  164479. ** the same cookie value.
  164480. **
  164481. ** Immediately following the configuration cookie, the record begins with
  164482. ** three varints:
  164483. **
  164484. ** + number of levels,
  164485. ** + total number of segments on all levels,
  164486. ** + value of write counter.
  164487. **
  164488. ** Then, for each level from 0 to nMax:
  164489. **
  164490. ** + number of input segments in ongoing merge.
  164491. ** + total number of segments in level.
  164492. ** + for each segment from oldest to newest:
  164493. ** + segment id (always > 0)
  164494. ** + first leaf page number (often 1, always greater than 0)
  164495. ** + final leaf page number
  164496. **
  164497. ** 2. The Averages Record:
  164498. **
  164499. ** A single record within the %_data table. The data is a list of varints.
  164500. ** The first value is the number of rows in the index. Then, for each column
  164501. ** from left to right, the total number of tokens in the column for all
  164502. ** rows of the table.
  164503. **
  164504. ** 3. Segment leaves:
  164505. **
  164506. ** TERM/DOCLIST FORMAT:
  164507. **
  164508. ** Most of each segment leaf is taken up by term/doclist data. The
  164509. ** general format of term/doclist, starting with the first term
  164510. ** on the leaf page, is:
  164511. **
  164512. ** varint : size of first term
  164513. ** blob: first term data
  164514. ** doclist: first doclist
  164515. ** zero-or-more {
  164516. ** varint: number of bytes in common with previous term
  164517. ** varint: number of bytes of new term data (nNew)
  164518. ** blob: nNew bytes of new term data
  164519. ** doclist: next doclist
  164520. ** }
  164521. **
  164522. ** doclist format:
  164523. **
  164524. ** varint: first rowid
  164525. ** poslist: first poslist
  164526. ** zero-or-more {
  164527. ** varint: rowid delta (always > 0)
  164528. ** poslist: next poslist
  164529. ** }
  164530. **
  164531. ** poslist format:
  164532. **
  164533. ** varint: size of poslist in bytes multiplied by 2, not including
  164534. ** this field. Plus 1 if this entry carries the "delete" flag.
  164535. ** collist: collist for column 0
  164536. ** zero-or-more {
  164537. ** 0x01 byte
  164538. ** varint: column number (I)
  164539. ** collist: collist for column I
  164540. ** }
  164541. **
  164542. ** collist format:
  164543. **
  164544. ** varint: first offset + 2
  164545. ** zero-or-more {
  164546. ** varint: offset delta + 2
  164547. ** }
  164548. **
  164549. ** PAGE FORMAT
  164550. **
  164551. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  164552. ** unsigned integer fields in big-endian format. They are:
  164553. **
  164554. ** * The byte offset of the first rowid on the page, if it exists
  164555. ** and occurs before the first term (otherwise 0).
  164556. **
  164557. ** * The byte offset of the start of the page footer. If the page
  164558. ** footer is 0 bytes in size, then this field is the same as the
  164559. ** size of the leaf page in bytes.
  164560. **
  164561. ** The page footer consists of a single varint for each term located
  164562. ** on the page. Each varint is the byte offset of the current term
  164563. ** within the page, delta-compressed against the previous value. In
  164564. ** other words, the first varint in the footer is the byte offset of
  164565. ** the first term, the second is the byte offset of the second less that
  164566. ** of the first, and so on.
  164567. **
  164568. ** The term/doclist format described above is accurate if the entire
  164569. ** term/doclist data fits on a single leaf page. If this is not the case,
  164570. ** the format is changed in two ways:
  164571. **
  164572. ** + if the first rowid on a page occurs before the first term, it
  164573. ** is stored as a literal value:
  164574. **
  164575. ** varint: first rowid
  164576. **
  164577. ** + the first term on each page is stored in the same way as the
  164578. ** very first term of the segment:
  164579. **
  164580. ** varint : size of first term
  164581. ** blob: first term data
  164582. **
  164583. ** 5. Segment doclist indexes:
  164584. **
  164585. ** Doclist indexes are themselves b-trees, however they usually consist of
  164586. ** a single leaf record only. The format of each doclist index leaf page
  164587. ** is:
  164588. **
  164589. ** * Flags byte. Bits are:
  164590. ** 0x01: Clear if leaf is also the root page, otherwise set.
  164591. **
  164592. ** * Page number of fts index leaf page. As a varint.
  164593. **
  164594. ** * First rowid on page indicated by previous field. As a varint.
  164595. **
  164596. ** * A list of varints, one for each subsequent termless page. A
  164597. ** positive delta if the termless page contains at least one rowid,
  164598. ** or an 0x00 byte otherwise.
  164599. **
  164600. ** Internal doclist index nodes are:
  164601. **
  164602. ** * Flags byte. Bits are:
  164603. ** 0x01: Clear for root page, otherwise set.
  164604. **
  164605. ** * Page number of first child page. As a varint.
  164606. **
  164607. ** * Copy of first rowid on page indicated by previous field. As a varint.
  164608. **
  164609. ** * A list of delta-encoded varints - the first rowid on each subsequent
  164610. ** child page.
  164611. **
  164612. */
  164613. /*
  164614. ** Rowids for the averages and structure records in the %_data table.
  164615. */
  164616. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  164617. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  164618. /*
  164619. ** Macros determining the rowids used by segment leaves and dlidx leaves
  164620. ** and nodes. All nodes and leaves are stored in the %_data table with large
  164621. ** positive rowids.
  164622. **
  164623. ** Each segment has a unique non-zero 16-bit id.
  164624. **
  164625. ** The rowid for each segment leaf is found by passing the segment id and
  164626. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  164627. ** sequentially starting from 1.
  164628. */
  164629. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  164630. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  164631. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  164632. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  164633. #define fts5_dri(segid, dlidx, height, pgno) ( \
  164634. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  164635. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  164636. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  164637. ((i64)(pgno)) \
  164638. )
  164639. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  164640. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  164641. /*
  164642. ** Maximum segments permitted in a single index
  164643. */
  164644. #define FTS5_MAX_SEGMENT 2000
  164645. #ifdef SQLITE_DEBUG
  164646. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  164647. #endif
  164648. /*
  164649. ** Each time a blob is read from the %_data table, it is padded with this
  164650. ** many zero bytes. This makes it easier to decode the various record formats
  164651. ** without overreading if the records are corrupt.
  164652. */
  164653. #define FTS5_DATA_ZERO_PADDING 8
  164654. #define FTS5_DATA_PADDING 20
  164655. typedef struct Fts5Data Fts5Data;
  164656. typedef struct Fts5DlidxIter Fts5DlidxIter;
  164657. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  164658. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  164659. typedef struct Fts5Iter Fts5Iter;
  164660. typedef struct Fts5PageWriter Fts5PageWriter;
  164661. typedef struct Fts5SegIter Fts5SegIter;
  164662. typedef struct Fts5DoclistIter Fts5DoclistIter;
  164663. typedef struct Fts5SegWriter Fts5SegWriter;
  164664. typedef struct Fts5Structure Fts5Structure;
  164665. typedef struct Fts5StructureLevel Fts5StructureLevel;
  164666. typedef struct Fts5StructureSegment Fts5StructureSegment;
  164667. struct Fts5Data {
  164668. u8 *p; /* Pointer to buffer containing record */
  164669. int nn; /* Size of record in bytes */
  164670. int szLeaf; /* Size of leaf without page-index */
  164671. };
  164672. /*
  164673. ** One object per %_data table.
  164674. */
  164675. struct Fts5Index {
  164676. Fts5Config *pConfig; /* Virtual table configuration */
  164677. char *zDataTbl; /* Name of %_data table */
  164678. int nWorkUnit; /* Leaf pages in a "unit" of work */
  164679. /*
  164680. ** Variables related to the accumulation of tokens and doclists within the
  164681. ** in-memory hash tables before they are flushed to disk.
  164682. */
  164683. Fts5Hash *pHash; /* Hash table for in-memory data */
  164684. int nPendingData; /* Current bytes of pending data */
  164685. i64 iWriteRowid; /* Rowid for current doc being written */
  164686. int bDelete; /* Current write is a delete */
  164687. /* Error state. */
  164688. int rc; /* Current error code */
  164689. /* State used by the fts5DataXXX() functions. */
  164690. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  164691. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  164692. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  164693. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  164694. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  164695. sqlite3_stmt *pIdxSelect;
  164696. int nRead; /* Total number of blocks read */
  164697. sqlite3_stmt *pDataVersion;
  164698. i64 iStructVersion; /* data_version when pStruct read */
  164699. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  164700. };
  164701. struct Fts5DoclistIter {
  164702. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  164703. /* Output variables. aPoslist==0 at EOF */
  164704. i64 iRowid;
  164705. u8 *aPoslist;
  164706. int nPoslist;
  164707. int nSize;
  164708. };
  164709. /*
  164710. ** The contents of the "structure" record for each index are represented
  164711. ** using an Fts5Structure record in memory. Which uses instances of the
  164712. ** other Fts5StructureXXX types as components.
  164713. */
  164714. struct Fts5StructureSegment {
  164715. int iSegid; /* Segment id */
  164716. int pgnoFirst; /* First leaf page number in segment */
  164717. int pgnoLast; /* Last leaf page number in segment */
  164718. };
  164719. struct Fts5StructureLevel {
  164720. int nMerge; /* Number of segments in incr-merge */
  164721. int nSeg; /* Total number of segments on level */
  164722. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  164723. };
  164724. struct Fts5Structure {
  164725. int nRef; /* Object reference count */
  164726. u64 nWriteCounter; /* Total leaves written to level 0 */
  164727. int nSegment; /* Total segments in this structure */
  164728. int nLevel; /* Number of levels in this index */
  164729. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  164730. };
  164731. /*
  164732. ** An object of type Fts5SegWriter is used to write to segments.
  164733. */
  164734. struct Fts5PageWriter {
  164735. int pgno; /* Page number for this page */
  164736. int iPrevPgidx; /* Previous value written into pgidx */
  164737. Fts5Buffer buf; /* Buffer containing leaf data */
  164738. Fts5Buffer pgidx; /* Buffer containing page-index */
  164739. Fts5Buffer term; /* Buffer containing previous term on page */
  164740. };
  164741. struct Fts5DlidxWriter {
  164742. int pgno; /* Page number for this page */
  164743. int bPrevValid; /* True if iPrev is valid */
  164744. i64 iPrev; /* Previous rowid value written to page */
  164745. Fts5Buffer buf; /* Buffer containing page data */
  164746. };
  164747. struct Fts5SegWriter {
  164748. int iSegid; /* Segid to write to */
  164749. Fts5PageWriter writer; /* PageWriter object */
  164750. i64 iPrevRowid; /* Previous rowid written to current leaf */
  164751. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  164752. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  164753. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  164754. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  164755. int nLeafWritten; /* Number of leaf pages written */
  164756. int nEmpty; /* Number of contiguous term-less nodes */
  164757. int nDlidx; /* Allocated size of aDlidx[] array */
  164758. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  164759. /* Values to insert into the %_idx table */
  164760. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  164761. int iBtPage; /* Page number corresponding to btterm */
  164762. };
  164763. typedef struct Fts5CResult Fts5CResult;
  164764. struct Fts5CResult {
  164765. u16 iFirst; /* aSeg[] index of firstest iterator */
  164766. u8 bTermEq; /* True if the terms are equal */
  164767. };
  164768. /*
  164769. ** Object for iterating through a single segment, visiting each term/rowid
  164770. ** pair in the segment.
  164771. **
  164772. ** pSeg:
  164773. ** The segment to iterate through.
  164774. **
  164775. ** iLeafPgno:
  164776. ** Current leaf page number within segment.
  164777. **
  164778. ** iLeafOffset:
  164779. ** Byte offset within the current leaf that is the first byte of the
  164780. ** position list data (one byte passed the position-list size field).
  164781. ** rowid field of the current entry. Usually this is the size field of the
  164782. ** position list data. The exception is if the rowid for the current entry
  164783. ** is the last thing on the leaf page.
  164784. **
  164785. ** pLeaf:
  164786. ** Buffer containing current leaf page data. Set to NULL at EOF.
  164787. **
  164788. ** iTermLeafPgno, iTermLeafOffset:
  164789. ** Leaf page number containing the last term read from the segment. And
  164790. ** the offset immediately following the term data.
  164791. **
  164792. ** flags:
  164793. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  164794. **
  164795. ** FTS5_SEGITER_ONETERM:
  164796. ** If set, set the iterator to point to EOF after the current doclist
  164797. ** has been exhausted. Do not proceed to the next term in the segment.
  164798. **
  164799. ** FTS5_SEGITER_REVERSE:
  164800. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  164801. ** it is set, iterate through rowid in descending order instead of the
  164802. ** default ascending order.
  164803. **
  164804. ** iRowidOffset/nRowidOffset/aRowidOffset:
  164805. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  164806. **
  164807. ** For each rowid on the page corresponding to the current term, the
  164808. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  164809. ** start of the "position-list-size" field within the page.
  164810. **
  164811. ** iTermIdx:
  164812. ** Index of current term on iTermLeafPgno.
  164813. */
  164814. struct Fts5SegIter {
  164815. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  164816. int flags; /* Mask of configuration flags */
  164817. int iLeafPgno; /* Current leaf page number */
  164818. Fts5Data *pLeaf; /* Current leaf data */
  164819. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  164820. int iLeafOffset; /* Byte offset within current leaf */
  164821. /* Next method */
  164822. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  164823. /* The page and offset from which the current term was read. The offset
  164824. ** is the offset of the first rowid in the current doclist. */
  164825. int iTermLeafPgno;
  164826. int iTermLeafOffset;
  164827. int iPgidxOff; /* Next offset in pgidx */
  164828. int iEndofDoclist;
  164829. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  164830. int iRowidOffset; /* Current entry in aRowidOffset[] */
  164831. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  164832. int *aRowidOffset; /* Array of offset to rowid fields */
  164833. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  164834. /* Variables populated based on current entry. */
  164835. Fts5Buffer term; /* Current term */
  164836. i64 iRowid; /* Current rowid */
  164837. int nPos; /* Number of bytes in current position list */
  164838. u8 bDel; /* True if the delete flag is set */
  164839. };
  164840. /*
  164841. ** Argument is a pointer to an Fts5Data structure that contains a
  164842. ** leaf page.
  164843. */
  164844. #define ASSERT_SZLEAF_OK(x) assert( \
  164845. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  164846. )
  164847. #define FTS5_SEGITER_ONETERM 0x01
  164848. #define FTS5_SEGITER_REVERSE 0x02
  164849. /*
  164850. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  164851. ** page. This macro evaluates to true if the leaf contains no terms, or
  164852. ** false if it contains at least one term.
  164853. */
  164854. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  164855. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  164856. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  164857. /*
  164858. ** Object for iterating through the merged results of one or more segments,
  164859. ** visiting each term/rowid pair in the merged data.
  164860. **
  164861. ** nSeg is always a power of two greater than or equal to the number of
  164862. ** segments that this object is merging data from. Both the aSeg[] and
  164863. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  164864. ** with zeroed objects - these are handled as if they were iterators opened
  164865. ** on empty segments.
  164866. **
  164867. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  164868. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  164869. ** comparison in this context is the index of the iterator that currently
  164870. ** points to the smaller term/rowid combination. Iterators at EOF are
  164871. ** considered to be greater than all other iterators.
  164872. **
  164873. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  164874. ** the smallest key overall. aFirst[0] is unused.
  164875. **
  164876. ** poslist:
  164877. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  164878. ** There is no way to tell if this is populated or not.
  164879. */
  164880. struct Fts5Iter {
  164881. Fts5IndexIter base; /* Base class containing output vars */
  164882. Fts5Index *pIndex; /* Index that owns this iterator */
  164883. Fts5Structure *pStruct; /* Database structure for this iterator */
  164884. Fts5Buffer poslist; /* Buffer containing current poslist */
  164885. Fts5Colset *pColset; /* Restrict matches to these columns */
  164886. /* Invoked to set output variables. */
  164887. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  164888. int nSeg; /* Size of aSeg[] array */
  164889. int bRev; /* True to iterate in reverse order */
  164890. u8 bSkipEmpty; /* True to skip deleted entries */
  164891. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  164892. Fts5CResult *aFirst; /* Current merge state (see above) */
  164893. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  164894. };
  164895. /*
  164896. ** An instance of the following type is used to iterate through the contents
  164897. ** of a doclist-index record.
  164898. **
  164899. ** pData:
  164900. ** Record containing the doclist-index data.
  164901. **
  164902. ** bEof:
  164903. ** Set to true once iterator has reached EOF.
  164904. **
  164905. ** iOff:
  164906. ** Set to the current offset within record pData.
  164907. */
  164908. struct Fts5DlidxLvl {
  164909. Fts5Data *pData; /* Data for current page of this level */
  164910. int iOff; /* Current offset into pData */
  164911. int bEof; /* At EOF already */
  164912. int iFirstOff; /* Used by reverse iterators */
  164913. /* Output variables */
  164914. int iLeafPgno; /* Page number of current leaf page */
  164915. i64 iRowid; /* First rowid on leaf iLeafPgno */
  164916. };
  164917. struct Fts5DlidxIter {
  164918. int nLvl;
  164919. int iSegid;
  164920. Fts5DlidxLvl aLvl[1];
  164921. };
  164922. static void fts5PutU16(u8 *aOut, u16 iVal){
  164923. aOut[0] = (iVal>>8);
  164924. aOut[1] = (iVal&0xFF);
  164925. }
  164926. static u16 fts5GetU16(const u8 *aIn){
  164927. return ((u16)aIn[0] << 8) + aIn[1];
  164928. }
  164929. /*
  164930. ** Allocate and return a buffer at least nByte bytes in size.
  164931. **
  164932. ** If an OOM error is encountered, return NULL and set the error code in
  164933. ** the Fts5Index handle passed as the first argument.
  164934. */
  164935. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  164936. return sqlite3Fts5MallocZero(&p->rc, nByte);
  164937. }
  164938. /*
  164939. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  164940. **
  164941. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  164942. ** +ve if pRight is smaller than pLeft. In other words:
  164943. **
  164944. ** res = *pLeft - *pRight
  164945. */
  164946. #ifdef SQLITE_DEBUG
  164947. static int fts5BufferCompareBlob(
  164948. Fts5Buffer *pLeft, /* Left hand side of comparison */
  164949. const u8 *pRight, int nRight /* Right hand side of comparison */
  164950. ){
  164951. int nCmp = MIN(pLeft->n, nRight);
  164952. int res = memcmp(pLeft->p, pRight, nCmp);
  164953. return (res==0 ? (pLeft->n - nRight) : res);
  164954. }
  164955. #endif
  164956. /*
  164957. ** Compare the contents of the two buffers using memcmp(). If one buffer
  164958. ** is a prefix of the other, it is considered the lesser.
  164959. **
  164960. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  164961. ** +ve if pRight is smaller than pLeft. In other words:
  164962. **
  164963. ** res = *pLeft - *pRight
  164964. */
  164965. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  164966. int nCmp = MIN(pLeft->n, pRight->n);
  164967. int res = memcmp(pLeft->p, pRight->p, nCmp);
  164968. return (res==0 ? (pLeft->n - pRight->n) : res);
  164969. }
  164970. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  164971. int ret;
  164972. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  164973. return ret;
  164974. }
  164975. /*
  164976. ** Close the read-only blob handle, if it is open.
  164977. */
  164978. static void fts5CloseReader(Fts5Index *p){
  164979. if( p->pReader ){
  164980. sqlite3_blob *pReader = p->pReader;
  164981. p->pReader = 0;
  164982. sqlite3_blob_close(pReader);
  164983. }
  164984. }
  164985. /*
  164986. ** Retrieve a record from the %_data table.
  164987. **
  164988. ** If an error occurs, NULL is returned and an error left in the
  164989. ** Fts5Index object.
  164990. */
  164991. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  164992. Fts5Data *pRet = 0;
  164993. if( p->rc==SQLITE_OK ){
  164994. int rc = SQLITE_OK;
  164995. if( p->pReader ){
  164996. /* This call may return SQLITE_ABORT if there has been a savepoint
  164997. ** rollback since it was last used. In this case a new blob handle
  164998. ** is required. */
  164999. sqlite3_blob *pBlob = p->pReader;
  165000. p->pReader = 0;
  165001. rc = sqlite3_blob_reopen(pBlob, iRowid);
  165002. assert( p->pReader==0 );
  165003. p->pReader = pBlob;
  165004. if( rc!=SQLITE_OK ){
  165005. fts5CloseReader(p);
  165006. }
  165007. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  165008. }
  165009. /* If the blob handle is not open at this point, open it and seek
  165010. ** to the requested entry. */
  165011. if( p->pReader==0 && rc==SQLITE_OK ){
  165012. Fts5Config *pConfig = p->pConfig;
  165013. rc = sqlite3_blob_open(pConfig->db,
  165014. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  165015. );
  165016. }
  165017. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  165018. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  165019. ** All the reasons those functions might return SQLITE_ERROR - missing
  165020. ** table, missing row, non-blob/text in block column - indicate
  165021. ** backing store corruption. */
  165022. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  165023. if( rc==SQLITE_OK ){
  165024. u8 *aOut = 0; /* Read blob data into this buffer */
  165025. int nByte = sqlite3_blob_bytes(p->pReader);
  165026. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  165027. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  165028. if( pRet ){
  165029. pRet->nn = nByte;
  165030. aOut = pRet->p = (u8*)&pRet[1];
  165031. }else{
  165032. rc = SQLITE_NOMEM;
  165033. }
  165034. if( rc==SQLITE_OK ){
  165035. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  165036. }
  165037. if( rc!=SQLITE_OK ){
  165038. sqlite3_free(pRet);
  165039. pRet = 0;
  165040. }else{
  165041. /* TODO1: Fix this */
  165042. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  165043. }
  165044. }
  165045. p->rc = rc;
  165046. p->nRead++;
  165047. }
  165048. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  165049. return pRet;
  165050. }
  165051. /*
  165052. ** Release a reference to data record returned by an earlier call to
  165053. ** fts5DataRead().
  165054. */
  165055. static void fts5DataRelease(Fts5Data *pData){
  165056. sqlite3_free(pData);
  165057. }
  165058. static int fts5IndexPrepareStmt(
  165059. Fts5Index *p,
  165060. sqlite3_stmt **ppStmt,
  165061. char *zSql
  165062. ){
  165063. if( p->rc==SQLITE_OK ){
  165064. if( zSql ){
  165065. p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
  165066. }else{
  165067. p->rc = SQLITE_NOMEM;
  165068. }
  165069. }
  165070. sqlite3_free(zSql);
  165071. return p->rc;
  165072. }
  165073. /*
  165074. ** INSERT OR REPLACE a record into the %_data table.
  165075. */
  165076. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  165077. if( p->rc!=SQLITE_OK ) return;
  165078. if( p->pWriter==0 ){
  165079. Fts5Config *pConfig = p->pConfig;
  165080. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  165081. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  165082. pConfig->zDb, pConfig->zName
  165083. ));
  165084. if( p->rc ) return;
  165085. }
  165086. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  165087. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  165088. sqlite3_step(p->pWriter);
  165089. p->rc = sqlite3_reset(p->pWriter);
  165090. }
  165091. /*
  165092. ** Execute the following SQL:
  165093. **
  165094. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  165095. */
  165096. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  165097. if( p->rc!=SQLITE_OK ) return;
  165098. if( p->pDeleter==0 ){
  165099. int rc;
  165100. Fts5Config *pConfig = p->pConfig;
  165101. char *zSql = sqlite3_mprintf(
  165102. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  165103. pConfig->zDb, pConfig->zName
  165104. );
  165105. if( zSql==0 ){
  165106. rc = SQLITE_NOMEM;
  165107. }else{
  165108. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
  165109. sqlite3_free(zSql);
  165110. }
  165111. if( rc!=SQLITE_OK ){
  165112. p->rc = rc;
  165113. return;
  165114. }
  165115. }
  165116. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  165117. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  165118. sqlite3_step(p->pDeleter);
  165119. p->rc = sqlite3_reset(p->pDeleter);
  165120. }
  165121. /*
  165122. ** Remove all records associated with segment iSegid.
  165123. */
  165124. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  165125. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  165126. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  165127. fts5DataDelete(p, iFirst, iLast);
  165128. if( p->pIdxDeleter==0 ){
  165129. Fts5Config *pConfig = p->pConfig;
  165130. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  165131. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  165132. pConfig->zDb, pConfig->zName
  165133. ));
  165134. }
  165135. if( p->rc==SQLITE_OK ){
  165136. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  165137. sqlite3_step(p->pIdxDeleter);
  165138. p->rc = sqlite3_reset(p->pIdxDeleter);
  165139. }
  165140. }
  165141. /*
  165142. ** Release a reference to an Fts5Structure object returned by an earlier
  165143. ** call to fts5StructureRead() or fts5StructureDecode().
  165144. */
  165145. static void fts5StructureRelease(Fts5Structure *pStruct){
  165146. if( pStruct && 0>=(--pStruct->nRef) ){
  165147. int i;
  165148. assert( pStruct->nRef==0 );
  165149. for(i=0; i<pStruct->nLevel; i++){
  165150. sqlite3_free(pStruct->aLevel[i].aSeg);
  165151. }
  165152. sqlite3_free(pStruct);
  165153. }
  165154. }
  165155. static void fts5StructureRef(Fts5Structure *pStruct){
  165156. pStruct->nRef++;
  165157. }
  165158. /*
  165159. ** Deserialize and return the structure record currently stored in serialized
  165160. ** form within buffer pData/nData.
  165161. **
  165162. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  165163. ** are over-allocated by one slot. This allows the structure contents
  165164. ** to be more easily edited.
  165165. **
  165166. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  165167. ** returned. Otherwise, *ppOut is set to point to the new object and
  165168. ** SQLITE_OK returned.
  165169. */
  165170. static int fts5StructureDecode(
  165171. const u8 *pData, /* Buffer containing serialized structure */
  165172. int nData, /* Size of buffer pData in bytes */
  165173. int *piCookie, /* Configuration cookie value */
  165174. Fts5Structure **ppOut /* OUT: Deserialized object */
  165175. ){
  165176. int rc = SQLITE_OK;
  165177. int i = 0;
  165178. int iLvl;
  165179. int nLevel = 0;
  165180. int nSegment = 0;
  165181. int nByte; /* Bytes of space to allocate at pRet */
  165182. Fts5Structure *pRet = 0; /* Structure object to return */
  165183. /* Grab the cookie value */
  165184. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  165185. i = 4;
  165186. /* Read the total number of levels and segments from the start of the
  165187. ** structure record. */
  165188. i += fts5GetVarint32(&pData[i], nLevel);
  165189. i += fts5GetVarint32(&pData[i], nSegment);
  165190. nByte = (
  165191. sizeof(Fts5Structure) + /* Main structure */
  165192. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  165193. );
  165194. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  165195. if( pRet ){
  165196. pRet->nRef = 1;
  165197. pRet->nLevel = nLevel;
  165198. pRet->nSegment = nSegment;
  165199. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  165200. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  165201. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  165202. int nTotal = 0;
  165203. int iSeg;
  165204. if( i>=nData ){
  165205. rc = FTS5_CORRUPT;
  165206. }else{
  165207. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  165208. i += fts5GetVarint32(&pData[i], nTotal);
  165209. assert( nTotal>=pLvl->nMerge );
  165210. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  165211. nTotal * sizeof(Fts5StructureSegment)
  165212. );
  165213. }
  165214. if( rc==SQLITE_OK ){
  165215. pLvl->nSeg = nTotal;
  165216. for(iSeg=0; iSeg<nTotal; iSeg++){
  165217. if( i>=nData ){
  165218. rc = FTS5_CORRUPT;
  165219. break;
  165220. }
  165221. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  165222. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  165223. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  165224. }
  165225. }
  165226. }
  165227. if( rc!=SQLITE_OK ){
  165228. fts5StructureRelease(pRet);
  165229. pRet = 0;
  165230. }
  165231. }
  165232. *ppOut = pRet;
  165233. return rc;
  165234. }
  165235. /*
  165236. **
  165237. */
  165238. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  165239. if( *pRc==SQLITE_OK ){
  165240. Fts5Structure *pStruct = *ppStruct;
  165241. int nLevel = pStruct->nLevel;
  165242. int nByte = (
  165243. sizeof(Fts5Structure) + /* Main structure */
  165244. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  165245. );
  165246. pStruct = sqlite3_realloc(pStruct, nByte);
  165247. if( pStruct ){
  165248. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  165249. pStruct->nLevel++;
  165250. *ppStruct = pStruct;
  165251. }else{
  165252. *pRc = SQLITE_NOMEM;
  165253. }
  165254. }
  165255. }
  165256. /*
  165257. ** Extend level iLvl so that there is room for at least nExtra more
  165258. ** segments.
  165259. */
  165260. static void fts5StructureExtendLevel(
  165261. int *pRc,
  165262. Fts5Structure *pStruct,
  165263. int iLvl,
  165264. int nExtra,
  165265. int bInsert
  165266. ){
  165267. if( *pRc==SQLITE_OK ){
  165268. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  165269. Fts5StructureSegment *aNew;
  165270. int nByte;
  165271. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  165272. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  165273. if( aNew ){
  165274. if( bInsert==0 ){
  165275. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  165276. }else{
  165277. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  165278. memmove(&aNew[nExtra], aNew, nMove);
  165279. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  165280. }
  165281. pLvl->aSeg = aNew;
  165282. }else{
  165283. *pRc = SQLITE_NOMEM;
  165284. }
  165285. }
  165286. }
  165287. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  165288. Fts5Structure *pRet = 0;
  165289. Fts5Config *pConfig = p->pConfig;
  165290. int iCookie; /* Configuration cookie */
  165291. Fts5Data *pData;
  165292. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  165293. if( p->rc==SQLITE_OK ){
  165294. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  165295. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  165296. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  165297. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  165298. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  165299. }
  165300. fts5DataRelease(pData);
  165301. if( p->rc!=SQLITE_OK ){
  165302. fts5StructureRelease(pRet);
  165303. pRet = 0;
  165304. }
  165305. }
  165306. return pRet;
  165307. }
  165308. static i64 fts5IndexDataVersion(Fts5Index *p){
  165309. i64 iVersion = 0;
  165310. if( p->rc==SQLITE_OK ){
  165311. if( p->pDataVersion==0 ){
  165312. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  165313. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  165314. );
  165315. if( p->rc ) return 0;
  165316. }
  165317. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  165318. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  165319. }
  165320. p->rc = sqlite3_reset(p->pDataVersion);
  165321. }
  165322. return iVersion;
  165323. }
  165324. /*
  165325. ** Read, deserialize and return the structure record.
  165326. **
  165327. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  165328. ** are over-allocated as described for function fts5StructureDecode()
  165329. ** above.
  165330. **
  165331. ** If an error occurs, NULL is returned and an error code left in the
  165332. ** Fts5Index handle. If an error has already occurred when this function
  165333. ** is called, it is a no-op.
  165334. */
  165335. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  165336. if( p->pStruct==0 ){
  165337. p->iStructVersion = fts5IndexDataVersion(p);
  165338. if( p->rc==SQLITE_OK ){
  165339. p->pStruct = fts5StructureReadUncached(p);
  165340. }
  165341. }
  165342. #if 0
  165343. else{
  165344. Fts5Structure *pTest = fts5StructureReadUncached(p);
  165345. if( pTest ){
  165346. int i, j;
  165347. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  165348. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  165349. for(i=0; i<pTest->nLevel; i++){
  165350. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  165351. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  165352. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  165353. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  165354. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  165355. assert_nc( p1->iSegid==p2->iSegid );
  165356. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  165357. assert_nc( p1->pgnoLast==p2->pgnoLast );
  165358. }
  165359. }
  165360. fts5StructureRelease(pTest);
  165361. }
  165362. }
  165363. #endif
  165364. if( p->rc!=SQLITE_OK ) return 0;
  165365. assert( p->iStructVersion!=0 );
  165366. assert( p->pStruct!=0 );
  165367. fts5StructureRef(p->pStruct);
  165368. return p->pStruct;
  165369. }
  165370. static void fts5StructureInvalidate(Fts5Index *p){
  165371. if( p->pStruct ){
  165372. fts5StructureRelease(p->pStruct);
  165373. p->pStruct = 0;
  165374. }
  165375. }
  165376. /*
  165377. ** Return the total number of segments in index structure pStruct. This
  165378. ** function is only ever used as part of assert() conditions.
  165379. */
  165380. #ifdef SQLITE_DEBUG
  165381. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  165382. int nSegment = 0; /* Total number of segments */
  165383. if( pStruct ){
  165384. int iLvl; /* Used to iterate through levels */
  165385. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  165386. nSegment += pStruct->aLevel[iLvl].nSeg;
  165387. }
  165388. }
  165389. return nSegment;
  165390. }
  165391. #endif
  165392. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  165393. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  165394. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  165395. (pBuf)->n += nBlob; \
  165396. }
  165397. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  165398. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  165399. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  165400. }
  165401. /*
  165402. ** Serialize and store the "structure" record.
  165403. **
  165404. ** If an error occurs, leave an error code in the Fts5Index object. If an
  165405. ** error has already occurred, this function is a no-op.
  165406. */
  165407. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  165408. if( p->rc==SQLITE_OK ){
  165409. Fts5Buffer buf; /* Buffer to serialize record into */
  165410. int iLvl; /* Used to iterate through levels */
  165411. int iCookie; /* Cookie value to store */
  165412. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  165413. memset(&buf, 0, sizeof(Fts5Buffer));
  165414. /* Append the current configuration cookie */
  165415. iCookie = p->pConfig->iCookie;
  165416. if( iCookie<0 ) iCookie = 0;
  165417. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  165418. sqlite3Fts5Put32(buf.p, iCookie);
  165419. buf.n = 4;
  165420. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  165421. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  165422. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  165423. }
  165424. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  165425. int iSeg; /* Used to iterate through segments */
  165426. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  165427. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  165428. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  165429. assert( pLvl->nMerge<=pLvl->nSeg );
  165430. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  165431. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  165432. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  165433. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  165434. }
  165435. }
  165436. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  165437. fts5BufferFree(&buf);
  165438. }
  165439. }
  165440. #if 0
  165441. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  165442. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  165443. int rc = SQLITE_OK;
  165444. Fts5Buffer buf;
  165445. memset(&buf, 0, sizeof(buf));
  165446. fts5DebugStructure(&rc, &buf, pStruct);
  165447. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  165448. fflush(stdout);
  165449. fts5BufferFree(&buf);
  165450. }
  165451. #else
  165452. # define fts5PrintStructure(x,y)
  165453. #endif
  165454. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  165455. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  165456. }
  165457. /*
  165458. ** Return a copy of index structure pStruct. Except, promote as many
  165459. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  165460. ** returned.
  165461. */
  165462. static void fts5StructurePromoteTo(
  165463. Fts5Index *p,
  165464. int iPromote,
  165465. int szPromote,
  165466. Fts5Structure *pStruct
  165467. ){
  165468. int il, is;
  165469. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  165470. if( pOut->nMerge==0 ){
  165471. for(il=iPromote+1; il<pStruct->nLevel; il++){
  165472. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  165473. if( pLvl->nMerge ) return;
  165474. for(is=pLvl->nSeg-1; is>=0; is--){
  165475. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  165476. if( sz>szPromote ) return;
  165477. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  165478. if( p->rc ) return;
  165479. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  165480. pOut->nSeg++;
  165481. pLvl->nSeg--;
  165482. }
  165483. }
  165484. }
  165485. }
  165486. /*
  165487. ** A new segment has just been written to level iLvl of index structure
  165488. ** pStruct. This function determines if any segments should be promoted
  165489. ** as a result. Segments are promoted in two scenarios:
  165490. **
  165491. ** a) If the segment just written is smaller than one or more segments
  165492. ** within the previous populated level, it is promoted to the previous
  165493. ** populated level.
  165494. **
  165495. ** b) If the segment just written is larger than the newest segment on
  165496. ** the next populated level, then that segment, and any other adjacent
  165497. ** segments that are also smaller than the one just written, are
  165498. ** promoted.
  165499. **
  165500. ** If one or more segments are promoted, the structure object is updated
  165501. ** to reflect this.
  165502. */
  165503. static void fts5StructurePromote(
  165504. Fts5Index *p, /* FTS5 backend object */
  165505. int iLvl, /* Index level just updated */
  165506. Fts5Structure *pStruct /* Index structure */
  165507. ){
  165508. if( p->rc==SQLITE_OK ){
  165509. int iTst;
  165510. int iPromote = -1;
  165511. int szPromote = 0; /* Promote anything this size or smaller */
  165512. Fts5StructureSegment *pSeg; /* Segment just written */
  165513. int szSeg; /* Size of segment just written */
  165514. int nSeg = pStruct->aLevel[iLvl].nSeg;
  165515. if( nSeg==0 ) return;
  165516. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  165517. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  165518. /* Check for condition (a) */
  165519. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  165520. if( iTst>=0 ){
  165521. int i;
  165522. int szMax = 0;
  165523. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  165524. assert( pTst->nMerge==0 );
  165525. for(i=0; i<pTst->nSeg; i++){
  165526. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  165527. if( sz>szMax ) szMax = sz;
  165528. }
  165529. if( szMax>=szSeg ){
  165530. /* Condition (a) is true. Promote the newest segment on level
  165531. ** iLvl to level iTst. */
  165532. iPromote = iTst;
  165533. szPromote = szMax;
  165534. }
  165535. }
  165536. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  165537. ** is a no-op if it is not. */
  165538. if( iPromote<0 ){
  165539. iPromote = iLvl;
  165540. szPromote = szSeg;
  165541. }
  165542. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  165543. }
  165544. }
  165545. /*
  165546. ** Advance the iterator passed as the only argument. If the end of the
  165547. ** doclist-index page is reached, return non-zero.
  165548. */
  165549. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  165550. Fts5Data *pData = pLvl->pData;
  165551. if( pLvl->iOff==0 ){
  165552. assert( pLvl->bEof==0 );
  165553. pLvl->iOff = 1;
  165554. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  165555. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  165556. pLvl->iFirstOff = pLvl->iOff;
  165557. }else{
  165558. int iOff;
  165559. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  165560. if( pData->p[iOff] ) break;
  165561. }
  165562. if( iOff<pData->nn ){
  165563. i64 iVal;
  165564. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  165565. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  165566. pLvl->iRowid += iVal;
  165567. pLvl->iOff = iOff;
  165568. }else{
  165569. pLvl->bEof = 1;
  165570. }
  165571. }
  165572. return pLvl->bEof;
  165573. }
  165574. /*
  165575. ** Advance the iterator passed as the only argument.
  165576. */
  165577. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  165578. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  165579. assert( iLvl<pIter->nLvl );
  165580. if( fts5DlidxLvlNext(pLvl) ){
  165581. if( (iLvl+1) < pIter->nLvl ){
  165582. fts5DlidxIterNextR(p, pIter, iLvl+1);
  165583. if( pLvl[1].bEof==0 ){
  165584. fts5DataRelease(pLvl->pData);
  165585. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  165586. pLvl->pData = fts5DataRead(p,
  165587. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  165588. );
  165589. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  165590. }
  165591. }
  165592. }
  165593. return pIter->aLvl[0].bEof;
  165594. }
  165595. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  165596. return fts5DlidxIterNextR(p, pIter, 0);
  165597. }
  165598. /*
  165599. ** The iterator passed as the first argument has the following fields set
  165600. ** as follows. This function sets up the rest of the iterator so that it
  165601. ** points to the first rowid in the doclist-index.
  165602. **
  165603. ** pData:
  165604. ** pointer to doclist-index record,
  165605. **
  165606. ** When this function is called pIter->iLeafPgno is the page number the
  165607. ** doclist is associated with (the one featuring the term).
  165608. */
  165609. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  165610. int i;
  165611. for(i=0; i<pIter->nLvl; i++){
  165612. fts5DlidxLvlNext(&pIter->aLvl[i]);
  165613. }
  165614. return pIter->aLvl[0].bEof;
  165615. }
  165616. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  165617. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  165618. }
  165619. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  165620. int i;
  165621. /* Advance each level to the last entry on the last page */
  165622. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  165623. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  165624. while( fts5DlidxLvlNext(pLvl)==0 );
  165625. pLvl->bEof = 0;
  165626. if( i>0 ){
  165627. Fts5DlidxLvl *pChild = &pLvl[-1];
  165628. fts5DataRelease(pChild->pData);
  165629. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  165630. pChild->pData = fts5DataRead(p,
  165631. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  165632. );
  165633. }
  165634. }
  165635. }
  165636. /*
  165637. ** Move the iterator passed as the only argument to the previous entry.
  165638. */
  165639. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  165640. int iOff = pLvl->iOff;
  165641. assert( pLvl->bEof==0 );
  165642. if( iOff<=pLvl->iFirstOff ){
  165643. pLvl->bEof = 1;
  165644. }else{
  165645. u8 *a = pLvl->pData->p;
  165646. i64 iVal;
  165647. int iLimit;
  165648. int ii;
  165649. int nZero = 0;
  165650. /* Currently iOff points to the first byte of a varint. This block
  165651. ** decrements iOff until it points to the first byte of the previous
  165652. ** varint. Taking care not to read any memory locations that occur
  165653. ** before the buffer in memory. */
  165654. iLimit = (iOff>9 ? iOff-9 : 0);
  165655. for(iOff--; iOff>iLimit; iOff--){
  165656. if( (a[iOff-1] & 0x80)==0 ) break;
  165657. }
  165658. fts5GetVarint(&a[iOff], (u64*)&iVal);
  165659. pLvl->iRowid -= iVal;
  165660. pLvl->iLeafPgno--;
  165661. /* Skip backwards past any 0x00 varints. */
  165662. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  165663. nZero++;
  165664. }
  165665. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  165666. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  165667. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  165668. ** bytes before a[ii]. */
  165669. int bZero = 0; /* True if last 0x00 counts */
  165670. if( (ii-8)>=pLvl->iFirstOff ){
  165671. int j;
  165672. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  165673. bZero = (j>8);
  165674. }
  165675. if( bZero==0 ) nZero--;
  165676. }
  165677. pLvl->iLeafPgno -= nZero;
  165678. pLvl->iOff = iOff - nZero;
  165679. }
  165680. return pLvl->bEof;
  165681. }
  165682. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  165683. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  165684. assert( iLvl<pIter->nLvl );
  165685. if( fts5DlidxLvlPrev(pLvl) ){
  165686. if( (iLvl+1) < pIter->nLvl ){
  165687. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  165688. if( pLvl[1].bEof==0 ){
  165689. fts5DataRelease(pLvl->pData);
  165690. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  165691. pLvl->pData = fts5DataRead(p,
  165692. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  165693. );
  165694. if( pLvl->pData ){
  165695. while( fts5DlidxLvlNext(pLvl)==0 );
  165696. pLvl->bEof = 0;
  165697. }
  165698. }
  165699. }
  165700. }
  165701. return pIter->aLvl[0].bEof;
  165702. }
  165703. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  165704. return fts5DlidxIterPrevR(p, pIter, 0);
  165705. }
  165706. /*
  165707. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  165708. */
  165709. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  165710. if( pIter ){
  165711. int i;
  165712. for(i=0; i<pIter->nLvl; i++){
  165713. fts5DataRelease(pIter->aLvl[i].pData);
  165714. }
  165715. sqlite3_free(pIter);
  165716. }
  165717. }
  165718. static Fts5DlidxIter *fts5DlidxIterInit(
  165719. Fts5Index *p, /* Fts5 Backend to iterate within */
  165720. int bRev, /* True for ORDER BY ASC */
  165721. int iSegid, /* Segment id */
  165722. int iLeafPg /* Leaf page number to load dlidx for */
  165723. ){
  165724. Fts5DlidxIter *pIter = 0;
  165725. int i;
  165726. int bDone = 0;
  165727. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  165728. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  165729. Fts5DlidxIter *pNew;
  165730. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  165731. if( pNew==0 ){
  165732. p->rc = SQLITE_NOMEM;
  165733. }else{
  165734. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  165735. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  165736. pIter = pNew;
  165737. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  165738. pLvl->pData = fts5DataRead(p, iRowid);
  165739. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  165740. bDone = 1;
  165741. }
  165742. pIter->nLvl = i+1;
  165743. }
  165744. }
  165745. if( p->rc==SQLITE_OK ){
  165746. pIter->iSegid = iSegid;
  165747. if( bRev==0 ){
  165748. fts5DlidxIterFirst(pIter);
  165749. }else{
  165750. fts5DlidxIterLast(p, pIter);
  165751. }
  165752. }
  165753. if( p->rc!=SQLITE_OK ){
  165754. fts5DlidxIterFree(pIter);
  165755. pIter = 0;
  165756. }
  165757. return pIter;
  165758. }
  165759. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  165760. return pIter->aLvl[0].iRowid;
  165761. }
  165762. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  165763. return pIter->aLvl[0].iLeafPgno;
  165764. }
  165765. /*
  165766. ** Load the next leaf page into the segment iterator.
  165767. */
  165768. static void fts5SegIterNextPage(
  165769. Fts5Index *p, /* FTS5 backend object */
  165770. Fts5SegIter *pIter /* Iterator to advance to next page */
  165771. ){
  165772. Fts5Data *pLeaf;
  165773. Fts5StructureSegment *pSeg = pIter->pSeg;
  165774. fts5DataRelease(pIter->pLeaf);
  165775. pIter->iLeafPgno++;
  165776. if( pIter->pNextLeaf ){
  165777. pIter->pLeaf = pIter->pNextLeaf;
  165778. pIter->pNextLeaf = 0;
  165779. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  165780. pIter->pLeaf = fts5DataRead(p,
  165781. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  165782. );
  165783. }else{
  165784. pIter->pLeaf = 0;
  165785. }
  165786. pLeaf = pIter->pLeaf;
  165787. if( pLeaf ){
  165788. pIter->iPgidxOff = pLeaf->szLeaf;
  165789. if( fts5LeafIsTermless(pLeaf) ){
  165790. pIter->iEndofDoclist = pLeaf->nn+1;
  165791. }else{
  165792. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  165793. pIter->iEndofDoclist
  165794. );
  165795. }
  165796. }
  165797. }
  165798. /*
  165799. ** Argument p points to a buffer containing a varint to be interpreted as a
  165800. ** position list size field. Read the varint and return the number of bytes
  165801. ** read. Before returning, set *pnSz to the number of bytes in the position
  165802. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  165803. */
  165804. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  165805. int nSz;
  165806. int n = 0;
  165807. fts5FastGetVarint32(p, n, nSz);
  165808. assert_nc( nSz>=0 );
  165809. *pnSz = nSz/2;
  165810. *pbDel = nSz & 0x0001;
  165811. return n;
  165812. }
  165813. /*
  165814. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  165815. ** position-list size field. Read the value of the field and store it
  165816. ** in the following variables:
  165817. **
  165818. ** Fts5SegIter.nPos
  165819. ** Fts5SegIter.bDel
  165820. **
  165821. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  165822. ** position list content (if any).
  165823. */
  165824. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  165825. if( p->rc==SQLITE_OK ){
  165826. int iOff = pIter->iLeafOffset; /* Offset to read at */
  165827. ASSERT_SZLEAF_OK(pIter->pLeaf);
  165828. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  165829. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  165830. pIter->bDel = 0;
  165831. pIter->nPos = 1;
  165832. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  165833. pIter->bDel = 1;
  165834. iOff++;
  165835. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  165836. pIter->nPos = 1;
  165837. iOff++;
  165838. }else{
  165839. pIter->nPos = 0;
  165840. }
  165841. }
  165842. }else{
  165843. int nSz;
  165844. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  165845. pIter->bDel = (nSz & 0x0001);
  165846. pIter->nPos = nSz>>1;
  165847. assert_nc( pIter->nPos>=0 );
  165848. }
  165849. pIter->iLeafOffset = iOff;
  165850. }
  165851. }
  165852. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  165853. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  165854. int iOff = pIter->iLeafOffset;
  165855. ASSERT_SZLEAF_OK(pIter->pLeaf);
  165856. if( iOff>=pIter->pLeaf->szLeaf ){
  165857. fts5SegIterNextPage(p, pIter);
  165858. if( pIter->pLeaf==0 ){
  165859. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  165860. return;
  165861. }
  165862. iOff = 4;
  165863. a = pIter->pLeaf->p;
  165864. }
  165865. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  165866. pIter->iLeafOffset = iOff;
  165867. }
  165868. /*
  165869. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  165870. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  165871. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  165872. ** the first term in the segment).
  165873. **
  165874. ** This function populates:
  165875. **
  165876. ** Fts5SegIter.term
  165877. ** Fts5SegIter.rowid
  165878. **
  165879. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  165880. ** the first position list. The position list belonging to document
  165881. ** (Fts5SegIter.iRowid).
  165882. */
  165883. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  165884. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  165885. int iOff = pIter->iLeafOffset; /* Offset to read at */
  165886. int nNew; /* Bytes of new data */
  165887. iOff += fts5GetVarint32(&a[iOff], nNew);
  165888. if( iOff+nNew>pIter->pLeaf->nn ){
  165889. p->rc = FTS5_CORRUPT;
  165890. return;
  165891. }
  165892. pIter->term.n = nKeep;
  165893. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  165894. iOff += nNew;
  165895. pIter->iTermLeafOffset = iOff;
  165896. pIter->iTermLeafPgno = pIter->iLeafPgno;
  165897. pIter->iLeafOffset = iOff;
  165898. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  165899. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  165900. }else{
  165901. int nExtra;
  165902. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  165903. pIter->iEndofDoclist += nExtra;
  165904. }
  165905. fts5SegIterLoadRowid(p, pIter);
  165906. }
  165907. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  165908. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  165909. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  165910. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  165911. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  165912. pIter->xNext = fts5SegIterNext_Reverse;
  165913. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  165914. pIter->xNext = fts5SegIterNext_None;
  165915. }else{
  165916. pIter->xNext = fts5SegIterNext;
  165917. }
  165918. }
  165919. /*
  165920. ** Initialize the iterator object pIter to iterate through the entries in
  165921. ** segment pSeg. The iterator is left pointing to the first entry when
  165922. ** this function returns.
  165923. **
  165924. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  165925. ** an error has already occurred when this function is called, it is a no-op.
  165926. */
  165927. static void fts5SegIterInit(
  165928. Fts5Index *p, /* FTS index object */
  165929. Fts5StructureSegment *pSeg, /* Description of segment */
  165930. Fts5SegIter *pIter /* Object to populate */
  165931. ){
  165932. if( pSeg->pgnoFirst==0 ){
  165933. /* This happens if the segment is being used as an input to an incremental
  165934. ** merge and all data has already been "trimmed". See function
  165935. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  165936. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  165937. ** at EOF already. */
  165938. assert( pIter->pLeaf==0 );
  165939. return;
  165940. }
  165941. if( p->rc==SQLITE_OK ){
  165942. memset(pIter, 0, sizeof(*pIter));
  165943. fts5SegIterSetNext(p, pIter);
  165944. pIter->pSeg = pSeg;
  165945. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  165946. fts5SegIterNextPage(p, pIter);
  165947. }
  165948. if( p->rc==SQLITE_OK ){
  165949. pIter->iLeafOffset = 4;
  165950. assert_nc( pIter->pLeaf->nn>4 );
  165951. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  165952. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  165953. fts5SegIterLoadTerm(p, pIter, 0);
  165954. fts5SegIterLoadNPos(p, pIter);
  165955. }
  165956. }
  165957. /*
  165958. ** This function is only ever called on iterators created by calls to
  165959. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  165960. **
  165961. ** The iterator is in an unusual state when this function is called: the
  165962. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  165963. ** the position-list size field for the first relevant rowid on the page.
  165964. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  165965. **
  165966. ** This function advances the iterator so that it points to the last
  165967. ** relevant rowid on the page and, if necessary, initializes the
  165968. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  165969. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  165970. ** byte of the position list content associated with said rowid.
  165971. */
  165972. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  165973. int eDetail = p->pConfig->eDetail;
  165974. int n = pIter->pLeaf->szLeaf;
  165975. int i = pIter->iLeafOffset;
  165976. u8 *a = pIter->pLeaf->p;
  165977. int iRowidOffset = 0;
  165978. if( n>pIter->iEndofDoclist ){
  165979. n = pIter->iEndofDoclist;
  165980. }
  165981. ASSERT_SZLEAF_OK(pIter->pLeaf);
  165982. while( 1 ){
  165983. i64 iDelta = 0;
  165984. if( eDetail==FTS5_DETAIL_NONE ){
  165985. /* todo */
  165986. if( i<n && a[i]==0 ){
  165987. i++;
  165988. if( i<n && a[i]==0 ) i++;
  165989. }
  165990. }else{
  165991. int nPos;
  165992. int bDummy;
  165993. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  165994. i += nPos;
  165995. }
  165996. if( i>=n ) break;
  165997. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  165998. pIter->iRowid += iDelta;
  165999. /* If necessary, grow the pIter->aRowidOffset[] array. */
  166000. if( iRowidOffset>=pIter->nRowidOffset ){
  166001. int nNew = pIter->nRowidOffset + 8;
  166002. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  166003. if( aNew==0 ){
  166004. p->rc = SQLITE_NOMEM;
  166005. break;
  166006. }
  166007. pIter->aRowidOffset = aNew;
  166008. pIter->nRowidOffset = nNew;
  166009. }
  166010. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  166011. pIter->iLeafOffset = i;
  166012. }
  166013. pIter->iRowidOffset = iRowidOffset;
  166014. fts5SegIterLoadNPos(p, pIter);
  166015. }
  166016. /*
  166017. **
  166018. */
  166019. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  166020. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  166021. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  166022. fts5DataRelease(pIter->pLeaf);
  166023. pIter->pLeaf = 0;
  166024. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  166025. Fts5Data *pNew;
  166026. pIter->iLeafPgno--;
  166027. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  166028. pIter->pSeg->iSegid, pIter->iLeafPgno
  166029. ));
  166030. if( pNew ){
  166031. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  166032. ** thing on the page - i.e. the first rowid is on the following page.
  166033. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  166034. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  166035. assert( pIter->pLeaf==0 );
  166036. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  166037. pIter->pLeaf = pNew;
  166038. pIter->iLeafOffset = pIter->iTermLeafOffset;
  166039. }
  166040. }else{
  166041. int iRowidOff;
  166042. iRowidOff = fts5LeafFirstRowidOff(pNew);
  166043. if( iRowidOff ){
  166044. pIter->pLeaf = pNew;
  166045. pIter->iLeafOffset = iRowidOff;
  166046. }
  166047. }
  166048. if( pIter->pLeaf ){
  166049. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  166050. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  166051. break;
  166052. }else{
  166053. fts5DataRelease(pNew);
  166054. }
  166055. }
  166056. }
  166057. if( pIter->pLeaf ){
  166058. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  166059. fts5SegIterReverseInitPage(p, pIter);
  166060. }
  166061. }
  166062. /*
  166063. ** Return true if the iterator passed as the second argument currently
  166064. ** points to a delete marker. A delete marker is an entry with a 0 byte
  166065. ** position-list.
  166066. */
  166067. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  166068. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  166069. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  166070. }
  166071. /*
  166072. ** Advance iterator pIter to the next entry.
  166073. **
  166074. ** This version of fts5SegIterNext() is only used by reverse iterators.
  166075. */
  166076. static void fts5SegIterNext_Reverse(
  166077. Fts5Index *p, /* FTS5 backend object */
  166078. Fts5SegIter *pIter, /* Iterator to advance */
  166079. int *pbUnused /* Unused */
  166080. ){
  166081. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  166082. assert( pIter->pNextLeaf==0 );
  166083. UNUSED_PARAM(pbUnused);
  166084. if( pIter->iRowidOffset>0 ){
  166085. u8 *a = pIter->pLeaf->p;
  166086. int iOff;
  166087. i64 iDelta;
  166088. pIter->iRowidOffset--;
  166089. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  166090. fts5SegIterLoadNPos(p, pIter);
  166091. iOff = pIter->iLeafOffset;
  166092. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  166093. iOff += pIter->nPos;
  166094. }
  166095. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  166096. pIter->iRowid -= iDelta;
  166097. }else{
  166098. fts5SegIterReverseNewPage(p, pIter);
  166099. }
  166100. }
  166101. /*
  166102. ** Advance iterator pIter to the next entry.
  166103. **
  166104. ** This version of fts5SegIterNext() is only used if detail=none and the
  166105. ** iterator is not a reverse direction iterator.
  166106. */
  166107. static void fts5SegIterNext_None(
  166108. Fts5Index *p, /* FTS5 backend object */
  166109. Fts5SegIter *pIter, /* Iterator to advance */
  166110. int *pbNewTerm /* OUT: Set for new term */
  166111. ){
  166112. int iOff;
  166113. assert( p->rc==SQLITE_OK );
  166114. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  166115. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  166116. ASSERT_SZLEAF_OK(pIter->pLeaf);
  166117. iOff = pIter->iLeafOffset;
  166118. /* Next entry is on the next page */
  166119. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  166120. fts5SegIterNextPage(p, pIter);
  166121. if( p->rc || pIter->pLeaf==0 ) return;
  166122. pIter->iRowid = 0;
  166123. iOff = 4;
  166124. }
  166125. if( iOff<pIter->iEndofDoclist ){
  166126. /* Next entry is on the current page */
  166127. i64 iDelta;
  166128. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  166129. pIter->iLeafOffset = iOff;
  166130. pIter->iRowid += iDelta;
  166131. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  166132. if( pIter->pSeg ){
  166133. int nKeep = 0;
  166134. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  166135. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  166136. }
  166137. pIter->iLeafOffset = iOff;
  166138. fts5SegIterLoadTerm(p, pIter, nKeep);
  166139. }else{
  166140. const u8 *pList = 0;
  166141. const char *zTerm = 0;
  166142. int nList;
  166143. sqlite3Fts5HashScanNext(p->pHash);
  166144. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  166145. if( pList==0 ) goto next_none_eof;
  166146. pIter->pLeaf->p = (u8*)pList;
  166147. pIter->pLeaf->nn = nList;
  166148. pIter->pLeaf->szLeaf = nList;
  166149. pIter->iEndofDoclist = nList;
  166150. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  166151. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  166152. }
  166153. if( pbNewTerm ) *pbNewTerm = 1;
  166154. }else{
  166155. goto next_none_eof;
  166156. }
  166157. fts5SegIterLoadNPos(p, pIter);
  166158. return;
  166159. next_none_eof:
  166160. fts5DataRelease(pIter->pLeaf);
  166161. pIter->pLeaf = 0;
  166162. }
  166163. /*
  166164. ** Advance iterator pIter to the next entry.
  166165. **
  166166. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  166167. ** is not considered an error if the iterator reaches EOF. If an error has
  166168. ** already occurred when this function is called, it is a no-op.
  166169. */
  166170. static void fts5SegIterNext(
  166171. Fts5Index *p, /* FTS5 backend object */
  166172. Fts5SegIter *pIter, /* Iterator to advance */
  166173. int *pbNewTerm /* OUT: Set for new term */
  166174. ){
  166175. Fts5Data *pLeaf = pIter->pLeaf;
  166176. int iOff;
  166177. int bNewTerm = 0;
  166178. int nKeep = 0;
  166179. u8 *a;
  166180. int n;
  166181. assert( pbNewTerm==0 || *pbNewTerm==0 );
  166182. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  166183. /* Search for the end of the position list within the current page. */
  166184. a = pLeaf->p;
  166185. n = pLeaf->szLeaf;
  166186. ASSERT_SZLEAF_OK(pLeaf);
  166187. iOff = pIter->iLeafOffset + pIter->nPos;
  166188. if( iOff<n ){
  166189. /* The next entry is on the current page. */
  166190. assert_nc( iOff<=pIter->iEndofDoclist );
  166191. if( iOff>=pIter->iEndofDoclist ){
  166192. bNewTerm = 1;
  166193. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  166194. iOff += fts5GetVarint32(&a[iOff], nKeep);
  166195. }
  166196. }else{
  166197. u64 iDelta;
  166198. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  166199. pIter->iRowid += iDelta;
  166200. assert_nc( iDelta>0 );
  166201. }
  166202. pIter->iLeafOffset = iOff;
  166203. }else if( pIter->pSeg==0 ){
  166204. const u8 *pList = 0;
  166205. const char *zTerm = 0;
  166206. int nList = 0;
  166207. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  166208. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  166209. sqlite3Fts5HashScanNext(p->pHash);
  166210. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  166211. }
  166212. if( pList==0 ){
  166213. fts5DataRelease(pIter->pLeaf);
  166214. pIter->pLeaf = 0;
  166215. }else{
  166216. pIter->pLeaf->p = (u8*)pList;
  166217. pIter->pLeaf->nn = nList;
  166218. pIter->pLeaf->szLeaf = nList;
  166219. pIter->iEndofDoclist = nList+1;
  166220. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  166221. (u8*)zTerm);
  166222. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  166223. *pbNewTerm = 1;
  166224. }
  166225. }else{
  166226. iOff = 0;
  166227. /* Next entry is not on the current page */
  166228. while( iOff==0 ){
  166229. fts5SegIterNextPage(p, pIter);
  166230. pLeaf = pIter->pLeaf;
  166231. if( pLeaf==0 ) break;
  166232. ASSERT_SZLEAF_OK(pLeaf);
  166233. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  166234. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  166235. pIter->iLeafOffset = iOff;
  166236. if( pLeaf->nn>pLeaf->szLeaf ){
  166237. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  166238. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  166239. );
  166240. }
  166241. }
  166242. else if( pLeaf->nn>pLeaf->szLeaf ){
  166243. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  166244. &pLeaf->p[pLeaf->szLeaf], iOff
  166245. );
  166246. pIter->iLeafOffset = iOff;
  166247. pIter->iEndofDoclist = iOff;
  166248. bNewTerm = 1;
  166249. }
  166250. assert_nc( iOff<pLeaf->szLeaf );
  166251. if( iOff>pLeaf->szLeaf ){
  166252. p->rc = FTS5_CORRUPT;
  166253. return;
  166254. }
  166255. }
  166256. }
  166257. /* Check if the iterator is now at EOF. If so, return early. */
  166258. if( pIter->pLeaf ){
  166259. if( bNewTerm ){
  166260. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  166261. fts5DataRelease(pIter->pLeaf);
  166262. pIter->pLeaf = 0;
  166263. }else{
  166264. fts5SegIterLoadTerm(p, pIter, nKeep);
  166265. fts5SegIterLoadNPos(p, pIter);
  166266. if( pbNewTerm ) *pbNewTerm = 1;
  166267. }
  166268. }else{
  166269. /* The following could be done by calling fts5SegIterLoadNPos(). But
  166270. ** this block is particularly performance critical, so equivalent
  166271. ** code is inlined.
  166272. **
  166273. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  166274. ** detail=none mode. Not ideal.
  166275. */
  166276. int nSz;
  166277. assert( p->rc==SQLITE_OK );
  166278. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  166279. pIter->bDel = (nSz & 0x0001);
  166280. pIter->nPos = nSz>>1;
  166281. assert_nc( pIter->nPos>=0 );
  166282. }
  166283. }
  166284. }
  166285. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  166286. #define fts5IndexSkipVarint(a, iOff) { \
  166287. int iEnd = iOff+9; \
  166288. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  166289. }
  166290. /*
  166291. ** Iterator pIter currently points to the first rowid in a doclist. This
  166292. ** function sets the iterator up so that iterates in reverse order through
  166293. ** the doclist.
  166294. */
  166295. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  166296. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  166297. Fts5Data *pLast = 0;
  166298. int pgnoLast = 0;
  166299. if( pDlidx ){
  166300. int iSegid = pIter->pSeg->iSegid;
  166301. pgnoLast = fts5DlidxIterPgno(pDlidx);
  166302. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  166303. }else{
  166304. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  166305. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  166306. ** position-list content for the current rowid. Back it up so that it
  166307. ** points to the start of the position-list size field. */
  166308. int iPoslist;
  166309. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  166310. iPoslist = pIter->iTermLeafOffset;
  166311. }else{
  166312. iPoslist = 4;
  166313. }
  166314. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  166315. pIter->iLeafOffset = iPoslist;
  166316. /* If this condition is true then the largest rowid for the current
  166317. ** term may not be stored on the current page. So search forward to
  166318. ** see where said rowid really is. */
  166319. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  166320. int pgno;
  166321. Fts5StructureSegment *pSeg = pIter->pSeg;
  166322. /* The last rowid in the doclist may not be on the current page. Search
  166323. ** forward to find the page containing the last rowid. */
  166324. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  166325. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  166326. Fts5Data *pNew = fts5DataRead(p, iAbs);
  166327. if( pNew ){
  166328. int iRowid, bTermless;
  166329. iRowid = fts5LeafFirstRowidOff(pNew);
  166330. bTermless = fts5LeafIsTermless(pNew);
  166331. if( iRowid ){
  166332. SWAPVAL(Fts5Data*, pNew, pLast);
  166333. pgnoLast = pgno;
  166334. }
  166335. fts5DataRelease(pNew);
  166336. if( bTermless==0 ) break;
  166337. }
  166338. }
  166339. }
  166340. }
  166341. /* If pLast is NULL at this point, then the last rowid for this doclist
  166342. ** lies on the page currently indicated by the iterator. In this case
  166343. ** pIter->iLeafOffset is already set to point to the position-list size
  166344. ** field associated with the first relevant rowid on the page.
  166345. **
  166346. ** Or, if pLast is non-NULL, then it is the page that contains the last
  166347. ** rowid. In this case configure the iterator so that it points to the
  166348. ** first rowid on this page.
  166349. */
  166350. if( pLast ){
  166351. int iOff;
  166352. fts5DataRelease(pIter->pLeaf);
  166353. pIter->pLeaf = pLast;
  166354. pIter->iLeafPgno = pgnoLast;
  166355. iOff = fts5LeafFirstRowidOff(pLast);
  166356. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  166357. pIter->iLeafOffset = iOff;
  166358. if( fts5LeafIsTermless(pLast) ){
  166359. pIter->iEndofDoclist = pLast->nn+1;
  166360. }else{
  166361. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  166362. }
  166363. }
  166364. fts5SegIterReverseInitPage(p, pIter);
  166365. }
  166366. /*
  166367. ** Iterator pIter currently points to the first rowid of a doclist.
  166368. ** There is a doclist-index associated with the final term on the current
  166369. ** page. If the current term is the last term on the page, load the
  166370. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  166371. */
  166372. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  166373. int iSeg = pIter->pSeg->iSegid;
  166374. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  166375. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  166376. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  166377. assert( pIter->pDlidx==0 );
  166378. /* Check if the current doclist ends on this page. If it does, return
  166379. ** early without loading the doclist-index (as it belongs to a different
  166380. ** term. */
  166381. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  166382. && pIter->iEndofDoclist<pLeaf->szLeaf
  166383. ){
  166384. return;
  166385. }
  166386. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  166387. }
  166388. /*
  166389. ** The iterator object passed as the second argument currently contains
  166390. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  166391. ** function searches the leaf page for a term matching (pTerm/nTerm).
  166392. **
  166393. ** If the specified term is found on the page, then the iterator is left
  166394. ** pointing to it. If argument bGe is zero and the term is not found,
  166395. ** the iterator is left pointing at EOF.
  166396. **
  166397. ** If bGe is non-zero and the specified term is not found, then the
  166398. ** iterator is left pointing to the smallest term in the segment that
  166399. ** is larger than the specified term, even if this term is not on the
  166400. ** current page.
  166401. */
  166402. static void fts5LeafSeek(
  166403. Fts5Index *p, /* Leave any error code here */
  166404. int bGe, /* True for a >= search */
  166405. Fts5SegIter *pIter, /* Iterator to seek */
  166406. const u8 *pTerm, int nTerm /* Term to search for */
  166407. ){
  166408. int iOff;
  166409. const u8 *a = pIter->pLeaf->p;
  166410. int szLeaf = pIter->pLeaf->szLeaf;
  166411. int n = pIter->pLeaf->nn;
  166412. int nMatch = 0;
  166413. int nKeep = 0;
  166414. int nNew = 0;
  166415. int iTermOff;
  166416. int iPgidx; /* Current offset in pgidx */
  166417. int bEndOfPage = 0;
  166418. assert( p->rc==SQLITE_OK );
  166419. iPgidx = szLeaf;
  166420. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  166421. iOff = iTermOff;
  166422. if( iOff>n ){
  166423. p->rc = FTS5_CORRUPT;
  166424. return;
  166425. }
  166426. while( 1 ){
  166427. /* Figure out how many new bytes are in this term */
  166428. fts5FastGetVarint32(a, iOff, nNew);
  166429. if( nKeep<nMatch ){
  166430. goto search_failed;
  166431. }
  166432. assert( nKeep>=nMatch );
  166433. if( nKeep==nMatch ){
  166434. int nCmp;
  166435. int i;
  166436. nCmp = MIN(nNew, nTerm-nMatch);
  166437. for(i=0; i<nCmp; i++){
  166438. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  166439. }
  166440. nMatch += i;
  166441. if( nTerm==nMatch ){
  166442. if( i==nNew ){
  166443. goto search_success;
  166444. }else{
  166445. goto search_failed;
  166446. }
  166447. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  166448. goto search_failed;
  166449. }
  166450. }
  166451. if( iPgidx>=n ){
  166452. bEndOfPage = 1;
  166453. break;
  166454. }
  166455. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  166456. iTermOff += nKeep;
  166457. iOff = iTermOff;
  166458. /* Read the nKeep field of the next term. */
  166459. fts5FastGetVarint32(a, iOff, nKeep);
  166460. }
  166461. search_failed:
  166462. if( bGe==0 ){
  166463. fts5DataRelease(pIter->pLeaf);
  166464. pIter->pLeaf = 0;
  166465. return;
  166466. }else if( bEndOfPage ){
  166467. do {
  166468. fts5SegIterNextPage(p, pIter);
  166469. if( pIter->pLeaf==0 ) return;
  166470. a = pIter->pLeaf->p;
  166471. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  166472. iPgidx = pIter->pLeaf->szLeaf;
  166473. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  166474. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  166475. p->rc = FTS5_CORRUPT;
  166476. }else{
  166477. nKeep = 0;
  166478. iTermOff = iOff;
  166479. n = pIter->pLeaf->nn;
  166480. iOff += fts5GetVarint32(&a[iOff], nNew);
  166481. break;
  166482. }
  166483. }
  166484. }while( 1 );
  166485. }
  166486. search_success:
  166487. pIter->iLeafOffset = iOff + nNew;
  166488. pIter->iTermLeafOffset = pIter->iLeafOffset;
  166489. pIter->iTermLeafPgno = pIter->iLeafPgno;
  166490. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  166491. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  166492. if( iPgidx>=n ){
  166493. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  166494. }else{
  166495. int nExtra;
  166496. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  166497. pIter->iEndofDoclist = iTermOff + nExtra;
  166498. }
  166499. pIter->iPgidxOff = iPgidx;
  166500. fts5SegIterLoadRowid(p, pIter);
  166501. fts5SegIterLoadNPos(p, pIter);
  166502. }
  166503. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  166504. if( p->pIdxSelect==0 ){
  166505. Fts5Config *pConfig = p->pConfig;
  166506. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  166507. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  166508. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  166509. pConfig->zDb, pConfig->zName
  166510. ));
  166511. }
  166512. return p->pIdxSelect;
  166513. }
  166514. /*
  166515. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  166516. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  166517. **
  166518. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  166519. ** an error has already occurred when this function is called, it is a no-op.
  166520. */
  166521. static void fts5SegIterSeekInit(
  166522. Fts5Index *p, /* FTS5 backend */
  166523. const u8 *pTerm, int nTerm, /* Term to seek to */
  166524. int flags, /* Mask of FTS5INDEX_XXX flags */
  166525. Fts5StructureSegment *pSeg, /* Description of segment */
  166526. Fts5SegIter *pIter /* Object to populate */
  166527. ){
  166528. int iPg = 1;
  166529. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  166530. int bDlidx = 0; /* True if there is a doclist-index */
  166531. sqlite3_stmt *pIdxSelect = 0;
  166532. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  166533. assert( pTerm && nTerm );
  166534. memset(pIter, 0, sizeof(*pIter));
  166535. pIter->pSeg = pSeg;
  166536. /* This block sets stack variable iPg to the leaf page number that may
  166537. ** contain term (pTerm/nTerm), if it is present in the segment. */
  166538. pIdxSelect = fts5IdxSelectStmt(p);
  166539. if( p->rc ) return;
  166540. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  166541. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  166542. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  166543. i64 val = sqlite3_column_int(pIdxSelect, 0);
  166544. iPg = (int)(val>>1);
  166545. bDlidx = (val & 0x0001);
  166546. }
  166547. p->rc = sqlite3_reset(pIdxSelect);
  166548. if( iPg<pSeg->pgnoFirst ){
  166549. iPg = pSeg->pgnoFirst;
  166550. bDlidx = 0;
  166551. }
  166552. pIter->iLeafPgno = iPg - 1;
  166553. fts5SegIterNextPage(p, pIter);
  166554. if( pIter->pLeaf ){
  166555. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  166556. }
  166557. if( p->rc==SQLITE_OK && bGe==0 ){
  166558. pIter->flags |= FTS5_SEGITER_ONETERM;
  166559. if( pIter->pLeaf ){
  166560. if( flags & FTS5INDEX_QUERY_DESC ){
  166561. pIter->flags |= FTS5_SEGITER_REVERSE;
  166562. }
  166563. if( bDlidx ){
  166564. fts5SegIterLoadDlidx(p, pIter);
  166565. }
  166566. if( flags & FTS5INDEX_QUERY_DESC ){
  166567. fts5SegIterReverse(p, pIter);
  166568. }
  166569. }
  166570. }
  166571. fts5SegIterSetNext(p, pIter);
  166572. /* Either:
  166573. **
  166574. ** 1) an error has occurred, or
  166575. ** 2) the iterator points to EOF, or
  166576. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  166577. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  166578. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  166579. */
  166580. assert( p->rc!=SQLITE_OK /* 1 */
  166581. || pIter->pLeaf==0 /* 2 */
  166582. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  166583. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  166584. );
  166585. }
  166586. /*
  166587. ** Initialize the object pIter to point to term pTerm/nTerm within the
  166588. ** in-memory hash table. If there is no such term in the hash-table, the
  166589. ** iterator is set to EOF.
  166590. **
  166591. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  166592. ** an error has already occurred when this function is called, it is a no-op.
  166593. */
  166594. static void fts5SegIterHashInit(
  166595. Fts5Index *p, /* FTS5 backend */
  166596. const u8 *pTerm, int nTerm, /* Term to seek to */
  166597. int flags, /* Mask of FTS5INDEX_XXX flags */
  166598. Fts5SegIter *pIter /* Object to populate */
  166599. ){
  166600. const u8 *pList = 0;
  166601. int nList = 0;
  166602. const u8 *z = 0;
  166603. int n = 0;
  166604. assert( p->pHash );
  166605. assert( p->rc==SQLITE_OK );
  166606. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  166607. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  166608. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  166609. n = (z ? (int)strlen((const char*)z) : 0);
  166610. }else{
  166611. pIter->flags |= FTS5_SEGITER_ONETERM;
  166612. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  166613. z = pTerm;
  166614. n = nTerm;
  166615. }
  166616. if( pList ){
  166617. Fts5Data *pLeaf;
  166618. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  166619. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  166620. if( pLeaf==0 ) return;
  166621. pLeaf->p = (u8*)pList;
  166622. pLeaf->nn = pLeaf->szLeaf = nList;
  166623. pIter->pLeaf = pLeaf;
  166624. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  166625. pIter->iEndofDoclist = pLeaf->nn;
  166626. if( flags & FTS5INDEX_QUERY_DESC ){
  166627. pIter->flags |= FTS5_SEGITER_REVERSE;
  166628. fts5SegIterReverseInitPage(p, pIter);
  166629. }else{
  166630. fts5SegIterLoadNPos(p, pIter);
  166631. }
  166632. }
  166633. fts5SegIterSetNext(p, pIter);
  166634. }
  166635. /*
  166636. ** Zero the iterator passed as the only argument.
  166637. */
  166638. static void fts5SegIterClear(Fts5SegIter *pIter){
  166639. fts5BufferFree(&pIter->term);
  166640. fts5DataRelease(pIter->pLeaf);
  166641. fts5DataRelease(pIter->pNextLeaf);
  166642. fts5DlidxIterFree(pIter->pDlidx);
  166643. sqlite3_free(pIter->aRowidOffset);
  166644. memset(pIter, 0, sizeof(Fts5SegIter));
  166645. }
  166646. #ifdef SQLITE_DEBUG
  166647. /*
  166648. ** This function is used as part of the big assert() procedure implemented by
  166649. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  166650. ** in *pRes is the correct result of comparing the current positions of the
  166651. ** two iterators.
  166652. */
  166653. static void fts5AssertComparisonResult(
  166654. Fts5Iter *pIter,
  166655. Fts5SegIter *p1,
  166656. Fts5SegIter *p2,
  166657. Fts5CResult *pRes
  166658. ){
  166659. int i1 = p1 - pIter->aSeg;
  166660. int i2 = p2 - pIter->aSeg;
  166661. if( p1->pLeaf || p2->pLeaf ){
  166662. if( p1->pLeaf==0 ){
  166663. assert( pRes->iFirst==i2 );
  166664. }else if( p2->pLeaf==0 ){
  166665. assert( pRes->iFirst==i1 );
  166666. }else{
  166667. int nMin = MIN(p1->term.n, p2->term.n);
  166668. int res = memcmp(p1->term.p, p2->term.p, nMin);
  166669. if( res==0 ) res = p1->term.n - p2->term.n;
  166670. if( res==0 ){
  166671. assert( pRes->bTermEq==1 );
  166672. assert( p1->iRowid!=p2->iRowid );
  166673. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  166674. }else{
  166675. assert( pRes->bTermEq==0 );
  166676. }
  166677. if( res<0 ){
  166678. assert( pRes->iFirst==i1 );
  166679. }else{
  166680. assert( pRes->iFirst==i2 );
  166681. }
  166682. }
  166683. }
  166684. }
  166685. /*
  166686. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  166687. ** is compiled. In that case, this function is essentially an assert()
  166688. ** statement used to verify that the contents of the pIter->aFirst[] array
  166689. ** are correct.
  166690. */
  166691. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  166692. if( p->rc==SQLITE_OK ){
  166693. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  166694. int i;
  166695. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  166696. /* Check that pIter->iSwitchRowid is set correctly. */
  166697. for(i=0; i<pIter->nSeg; i++){
  166698. Fts5SegIter *p1 = &pIter->aSeg[i];
  166699. assert( p1==pFirst
  166700. || p1->pLeaf==0
  166701. || fts5BufferCompare(&pFirst->term, &p1->term)
  166702. || p1->iRowid==pIter->iSwitchRowid
  166703. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  166704. );
  166705. }
  166706. for(i=0; i<pIter->nSeg; i+=2){
  166707. Fts5SegIter *p1 = &pIter->aSeg[i];
  166708. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  166709. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  166710. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  166711. }
  166712. for(i=1; i<(pIter->nSeg / 2); i+=2){
  166713. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  166714. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  166715. Fts5CResult *pRes = &pIter->aFirst[i];
  166716. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  166717. }
  166718. }
  166719. }
  166720. #else
  166721. # define fts5AssertMultiIterSetup(x,y)
  166722. #endif
  166723. /*
  166724. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  166725. **
  166726. ** If the returned value is non-zero, then it is the index of an entry
  166727. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  166728. ** to a key that is a duplicate of another, higher priority,
  166729. ** segment-iterator in the pSeg->aSeg[] array.
  166730. */
  166731. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  166732. int i1; /* Index of left-hand Fts5SegIter */
  166733. int i2; /* Index of right-hand Fts5SegIter */
  166734. int iRes;
  166735. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  166736. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  166737. Fts5CResult *pRes = &pIter->aFirst[iOut];
  166738. assert( iOut<pIter->nSeg && iOut>0 );
  166739. assert( pIter->bRev==0 || pIter->bRev==1 );
  166740. if( iOut>=(pIter->nSeg/2) ){
  166741. i1 = (iOut - pIter->nSeg/2) * 2;
  166742. i2 = i1 + 1;
  166743. }else{
  166744. i1 = pIter->aFirst[iOut*2].iFirst;
  166745. i2 = pIter->aFirst[iOut*2+1].iFirst;
  166746. }
  166747. p1 = &pIter->aSeg[i1];
  166748. p2 = &pIter->aSeg[i2];
  166749. pRes->bTermEq = 0;
  166750. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  166751. iRes = i2;
  166752. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  166753. iRes = i1;
  166754. }else{
  166755. int res = fts5BufferCompare(&p1->term, &p2->term);
  166756. if( res==0 ){
  166757. assert( i2>i1 );
  166758. assert( i2!=0 );
  166759. pRes->bTermEq = 1;
  166760. if( p1->iRowid==p2->iRowid ){
  166761. p1->bDel = p2->bDel;
  166762. return i2;
  166763. }
  166764. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  166765. }
  166766. assert( res!=0 );
  166767. if( res<0 ){
  166768. iRes = i1;
  166769. }else{
  166770. iRes = i2;
  166771. }
  166772. }
  166773. pRes->iFirst = (u16)iRes;
  166774. return 0;
  166775. }
  166776. /*
  166777. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  166778. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  166779. */
  166780. static void fts5SegIterGotoPage(
  166781. Fts5Index *p, /* FTS5 backend object */
  166782. Fts5SegIter *pIter, /* Iterator to advance */
  166783. int iLeafPgno
  166784. ){
  166785. assert( iLeafPgno>pIter->iLeafPgno );
  166786. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  166787. p->rc = FTS5_CORRUPT;
  166788. }else{
  166789. fts5DataRelease(pIter->pNextLeaf);
  166790. pIter->pNextLeaf = 0;
  166791. pIter->iLeafPgno = iLeafPgno-1;
  166792. fts5SegIterNextPage(p, pIter);
  166793. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  166794. if( p->rc==SQLITE_OK ){
  166795. int iOff;
  166796. u8 *a = pIter->pLeaf->p;
  166797. int n = pIter->pLeaf->szLeaf;
  166798. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  166799. if( iOff<4 || iOff>=n ){
  166800. p->rc = FTS5_CORRUPT;
  166801. }else{
  166802. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  166803. pIter->iLeafOffset = iOff;
  166804. fts5SegIterLoadNPos(p, pIter);
  166805. }
  166806. }
  166807. }
  166808. }
  166809. /*
  166810. ** Advance the iterator passed as the second argument until it is at or
  166811. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  166812. ** always advanced at least once.
  166813. */
  166814. static void fts5SegIterNextFrom(
  166815. Fts5Index *p, /* FTS5 backend object */
  166816. Fts5SegIter *pIter, /* Iterator to advance */
  166817. i64 iMatch /* Advance iterator at least this far */
  166818. ){
  166819. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  166820. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  166821. int iLeafPgno = pIter->iLeafPgno;
  166822. int bMove = 1;
  166823. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  166824. assert( pIter->pDlidx );
  166825. assert( pIter->pLeaf );
  166826. if( bRev==0 ){
  166827. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  166828. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  166829. fts5DlidxIterNext(p, pDlidx);
  166830. }
  166831. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  166832. if( iLeafPgno>pIter->iLeafPgno ){
  166833. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  166834. bMove = 0;
  166835. }
  166836. }else{
  166837. assert( pIter->pNextLeaf==0 );
  166838. assert( iMatch<pIter->iRowid );
  166839. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  166840. fts5DlidxIterPrev(p, pDlidx);
  166841. }
  166842. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  166843. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  166844. if( iLeafPgno<pIter->iLeafPgno ){
  166845. pIter->iLeafPgno = iLeafPgno+1;
  166846. fts5SegIterReverseNewPage(p, pIter);
  166847. bMove = 0;
  166848. }
  166849. }
  166850. do{
  166851. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  166852. if( pIter->pLeaf==0 ) break;
  166853. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  166854. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  166855. bMove = 1;
  166856. }while( p->rc==SQLITE_OK );
  166857. }
  166858. /*
  166859. ** Free the iterator object passed as the second argument.
  166860. */
  166861. static void fts5MultiIterFree(Fts5Iter *pIter){
  166862. if( pIter ){
  166863. int i;
  166864. for(i=0; i<pIter->nSeg; i++){
  166865. fts5SegIterClear(&pIter->aSeg[i]);
  166866. }
  166867. fts5StructureRelease(pIter->pStruct);
  166868. fts5BufferFree(&pIter->poslist);
  166869. sqlite3_free(pIter);
  166870. }
  166871. }
  166872. static void fts5MultiIterAdvanced(
  166873. Fts5Index *p, /* FTS5 backend to iterate within */
  166874. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  166875. int iChanged, /* Index of sub-iterator just advanced */
  166876. int iMinset /* Minimum entry in aFirst[] to set */
  166877. ){
  166878. int i;
  166879. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  166880. int iEq;
  166881. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  166882. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  166883. assert( p->rc==SQLITE_OK );
  166884. pSeg->xNext(p, pSeg, 0);
  166885. i = pIter->nSeg + iEq;
  166886. }
  166887. }
  166888. }
  166889. /*
  166890. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  166891. ** points to the same term though - just a different rowid. This function
  166892. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  166893. ** If it does so successfully, 0 is returned. Otherwise 1.
  166894. **
  166895. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  166896. ** on the iterator instead. That function does the same as this one, except
  166897. ** that it deals with more complicated cases as well.
  166898. */
  166899. static int fts5MultiIterAdvanceRowid(
  166900. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  166901. int iChanged, /* Index of sub-iterator just advanced */
  166902. Fts5SegIter **ppFirst
  166903. ){
  166904. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  166905. if( pNew->iRowid==pIter->iSwitchRowid
  166906. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  166907. ){
  166908. int i;
  166909. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  166910. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  166911. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  166912. Fts5CResult *pRes = &pIter->aFirst[i];
  166913. assert( pNew->pLeaf );
  166914. assert( pRes->bTermEq==0 || pOther->pLeaf );
  166915. if( pRes->bTermEq ){
  166916. if( pNew->iRowid==pOther->iRowid ){
  166917. return 1;
  166918. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  166919. pIter->iSwitchRowid = pOther->iRowid;
  166920. pNew = pOther;
  166921. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  166922. pIter->iSwitchRowid = pOther->iRowid;
  166923. }
  166924. }
  166925. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  166926. if( i==1 ) break;
  166927. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  166928. }
  166929. }
  166930. *ppFirst = pNew;
  166931. return 0;
  166932. }
  166933. /*
  166934. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  166935. */
  166936. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  166937. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  166938. pIter->base.bEof = pSeg->pLeaf==0;
  166939. pIter->iSwitchRowid = pSeg->iRowid;
  166940. }
  166941. /*
  166942. ** Move the iterator to the next entry.
  166943. **
  166944. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  166945. ** considered an error if the iterator reaches EOF, or if it is already at
  166946. ** EOF when this function is called.
  166947. */
  166948. static void fts5MultiIterNext(
  166949. Fts5Index *p,
  166950. Fts5Iter *pIter,
  166951. int bFrom, /* True if argument iFrom is valid */
  166952. i64 iFrom /* Advance at least as far as this */
  166953. ){
  166954. int bUseFrom = bFrom;
  166955. while( p->rc==SQLITE_OK ){
  166956. int iFirst = pIter->aFirst[1].iFirst;
  166957. int bNewTerm = 0;
  166958. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  166959. assert( p->rc==SQLITE_OK );
  166960. if( bUseFrom && pSeg->pDlidx ){
  166961. fts5SegIterNextFrom(p, pSeg, iFrom);
  166962. }else{
  166963. pSeg->xNext(p, pSeg, &bNewTerm);
  166964. }
  166965. if( pSeg->pLeaf==0 || bNewTerm
  166966. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  166967. ){
  166968. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  166969. fts5MultiIterSetEof(pIter);
  166970. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  166971. if( pSeg->pLeaf==0 ) return;
  166972. }
  166973. fts5AssertMultiIterSetup(p, pIter);
  166974. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  166975. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  166976. pIter->xSetOutputs(pIter, pSeg);
  166977. return;
  166978. }
  166979. bUseFrom = 0;
  166980. }
  166981. }
  166982. static void fts5MultiIterNext2(
  166983. Fts5Index *p,
  166984. Fts5Iter *pIter,
  166985. int *pbNewTerm /* OUT: True if *might* be new term */
  166986. ){
  166987. assert( pIter->bSkipEmpty );
  166988. if( p->rc==SQLITE_OK ){
  166989. do {
  166990. int iFirst = pIter->aFirst[1].iFirst;
  166991. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  166992. int bNewTerm = 0;
  166993. assert( p->rc==SQLITE_OK );
  166994. pSeg->xNext(p, pSeg, &bNewTerm);
  166995. if( pSeg->pLeaf==0 || bNewTerm
  166996. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  166997. ){
  166998. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  166999. fts5MultiIterSetEof(pIter);
  167000. *pbNewTerm = 1;
  167001. }else{
  167002. *pbNewTerm = 0;
  167003. }
  167004. fts5AssertMultiIterSetup(p, pIter);
  167005. }while( fts5MultiIterIsEmpty(p, pIter) );
  167006. }
  167007. }
  167008. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  167009. UNUSED_PARAM2(pUnused1, pUnused2);
  167010. }
  167011. static Fts5Iter *fts5MultiIterAlloc(
  167012. Fts5Index *p, /* FTS5 backend to iterate within */
  167013. int nSeg
  167014. ){
  167015. Fts5Iter *pNew;
  167016. int nSlot; /* Power of two >= nSeg */
  167017. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  167018. pNew = fts5IdxMalloc(p,
  167019. sizeof(Fts5Iter) + /* pNew */
  167020. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  167021. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  167022. );
  167023. if( pNew ){
  167024. pNew->nSeg = nSlot;
  167025. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  167026. pNew->pIndex = p;
  167027. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  167028. }
  167029. return pNew;
  167030. }
  167031. static void fts5PoslistCallback(
  167032. Fts5Index *pUnused,
  167033. void *pContext,
  167034. const u8 *pChunk, int nChunk
  167035. ){
  167036. UNUSED_PARAM(pUnused);
  167037. assert_nc( nChunk>=0 );
  167038. if( nChunk>0 ){
  167039. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  167040. }
  167041. }
  167042. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  167043. struct PoslistCallbackCtx {
  167044. Fts5Buffer *pBuf; /* Append to this buffer */
  167045. Fts5Colset *pColset; /* Restrict matches to this column */
  167046. int eState; /* See above */
  167047. };
  167048. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  167049. struct PoslistOffsetsCtx {
  167050. Fts5Buffer *pBuf; /* Append to this buffer */
  167051. Fts5Colset *pColset; /* Restrict matches to this column */
  167052. int iRead;
  167053. int iWrite;
  167054. };
  167055. /*
  167056. ** TODO: Make this more efficient!
  167057. */
  167058. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  167059. int i;
  167060. for(i=0; i<pColset->nCol; i++){
  167061. if( pColset->aiCol[i]==iCol ) return 1;
  167062. }
  167063. return 0;
  167064. }
  167065. static void fts5PoslistOffsetsCallback(
  167066. Fts5Index *pUnused,
  167067. void *pContext,
  167068. const u8 *pChunk, int nChunk
  167069. ){
  167070. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  167071. UNUSED_PARAM(pUnused);
  167072. assert_nc( nChunk>=0 );
  167073. if( nChunk>0 ){
  167074. int i = 0;
  167075. while( i<nChunk ){
  167076. int iVal;
  167077. i += fts5GetVarint32(&pChunk[i], iVal);
  167078. iVal += pCtx->iRead - 2;
  167079. pCtx->iRead = iVal;
  167080. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  167081. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  167082. pCtx->iWrite = iVal;
  167083. }
  167084. }
  167085. }
  167086. }
  167087. static void fts5PoslistFilterCallback(
  167088. Fts5Index *pUnused,
  167089. void *pContext,
  167090. const u8 *pChunk, int nChunk
  167091. ){
  167092. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  167093. UNUSED_PARAM(pUnused);
  167094. assert_nc( nChunk>=0 );
  167095. if( nChunk>0 ){
  167096. /* Search through to find the first varint with value 1. This is the
  167097. ** start of the next columns hits. */
  167098. int i = 0;
  167099. int iStart = 0;
  167100. if( pCtx->eState==2 ){
  167101. int iCol;
  167102. fts5FastGetVarint32(pChunk, i, iCol);
  167103. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  167104. pCtx->eState = 1;
  167105. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  167106. }else{
  167107. pCtx->eState = 0;
  167108. }
  167109. }
  167110. do {
  167111. while( i<nChunk && pChunk[i]!=0x01 ){
  167112. while( pChunk[i] & 0x80 ) i++;
  167113. i++;
  167114. }
  167115. if( pCtx->eState ){
  167116. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  167117. }
  167118. if( i<nChunk ){
  167119. int iCol;
  167120. iStart = i;
  167121. i++;
  167122. if( i>=nChunk ){
  167123. pCtx->eState = 2;
  167124. }else{
  167125. fts5FastGetVarint32(pChunk, i, iCol);
  167126. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  167127. if( pCtx->eState ){
  167128. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  167129. iStart = i;
  167130. }
  167131. }
  167132. }
  167133. }while( i<nChunk );
  167134. }
  167135. }
  167136. static void fts5ChunkIterate(
  167137. Fts5Index *p, /* Index object */
  167138. Fts5SegIter *pSeg, /* Poslist of this iterator */
  167139. void *pCtx, /* Context pointer for xChunk callback */
  167140. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  167141. ){
  167142. int nRem = pSeg->nPos; /* Number of bytes still to come */
  167143. Fts5Data *pData = 0;
  167144. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  167145. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  167146. int pgno = pSeg->iLeafPgno;
  167147. int pgnoSave = 0;
  167148. /* This function does notmwork with detail=none databases. */
  167149. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  167150. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  167151. pgnoSave = pgno+1;
  167152. }
  167153. while( 1 ){
  167154. xChunk(p, pCtx, pChunk, nChunk);
  167155. nRem -= nChunk;
  167156. fts5DataRelease(pData);
  167157. if( nRem<=0 ){
  167158. break;
  167159. }else{
  167160. pgno++;
  167161. pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  167162. if( pData==0 ) break;
  167163. pChunk = &pData->p[4];
  167164. nChunk = MIN(nRem, pData->szLeaf - 4);
  167165. if( pgno==pgnoSave ){
  167166. assert( pSeg->pNextLeaf==0 );
  167167. pSeg->pNextLeaf = pData;
  167168. pData = 0;
  167169. }
  167170. }
  167171. }
  167172. }
  167173. /*
  167174. ** Iterator pIter currently points to a valid entry (not EOF). This
  167175. ** function appends the position list data for the current entry to
  167176. ** buffer pBuf. It does not make a copy of the position-list size
  167177. ** field.
  167178. */
  167179. static void fts5SegiterPoslist(
  167180. Fts5Index *p,
  167181. Fts5SegIter *pSeg,
  167182. Fts5Colset *pColset,
  167183. Fts5Buffer *pBuf
  167184. ){
  167185. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  167186. if( pColset==0 ){
  167187. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  167188. }else{
  167189. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  167190. PoslistCallbackCtx sCtx;
  167191. sCtx.pBuf = pBuf;
  167192. sCtx.pColset = pColset;
  167193. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  167194. assert( sCtx.eState==0 || sCtx.eState==1 );
  167195. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  167196. }else{
  167197. PoslistOffsetsCtx sCtx;
  167198. memset(&sCtx, 0, sizeof(sCtx));
  167199. sCtx.pBuf = pBuf;
  167200. sCtx.pColset = pColset;
  167201. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  167202. }
  167203. }
  167204. }
  167205. }
  167206. /*
  167207. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  167208. ** the position list contains entries for column iCol, then (*pa) is set
  167209. ** to point to the sub-position-list for that column and the number of
  167210. ** bytes in it returned. Or, if the argument position list does not
  167211. ** contain any entries for column iCol, return 0.
  167212. */
  167213. static int fts5IndexExtractCol(
  167214. const u8 **pa, /* IN/OUT: Pointer to poslist */
  167215. int n, /* IN: Size of poslist in bytes */
  167216. int iCol /* Column to extract from poslist */
  167217. ){
  167218. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  167219. const u8 *p = *pa;
  167220. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  167221. while( iCol>iCurrent ){
  167222. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  167223. ** not part of a varint. Note that it is not possible for a negative
  167224. ** or extremely large varint to occur within an uncorrupted position
  167225. ** list. So the last byte of each varint may be assumed to have a clear
  167226. ** 0x80 bit. */
  167227. while( *p!=0x01 ){
  167228. while( *p++ & 0x80 );
  167229. if( p>=pEnd ) return 0;
  167230. }
  167231. *pa = p++;
  167232. iCurrent = *p++;
  167233. if( iCurrent & 0x80 ){
  167234. p--;
  167235. p += fts5GetVarint32(p, iCurrent);
  167236. }
  167237. }
  167238. if( iCol!=iCurrent ) return 0;
  167239. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  167240. ** not part of a varint */
  167241. while( p<pEnd && *p!=0x01 ){
  167242. while( *p++ & 0x80 );
  167243. }
  167244. return p - (*pa);
  167245. }
  167246. static int fts5IndexExtractColset (
  167247. Fts5Colset *pColset, /* Colset to filter on */
  167248. const u8 *pPos, int nPos, /* Position list */
  167249. Fts5Buffer *pBuf /* Output buffer */
  167250. ){
  167251. int rc = SQLITE_OK;
  167252. int i;
  167253. fts5BufferZero(pBuf);
  167254. for(i=0; i<pColset->nCol; i++){
  167255. const u8 *pSub = pPos;
  167256. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  167257. if( nSub ){
  167258. fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
  167259. }
  167260. }
  167261. return rc;
  167262. }
  167263. /*
  167264. ** xSetOutputs callback used by detail=none tables.
  167265. */
  167266. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  167267. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  167268. pIter->base.iRowid = pSeg->iRowid;
  167269. pIter->base.nData = pSeg->nPos;
  167270. }
  167271. /*
  167272. ** xSetOutputs callback used by detail=full and detail=col tables when no
  167273. ** column filters are specified.
  167274. */
  167275. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  167276. pIter->base.iRowid = pSeg->iRowid;
  167277. pIter->base.nData = pSeg->nPos;
  167278. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  167279. assert( pIter->pColset==0 );
  167280. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  167281. /* All data is stored on the current page. Populate the output
  167282. ** variables to point into the body of the page object. */
  167283. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  167284. }else{
  167285. /* The data is distributed over two or more pages. Copy it into the
  167286. ** Fts5Iter.poslist buffer and then set the output pointer to point
  167287. ** to this buffer. */
  167288. fts5BufferZero(&pIter->poslist);
  167289. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  167290. pIter->base.pData = pIter->poslist.p;
  167291. }
  167292. }
  167293. /*
  167294. ** xSetOutputs callback used by detail=col when there is a column filter
  167295. ** and there are 100 or more columns. Also called as a fallback from
  167296. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  167297. */
  167298. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  167299. fts5BufferZero(&pIter->poslist);
  167300. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  167301. pIter->base.iRowid = pSeg->iRowid;
  167302. pIter->base.pData = pIter->poslist.p;
  167303. pIter->base.nData = pIter->poslist.n;
  167304. }
  167305. /*
  167306. ** xSetOutputs callback used when:
  167307. **
  167308. ** * detail=col,
  167309. ** * there is a column filter, and
  167310. ** * the table contains 100 or fewer columns.
  167311. **
  167312. ** The last point is to ensure all column numbers are stored as
  167313. ** single-byte varints.
  167314. */
  167315. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  167316. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  167317. assert( pIter->pColset );
  167318. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  167319. fts5IterSetOutputs_Col(pIter, pSeg);
  167320. }else{
  167321. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  167322. u8 *pEnd = (u8*)&a[pSeg->nPos];
  167323. int iPrev = 0;
  167324. int *aiCol = pIter->pColset->aiCol;
  167325. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  167326. u8 *aOut = pIter->poslist.p;
  167327. int iPrevOut = 0;
  167328. pIter->base.iRowid = pSeg->iRowid;
  167329. while( a<pEnd ){
  167330. iPrev += (int)a++[0] - 2;
  167331. while( *aiCol<iPrev ){
  167332. aiCol++;
  167333. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  167334. }
  167335. if( *aiCol==iPrev ){
  167336. *aOut++ = (iPrev - iPrevOut) + 2;
  167337. iPrevOut = iPrev;
  167338. }
  167339. }
  167340. setoutputs_col_out:
  167341. pIter->base.pData = pIter->poslist.p;
  167342. pIter->base.nData = aOut - pIter->poslist.p;
  167343. }
  167344. }
  167345. /*
  167346. ** xSetOutputs callback used by detail=full when there is a column filter.
  167347. */
  167348. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  167349. Fts5Colset *pColset = pIter->pColset;
  167350. pIter->base.iRowid = pSeg->iRowid;
  167351. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  167352. assert( pColset );
  167353. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  167354. /* All data is stored on the current page. Populate the output
  167355. ** variables to point into the body of the page object. */
  167356. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  167357. if( pColset->nCol==1 ){
  167358. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  167359. pIter->base.pData = a;
  167360. }else{
  167361. fts5BufferZero(&pIter->poslist);
  167362. fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
  167363. pIter->base.pData = pIter->poslist.p;
  167364. pIter->base.nData = pIter->poslist.n;
  167365. }
  167366. }else{
  167367. /* The data is distributed over two or more pages. Copy it into the
  167368. ** Fts5Iter.poslist buffer and then set the output pointer to point
  167369. ** to this buffer. */
  167370. fts5BufferZero(&pIter->poslist);
  167371. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  167372. pIter->base.pData = pIter->poslist.p;
  167373. pIter->base.nData = pIter->poslist.n;
  167374. }
  167375. }
  167376. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  167377. if( *pRc==SQLITE_OK ){
  167378. Fts5Config *pConfig = pIter->pIndex->pConfig;
  167379. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  167380. pIter->xSetOutputs = fts5IterSetOutputs_None;
  167381. }
  167382. else if( pIter->pColset==0 ){
  167383. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  167384. }
  167385. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  167386. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  167387. }
  167388. else{
  167389. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  167390. if( pConfig->nCol<=100 ){
  167391. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  167392. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  167393. }else{
  167394. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  167395. }
  167396. }
  167397. }
  167398. }
  167399. /*
  167400. ** Allocate a new Fts5Iter object.
  167401. **
  167402. ** The new object will be used to iterate through data in structure pStruct.
  167403. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  167404. ** is zero or greater, data from the first nSegment segments on level iLevel
  167405. ** is merged.
  167406. **
  167407. ** The iterator initially points to the first term/rowid entry in the
  167408. ** iterated data.
  167409. */
  167410. static void fts5MultiIterNew(
  167411. Fts5Index *p, /* FTS5 backend to iterate within */
  167412. Fts5Structure *pStruct, /* Structure of specific index */
  167413. int flags, /* FTS5INDEX_QUERY_XXX flags */
  167414. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  167415. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  167416. int iLevel, /* Level to iterate (-1 for all) */
  167417. int nSegment, /* Number of segments to merge (iLevel>=0) */
  167418. Fts5Iter **ppOut /* New object */
  167419. ){
  167420. int nSeg = 0; /* Number of segment-iters in use */
  167421. int iIter = 0; /* */
  167422. int iSeg; /* Used to iterate through segments */
  167423. Fts5StructureLevel *pLvl;
  167424. Fts5Iter *pNew;
  167425. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  167426. /* Allocate space for the new multi-seg-iterator. */
  167427. if( p->rc==SQLITE_OK ){
  167428. if( iLevel<0 ){
  167429. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  167430. nSeg = pStruct->nSegment;
  167431. nSeg += (p->pHash ? 1 : 0);
  167432. }else{
  167433. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  167434. }
  167435. }
  167436. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  167437. if( pNew==0 ) return;
  167438. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  167439. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  167440. pNew->pStruct = pStruct;
  167441. pNew->pColset = pColset;
  167442. fts5StructureRef(pStruct);
  167443. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  167444. fts5IterSetOutputCb(&p->rc, pNew);
  167445. }
  167446. /* Initialize each of the component segment iterators. */
  167447. if( p->rc==SQLITE_OK ){
  167448. if( iLevel<0 ){
  167449. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  167450. if( p->pHash ){
  167451. /* Add a segment iterator for the current contents of the hash table. */
  167452. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  167453. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  167454. }
  167455. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  167456. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  167457. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  167458. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  167459. if( pTerm==0 ){
  167460. fts5SegIterInit(p, pSeg, pIter);
  167461. }else{
  167462. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  167463. }
  167464. }
  167465. }
  167466. }else{
  167467. pLvl = &pStruct->aLevel[iLevel];
  167468. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  167469. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  167470. }
  167471. }
  167472. assert( iIter==nSeg );
  167473. }
  167474. /* If the above was successful, each component iterators now points
  167475. ** to the first entry in its segment. In this case initialize the
  167476. ** aFirst[] array. Or, if an error has occurred, free the iterator
  167477. ** object and set the output variable to NULL. */
  167478. if( p->rc==SQLITE_OK ){
  167479. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  167480. int iEq;
  167481. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  167482. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  167483. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  167484. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  167485. }
  167486. }
  167487. fts5MultiIterSetEof(pNew);
  167488. fts5AssertMultiIterSetup(p, pNew);
  167489. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  167490. fts5MultiIterNext(p, pNew, 0, 0);
  167491. }else if( pNew->base.bEof==0 ){
  167492. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  167493. pNew->xSetOutputs(pNew, pSeg);
  167494. }
  167495. }else{
  167496. fts5MultiIterFree(pNew);
  167497. *ppOut = 0;
  167498. }
  167499. }
  167500. /*
  167501. ** Create an Fts5Iter that iterates through the doclist provided
  167502. ** as the second argument.
  167503. */
  167504. static void fts5MultiIterNew2(
  167505. Fts5Index *p, /* FTS5 backend to iterate within */
  167506. Fts5Data *pData, /* Doclist to iterate through */
  167507. int bDesc, /* True for descending rowid order */
  167508. Fts5Iter **ppOut /* New object */
  167509. ){
  167510. Fts5Iter *pNew;
  167511. pNew = fts5MultiIterAlloc(p, 2);
  167512. if( pNew ){
  167513. Fts5SegIter *pIter = &pNew->aSeg[1];
  167514. pIter->flags = FTS5_SEGITER_ONETERM;
  167515. if( pData->szLeaf>0 ){
  167516. pIter->pLeaf = pData;
  167517. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  167518. pIter->iEndofDoclist = pData->nn;
  167519. pNew->aFirst[1].iFirst = 1;
  167520. if( bDesc ){
  167521. pNew->bRev = 1;
  167522. pIter->flags |= FTS5_SEGITER_REVERSE;
  167523. fts5SegIterReverseInitPage(p, pIter);
  167524. }else{
  167525. fts5SegIterLoadNPos(p, pIter);
  167526. }
  167527. pData = 0;
  167528. }else{
  167529. pNew->base.bEof = 1;
  167530. }
  167531. fts5SegIterSetNext(p, pIter);
  167532. *ppOut = pNew;
  167533. }
  167534. fts5DataRelease(pData);
  167535. }
  167536. /*
  167537. ** Return true if the iterator is at EOF or if an error has occurred.
  167538. ** False otherwise.
  167539. */
  167540. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  167541. assert( p->rc
  167542. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  167543. );
  167544. return (p->rc || pIter->base.bEof);
  167545. }
  167546. /*
  167547. ** Return the rowid of the entry that the iterator currently points
  167548. ** to. If the iterator points to EOF when this function is called the
  167549. ** results are undefined.
  167550. */
  167551. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  167552. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  167553. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  167554. }
  167555. /*
  167556. ** Move the iterator to the next entry at or following iMatch.
  167557. */
  167558. static void fts5MultiIterNextFrom(
  167559. Fts5Index *p,
  167560. Fts5Iter *pIter,
  167561. i64 iMatch
  167562. ){
  167563. while( 1 ){
  167564. i64 iRowid;
  167565. fts5MultiIterNext(p, pIter, 1, iMatch);
  167566. if( fts5MultiIterEof(p, pIter) ) break;
  167567. iRowid = fts5MultiIterRowid(pIter);
  167568. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  167569. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  167570. }
  167571. }
  167572. /*
  167573. ** Return a pointer to a buffer containing the term associated with the
  167574. ** entry that the iterator currently points to.
  167575. */
  167576. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  167577. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  167578. *pn = p->term.n;
  167579. return p->term.p;
  167580. }
  167581. /*
  167582. ** Allocate a new segment-id for the structure pStruct. The new segment
  167583. ** id must be between 1 and 65335 inclusive, and must not be used by
  167584. ** any currently existing segment. If a free segment id cannot be found,
  167585. ** SQLITE_FULL is returned.
  167586. **
  167587. ** If an error has already occurred, this function is a no-op. 0 is
  167588. ** returned in this case.
  167589. */
  167590. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  167591. int iSegid = 0;
  167592. if( p->rc==SQLITE_OK ){
  167593. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  167594. p->rc = SQLITE_FULL;
  167595. }else{
  167596. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  167597. ** array is 63 elements, or 252 bytes, in size. */
  167598. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  167599. int iLvl, iSeg;
  167600. int i;
  167601. u32 mask;
  167602. memset(aUsed, 0, sizeof(aUsed));
  167603. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  167604. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  167605. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  167606. if( iId<=FTS5_MAX_SEGMENT ){
  167607. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  167608. }
  167609. }
  167610. }
  167611. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  167612. mask = aUsed[i];
  167613. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  167614. iSegid += 1 + i*32;
  167615. #ifdef SQLITE_DEBUG
  167616. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  167617. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  167618. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  167619. }
  167620. }
  167621. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  167622. {
  167623. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  167624. if( p->rc==SQLITE_OK ){
  167625. u8 aBlob[2] = {0xff, 0xff};
  167626. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  167627. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  167628. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  167629. p->rc = sqlite3_reset(pIdxSelect);
  167630. }
  167631. }
  167632. #endif
  167633. }
  167634. }
  167635. return iSegid;
  167636. }
  167637. /*
  167638. ** Discard all data currently cached in the hash-tables.
  167639. */
  167640. static void fts5IndexDiscardData(Fts5Index *p){
  167641. assert( p->pHash || p->nPendingData==0 );
  167642. if( p->pHash ){
  167643. sqlite3Fts5HashClear(p->pHash);
  167644. p->nPendingData = 0;
  167645. }
  167646. }
  167647. /*
  167648. ** Return the size of the prefix, in bytes, that buffer
  167649. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  167650. **
  167651. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  167652. ** than buffer (pOld/nOld).
  167653. */
  167654. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  167655. int i;
  167656. for(i=0; i<nOld; i++){
  167657. if( pOld[i]!=pNew[i] ) break;
  167658. }
  167659. return i;
  167660. }
  167661. static void fts5WriteDlidxClear(
  167662. Fts5Index *p,
  167663. Fts5SegWriter *pWriter,
  167664. int bFlush /* If true, write dlidx to disk */
  167665. ){
  167666. int i;
  167667. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  167668. for(i=0; i<pWriter->nDlidx; i++){
  167669. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  167670. if( pDlidx->buf.n==0 ) break;
  167671. if( bFlush ){
  167672. assert( pDlidx->pgno!=0 );
  167673. fts5DataWrite(p,
  167674. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  167675. pDlidx->buf.p, pDlidx->buf.n
  167676. );
  167677. }
  167678. sqlite3Fts5BufferZero(&pDlidx->buf);
  167679. pDlidx->bPrevValid = 0;
  167680. }
  167681. }
  167682. /*
  167683. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  167684. ** Any new array elements are zeroed before returning.
  167685. */
  167686. static int fts5WriteDlidxGrow(
  167687. Fts5Index *p,
  167688. Fts5SegWriter *pWriter,
  167689. int nLvl
  167690. ){
  167691. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  167692. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  167693. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  167694. );
  167695. if( aDlidx==0 ){
  167696. p->rc = SQLITE_NOMEM;
  167697. }else{
  167698. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  167699. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  167700. pWriter->aDlidx = aDlidx;
  167701. pWriter->nDlidx = nLvl;
  167702. }
  167703. }
  167704. return p->rc;
  167705. }
  167706. /*
  167707. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  167708. ** enough, flush it to disk and return 1. Otherwise discard it and return
  167709. ** zero.
  167710. */
  167711. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  167712. int bFlag = 0;
  167713. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  167714. ** to the database, also write the doclist-index to disk. */
  167715. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  167716. bFlag = 1;
  167717. }
  167718. fts5WriteDlidxClear(p, pWriter, bFlag);
  167719. pWriter->nEmpty = 0;
  167720. return bFlag;
  167721. }
  167722. /*
  167723. ** This function is called whenever processing of the doclist for the
  167724. ** last term on leaf page (pWriter->iBtPage) is completed.
  167725. **
  167726. ** The doclist-index for that term is currently stored in-memory within the
  167727. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  167728. ** writes it out to disk. Or, if it is too small to bother with, discards
  167729. ** it.
  167730. **
  167731. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  167732. */
  167733. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  167734. int bFlag;
  167735. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  167736. if( pWriter->iBtPage==0 ) return;
  167737. bFlag = fts5WriteFlushDlidx(p, pWriter);
  167738. if( p->rc==SQLITE_OK ){
  167739. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  167740. /* The following was already done in fts5WriteInit(): */
  167741. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  167742. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  167743. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  167744. sqlite3_step(p->pIdxWriter);
  167745. p->rc = sqlite3_reset(p->pIdxWriter);
  167746. }
  167747. pWriter->iBtPage = 0;
  167748. }
  167749. /*
  167750. ** This is called once for each leaf page except the first that contains
  167751. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  167752. ** is larger than all terms written to earlier leaves, and equal to or
  167753. ** smaller than the first term on the new leaf.
  167754. **
  167755. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  167756. ** has already occurred when this function is called, it is a no-op.
  167757. */
  167758. static void fts5WriteBtreeTerm(
  167759. Fts5Index *p, /* FTS5 backend object */
  167760. Fts5SegWriter *pWriter, /* Writer object */
  167761. int nTerm, const u8 *pTerm /* First term on new page */
  167762. ){
  167763. fts5WriteFlushBtree(p, pWriter);
  167764. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  167765. pWriter->iBtPage = pWriter->writer.pgno;
  167766. }
  167767. /*
  167768. ** This function is called when flushing a leaf page that contains no
  167769. ** terms at all to disk.
  167770. */
  167771. static void fts5WriteBtreeNoTerm(
  167772. Fts5Index *p, /* FTS5 backend object */
  167773. Fts5SegWriter *pWriter /* Writer object */
  167774. ){
  167775. /* If there were no rowids on the leaf page either and the doclist-index
  167776. ** has already been started, append an 0x00 byte to it. */
  167777. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  167778. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  167779. assert( pDlidx->bPrevValid );
  167780. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  167781. }
  167782. /* Increment the "number of sequential leaves without a term" counter. */
  167783. pWriter->nEmpty++;
  167784. }
  167785. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  167786. i64 iRowid;
  167787. int iOff;
  167788. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  167789. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  167790. return iRowid;
  167791. }
  167792. /*
  167793. ** Rowid iRowid has just been appended to the current leaf page. It is the
  167794. ** first on the page. This function appends an appropriate entry to the current
  167795. ** doclist-index.
  167796. */
  167797. static void fts5WriteDlidxAppend(
  167798. Fts5Index *p,
  167799. Fts5SegWriter *pWriter,
  167800. i64 iRowid
  167801. ){
  167802. int i;
  167803. int bDone = 0;
  167804. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  167805. i64 iVal;
  167806. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  167807. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  167808. /* The current doclist-index page is full. Write it to disk and push
  167809. ** a copy of iRowid (which will become the first rowid on the next
  167810. ** doclist-index leaf page) up into the next level of the b-tree
  167811. ** hierarchy. If the node being flushed is currently the root node,
  167812. ** also push its first rowid upwards. */
  167813. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  167814. fts5DataWrite(p,
  167815. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  167816. pDlidx->buf.p, pDlidx->buf.n
  167817. );
  167818. fts5WriteDlidxGrow(p, pWriter, i+2);
  167819. pDlidx = &pWriter->aDlidx[i];
  167820. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  167821. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  167822. /* This was the root node. Push its first rowid up to the new root. */
  167823. pDlidx[1].pgno = pDlidx->pgno;
  167824. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  167825. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  167826. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  167827. pDlidx[1].bPrevValid = 1;
  167828. pDlidx[1].iPrev = iFirst;
  167829. }
  167830. sqlite3Fts5BufferZero(&pDlidx->buf);
  167831. pDlidx->bPrevValid = 0;
  167832. pDlidx->pgno++;
  167833. }else{
  167834. bDone = 1;
  167835. }
  167836. if( pDlidx->bPrevValid ){
  167837. iVal = iRowid - pDlidx->iPrev;
  167838. }else{
  167839. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  167840. assert( pDlidx->buf.n==0 );
  167841. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  167842. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  167843. iVal = iRowid;
  167844. }
  167845. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  167846. pDlidx->bPrevValid = 1;
  167847. pDlidx->iPrev = iRowid;
  167848. }
  167849. }
  167850. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  167851. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  167852. Fts5PageWriter *pPage = &pWriter->writer;
  167853. i64 iRowid;
  167854. static int nCall = 0;
  167855. nCall++;
  167856. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  167857. /* Set the szLeaf header field. */
  167858. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  167859. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  167860. if( pWriter->bFirstTermInPage ){
  167861. /* No term was written to this page. */
  167862. assert( pPage->pgidx.n==0 );
  167863. fts5WriteBtreeNoTerm(p, pWriter);
  167864. }else{
  167865. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  167866. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  167867. }
  167868. /* Write the page out to disk */
  167869. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  167870. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  167871. /* Initialize the next page. */
  167872. fts5BufferZero(&pPage->buf);
  167873. fts5BufferZero(&pPage->pgidx);
  167874. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  167875. pPage->iPrevPgidx = 0;
  167876. pPage->pgno++;
  167877. /* Increase the leaves written counter */
  167878. pWriter->nLeafWritten++;
  167879. /* The new leaf holds no terms or rowids */
  167880. pWriter->bFirstTermInPage = 1;
  167881. pWriter->bFirstRowidInPage = 1;
  167882. }
  167883. /*
  167884. ** Append term pTerm/nTerm to the segment being written by the writer passed
  167885. ** as the second argument.
  167886. **
  167887. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  167888. ** already occurred, this function is a no-op.
  167889. */
  167890. static void fts5WriteAppendTerm(
  167891. Fts5Index *p,
  167892. Fts5SegWriter *pWriter,
  167893. int nTerm, const u8 *pTerm
  167894. ){
  167895. int nPrefix; /* Bytes of prefix compression for term */
  167896. Fts5PageWriter *pPage = &pWriter->writer;
  167897. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  167898. assert( p->rc==SQLITE_OK );
  167899. assert( pPage->buf.n>=4 );
  167900. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  167901. /* If the current leaf page is full, flush it to disk. */
  167902. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  167903. if( pPage->buf.n>4 ){
  167904. fts5WriteFlushLeaf(p, pWriter);
  167905. }
  167906. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  167907. }
  167908. /* TODO1: Updating pgidx here. */
  167909. pPgidx->n += sqlite3Fts5PutVarint(
  167910. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  167911. );
  167912. pPage->iPrevPgidx = pPage->buf.n;
  167913. #if 0
  167914. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  167915. pPgidx->n += 2;
  167916. #endif
  167917. if( pWriter->bFirstTermInPage ){
  167918. nPrefix = 0;
  167919. if( pPage->pgno!=1 ){
  167920. /* This is the first term on a leaf that is not the leftmost leaf in
  167921. ** the segment b-tree. In this case it is necessary to add a term to
  167922. ** the b-tree hierarchy that is (a) larger than the largest term
  167923. ** already written to the segment and (b) smaller than or equal to
  167924. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  167925. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  167926. ** previous term.
  167927. **
  167928. ** Usually, the previous term is available in pPage->term. The exception
  167929. ** is if this is the first term written in an incremental-merge step.
  167930. ** In this case the previous term is not available, so just write a
  167931. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  167932. ** inefficient, but still correct. */
  167933. int n = nTerm;
  167934. if( pPage->term.n ){
  167935. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  167936. }
  167937. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  167938. pPage = &pWriter->writer;
  167939. }
  167940. }else{
  167941. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  167942. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  167943. }
  167944. /* Append the number of bytes of new data, then the term data itself
  167945. ** to the page. */
  167946. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  167947. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  167948. /* Update the Fts5PageWriter.term field. */
  167949. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  167950. pWriter->bFirstTermInPage = 0;
  167951. pWriter->bFirstRowidInPage = 0;
  167952. pWriter->bFirstRowidInDoclist = 1;
  167953. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  167954. pWriter->aDlidx[0].pgno = pPage->pgno;
  167955. }
  167956. /*
  167957. ** Append a rowid and position-list size field to the writers output.
  167958. */
  167959. static void fts5WriteAppendRowid(
  167960. Fts5Index *p,
  167961. Fts5SegWriter *pWriter,
  167962. i64 iRowid
  167963. ){
  167964. if( p->rc==SQLITE_OK ){
  167965. Fts5PageWriter *pPage = &pWriter->writer;
  167966. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  167967. fts5WriteFlushLeaf(p, pWriter);
  167968. }
  167969. /* If this is to be the first rowid written to the page, set the
  167970. ** rowid-pointer in the page-header. Also append a value to the dlidx
  167971. ** buffer, in case a doclist-index is required. */
  167972. if( pWriter->bFirstRowidInPage ){
  167973. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  167974. fts5WriteDlidxAppend(p, pWriter, iRowid);
  167975. }
  167976. /* Write the rowid. */
  167977. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  167978. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  167979. }else{
  167980. assert( p->rc || iRowid>pWriter->iPrevRowid );
  167981. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  167982. }
  167983. pWriter->iPrevRowid = iRowid;
  167984. pWriter->bFirstRowidInDoclist = 0;
  167985. pWriter->bFirstRowidInPage = 0;
  167986. }
  167987. }
  167988. static void fts5WriteAppendPoslistData(
  167989. Fts5Index *p,
  167990. Fts5SegWriter *pWriter,
  167991. const u8 *aData,
  167992. int nData
  167993. ){
  167994. Fts5PageWriter *pPage = &pWriter->writer;
  167995. const u8 *a = aData;
  167996. int n = nData;
  167997. assert( p->pConfig->pgsz>0 );
  167998. while( p->rc==SQLITE_OK
  167999. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  168000. ){
  168001. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  168002. int nCopy = 0;
  168003. while( nCopy<nReq ){
  168004. i64 dummy;
  168005. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  168006. }
  168007. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  168008. a += nCopy;
  168009. n -= nCopy;
  168010. fts5WriteFlushLeaf(p, pWriter);
  168011. }
  168012. if( n>0 ){
  168013. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  168014. }
  168015. }
  168016. /*
  168017. ** Flush any data cached by the writer object to the database. Free any
  168018. ** allocations associated with the writer.
  168019. */
  168020. static void fts5WriteFinish(
  168021. Fts5Index *p,
  168022. Fts5SegWriter *pWriter, /* Writer object */
  168023. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  168024. ){
  168025. int i;
  168026. Fts5PageWriter *pLeaf = &pWriter->writer;
  168027. if( p->rc==SQLITE_OK ){
  168028. assert( pLeaf->pgno>=1 );
  168029. if( pLeaf->buf.n>4 ){
  168030. fts5WriteFlushLeaf(p, pWriter);
  168031. }
  168032. *pnLeaf = pLeaf->pgno-1;
  168033. if( pLeaf->pgno>1 ){
  168034. fts5WriteFlushBtree(p, pWriter);
  168035. }
  168036. }
  168037. fts5BufferFree(&pLeaf->term);
  168038. fts5BufferFree(&pLeaf->buf);
  168039. fts5BufferFree(&pLeaf->pgidx);
  168040. fts5BufferFree(&pWriter->btterm);
  168041. for(i=0; i<pWriter->nDlidx; i++){
  168042. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  168043. }
  168044. sqlite3_free(pWriter->aDlidx);
  168045. }
  168046. static void fts5WriteInit(
  168047. Fts5Index *p,
  168048. Fts5SegWriter *pWriter,
  168049. int iSegid
  168050. ){
  168051. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  168052. memset(pWriter, 0, sizeof(Fts5SegWriter));
  168053. pWriter->iSegid = iSegid;
  168054. fts5WriteDlidxGrow(p, pWriter, 1);
  168055. pWriter->writer.pgno = 1;
  168056. pWriter->bFirstTermInPage = 1;
  168057. pWriter->iBtPage = 1;
  168058. assert( pWriter->writer.buf.n==0 );
  168059. assert( pWriter->writer.pgidx.n==0 );
  168060. /* Grow the two buffers to pgsz + padding bytes in size. */
  168061. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  168062. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  168063. if( p->pIdxWriter==0 ){
  168064. Fts5Config *pConfig = p->pConfig;
  168065. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  168066. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  168067. pConfig->zDb, pConfig->zName
  168068. ));
  168069. }
  168070. if( p->rc==SQLITE_OK ){
  168071. /* Initialize the 4-byte leaf-page header to 0x00. */
  168072. memset(pWriter->writer.buf.p, 0, 4);
  168073. pWriter->writer.buf.n = 4;
  168074. /* Bind the current output segment id to the index-writer. This is an
  168075. ** optimization over binding the same value over and over as rows are
  168076. ** inserted into %_idx by the current writer. */
  168077. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  168078. }
  168079. }
  168080. /*
  168081. ** Iterator pIter was used to iterate through the input segments of on an
  168082. ** incremental merge operation. This function is called if the incremental
  168083. ** merge step has finished but the input has not been completely exhausted.
  168084. */
  168085. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  168086. int i;
  168087. Fts5Buffer buf;
  168088. memset(&buf, 0, sizeof(Fts5Buffer));
  168089. for(i=0; i<pIter->nSeg; i++){
  168090. Fts5SegIter *pSeg = &pIter->aSeg[i];
  168091. if( pSeg->pSeg==0 ){
  168092. /* no-op */
  168093. }else if( pSeg->pLeaf==0 ){
  168094. /* All keys from this input segment have been transfered to the output.
  168095. ** Set both the first and last page-numbers to 0 to indicate that the
  168096. ** segment is now empty. */
  168097. pSeg->pSeg->pgnoLast = 0;
  168098. pSeg->pSeg->pgnoFirst = 0;
  168099. }else{
  168100. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  168101. i64 iLeafRowid;
  168102. Fts5Data *pData;
  168103. int iId = pSeg->pSeg->iSegid;
  168104. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  168105. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  168106. pData = fts5DataRead(p, iLeafRowid);
  168107. if( pData ){
  168108. fts5BufferZero(&buf);
  168109. fts5BufferGrow(&p->rc, &buf, pData->nn);
  168110. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  168111. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  168112. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  168113. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  168114. if( p->rc==SQLITE_OK ){
  168115. /* Set the szLeaf field */
  168116. fts5PutU16(&buf.p[2], (u16)buf.n);
  168117. }
  168118. /* Set up the new page-index array */
  168119. fts5BufferAppendVarint(&p->rc, &buf, 4);
  168120. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  168121. && pSeg->iEndofDoclist<pData->szLeaf
  168122. ){
  168123. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  168124. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  168125. fts5BufferAppendBlob(&p->rc, &buf,
  168126. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  168127. );
  168128. }
  168129. fts5DataRelease(pData);
  168130. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  168131. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  168132. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  168133. }
  168134. }
  168135. }
  168136. fts5BufferFree(&buf);
  168137. }
  168138. static void fts5MergeChunkCallback(
  168139. Fts5Index *p,
  168140. void *pCtx,
  168141. const u8 *pChunk, int nChunk
  168142. ){
  168143. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  168144. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  168145. }
  168146. /*
  168147. **
  168148. */
  168149. static void fts5IndexMergeLevel(
  168150. Fts5Index *p, /* FTS5 backend object */
  168151. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  168152. int iLvl, /* Level to read input from */
  168153. int *pnRem /* Write up to this many output leaves */
  168154. ){
  168155. Fts5Structure *pStruct = *ppStruct;
  168156. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  168157. Fts5StructureLevel *pLvlOut;
  168158. Fts5Iter *pIter = 0; /* Iterator to read input data */
  168159. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  168160. int nInput; /* Number of input segments */
  168161. Fts5SegWriter writer; /* Writer object */
  168162. Fts5StructureSegment *pSeg; /* Output segment */
  168163. Fts5Buffer term;
  168164. int bOldest; /* True if the output segment is the oldest */
  168165. int eDetail = p->pConfig->eDetail;
  168166. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  168167. assert( iLvl<pStruct->nLevel );
  168168. assert( pLvl->nMerge<=pLvl->nSeg );
  168169. memset(&writer, 0, sizeof(Fts5SegWriter));
  168170. memset(&term, 0, sizeof(Fts5Buffer));
  168171. if( pLvl->nMerge ){
  168172. pLvlOut = &pStruct->aLevel[iLvl+1];
  168173. assert( pLvlOut->nSeg>0 );
  168174. nInput = pLvl->nMerge;
  168175. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  168176. fts5WriteInit(p, &writer, pSeg->iSegid);
  168177. writer.writer.pgno = pSeg->pgnoLast+1;
  168178. writer.iBtPage = 0;
  168179. }else{
  168180. int iSegid = fts5AllocateSegid(p, pStruct);
  168181. /* Extend the Fts5Structure object as required to ensure the output
  168182. ** segment exists. */
  168183. if( iLvl==pStruct->nLevel-1 ){
  168184. fts5StructureAddLevel(&p->rc, ppStruct);
  168185. pStruct = *ppStruct;
  168186. }
  168187. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  168188. if( p->rc ) return;
  168189. pLvl = &pStruct->aLevel[iLvl];
  168190. pLvlOut = &pStruct->aLevel[iLvl+1];
  168191. fts5WriteInit(p, &writer, iSegid);
  168192. /* Add the new segment to the output level */
  168193. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  168194. pLvlOut->nSeg++;
  168195. pSeg->pgnoFirst = 1;
  168196. pSeg->iSegid = iSegid;
  168197. pStruct->nSegment++;
  168198. /* Read input from all segments in the input level */
  168199. nInput = pLvl->nSeg;
  168200. }
  168201. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  168202. assert( iLvl>=0 );
  168203. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  168204. fts5MultiIterEof(p, pIter)==0;
  168205. fts5MultiIterNext(p, pIter, 0, 0)
  168206. ){
  168207. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  168208. int nPos; /* position-list size field value */
  168209. int nTerm;
  168210. const u8 *pTerm;
  168211. /* Check for key annihilation. */
  168212. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  168213. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  168214. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  168215. if( pnRem && writer.nLeafWritten>nRem ){
  168216. break;
  168217. }
  168218. /* This is a new term. Append a term to the output segment. */
  168219. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  168220. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  168221. }
  168222. /* Append the rowid to the output */
  168223. /* WRITEPOSLISTSIZE */
  168224. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  168225. if( eDetail==FTS5_DETAIL_NONE ){
  168226. if( pSegIter->bDel ){
  168227. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  168228. if( pSegIter->nPos>0 ){
  168229. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  168230. }
  168231. }
  168232. }else{
  168233. /* Append the position-list data to the output */
  168234. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  168235. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  168236. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  168237. }
  168238. }
  168239. /* Flush the last leaf page to disk. Set the output segment b-tree height
  168240. ** and last leaf page number at the same time. */
  168241. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  168242. if( fts5MultiIterEof(p, pIter) ){
  168243. int i;
  168244. /* Remove the redundant segments from the %_data table */
  168245. for(i=0; i<nInput; i++){
  168246. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  168247. }
  168248. /* Remove the redundant segments from the input level */
  168249. if( pLvl->nSeg!=nInput ){
  168250. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  168251. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  168252. }
  168253. pStruct->nSegment -= nInput;
  168254. pLvl->nSeg -= nInput;
  168255. pLvl->nMerge = 0;
  168256. if( pSeg->pgnoLast==0 ){
  168257. pLvlOut->nSeg--;
  168258. pStruct->nSegment--;
  168259. }
  168260. }else{
  168261. assert( pSeg->pgnoLast>0 );
  168262. fts5TrimSegments(p, pIter);
  168263. pLvl->nMerge = nInput;
  168264. }
  168265. fts5MultiIterFree(pIter);
  168266. fts5BufferFree(&term);
  168267. if( pnRem ) *pnRem -= writer.nLeafWritten;
  168268. }
  168269. /*
  168270. ** Do up to nPg pages of automerge work on the index.
  168271. **
  168272. ** Return true if any changes were actually made, or false otherwise.
  168273. */
  168274. static int fts5IndexMerge(
  168275. Fts5Index *p, /* FTS5 backend object */
  168276. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  168277. int nPg, /* Pages of work to do */
  168278. int nMin /* Minimum number of segments to merge */
  168279. ){
  168280. int nRem = nPg;
  168281. int bRet = 0;
  168282. Fts5Structure *pStruct = *ppStruct;
  168283. while( nRem>0 && p->rc==SQLITE_OK ){
  168284. int iLvl; /* To iterate through levels */
  168285. int iBestLvl = 0; /* Level offering the most input segments */
  168286. int nBest = 0; /* Number of input segments on best level */
  168287. /* Set iBestLvl to the level to read input segments from. */
  168288. assert( pStruct->nLevel>0 );
  168289. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  168290. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  168291. if( pLvl->nMerge ){
  168292. if( pLvl->nMerge>nBest ){
  168293. iBestLvl = iLvl;
  168294. nBest = pLvl->nMerge;
  168295. }
  168296. break;
  168297. }
  168298. if( pLvl->nSeg>nBest ){
  168299. nBest = pLvl->nSeg;
  168300. iBestLvl = iLvl;
  168301. }
  168302. }
  168303. /* If nBest is still 0, then the index must be empty. */
  168304. #ifdef SQLITE_DEBUG
  168305. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  168306. assert( pStruct->aLevel[iLvl].nSeg==0 );
  168307. }
  168308. #endif
  168309. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  168310. break;
  168311. }
  168312. bRet = 1;
  168313. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  168314. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  168315. fts5StructurePromote(p, iBestLvl+1, pStruct);
  168316. }
  168317. }
  168318. *ppStruct = pStruct;
  168319. return bRet;
  168320. }
  168321. /*
  168322. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  168323. ** segment. This function updates the write-counter accordingly and, if
  168324. ** necessary, performs incremental merge work.
  168325. **
  168326. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  168327. ** already occurred, this function is a no-op.
  168328. */
  168329. static void fts5IndexAutomerge(
  168330. Fts5Index *p, /* FTS5 backend object */
  168331. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  168332. int nLeaf /* Number of output leaves just written */
  168333. ){
  168334. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  168335. Fts5Structure *pStruct = *ppStruct;
  168336. u64 nWrite; /* Initial value of write-counter */
  168337. int nWork; /* Number of work-quanta to perform */
  168338. int nRem; /* Number of leaf pages left to write */
  168339. /* Update the write-counter. While doing so, set nWork. */
  168340. nWrite = pStruct->nWriteCounter;
  168341. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  168342. pStruct->nWriteCounter += nLeaf;
  168343. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  168344. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  168345. }
  168346. }
  168347. static void fts5IndexCrisismerge(
  168348. Fts5Index *p, /* FTS5 backend object */
  168349. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  168350. ){
  168351. const int nCrisis = p->pConfig->nCrisisMerge;
  168352. Fts5Structure *pStruct = *ppStruct;
  168353. int iLvl = 0;
  168354. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  168355. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  168356. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  168357. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  168358. fts5StructurePromote(p, iLvl+1, pStruct);
  168359. iLvl++;
  168360. }
  168361. *ppStruct = pStruct;
  168362. }
  168363. static int fts5IndexReturn(Fts5Index *p){
  168364. int rc = p->rc;
  168365. p->rc = SQLITE_OK;
  168366. return rc;
  168367. }
  168368. typedef struct Fts5FlushCtx Fts5FlushCtx;
  168369. struct Fts5FlushCtx {
  168370. Fts5Index *pIdx;
  168371. Fts5SegWriter writer;
  168372. };
  168373. /*
  168374. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  168375. ** in a 32-bit integer. Return the size of the largest prefix of this
  168376. ** list nMax bytes or less in size.
  168377. */
  168378. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  168379. int ret;
  168380. u32 dummy;
  168381. ret = fts5GetVarint32(aBuf, dummy);
  168382. if( ret<nMax ){
  168383. while( 1 ){
  168384. int i = fts5GetVarint32(&aBuf[ret], dummy);
  168385. if( (ret + i) > nMax ) break;
  168386. ret += i;
  168387. }
  168388. }
  168389. return ret;
  168390. }
  168391. /*
  168392. ** Flush the contents of in-memory hash table iHash to a new level-0
  168393. ** segment on disk. Also update the corresponding structure record.
  168394. **
  168395. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  168396. ** already occurred, this function is a no-op.
  168397. */
  168398. static void fts5FlushOneHash(Fts5Index *p){
  168399. Fts5Hash *pHash = p->pHash;
  168400. Fts5Structure *pStruct;
  168401. int iSegid;
  168402. int pgnoLast = 0; /* Last leaf page number in segment */
  168403. /* Obtain a reference to the index structure and allocate a new segment-id
  168404. ** for the new level-0 segment. */
  168405. pStruct = fts5StructureRead(p);
  168406. iSegid = fts5AllocateSegid(p, pStruct);
  168407. fts5StructureInvalidate(p);
  168408. if( iSegid ){
  168409. const int pgsz = p->pConfig->pgsz;
  168410. int eDetail = p->pConfig->eDetail;
  168411. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  168412. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  168413. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  168414. Fts5SegWriter writer;
  168415. fts5WriteInit(p, &writer, iSegid);
  168416. pBuf = &writer.writer.buf;
  168417. pPgidx = &writer.writer.pgidx;
  168418. /* fts5WriteInit() should have initialized the buffers to (most likely)
  168419. ** the maximum space required. */
  168420. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  168421. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  168422. /* Begin scanning through hash table entries. This loop runs once for each
  168423. ** term/doclist currently stored within the hash table. */
  168424. if( p->rc==SQLITE_OK ){
  168425. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  168426. }
  168427. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  168428. const char *zTerm; /* Buffer containing term */
  168429. const u8 *pDoclist; /* Pointer to doclist for this term */
  168430. int nDoclist; /* Size of doclist in bytes */
  168431. /* Write the term for this entry to disk. */
  168432. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  168433. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  168434. assert( writer.bFirstRowidInPage==0 );
  168435. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  168436. /* The entire doclist will fit on the current leaf. */
  168437. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  168438. }else{
  168439. i64 iRowid = 0;
  168440. i64 iDelta = 0;
  168441. int iOff = 0;
  168442. /* The entire doclist will not fit on this leaf. The following
  168443. ** loop iterates through the poslists that make up the current
  168444. ** doclist. */
  168445. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  168446. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  168447. iRowid += iDelta;
  168448. if( writer.bFirstRowidInPage ){
  168449. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  168450. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  168451. writer.bFirstRowidInPage = 0;
  168452. fts5WriteDlidxAppend(p, &writer, iRowid);
  168453. }else{
  168454. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  168455. }
  168456. assert( pBuf->n<=pBuf->nSpace );
  168457. if( eDetail==FTS5_DETAIL_NONE ){
  168458. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  168459. pBuf->p[pBuf->n++] = 0;
  168460. iOff++;
  168461. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  168462. pBuf->p[pBuf->n++] = 0;
  168463. iOff++;
  168464. }
  168465. }
  168466. if( (pBuf->n + pPgidx->n)>=pgsz ){
  168467. fts5WriteFlushLeaf(p, &writer);
  168468. }
  168469. }else{
  168470. int bDummy;
  168471. int nPos;
  168472. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  168473. nCopy += nPos;
  168474. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  168475. /* The entire poslist will fit on the current leaf. So copy
  168476. ** it in one go. */
  168477. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  168478. }else{
  168479. /* The entire poslist will not fit on this leaf. So it needs
  168480. ** to be broken into sections. The only qualification being
  168481. ** that each varint must be stored contiguously. */
  168482. const u8 *pPoslist = &pDoclist[iOff];
  168483. int iPos = 0;
  168484. while( p->rc==SQLITE_OK ){
  168485. int nSpace = pgsz - pBuf->n - pPgidx->n;
  168486. int n = 0;
  168487. if( (nCopy - iPos)<=nSpace ){
  168488. n = nCopy - iPos;
  168489. }else{
  168490. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  168491. }
  168492. assert( n>0 );
  168493. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  168494. iPos += n;
  168495. if( (pBuf->n + pPgidx->n)>=pgsz ){
  168496. fts5WriteFlushLeaf(p, &writer);
  168497. }
  168498. if( iPos>=nCopy ) break;
  168499. }
  168500. }
  168501. iOff += nCopy;
  168502. }
  168503. }
  168504. }
  168505. /* TODO2: Doclist terminator written here. */
  168506. /* pBuf->p[pBuf->n++] = '\0'; */
  168507. assert( pBuf->n<=pBuf->nSpace );
  168508. sqlite3Fts5HashScanNext(pHash);
  168509. }
  168510. sqlite3Fts5HashClear(pHash);
  168511. fts5WriteFinish(p, &writer, &pgnoLast);
  168512. /* Update the Fts5Structure. It is written back to the database by the
  168513. ** fts5StructureRelease() call below. */
  168514. if( pStruct->nLevel==0 ){
  168515. fts5StructureAddLevel(&p->rc, &pStruct);
  168516. }
  168517. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  168518. if( p->rc==SQLITE_OK ){
  168519. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  168520. pSeg->iSegid = iSegid;
  168521. pSeg->pgnoFirst = 1;
  168522. pSeg->pgnoLast = pgnoLast;
  168523. pStruct->nSegment++;
  168524. }
  168525. fts5StructurePromote(p, 0, pStruct);
  168526. }
  168527. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  168528. fts5IndexCrisismerge(p, &pStruct);
  168529. fts5StructureWrite(p, pStruct);
  168530. fts5StructureRelease(pStruct);
  168531. }
  168532. /*
  168533. ** Flush any data stored in the in-memory hash tables to the database.
  168534. */
  168535. static void fts5IndexFlush(Fts5Index *p){
  168536. /* Unless it is empty, flush the hash table to disk */
  168537. if( p->nPendingData ){
  168538. assert( p->pHash );
  168539. p->nPendingData = 0;
  168540. fts5FlushOneHash(p);
  168541. }
  168542. }
  168543. static Fts5Structure *fts5IndexOptimizeStruct(
  168544. Fts5Index *p,
  168545. Fts5Structure *pStruct
  168546. ){
  168547. Fts5Structure *pNew = 0;
  168548. int nByte = sizeof(Fts5Structure);
  168549. int nSeg = pStruct->nSegment;
  168550. int i;
  168551. /* Figure out if this structure requires optimization. A structure does
  168552. ** not require optimization if either:
  168553. **
  168554. ** + it consists of fewer than two segments, or
  168555. ** + all segments are on the same level, or
  168556. ** + all segments except one are currently inputs to a merge operation.
  168557. **
  168558. ** In the first case, return NULL. In the second, increment the ref-count
  168559. ** on *pStruct and return a copy of the pointer to it.
  168560. */
  168561. if( nSeg<2 ) return 0;
  168562. for(i=0; i<pStruct->nLevel; i++){
  168563. int nThis = pStruct->aLevel[i].nSeg;
  168564. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  168565. fts5StructureRef(pStruct);
  168566. return pStruct;
  168567. }
  168568. assert( pStruct->aLevel[i].nMerge<=nThis );
  168569. }
  168570. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  168571. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  168572. if( pNew ){
  168573. Fts5StructureLevel *pLvl;
  168574. nByte = nSeg * sizeof(Fts5StructureSegment);
  168575. pNew->nLevel = pStruct->nLevel+1;
  168576. pNew->nRef = 1;
  168577. pNew->nWriteCounter = pStruct->nWriteCounter;
  168578. pLvl = &pNew->aLevel[pStruct->nLevel];
  168579. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  168580. if( pLvl->aSeg ){
  168581. int iLvl, iSeg;
  168582. int iSegOut = 0;
  168583. /* Iterate through all segments, from oldest to newest. Add them to
  168584. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  168585. ** segment in the data structure. */
  168586. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  168587. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  168588. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  168589. iSegOut++;
  168590. }
  168591. }
  168592. pNew->nSegment = pLvl->nSeg = nSeg;
  168593. }else{
  168594. sqlite3_free(pNew);
  168595. pNew = 0;
  168596. }
  168597. }
  168598. return pNew;
  168599. }
  168600. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  168601. Fts5Structure *pStruct;
  168602. Fts5Structure *pNew = 0;
  168603. assert( p->rc==SQLITE_OK );
  168604. fts5IndexFlush(p);
  168605. pStruct = fts5StructureRead(p);
  168606. fts5StructureInvalidate(p);
  168607. if( pStruct ){
  168608. pNew = fts5IndexOptimizeStruct(p, pStruct);
  168609. }
  168610. fts5StructureRelease(pStruct);
  168611. assert( pNew==0 || pNew->nSegment>0 );
  168612. if( pNew ){
  168613. int iLvl;
  168614. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  168615. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  168616. int nRem = FTS5_OPT_WORK_UNIT;
  168617. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  168618. }
  168619. fts5StructureWrite(p, pNew);
  168620. fts5StructureRelease(pNew);
  168621. }
  168622. return fts5IndexReturn(p);
  168623. }
  168624. /*
  168625. ** This is called to implement the special "VALUES('merge', $nMerge)"
  168626. ** INSERT command.
  168627. */
  168628. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  168629. Fts5Structure *pStruct = fts5StructureRead(p);
  168630. if( pStruct ){
  168631. int nMin = p->pConfig->nUsermerge;
  168632. fts5StructureInvalidate(p);
  168633. if( nMerge<0 ){
  168634. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  168635. fts5StructureRelease(pStruct);
  168636. pStruct = pNew;
  168637. nMin = 2;
  168638. nMerge = nMerge*-1;
  168639. }
  168640. if( pStruct && pStruct->nLevel ){
  168641. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  168642. fts5StructureWrite(p, pStruct);
  168643. }
  168644. }
  168645. fts5StructureRelease(pStruct);
  168646. }
  168647. return fts5IndexReturn(p);
  168648. }
  168649. static void fts5AppendRowid(
  168650. Fts5Index *p,
  168651. i64 iDelta,
  168652. Fts5Iter *pUnused,
  168653. Fts5Buffer *pBuf
  168654. ){
  168655. UNUSED_PARAM(pUnused);
  168656. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  168657. }
  168658. static void fts5AppendPoslist(
  168659. Fts5Index *p,
  168660. i64 iDelta,
  168661. Fts5Iter *pMulti,
  168662. Fts5Buffer *pBuf
  168663. ){
  168664. int nData = pMulti->base.nData;
  168665. assert( nData>0 );
  168666. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  168667. fts5BufferSafeAppendVarint(pBuf, iDelta);
  168668. fts5BufferSafeAppendVarint(pBuf, nData*2);
  168669. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  168670. }
  168671. }
  168672. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  168673. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  168674. assert( pIter->aPoslist );
  168675. if( p>=pIter->aEof ){
  168676. pIter->aPoslist = 0;
  168677. }else{
  168678. i64 iDelta;
  168679. p += fts5GetVarint(p, (u64*)&iDelta);
  168680. pIter->iRowid += iDelta;
  168681. /* Read position list size */
  168682. if( p[0] & 0x80 ){
  168683. int nPos;
  168684. pIter->nSize = fts5GetVarint32(p, nPos);
  168685. pIter->nPoslist = (nPos>>1);
  168686. }else{
  168687. pIter->nPoslist = ((int)(p[0])) >> 1;
  168688. pIter->nSize = 1;
  168689. }
  168690. pIter->aPoslist = p;
  168691. }
  168692. }
  168693. static void fts5DoclistIterInit(
  168694. Fts5Buffer *pBuf,
  168695. Fts5DoclistIter *pIter
  168696. ){
  168697. memset(pIter, 0, sizeof(*pIter));
  168698. pIter->aPoslist = pBuf->p;
  168699. pIter->aEof = &pBuf->p[pBuf->n];
  168700. fts5DoclistIterNext(pIter);
  168701. }
  168702. #if 0
  168703. /*
  168704. ** Append a doclist to buffer pBuf.
  168705. **
  168706. ** This function assumes that space within the buffer has already been
  168707. ** allocated.
  168708. */
  168709. static void fts5MergeAppendDocid(
  168710. Fts5Buffer *pBuf, /* Buffer to write to */
  168711. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  168712. i64 iRowid /* Rowid to append */
  168713. ){
  168714. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  168715. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  168716. *piLastRowid = iRowid;
  168717. }
  168718. #endif
  168719. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  168720. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  168721. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  168722. (iLastRowid) = (iRowid); \
  168723. }
  168724. /*
  168725. ** Swap the contents of buffer *p1 with that of *p2.
  168726. */
  168727. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  168728. Fts5Buffer tmp = *p1;
  168729. *p1 = *p2;
  168730. *p2 = tmp;
  168731. }
  168732. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  168733. int i = *piOff;
  168734. if( i>=pBuf->n ){
  168735. *piOff = -1;
  168736. }else{
  168737. u64 iVal;
  168738. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  168739. *piRowid += iVal;
  168740. }
  168741. }
  168742. /*
  168743. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  168744. ** In this case the buffers consist of a delta-encoded list of rowids only.
  168745. */
  168746. static void fts5MergeRowidLists(
  168747. Fts5Index *p, /* FTS5 backend object */
  168748. Fts5Buffer *p1, /* First list to merge */
  168749. Fts5Buffer *p2 /* Second list to merge */
  168750. ){
  168751. int i1 = 0;
  168752. int i2 = 0;
  168753. i64 iRowid1 = 0;
  168754. i64 iRowid2 = 0;
  168755. i64 iOut = 0;
  168756. Fts5Buffer out;
  168757. memset(&out, 0, sizeof(out));
  168758. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  168759. if( p->rc ) return;
  168760. fts5NextRowid(p1, &i1, &iRowid1);
  168761. fts5NextRowid(p2, &i2, &iRowid2);
  168762. while( i1>=0 || i2>=0 ){
  168763. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  168764. assert( iOut==0 || iRowid1>iOut );
  168765. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  168766. iOut = iRowid1;
  168767. fts5NextRowid(p1, &i1, &iRowid1);
  168768. }else{
  168769. assert( iOut==0 || iRowid2>iOut );
  168770. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  168771. iOut = iRowid2;
  168772. if( i1>=0 && iRowid1==iRowid2 ){
  168773. fts5NextRowid(p1, &i1, &iRowid1);
  168774. }
  168775. fts5NextRowid(p2, &i2, &iRowid2);
  168776. }
  168777. }
  168778. fts5BufferSwap(&out, p1);
  168779. fts5BufferFree(&out);
  168780. }
  168781. /*
  168782. ** Buffers p1 and p2 contain doclists. This function merges the content
  168783. ** of the two doclists together and sets buffer p1 to the result before
  168784. ** returning.
  168785. **
  168786. ** If an error occurs, an error code is left in p->rc. If an error has
  168787. ** already occurred, this function is a no-op.
  168788. */
  168789. static void fts5MergePrefixLists(
  168790. Fts5Index *p, /* FTS5 backend object */
  168791. Fts5Buffer *p1, /* First list to merge */
  168792. Fts5Buffer *p2 /* Second list to merge */
  168793. ){
  168794. if( p2->n ){
  168795. i64 iLastRowid = 0;
  168796. Fts5DoclistIter i1;
  168797. Fts5DoclistIter i2;
  168798. Fts5Buffer out = {0, 0, 0};
  168799. Fts5Buffer tmp = {0, 0, 0};
  168800. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
  168801. fts5DoclistIterInit(p1, &i1);
  168802. fts5DoclistIterInit(p2, &i2);
  168803. while( 1 ){
  168804. if( i1.iRowid<i2.iRowid ){
  168805. /* Copy entry from i1 */
  168806. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  168807. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  168808. fts5DoclistIterNext(&i1);
  168809. if( i1.aPoslist==0 ) break;
  168810. }
  168811. else if( i2.iRowid!=i1.iRowid ){
  168812. /* Copy entry from i2 */
  168813. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  168814. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  168815. fts5DoclistIterNext(&i2);
  168816. if( i2.aPoslist==0 ) break;
  168817. }
  168818. else{
  168819. /* Merge the two position lists. */
  168820. i64 iPos1 = 0;
  168821. i64 iPos2 = 0;
  168822. int iOff1 = 0;
  168823. int iOff2 = 0;
  168824. u8 *a1 = &i1.aPoslist[i1.nSize];
  168825. u8 *a2 = &i2.aPoslist[i2.nSize];
  168826. i64 iPrev = 0;
  168827. Fts5PoslistWriter writer;
  168828. memset(&writer, 0, sizeof(writer));
  168829. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  168830. fts5BufferZero(&tmp);
  168831. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  168832. if( p->rc ) break;
  168833. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  168834. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  168835. assert( iPos1>=0 && iPos2>=0 );
  168836. if( iPos1<iPos2 ){
  168837. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  168838. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  168839. }else{
  168840. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  168841. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  168842. }
  168843. if( iPos1>=0 && iPos2>=0 ){
  168844. while( 1 ){
  168845. if( iPos1<iPos2 ){
  168846. if( iPos1!=iPrev ){
  168847. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  168848. }
  168849. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  168850. if( iPos1<0 ) break;
  168851. }else{
  168852. assert( iPos2!=iPrev );
  168853. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  168854. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  168855. if( iPos2<0 ) break;
  168856. }
  168857. }
  168858. }
  168859. if( iPos1>=0 ){
  168860. if( iPos1!=iPrev ){
  168861. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  168862. }
  168863. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  168864. }else{
  168865. assert( iPos2>=0 && iPos2!=iPrev );
  168866. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  168867. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  168868. }
  168869. /* WRITEPOSLISTSIZE */
  168870. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  168871. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  168872. fts5DoclistIterNext(&i1);
  168873. fts5DoclistIterNext(&i2);
  168874. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  168875. }
  168876. }
  168877. if( i1.aPoslist ){
  168878. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  168879. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  168880. }
  168881. else if( i2.aPoslist ){
  168882. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  168883. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  168884. }
  168885. fts5BufferSet(&p->rc, p1, out.n, out.p);
  168886. fts5BufferFree(&tmp);
  168887. fts5BufferFree(&out);
  168888. }
  168889. }
  168890. static void fts5SetupPrefixIter(
  168891. Fts5Index *p, /* Index to read from */
  168892. int bDesc, /* True for "ORDER BY rowid DESC" */
  168893. const u8 *pToken, /* Buffer containing prefix to match */
  168894. int nToken, /* Size of buffer pToken in bytes */
  168895. Fts5Colset *pColset, /* Restrict matches to these columns */
  168896. Fts5Iter **ppIter /* OUT: New iterator */
  168897. ){
  168898. Fts5Structure *pStruct;
  168899. Fts5Buffer *aBuf;
  168900. const int nBuf = 32;
  168901. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  168902. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  168903. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  168904. xMerge = fts5MergeRowidLists;
  168905. xAppend = fts5AppendRowid;
  168906. }else{
  168907. xMerge = fts5MergePrefixLists;
  168908. xAppend = fts5AppendPoslist;
  168909. }
  168910. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  168911. pStruct = fts5StructureRead(p);
  168912. if( aBuf && pStruct ){
  168913. const int flags = FTS5INDEX_QUERY_SCAN
  168914. | FTS5INDEX_QUERY_SKIPEMPTY
  168915. | FTS5INDEX_QUERY_NOOUTPUT;
  168916. int i;
  168917. i64 iLastRowid = 0;
  168918. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  168919. Fts5Data *pData;
  168920. Fts5Buffer doclist;
  168921. int bNewTerm = 1;
  168922. memset(&doclist, 0, sizeof(doclist));
  168923. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  168924. fts5IterSetOutputCb(&p->rc, p1);
  168925. for( /* no-op */ ;
  168926. fts5MultiIterEof(p, p1)==0;
  168927. fts5MultiIterNext2(p, p1, &bNewTerm)
  168928. ){
  168929. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  168930. int nTerm = pSeg->term.n;
  168931. const u8 *pTerm = pSeg->term.p;
  168932. p1->xSetOutputs(p1, pSeg);
  168933. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  168934. if( bNewTerm ){
  168935. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  168936. }
  168937. if( p1->base.nData==0 ) continue;
  168938. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  168939. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  168940. assert( i<nBuf );
  168941. if( aBuf[i].n==0 ){
  168942. fts5BufferSwap(&doclist, &aBuf[i]);
  168943. fts5BufferZero(&doclist);
  168944. }else{
  168945. xMerge(p, &doclist, &aBuf[i]);
  168946. fts5BufferZero(&aBuf[i]);
  168947. }
  168948. }
  168949. iLastRowid = 0;
  168950. }
  168951. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  168952. iLastRowid = p1->base.iRowid;
  168953. }
  168954. for(i=0; i<nBuf; i++){
  168955. if( p->rc==SQLITE_OK ){
  168956. xMerge(p, &doclist, &aBuf[i]);
  168957. }
  168958. fts5BufferFree(&aBuf[i]);
  168959. }
  168960. fts5MultiIterFree(p1);
  168961. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  168962. if( pData ){
  168963. pData->p = (u8*)&pData[1];
  168964. pData->nn = pData->szLeaf = doclist.n;
  168965. memcpy(pData->p, doclist.p, doclist.n);
  168966. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  168967. }
  168968. fts5BufferFree(&doclist);
  168969. }
  168970. fts5StructureRelease(pStruct);
  168971. sqlite3_free(aBuf);
  168972. }
  168973. /*
  168974. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  168975. ** to the document with rowid iRowid.
  168976. */
  168977. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  168978. assert( p->rc==SQLITE_OK );
  168979. /* Allocate the hash table if it has not already been allocated */
  168980. if( p->pHash==0 ){
  168981. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  168982. }
  168983. /* Flush the hash table to disk if required */
  168984. if( iRowid<p->iWriteRowid
  168985. || (iRowid==p->iWriteRowid && p->bDelete==0)
  168986. || (p->nPendingData > p->pConfig->nHashSize)
  168987. ){
  168988. fts5IndexFlush(p);
  168989. }
  168990. p->iWriteRowid = iRowid;
  168991. p->bDelete = bDelete;
  168992. return fts5IndexReturn(p);
  168993. }
  168994. /*
  168995. ** Commit data to disk.
  168996. */
  168997. static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
  168998. assert( p->rc==SQLITE_OK );
  168999. fts5IndexFlush(p);
  169000. if( bCommit ) fts5CloseReader(p);
  169001. return fts5IndexReturn(p);
  169002. }
  169003. /*
  169004. ** Discard any data stored in the in-memory hash tables. Do not write it
  169005. ** to the database. Additionally, assume that the contents of the %_data
  169006. ** table may have changed on disk. So any in-memory caches of %_data
  169007. ** records must be invalidated.
  169008. */
  169009. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  169010. fts5CloseReader(p);
  169011. fts5IndexDiscardData(p);
  169012. fts5StructureInvalidate(p);
  169013. /* assert( p->rc==SQLITE_OK ); */
  169014. return SQLITE_OK;
  169015. }
  169016. /*
  169017. ** The %_data table is completely empty when this function is called. This
  169018. ** function populates it with the initial structure objects for each index,
  169019. ** and the initial version of the "averages" record (a zero-byte blob).
  169020. */
  169021. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  169022. Fts5Structure s;
  169023. fts5StructureInvalidate(p);
  169024. memset(&s, 0, sizeof(Fts5Structure));
  169025. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  169026. fts5StructureWrite(p, &s);
  169027. return fts5IndexReturn(p);
  169028. }
  169029. /*
  169030. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  169031. ** and initialize the underlying %_data table.
  169032. **
  169033. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  169034. ** Otherwise, set *pp to NULL and return an SQLite error code.
  169035. */
  169036. static int sqlite3Fts5IndexOpen(
  169037. Fts5Config *pConfig,
  169038. int bCreate,
  169039. Fts5Index **pp,
  169040. char **pzErr
  169041. ){
  169042. int rc = SQLITE_OK;
  169043. Fts5Index *p; /* New object */
  169044. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  169045. if( rc==SQLITE_OK ){
  169046. p->pConfig = pConfig;
  169047. p->nWorkUnit = FTS5_WORK_UNIT;
  169048. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  169049. if( p->zDataTbl && bCreate ){
  169050. rc = sqlite3Fts5CreateTable(
  169051. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  169052. );
  169053. if( rc==SQLITE_OK ){
  169054. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  169055. "segid, term, pgno, PRIMARY KEY(segid, term)",
  169056. 1, pzErr
  169057. );
  169058. }
  169059. if( rc==SQLITE_OK ){
  169060. rc = sqlite3Fts5IndexReinit(p);
  169061. }
  169062. }
  169063. }
  169064. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  169065. if( rc ){
  169066. sqlite3Fts5IndexClose(p);
  169067. *pp = 0;
  169068. }
  169069. return rc;
  169070. }
  169071. /*
  169072. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  169073. */
  169074. static int sqlite3Fts5IndexClose(Fts5Index *p){
  169075. int rc = SQLITE_OK;
  169076. if( p ){
  169077. assert( p->pReader==0 );
  169078. fts5StructureInvalidate(p);
  169079. sqlite3_finalize(p->pWriter);
  169080. sqlite3_finalize(p->pDeleter);
  169081. sqlite3_finalize(p->pIdxWriter);
  169082. sqlite3_finalize(p->pIdxDeleter);
  169083. sqlite3_finalize(p->pIdxSelect);
  169084. sqlite3_finalize(p->pDataVersion);
  169085. sqlite3Fts5HashFree(p->pHash);
  169086. sqlite3_free(p->zDataTbl);
  169087. sqlite3_free(p);
  169088. }
  169089. return rc;
  169090. }
  169091. /*
  169092. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  169093. ** size. Return the number of bytes in the nChar character prefix of the
  169094. ** buffer, or 0 if there are less than nChar characters in total.
  169095. */
  169096. static int sqlite3Fts5IndexCharlenToBytelen(
  169097. const char *p,
  169098. int nByte,
  169099. int nChar
  169100. ){
  169101. int n = 0;
  169102. int i;
  169103. for(i=0; i<nChar; i++){
  169104. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  169105. if( (unsigned char)p[n++]>=0xc0 ){
  169106. while( (p[n] & 0xc0)==0x80 ) n++;
  169107. }
  169108. }
  169109. return n;
  169110. }
  169111. /*
  169112. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  169113. ** unicode characters in the string.
  169114. */
  169115. static int fts5IndexCharlen(const char *pIn, int nIn){
  169116. int nChar = 0;
  169117. int i = 0;
  169118. while( i<nIn ){
  169119. if( (unsigned char)pIn[i++]>=0xc0 ){
  169120. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  169121. }
  169122. nChar++;
  169123. }
  169124. return nChar;
  169125. }
  169126. /*
  169127. ** Insert or remove data to or from the index. Each time a document is
  169128. ** added to or removed from the index, this function is called one or more
  169129. ** times.
  169130. **
  169131. ** For an insert, it must be called once for each token in the new document.
  169132. ** If the operation is a delete, it must be called (at least) once for each
  169133. ** unique token in the document with an iCol value less than zero. The iPos
  169134. ** argument is ignored for a delete.
  169135. */
  169136. static int sqlite3Fts5IndexWrite(
  169137. Fts5Index *p, /* Index to write to */
  169138. int iCol, /* Column token appears in (-ve -> delete) */
  169139. int iPos, /* Position of token within column */
  169140. const char *pToken, int nToken /* Token to add or remove to or from index */
  169141. ){
  169142. int i; /* Used to iterate through indexes */
  169143. int rc = SQLITE_OK; /* Return code */
  169144. Fts5Config *pConfig = p->pConfig;
  169145. assert( p->rc==SQLITE_OK );
  169146. assert( (iCol<0)==p->bDelete );
  169147. /* Add the entry to the main terms index. */
  169148. rc = sqlite3Fts5HashWrite(
  169149. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  169150. );
  169151. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  169152. const int nChar = pConfig->aPrefix[i];
  169153. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  169154. if( nByte ){
  169155. rc = sqlite3Fts5HashWrite(p->pHash,
  169156. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  169157. nByte
  169158. );
  169159. }
  169160. }
  169161. return rc;
  169162. }
  169163. /*
  169164. ** Open a new iterator to iterate though all rowid that match the
  169165. ** specified token or token prefix.
  169166. */
  169167. static int sqlite3Fts5IndexQuery(
  169168. Fts5Index *p, /* FTS index to query */
  169169. const char *pToken, int nToken, /* Token (or prefix) to query for */
  169170. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  169171. Fts5Colset *pColset, /* Match these columns only */
  169172. Fts5IndexIter **ppIter /* OUT: New iterator object */
  169173. ){
  169174. Fts5Config *pConfig = p->pConfig;
  169175. Fts5Iter *pRet = 0;
  169176. Fts5Buffer buf = {0, 0, 0};
  169177. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  169178. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  169179. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  169180. int iIdx = 0; /* Index to search */
  169181. memcpy(&buf.p[1], pToken, nToken);
  169182. /* Figure out which index to search and set iIdx accordingly. If this
  169183. ** is a prefix query for which there is no prefix index, set iIdx to
  169184. ** greater than pConfig->nPrefix to indicate that the query will be
  169185. ** satisfied by scanning multiple terms in the main index.
  169186. **
  169187. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  169188. ** prefix-query. Instead of using a prefix-index (if one exists),
  169189. ** evaluate the prefix query using the main FTS index. This is used
  169190. ** for internal sanity checking by the integrity-check in debug
  169191. ** mode only. */
  169192. #ifdef SQLITE_DEBUG
  169193. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  169194. assert( flags & FTS5INDEX_QUERY_PREFIX );
  169195. iIdx = 1+pConfig->nPrefix;
  169196. }else
  169197. #endif
  169198. if( flags & FTS5INDEX_QUERY_PREFIX ){
  169199. int nChar = fts5IndexCharlen(pToken, nToken);
  169200. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  169201. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  169202. }
  169203. }
  169204. if( iIdx<=pConfig->nPrefix ){
  169205. /* Straight index lookup */
  169206. Fts5Structure *pStruct = fts5StructureRead(p);
  169207. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  169208. if( pStruct ){
  169209. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  169210. pColset, buf.p, nToken+1, -1, 0, &pRet
  169211. );
  169212. fts5StructureRelease(pStruct);
  169213. }
  169214. }else{
  169215. /* Scan multiple terms in the main index */
  169216. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  169217. buf.p[0] = FTS5_MAIN_PREFIX;
  169218. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  169219. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  169220. fts5IterSetOutputCb(&p->rc, pRet);
  169221. if( p->rc==SQLITE_OK ){
  169222. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  169223. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  169224. }
  169225. }
  169226. if( p->rc ){
  169227. sqlite3Fts5IterClose(&pRet->base);
  169228. pRet = 0;
  169229. fts5CloseReader(p);
  169230. }
  169231. *ppIter = &pRet->base;
  169232. sqlite3Fts5BufferFree(&buf);
  169233. }
  169234. return fts5IndexReturn(p);
  169235. }
  169236. /*
  169237. ** Return true if the iterator passed as the only argument is at EOF.
  169238. */
  169239. /*
  169240. ** Move to the next matching rowid.
  169241. */
  169242. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  169243. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  169244. assert( pIter->pIndex->rc==SQLITE_OK );
  169245. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  169246. return fts5IndexReturn(pIter->pIndex);
  169247. }
  169248. /*
  169249. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  169250. */
  169251. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  169252. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  169253. Fts5Index *p = pIter->pIndex;
  169254. assert( pIter->pIndex->rc==SQLITE_OK );
  169255. fts5MultiIterNext(p, pIter, 0, 0);
  169256. if( p->rc==SQLITE_OK ){
  169257. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  169258. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  169259. fts5DataRelease(pSeg->pLeaf);
  169260. pSeg->pLeaf = 0;
  169261. pIter->base.bEof = 1;
  169262. }
  169263. }
  169264. return fts5IndexReturn(pIter->pIndex);
  169265. }
  169266. /*
  169267. ** Move to the next matching rowid that occurs at or after iMatch. The
  169268. ** definition of "at or after" depends on whether this iterator iterates
  169269. ** in ascending or descending rowid order.
  169270. */
  169271. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  169272. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  169273. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  169274. return fts5IndexReturn(pIter->pIndex);
  169275. }
  169276. /*
  169277. ** Return the current term.
  169278. */
  169279. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  169280. int n;
  169281. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  169282. *pn = n-1;
  169283. return &z[1];
  169284. }
  169285. /*
  169286. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  169287. */
  169288. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  169289. if( pIndexIter ){
  169290. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  169291. Fts5Index *pIndex = pIter->pIndex;
  169292. fts5MultiIterFree(pIter);
  169293. fts5CloseReader(pIndex);
  169294. }
  169295. }
  169296. /*
  169297. ** Read and decode the "averages" record from the database.
  169298. **
  169299. ** Parameter anSize must point to an array of size nCol, where nCol is
  169300. ** the number of user defined columns in the FTS table.
  169301. */
  169302. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  169303. int nCol = p->pConfig->nCol;
  169304. Fts5Data *pData;
  169305. *pnRow = 0;
  169306. memset(anSize, 0, sizeof(i64) * nCol);
  169307. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  169308. if( p->rc==SQLITE_OK && pData->nn ){
  169309. int i = 0;
  169310. int iCol;
  169311. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  169312. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  169313. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  169314. }
  169315. }
  169316. fts5DataRelease(pData);
  169317. return fts5IndexReturn(p);
  169318. }
  169319. /*
  169320. ** Replace the current "averages" record with the contents of the buffer
  169321. ** supplied as the second argument.
  169322. */
  169323. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  169324. assert( p->rc==SQLITE_OK );
  169325. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  169326. return fts5IndexReturn(p);
  169327. }
  169328. /*
  169329. ** Return the total number of blocks this module has read from the %_data
  169330. ** table since it was created.
  169331. */
  169332. static int sqlite3Fts5IndexReads(Fts5Index *p){
  169333. return p->nRead;
  169334. }
  169335. /*
  169336. ** Set the 32-bit cookie value stored at the start of all structure
  169337. ** records to the value passed as the second argument.
  169338. **
  169339. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  169340. ** occurs.
  169341. */
  169342. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  169343. int rc; /* Return code */
  169344. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  169345. u8 aCookie[4]; /* Binary representation of iNew */
  169346. sqlite3_blob *pBlob = 0;
  169347. assert( p->rc==SQLITE_OK );
  169348. sqlite3Fts5Put32(aCookie, iNew);
  169349. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  169350. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  169351. );
  169352. if( rc==SQLITE_OK ){
  169353. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  169354. rc = sqlite3_blob_close(pBlob);
  169355. }
  169356. return rc;
  169357. }
  169358. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  169359. Fts5Structure *pStruct;
  169360. pStruct = fts5StructureRead(p);
  169361. fts5StructureRelease(pStruct);
  169362. return fts5IndexReturn(p);
  169363. }
  169364. /*************************************************************************
  169365. **************************************************************************
  169366. ** Below this point is the implementation of the integrity-check
  169367. ** functionality.
  169368. */
  169369. /*
  169370. ** Return a simple checksum value based on the arguments.
  169371. */
  169372. static u64 sqlite3Fts5IndexEntryCksum(
  169373. i64 iRowid,
  169374. int iCol,
  169375. int iPos,
  169376. int iIdx,
  169377. const char *pTerm,
  169378. int nTerm
  169379. ){
  169380. int i;
  169381. u64 ret = iRowid;
  169382. ret += (ret<<3) + iCol;
  169383. ret += (ret<<3) + iPos;
  169384. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  169385. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  169386. return ret;
  169387. }
  169388. #ifdef SQLITE_DEBUG
  169389. /*
  169390. ** This function is purely an internal test. It does not contribute to
  169391. ** FTS functionality, or even the integrity-check, in any way.
  169392. **
  169393. ** Instead, it tests that the same set of pgno/rowid combinations are
  169394. ** visited regardless of whether the doclist-index identified by parameters
  169395. ** iSegid/iLeaf is iterated in forwards or reverse order.
  169396. */
  169397. static void fts5TestDlidxReverse(
  169398. Fts5Index *p,
  169399. int iSegid, /* Segment id to load from */
  169400. int iLeaf /* Load doclist-index for this leaf */
  169401. ){
  169402. Fts5DlidxIter *pDlidx = 0;
  169403. u64 cksum1 = 13;
  169404. u64 cksum2 = 13;
  169405. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  169406. fts5DlidxIterEof(p, pDlidx)==0;
  169407. fts5DlidxIterNext(p, pDlidx)
  169408. ){
  169409. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  169410. int pgno = fts5DlidxIterPgno(pDlidx);
  169411. assert( pgno>iLeaf );
  169412. cksum1 += iRowid + ((i64)pgno<<32);
  169413. }
  169414. fts5DlidxIterFree(pDlidx);
  169415. pDlidx = 0;
  169416. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  169417. fts5DlidxIterEof(p, pDlidx)==0;
  169418. fts5DlidxIterPrev(p, pDlidx)
  169419. ){
  169420. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  169421. int pgno = fts5DlidxIterPgno(pDlidx);
  169422. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  169423. cksum2 += iRowid + ((i64)pgno<<32);
  169424. }
  169425. fts5DlidxIterFree(pDlidx);
  169426. pDlidx = 0;
  169427. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  169428. }
  169429. static int fts5QueryCksum(
  169430. Fts5Index *p, /* Fts5 index object */
  169431. int iIdx,
  169432. const char *z, /* Index key to query for */
  169433. int n, /* Size of index key in bytes */
  169434. int flags, /* Flags for Fts5IndexQuery */
  169435. u64 *pCksum /* IN/OUT: Checksum value */
  169436. ){
  169437. int eDetail = p->pConfig->eDetail;
  169438. u64 cksum = *pCksum;
  169439. Fts5IndexIter *pIter = 0;
  169440. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  169441. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  169442. i64 rowid = pIter->iRowid;
  169443. if( eDetail==FTS5_DETAIL_NONE ){
  169444. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  169445. }else{
  169446. Fts5PoslistReader sReader;
  169447. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  169448. sReader.bEof==0;
  169449. sqlite3Fts5PoslistReaderNext(&sReader)
  169450. ){
  169451. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  169452. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  169453. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  169454. }
  169455. }
  169456. if( rc==SQLITE_OK ){
  169457. rc = sqlite3Fts5IterNext(pIter);
  169458. }
  169459. }
  169460. sqlite3Fts5IterClose(pIter);
  169461. *pCksum = cksum;
  169462. return rc;
  169463. }
  169464. /*
  169465. ** This function is also purely an internal test. It does not contribute to
  169466. ** FTS functionality, or even the integrity-check, in any way.
  169467. */
  169468. static void fts5TestTerm(
  169469. Fts5Index *p,
  169470. Fts5Buffer *pPrev, /* Previous term */
  169471. const char *z, int n, /* Possibly new term to test */
  169472. u64 expected,
  169473. u64 *pCksum
  169474. ){
  169475. int rc = p->rc;
  169476. if( pPrev->n==0 ){
  169477. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  169478. }else
  169479. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  169480. u64 cksum3 = *pCksum;
  169481. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  169482. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  169483. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  169484. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  169485. u64 ck1 = 0;
  169486. u64 ck2 = 0;
  169487. /* Check that the results returned for ASC and DESC queries are
  169488. ** the same. If not, call this corruption. */
  169489. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  169490. if( rc==SQLITE_OK ){
  169491. int f = flags|FTS5INDEX_QUERY_DESC;
  169492. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  169493. }
  169494. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  169495. /* If this is a prefix query, check that the results returned if the
  169496. ** the index is disabled are the same. In both ASC and DESC order.
  169497. **
  169498. ** This check may only be performed if the hash table is empty. This
  169499. ** is because the hash table only supports a single scan query at
  169500. ** a time, and the multi-iter loop from which this function is called
  169501. ** is already performing such a scan. */
  169502. if( p->nPendingData==0 ){
  169503. if( iIdx>0 && rc==SQLITE_OK ){
  169504. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  169505. ck2 = 0;
  169506. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  169507. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  169508. }
  169509. if( iIdx>0 && rc==SQLITE_OK ){
  169510. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  169511. ck2 = 0;
  169512. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  169513. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  169514. }
  169515. }
  169516. cksum3 ^= ck1;
  169517. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  169518. if( rc==SQLITE_OK && cksum3!=expected ){
  169519. rc = FTS5_CORRUPT;
  169520. }
  169521. *pCksum = cksum3;
  169522. }
  169523. p->rc = rc;
  169524. }
  169525. #else
  169526. # define fts5TestDlidxReverse(x,y,z)
  169527. # define fts5TestTerm(u,v,w,x,y,z)
  169528. #endif
  169529. /*
  169530. ** Check that:
  169531. **
  169532. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  169533. ** contain zero terms.
  169534. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  169535. ** contain zero rowids.
  169536. */
  169537. static void fts5IndexIntegrityCheckEmpty(
  169538. Fts5Index *p,
  169539. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  169540. int iFirst,
  169541. int iNoRowid,
  169542. int iLast
  169543. ){
  169544. int i;
  169545. /* Now check that the iter.nEmpty leaves following the current leaf
  169546. ** (a) exist and (b) contain no terms. */
  169547. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  169548. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  169549. if( pLeaf ){
  169550. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  169551. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  169552. }
  169553. fts5DataRelease(pLeaf);
  169554. }
  169555. }
  169556. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  169557. int iTermOff = 0;
  169558. int ii;
  169559. Fts5Buffer buf1 = {0,0,0};
  169560. Fts5Buffer buf2 = {0,0,0};
  169561. ii = pLeaf->szLeaf;
  169562. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  169563. int res;
  169564. int iOff;
  169565. int nIncr;
  169566. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  169567. iTermOff += nIncr;
  169568. iOff = iTermOff;
  169569. if( iOff>=pLeaf->szLeaf ){
  169570. p->rc = FTS5_CORRUPT;
  169571. }else if( iTermOff==nIncr ){
  169572. int nByte;
  169573. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  169574. if( (iOff+nByte)>pLeaf->szLeaf ){
  169575. p->rc = FTS5_CORRUPT;
  169576. }else{
  169577. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  169578. }
  169579. }else{
  169580. int nKeep, nByte;
  169581. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  169582. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  169583. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  169584. p->rc = FTS5_CORRUPT;
  169585. }else{
  169586. buf1.n = nKeep;
  169587. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  169588. }
  169589. if( p->rc==SQLITE_OK ){
  169590. res = fts5BufferCompare(&buf1, &buf2);
  169591. if( res<=0 ) p->rc = FTS5_CORRUPT;
  169592. }
  169593. }
  169594. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  169595. }
  169596. fts5BufferFree(&buf1);
  169597. fts5BufferFree(&buf2);
  169598. }
  169599. static void fts5IndexIntegrityCheckSegment(
  169600. Fts5Index *p, /* FTS5 backend object */
  169601. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  169602. ){
  169603. Fts5Config *pConfig = p->pConfig;
  169604. sqlite3_stmt *pStmt = 0;
  169605. int rc2;
  169606. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  169607. int iDlidxPrevLeaf = pSeg->pgnoLast;
  169608. if( pSeg->pgnoFirst==0 ) return;
  169609. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  169610. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  169611. pConfig->zDb, pConfig->zName, pSeg->iSegid
  169612. ));
  169613. /* Iterate through the b-tree hierarchy. */
  169614. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  169615. i64 iRow; /* Rowid for this leaf */
  169616. Fts5Data *pLeaf; /* Data for this leaf */
  169617. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  169618. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  169619. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  169620. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  169621. /* If the leaf in question has already been trimmed from the segment,
  169622. ** ignore this b-tree entry. Otherwise, load it into memory. */
  169623. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  169624. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  169625. pLeaf = fts5DataRead(p, iRow);
  169626. if( pLeaf==0 ) break;
  169627. /* Check that the leaf contains at least one term, and that it is equal
  169628. ** to or larger than the split-key in zIdxTerm. Also check that if there
  169629. ** is also a rowid pointer within the leaf page header, it points to a
  169630. ** location before the term. */
  169631. if( pLeaf->nn<=pLeaf->szLeaf ){
  169632. p->rc = FTS5_CORRUPT;
  169633. }else{
  169634. int iOff; /* Offset of first term on leaf */
  169635. int iRowidOff; /* Offset of first rowid on leaf */
  169636. int nTerm; /* Size of term on leaf in bytes */
  169637. int res; /* Comparison of term and split-key */
  169638. iOff = fts5LeafFirstTermOff(pLeaf);
  169639. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  169640. if( iRowidOff>=iOff ){
  169641. p->rc = FTS5_CORRUPT;
  169642. }else{
  169643. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  169644. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  169645. if( res==0 ) res = nTerm - nIdxTerm;
  169646. if( res<0 ) p->rc = FTS5_CORRUPT;
  169647. }
  169648. fts5IntegrityCheckPgidx(p, pLeaf);
  169649. }
  169650. fts5DataRelease(pLeaf);
  169651. if( p->rc ) break;
  169652. /* Now check that the iter.nEmpty leaves following the current leaf
  169653. ** (a) exist and (b) contain no terms. */
  169654. fts5IndexIntegrityCheckEmpty(
  169655. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  169656. );
  169657. if( p->rc ) break;
  169658. /* If there is a doclist-index, check that it looks right. */
  169659. if( bIdxDlidx ){
  169660. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  169661. int iPrevLeaf = iIdxLeaf;
  169662. int iSegid = pSeg->iSegid;
  169663. int iPg = 0;
  169664. i64 iKey;
  169665. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  169666. fts5DlidxIterEof(p, pDlidx)==0;
  169667. fts5DlidxIterNext(p, pDlidx)
  169668. ){
  169669. /* Check any rowid-less pages that occur before the current leaf. */
  169670. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  169671. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  169672. pLeaf = fts5DataRead(p, iKey);
  169673. if( pLeaf ){
  169674. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  169675. fts5DataRelease(pLeaf);
  169676. }
  169677. }
  169678. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  169679. /* Check that the leaf page indicated by the iterator really does
  169680. ** contain the rowid suggested by the same. */
  169681. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  169682. pLeaf = fts5DataRead(p, iKey);
  169683. if( pLeaf ){
  169684. i64 iRowid;
  169685. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  169686. ASSERT_SZLEAF_OK(pLeaf);
  169687. if( iRowidOff>=pLeaf->szLeaf ){
  169688. p->rc = FTS5_CORRUPT;
  169689. }else{
  169690. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  169691. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  169692. }
  169693. fts5DataRelease(pLeaf);
  169694. }
  169695. }
  169696. iDlidxPrevLeaf = iPg;
  169697. fts5DlidxIterFree(pDlidx);
  169698. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  169699. }else{
  169700. iDlidxPrevLeaf = pSeg->pgnoLast;
  169701. /* TODO: Check there is no doclist index */
  169702. }
  169703. iIdxPrevLeaf = iIdxLeaf;
  169704. }
  169705. rc2 = sqlite3_finalize(pStmt);
  169706. if( p->rc==SQLITE_OK ) p->rc = rc2;
  169707. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  169708. #if 0
  169709. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  169710. p->rc = FTS5_CORRUPT;
  169711. }
  169712. #endif
  169713. }
  169714. /*
  169715. ** Run internal checks to ensure that the FTS index (a) is internally
  169716. ** consistent and (b) contains entries for which the XOR of the checksums
  169717. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  169718. **
  169719. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  169720. ** checksum does not match. Return SQLITE_OK if all checks pass without
  169721. ** error, or some other SQLite error code if another error (e.g. OOM)
  169722. ** occurs.
  169723. */
  169724. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  169725. int eDetail = p->pConfig->eDetail;
  169726. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  169727. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  169728. Fts5Iter *pIter; /* Used to iterate through entire index */
  169729. Fts5Structure *pStruct; /* Index structure */
  169730. #ifdef SQLITE_DEBUG
  169731. /* Used by extra internal tests only run if NDEBUG is not defined */
  169732. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  169733. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  169734. #endif
  169735. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  169736. /* Load the FTS index structure */
  169737. pStruct = fts5StructureRead(p);
  169738. /* Check that the internal nodes of each segment match the leaves */
  169739. if( pStruct ){
  169740. int iLvl, iSeg;
  169741. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  169742. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  169743. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  169744. fts5IndexIntegrityCheckSegment(p, pSeg);
  169745. }
  169746. }
  169747. }
  169748. /* The cksum argument passed to this function is a checksum calculated
  169749. ** based on all expected entries in the FTS index (including prefix index
  169750. ** entries). This block checks that a checksum calculated based on the
  169751. ** actual contents of FTS index is identical.
  169752. **
  169753. ** Two versions of the same checksum are calculated. The first (stack
  169754. ** variable cksum2) based on entries extracted from the full-text index
  169755. ** while doing a linear scan of each individual index in turn.
  169756. **
  169757. ** As each term visited by the linear scans, a separate query for the
  169758. ** same term is performed. cksum3 is calculated based on the entries
  169759. ** extracted by these queries.
  169760. */
  169761. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  169762. fts5MultiIterEof(p, pIter)==0;
  169763. fts5MultiIterNext(p, pIter, 0, 0)
  169764. ){
  169765. int n; /* Size of term in bytes */
  169766. i64 iPos = 0; /* Position read from poslist */
  169767. int iOff = 0; /* Offset within poslist */
  169768. i64 iRowid = fts5MultiIterRowid(pIter);
  169769. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  169770. /* If this is a new term, query for it. Update cksum3 with the results. */
  169771. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  169772. if( eDetail==FTS5_DETAIL_NONE ){
  169773. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  169774. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  169775. }
  169776. }else{
  169777. poslist.n = 0;
  169778. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  169779. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  169780. int iCol = FTS5_POS2COLUMN(iPos);
  169781. int iTokOff = FTS5_POS2OFFSET(iPos);
  169782. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  169783. }
  169784. }
  169785. }
  169786. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  169787. fts5MultiIterFree(pIter);
  169788. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  169789. fts5StructureRelease(pStruct);
  169790. #ifdef SQLITE_DEBUG
  169791. fts5BufferFree(&term);
  169792. #endif
  169793. fts5BufferFree(&poslist);
  169794. return fts5IndexReturn(p);
  169795. }
  169796. /*************************************************************************
  169797. **************************************************************************
  169798. ** Below this point is the implementation of the fts5_decode() scalar
  169799. ** function only.
  169800. */
  169801. /*
  169802. ** Decode a segment-data rowid from the %_data table. This function is
  169803. ** the opposite of macro FTS5_SEGMENT_ROWID().
  169804. */
  169805. static void fts5DecodeRowid(
  169806. i64 iRowid, /* Rowid from %_data table */
  169807. int *piSegid, /* OUT: Segment id */
  169808. int *pbDlidx, /* OUT: Dlidx flag */
  169809. int *piHeight, /* OUT: Height */
  169810. int *piPgno /* OUT: Page number */
  169811. ){
  169812. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  169813. iRowid >>= FTS5_DATA_PAGE_B;
  169814. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  169815. iRowid >>= FTS5_DATA_HEIGHT_B;
  169816. *pbDlidx = (int)(iRowid & 0x0001);
  169817. iRowid >>= FTS5_DATA_DLI_B;
  169818. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  169819. }
  169820. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  169821. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  169822. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  169823. if( iSegid==0 ){
  169824. if( iKey==FTS5_AVERAGES_ROWID ){
  169825. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  169826. }else{
  169827. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  169828. }
  169829. }
  169830. else{
  169831. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  169832. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  169833. );
  169834. }
  169835. }
  169836. static void fts5DebugStructure(
  169837. int *pRc, /* IN/OUT: error code */
  169838. Fts5Buffer *pBuf,
  169839. Fts5Structure *p
  169840. ){
  169841. int iLvl, iSeg; /* Iterate through levels, segments */
  169842. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  169843. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  169844. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  169845. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  169846. );
  169847. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  169848. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  169849. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  169850. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  169851. );
  169852. }
  169853. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  169854. }
  169855. }
  169856. /*
  169857. ** This is part of the fts5_decode() debugging aid.
  169858. **
  169859. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  169860. ** function appends a human-readable representation of the same object
  169861. ** to the buffer passed as the second argument.
  169862. */
  169863. static void fts5DecodeStructure(
  169864. int *pRc, /* IN/OUT: error code */
  169865. Fts5Buffer *pBuf,
  169866. const u8 *pBlob, int nBlob
  169867. ){
  169868. int rc; /* Return code */
  169869. Fts5Structure *p = 0; /* Decoded structure object */
  169870. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  169871. if( rc!=SQLITE_OK ){
  169872. *pRc = rc;
  169873. return;
  169874. }
  169875. fts5DebugStructure(pRc, pBuf, p);
  169876. fts5StructureRelease(p);
  169877. }
  169878. /*
  169879. ** This is part of the fts5_decode() debugging aid.
  169880. **
  169881. ** Arguments pBlob/nBlob contain an "averages" record. This function
  169882. ** appends a human-readable representation of record to the buffer passed
  169883. ** as the second argument.
  169884. */
  169885. static void fts5DecodeAverages(
  169886. int *pRc, /* IN/OUT: error code */
  169887. Fts5Buffer *pBuf,
  169888. const u8 *pBlob, int nBlob
  169889. ){
  169890. int i = 0;
  169891. const char *zSpace = "";
  169892. while( i<nBlob ){
  169893. u64 iVal;
  169894. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  169895. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  169896. zSpace = " ";
  169897. }
  169898. }
  169899. /*
  169900. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  169901. ** each varint and append its string representation to buffer pBuf. Return
  169902. ** after either the input buffer is exhausted or a 0 value is read.
  169903. **
  169904. ** The return value is the number of bytes read from the input buffer.
  169905. */
  169906. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  169907. int iOff = 0;
  169908. while( iOff<n ){
  169909. int iVal;
  169910. iOff += fts5GetVarint32(&a[iOff], iVal);
  169911. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  169912. }
  169913. return iOff;
  169914. }
  169915. /*
  169916. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  169917. ** may or may not finish within the buffer. This function appends a text
  169918. ** representation of the part of the doclist that is present to buffer
  169919. ** pBuf.
  169920. **
  169921. ** The return value is the number of bytes read from the input buffer.
  169922. */
  169923. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  169924. i64 iDocid = 0;
  169925. int iOff = 0;
  169926. if( n>0 ){
  169927. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  169928. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  169929. }
  169930. while( iOff<n ){
  169931. int nPos;
  169932. int bDel;
  169933. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  169934. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  169935. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  169936. if( iOff<n ){
  169937. i64 iDelta;
  169938. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  169939. iDocid += iDelta;
  169940. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  169941. }
  169942. }
  169943. return iOff;
  169944. }
  169945. /*
  169946. ** This function is part of the fts5_decode() debugging function. It is
  169947. ** only ever used with detail=none tables.
  169948. **
  169949. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  169950. ** tables. This function appends a human-readable version of that list to
  169951. ** buffer pBuf.
  169952. **
  169953. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  169954. ** no-op. If an OOM or other error occurs within this function, *pRc is
  169955. ** set to an SQLite error code before returning. The final state of buffer
  169956. ** pBuf is undefined in this case.
  169957. */
  169958. static void fts5DecodeRowidList(
  169959. int *pRc, /* IN/OUT: Error code */
  169960. Fts5Buffer *pBuf, /* Buffer to append text to */
  169961. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  169962. ){
  169963. int i = 0;
  169964. i64 iRowid = 0;
  169965. while( i<nData ){
  169966. const char *zApp = "";
  169967. u64 iVal;
  169968. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  169969. iRowid += iVal;
  169970. if( i<nData && pData[i]==0x00 ){
  169971. i++;
  169972. if( i<nData && pData[i]==0x00 ){
  169973. i++;
  169974. zApp = "+";
  169975. }else{
  169976. zApp = "*";
  169977. }
  169978. }
  169979. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  169980. }
  169981. }
  169982. /*
  169983. ** The implementation of user-defined scalar function fts5_decode().
  169984. */
  169985. static void fts5DecodeFunction(
  169986. sqlite3_context *pCtx, /* Function call context */
  169987. int nArg, /* Number of args (always 2) */
  169988. sqlite3_value **apVal /* Function arguments */
  169989. ){
  169990. i64 iRowid; /* Rowid for record being decoded */
  169991. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  169992. const u8 *aBlob; int n; /* Record to decode */
  169993. u8 *a = 0;
  169994. Fts5Buffer s; /* Build up text to return here */
  169995. int rc = SQLITE_OK; /* Return code */
  169996. int nSpace = 0;
  169997. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  169998. assert( nArg==2 );
  169999. UNUSED_PARAM(nArg);
  170000. memset(&s, 0, sizeof(Fts5Buffer));
  170001. iRowid = sqlite3_value_int64(apVal[0]);
  170002. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  170003. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  170004. ** buffer overreads even if the record is corrupt. */
  170005. n = sqlite3_value_bytes(apVal[1]);
  170006. aBlob = sqlite3_value_blob(apVal[1]);
  170007. nSpace = n + FTS5_DATA_ZERO_PADDING;
  170008. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  170009. if( a==0 ) goto decode_out;
  170010. memcpy(a, aBlob, n);
  170011. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  170012. fts5DebugRowid(&rc, &s, iRowid);
  170013. if( bDlidx ){
  170014. Fts5Data dlidx;
  170015. Fts5DlidxLvl lvl;
  170016. dlidx.p = a;
  170017. dlidx.nn = n;
  170018. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  170019. lvl.pData = &dlidx;
  170020. lvl.iLeafPgno = iPgno;
  170021. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  170022. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  170023. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  170024. );
  170025. }
  170026. }else if( iSegid==0 ){
  170027. if( iRowid==FTS5_AVERAGES_ROWID ){
  170028. fts5DecodeAverages(&rc, &s, a, n);
  170029. }else{
  170030. fts5DecodeStructure(&rc, &s, a, n);
  170031. }
  170032. }else if( eDetailNone ){
  170033. Fts5Buffer term; /* Current term read from page */
  170034. int szLeaf;
  170035. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  170036. int iTermOff;
  170037. int nKeep = 0;
  170038. int iOff;
  170039. memset(&term, 0, sizeof(Fts5Buffer));
  170040. /* Decode any entries that occur before the first term. */
  170041. if( szLeaf<n ){
  170042. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  170043. }else{
  170044. iTermOff = szLeaf;
  170045. }
  170046. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  170047. iOff = iTermOff;
  170048. while( iOff<szLeaf ){
  170049. int nAppend;
  170050. /* Read the term data for the next term*/
  170051. iOff += fts5GetVarint32(&a[iOff], nAppend);
  170052. term.n = nKeep;
  170053. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  170054. sqlite3Fts5BufferAppendPrintf(
  170055. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  170056. );
  170057. iOff += nAppend;
  170058. /* Figure out where the doclist for this term ends */
  170059. if( iPgidxOff<n ){
  170060. int nIncr;
  170061. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  170062. iTermOff += nIncr;
  170063. }else{
  170064. iTermOff = szLeaf;
  170065. }
  170066. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  170067. iOff = iTermOff;
  170068. if( iOff<szLeaf ){
  170069. iOff += fts5GetVarint32(&a[iOff], nKeep);
  170070. }
  170071. }
  170072. fts5BufferFree(&term);
  170073. }else{
  170074. Fts5Buffer term; /* Current term read from page */
  170075. int szLeaf; /* Offset of pgidx in a[] */
  170076. int iPgidxOff;
  170077. int iPgidxPrev = 0; /* Previous value read from pgidx */
  170078. int iTermOff = 0;
  170079. int iRowidOff = 0;
  170080. int iOff;
  170081. int nDoclist;
  170082. memset(&term, 0, sizeof(Fts5Buffer));
  170083. if( n<4 ){
  170084. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  170085. goto decode_out;
  170086. }else{
  170087. iRowidOff = fts5GetU16(&a[0]);
  170088. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  170089. if( iPgidxOff<n ){
  170090. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  170091. }
  170092. }
  170093. /* Decode the position list tail at the start of the page */
  170094. if( iRowidOff!=0 ){
  170095. iOff = iRowidOff;
  170096. }else if( iTermOff!=0 ){
  170097. iOff = iTermOff;
  170098. }else{
  170099. iOff = szLeaf;
  170100. }
  170101. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  170102. /* Decode any more doclist data that appears on the page before the
  170103. ** first term. */
  170104. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  170105. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  170106. while( iPgidxOff<n ){
  170107. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  170108. int nByte; /* Bytes of data */
  170109. int iEnd;
  170110. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  170111. iPgidxPrev += nByte;
  170112. iOff = iPgidxPrev;
  170113. if( iPgidxOff<n ){
  170114. fts5GetVarint32(&a[iPgidxOff], nByte);
  170115. iEnd = iPgidxPrev + nByte;
  170116. }else{
  170117. iEnd = szLeaf;
  170118. }
  170119. if( bFirst==0 ){
  170120. iOff += fts5GetVarint32(&a[iOff], nByte);
  170121. term.n = nByte;
  170122. }
  170123. iOff += fts5GetVarint32(&a[iOff], nByte);
  170124. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  170125. iOff += nByte;
  170126. sqlite3Fts5BufferAppendPrintf(
  170127. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  170128. );
  170129. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  170130. }
  170131. fts5BufferFree(&term);
  170132. }
  170133. decode_out:
  170134. sqlite3_free(a);
  170135. if( rc==SQLITE_OK ){
  170136. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  170137. }else{
  170138. sqlite3_result_error_code(pCtx, rc);
  170139. }
  170140. fts5BufferFree(&s);
  170141. }
  170142. /*
  170143. ** The implementation of user-defined scalar function fts5_rowid().
  170144. */
  170145. static void fts5RowidFunction(
  170146. sqlite3_context *pCtx, /* Function call context */
  170147. int nArg, /* Number of args (always 2) */
  170148. sqlite3_value **apVal /* Function arguments */
  170149. ){
  170150. const char *zArg;
  170151. if( nArg==0 ){
  170152. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  170153. }else{
  170154. zArg = (const char*)sqlite3_value_text(apVal[0]);
  170155. if( 0==sqlite3_stricmp(zArg, "segment") ){
  170156. i64 iRowid;
  170157. int segid, pgno;
  170158. if( nArg!=3 ){
  170159. sqlite3_result_error(pCtx,
  170160. "should be: fts5_rowid('segment', segid, pgno))", -1
  170161. );
  170162. }else{
  170163. segid = sqlite3_value_int(apVal[1]);
  170164. pgno = sqlite3_value_int(apVal[2]);
  170165. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  170166. sqlite3_result_int64(pCtx, iRowid);
  170167. }
  170168. }else{
  170169. sqlite3_result_error(pCtx,
  170170. "first arg to fts5_rowid() must be 'segment'" , -1
  170171. );
  170172. }
  170173. }
  170174. }
  170175. /*
  170176. ** This is called as part of registering the FTS5 module with database
  170177. ** connection db. It registers several user-defined scalar functions useful
  170178. ** with FTS5.
  170179. **
  170180. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  170181. ** SQLite error code is returned instead.
  170182. */
  170183. static int sqlite3Fts5IndexInit(sqlite3 *db){
  170184. int rc = sqlite3_create_function(
  170185. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  170186. );
  170187. if( rc==SQLITE_OK ){
  170188. rc = sqlite3_create_function(
  170189. db, "fts5_decode_none", 2,
  170190. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  170191. );
  170192. }
  170193. if( rc==SQLITE_OK ){
  170194. rc = sqlite3_create_function(
  170195. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  170196. );
  170197. }
  170198. return rc;
  170199. }
  170200. static int sqlite3Fts5IndexReset(Fts5Index *p){
  170201. assert( p->pStruct==0 || p->iStructVersion!=0 );
  170202. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  170203. fts5StructureInvalidate(p);
  170204. }
  170205. return fts5IndexReturn(p);
  170206. }
  170207. /*
  170208. ** 2014 Jun 09
  170209. **
  170210. ** The author disclaims copyright to this source code. In place of
  170211. ** a legal notice, here is a blessing:
  170212. **
  170213. ** May you do good and not evil.
  170214. ** May you find forgiveness for yourself and forgive others.
  170215. ** May you share freely, never taking more than you give.
  170216. **
  170217. ******************************************************************************
  170218. **
  170219. ** This is an SQLite module implementing full-text search.
  170220. */
  170221. /* #include "fts5Int.h" */
  170222. /*
  170223. ** This variable is set to false when running tests for which the on disk
  170224. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  170225. ** assert() conditions in the fts5 code are activated - conditions that are
  170226. ** only true if it is guaranteed that the fts5 database is not corrupt.
  170227. */
  170228. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  170229. typedef struct Fts5Auxdata Fts5Auxdata;
  170230. typedef struct Fts5Auxiliary Fts5Auxiliary;
  170231. typedef struct Fts5Cursor Fts5Cursor;
  170232. typedef struct Fts5Sorter Fts5Sorter;
  170233. typedef struct Fts5Table Fts5Table;
  170234. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  170235. /*
  170236. ** NOTES ON TRANSACTIONS:
  170237. **
  170238. ** SQLite invokes the following virtual table methods as transactions are
  170239. ** opened and closed by the user:
  170240. **
  170241. ** xBegin(): Start of a new transaction.
  170242. ** xSync(): Initial part of two-phase commit.
  170243. ** xCommit(): Final part of two-phase commit.
  170244. ** xRollback(): Rollback the transaction.
  170245. **
  170246. ** Anything that is required as part of a commit that may fail is performed
  170247. ** in the xSync() callback. Current versions of SQLite ignore any errors
  170248. ** returned by xCommit().
  170249. **
  170250. ** And as sub-transactions are opened/closed:
  170251. **
  170252. ** xSavepoint(int S): Open savepoint S.
  170253. ** xRelease(int S): Commit and close savepoint S.
  170254. ** xRollbackTo(int S): Rollback to start of savepoint S.
  170255. **
  170256. ** During a write-transaction the fts5_index.c module may cache some data
  170257. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  170258. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  170259. ** is called.
  170260. **
  170261. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  170262. ** structure is used to record the current transaction state. This information
  170263. ** is not required, but it is used in the assert() statements executed by
  170264. ** function fts5CheckTransactionState() (see below).
  170265. */
  170266. struct Fts5TransactionState {
  170267. int eState; /* 0==closed, 1==open, 2==synced */
  170268. int iSavepoint; /* Number of open savepoints (0 -> none) */
  170269. };
  170270. /*
  170271. ** A single object of this type is allocated when the FTS5 module is
  170272. ** registered with a database handle. It is used to store pointers to
  170273. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  170274. */
  170275. struct Fts5Global {
  170276. fts5_api api; /* User visible part of object (see fts5.h) */
  170277. sqlite3 *db; /* Associated database connection */
  170278. i64 iNextId; /* Used to allocate unique cursor ids */
  170279. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  170280. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  170281. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  170282. Fts5Cursor *pCsr; /* First in list of all open cursors */
  170283. };
  170284. /*
  170285. ** Each auxiliary function registered with the FTS5 module is represented
  170286. ** by an object of the following type. All such objects are stored as part
  170287. ** of the Fts5Global.pAux list.
  170288. */
  170289. struct Fts5Auxiliary {
  170290. Fts5Global *pGlobal; /* Global context for this function */
  170291. char *zFunc; /* Function name (nul-terminated) */
  170292. void *pUserData; /* User-data pointer */
  170293. fts5_extension_function xFunc; /* Callback function */
  170294. void (*xDestroy)(void*); /* Destructor function */
  170295. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  170296. };
  170297. /*
  170298. ** Each tokenizer module registered with the FTS5 module is represented
  170299. ** by an object of the following type. All such objects are stored as part
  170300. ** of the Fts5Global.pTok list.
  170301. */
  170302. struct Fts5TokenizerModule {
  170303. char *zName; /* Name of tokenizer */
  170304. void *pUserData; /* User pointer passed to xCreate() */
  170305. fts5_tokenizer x; /* Tokenizer functions */
  170306. void (*xDestroy)(void*); /* Destructor function */
  170307. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  170308. };
  170309. /*
  170310. ** Virtual-table object.
  170311. */
  170312. struct Fts5Table {
  170313. sqlite3_vtab base; /* Base class used by SQLite core */
  170314. Fts5Config *pConfig; /* Virtual table configuration */
  170315. Fts5Index *pIndex; /* Full-text index */
  170316. Fts5Storage *pStorage; /* Document store */
  170317. Fts5Global *pGlobal; /* Global (connection wide) data */
  170318. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  170319. #ifdef SQLITE_DEBUG
  170320. struct Fts5TransactionState ts;
  170321. #endif
  170322. };
  170323. struct Fts5MatchPhrase {
  170324. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  170325. int nTerm; /* Size of phrase in terms */
  170326. };
  170327. /*
  170328. ** pStmt:
  170329. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  170330. **
  170331. ** aIdx[]:
  170332. ** There is one entry in the aIdx[] array for each phrase in the query,
  170333. ** the value of which is the offset within aPoslist[] following the last
  170334. ** byte of the position list for the corresponding phrase.
  170335. */
  170336. struct Fts5Sorter {
  170337. sqlite3_stmt *pStmt;
  170338. i64 iRowid; /* Current rowid */
  170339. const u8 *aPoslist; /* Position lists for current row */
  170340. int nIdx; /* Number of entries in aIdx[] */
  170341. int aIdx[1]; /* Offsets into aPoslist for current row */
  170342. };
  170343. /*
  170344. ** Virtual-table cursor object.
  170345. **
  170346. ** iSpecial:
  170347. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  170348. ** then this variable contains the result of the query.
  170349. **
  170350. ** iFirstRowid, iLastRowid:
  170351. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  170352. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  170353. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  170354. ** WHERE clause in the user's query might have been:
  170355. **
  170356. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  170357. **
  170358. ** If the cursor iterates in descending order of rowid, iFirstRowid
  170359. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  170360. ** the lower.
  170361. */
  170362. struct Fts5Cursor {
  170363. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  170364. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  170365. int *aColumnSize; /* Values for xColumnSize() */
  170366. i64 iCsrId; /* Cursor id */
  170367. /* Zero from this point onwards on cursor reset */
  170368. int ePlan; /* FTS5_PLAN_XXX value */
  170369. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  170370. i64 iFirstRowid; /* Return no rowids earlier than this */
  170371. i64 iLastRowid; /* Return no rowids later than this */
  170372. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  170373. Fts5Expr *pExpr; /* Expression for MATCH queries */
  170374. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  170375. int csrflags; /* Mask of cursor flags (see below) */
  170376. i64 iSpecial; /* Result of special query */
  170377. /* "rank" function. Populated on demand from vtab.xColumn(). */
  170378. char *zRank; /* Custom rank function */
  170379. char *zRankArgs; /* Custom rank function args */
  170380. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  170381. int nRankArg; /* Number of trailing arguments for rank() */
  170382. sqlite3_value **apRankArg; /* Array of trailing arguments */
  170383. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  170384. /* Auxiliary data storage */
  170385. Fts5Auxiliary *pAux; /* Currently executing extension function */
  170386. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  170387. /* Cache used by auxiliary functions xInst() and xInstCount() */
  170388. Fts5PoslistReader *aInstIter; /* One for each phrase */
  170389. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  170390. int nInstCount; /* Number of phrase instances */
  170391. int *aInst; /* 3 integers per phrase instance */
  170392. };
  170393. /*
  170394. ** Bits that make up the "idxNum" parameter passed indirectly by
  170395. ** xBestIndex() to xFilter().
  170396. */
  170397. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  170398. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  170399. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  170400. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  170401. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  170402. #define FTS5_BI_ORDER_RANK 0x0020
  170403. #define FTS5_BI_ORDER_ROWID 0x0040
  170404. #define FTS5_BI_ORDER_DESC 0x0080
  170405. /*
  170406. ** Values for Fts5Cursor.csrflags
  170407. */
  170408. #define FTS5CSR_EOF 0x01
  170409. #define FTS5CSR_REQUIRE_CONTENT 0x02
  170410. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  170411. #define FTS5CSR_REQUIRE_INST 0x08
  170412. #define FTS5CSR_FREE_ZRANK 0x10
  170413. #define FTS5CSR_REQUIRE_RESEEK 0x20
  170414. #define FTS5CSR_REQUIRE_POSLIST 0x40
  170415. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  170416. #define BitFlagTest(x,y) (((x) & (y))!=0)
  170417. /*
  170418. ** Macros to Set(), Clear() and Test() cursor flags.
  170419. */
  170420. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  170421. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  170422. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  170423. struct Fts5Auxdata {
  170424. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  170425. void *pPtr; /* Pointer value */
  170426. void(*xDelete)(void*); /* Destructor */
  170427. Fts5Auxdata *pNext; /* Next object in linked list */
  170428. };
  170429. #ifdef SQLITE_DEBUG
  170430. #define FTS5_BEGIN 1
  170431. #define FTS5_SYNC 2
  170432. #define FTS5_COMMIT 3
  170433. #define FTS5_ROLLBACK 4
  170434. #define FTS5_SAVEPOINT 5
  170435. #define FTS5_RELEASE 6
  170436. #define FTS5_ROLLBACKTO 7
  170437. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  170438. switch( op ){
  170439. case FTS5_BEGIN:
  170440. assert( p->ts.eState==0 );
  170441. p->ts.eState = 1;
  170442. p->ts.iSavepoint = -1;
  170443. break;
  170444. case FTS5_SYNC:
  170445. assert( p->ts.eState==1 );
  170446. p->ts.eState = 2;
  170447. break;
  170448. case FTS5_COMMIT:
  170449. assert( p->ts.eState==2 );
  170450. p->ts.eState = 0;
  170451. break;
  170452. case FTS5_ROLLBACK:
  170453. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  170454. p->ts.eState = 0;
  170455. break;
  170456. case FTS5_SAVEPOINT:
  170457. assert( p->ts.eState==1 );
  170458. assert( iSavepoint>=0 );
  170459. assert( iSavepoint>p->ts.iSavepoint );
  170460. p->ts.iSavepoint = iSavepoint;
  170461. break;
  170462. case FTS5_RELEASE:
  170463. assert( p->ts.eState==1 );
  170464. assert( iSavepoint>=0 );
  170465. assert( iSavepoint<=p->ts.iSavepoint );
  170466. p->ts.iSavepoint = iSavepoint-1;
  170467. break;
  170468. case FTS5_ROLLBACKTO:
  170469. assert( p->ts.eState==1 );
  170470. assert( iSavepoint>=0 );
  170471. assert( iSavepoint<=p->ts.iSavepoint );
  170472. p->ts.iSavepoint = iSavepoint;
  170473. break;
  170474. }
  170475. }
  170476. #else
  170477. # define fts5CheckTransactionState(x,y,z)
  170478. #endif
  170479. /*
  170480. ** Return true if pTab is a contentless table.
  170481. */
  170482. static int fts5IsContentless(Fts5Table *pTab){
  170483. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  170484. }
  170485. /*
  170486. ** Delete a virtual table handle allocated by fts5InitVtab().
  170487. */
  170488. static void fts5FreeVtab(Fts5Table *pTab){
  170489. if( pTab ){
  170490. sqlite3Fts5IndexClose(pTab->pIndex);
  170491. sqlite3Fts5StorageClose(pTab->pStorage);
  170492. sqlite3Fts5ConfigFree(pTab->pConfig);
  170493. sqlite3_free(pTab);
  170494. }
  170495. }
  170496. /*
  170497. ** The xDisconnect() virtual table method.
  170498. */
  170499. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  170500. fts5FreeVtab((Fts5Table*)pVtab);
  170501. return SQLITE_OK;
  170502. }
  170503. /*
  170504. ** The xDestroy() virtual table method.
  170505. */
  170506. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  170507. Fts5Table *pTab = (Fts5Table*)pVtab;
  170508. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  170509. if( rc==SQLITE_OK ){
  170510. fts5FreeVtab((Fts5Table*)pVtab);
  170511. }
  170512. return rc;
  170513. }
  170514. /*
  170515. ** This function is the implementation of both the xConnect and xCreate
  170516. ** methods of the FTS3 virtual table.
  170517. **
  170518. ** The argv[] array contains the following:
  170519. **
  170520. ** argv[0] -> module name ("fts5")
  170521. ** argv[1] -> database name
  170522. ** argv[2] -> table name
  170523. ** argv[...] -> "column name" and other module argument fields.
  170524. */
  170525. static int fts5InitVtab(
  170526. int bCreate, /* True for xCreate, false for xConnect */
  170527. sqlite3 *db, /* The SQLite database connection */
  170528. void *pAux, /* Hash table containing tokenizers */
  170529. int argc, /* Number of elements in argv array */
  170530. const char * const *argv, /* xCreate/xConnect argument array */
  170531. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  170532. char **pzErr /* Write any error message here */
  170533. ){
  170534. Fts5Global *pGlobal = (Fts5Global*)pAux;
  170535. const char **azConfig = (const char**)argv;
  170536. int rc = SQLITE_OK; /* Return code */
  170537. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  170538. Fts5Table *pTab = 0; /* New virtual table object */
  170539. /* Allocate the new vtab object and parse the configuration */
  170540. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  170541. if( rc==SQLITE_OK ){
  170542. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  170543. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  170544. }
  170545. if( rc==SQLITE_OK ){
  170546. pTab->pConfig = pConfig;
  170547. pTab->pGlobal = pGlobal;
  170548. }
  170549. /* Open the index sub-system */
  170550. if( rc==SQLITE_OK ){
  170551. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  170552. }
  170553. /* Open the storage sub-system */
  170554. if( rc==SQLITE_OK ){
  170555. rc = sqlite3Fts5StorageOpen(
  170556. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  170557. );
  170558. }
  170559. /* Call sqlite3_declare_vtab() */
  170560. if( rc==SQLITE_OK ){
  170561. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  170562. }
  170563. /* Load the initial configuration */
  170564. if( rc==SQLITE_OK ){
  170565. assert( pConfig->pzErrmsg==0 );
  170566. pConfig->pzErrmsg = pzErr;
  170567. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  170568. sqlite3Fts5IndexRollback(pTab->pIndex);
  170569. pConfig->pzErrmsg = 0;
  170570. }
  170571. if( rc!=SQLITE_OK ){
  170572. fts5FreeVtab(pTab);
  170573. pTab = 0;
  170574. }else if( bCreate ){
  170575. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  170576. }
  170577. *ppVTab = (sqlite3_vtab*)pTab;
  170578. return rc;
  170579. }
  170580. /*
  170581. ** The xConnect() and xCreate() methods for the virtual table. All the
  170582. ** work is done in function fts5InitVtab().
  170583. */
  170584. static int fts5ConnectMethod(
  170585. sqlite3 *db, /* Database connection */
  170586. void *pAux, /* Pointer to tokenizer hash table */
  170587. int argc, /* Number of elements in argv array */
  170588. const char * const *argv, /* xCreate/xConnect argument array */
  170589. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  170590. char **pzErr /* OUT: sqlite3_malloc'd error message */
  170591. ){
  170592. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  170593. }
  170594. static int fts5CreateMethod(
  170595. sqlite3 *db, /* Database connection */
  170596. void *pAux, /* Pointer to tokenizer hash table */
  170597. int argc, /* Number of elements in argv array */
  170598. const char * const *argv, /* xCreate/xConnect argument array */
  170599. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  170600. char **pzErr /* OUT: sqlite3_malloc'd error message */
  170601. ){
  170602. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  170603. }
  170604. /*
  170605. ** The different query plans.
  170606. */
  170607. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  170608. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  170609. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  170610. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  170611. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  170612. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  170613. /*
  170614. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  170615. ** extension is currently being used by a version of SQLite too old to
  170616. ** support index-info flags. In that case this function is a no-op.
  170617. */
  170618. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  170619. #if SQLITE_VERSION_NUMBER>=3008012
  170620. #ifndef SQLITE_CORE
  170621. if( sqlite3_libversion_number()>=3008012 )
  170622. #endif
  170623. {
  170624. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  170625. }
  170626. #endif
  170627. }
  170628. /*
  170629. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  170630. ** WHERE constraint, it searches for the following:
  170631. **
  170632. ** 1. A MATCH constraint against the special column.
  170633. ** 2. A MATCH constraint against the "rank" column.
  170634. ** 3. An == constraint against the rowid column.
  170635. ** 4. A < or <= constraint against the rowid column.
  170636. ** 5. A > or >= constraint against the rowid column.
  170637. **
  170638. ** Within the ORDER BY, either:
  170639. **
  170640. ** 5. ORDER BY rank [ASC|DESC]
  170641. ** 6. ORDER BY rowid [ASC|DESC]
  170642. **
  170643. ** Costs are assigned as follows:
  170644. **
  170645. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  170646. ** cost is unconditionally set to 1e50 (a really big number).
  170647. **
  170648. ** a) If a MATCH operator is present, the cost depends on the other
  170649. ** constraints also present. As follows:
  170650. **
  170651. ** * No other constraints: cost=1000.0
  170652. ** * One rowid range constraint: cost=750.0
  170653. ** * Both rowid range constraints: cost=500.0
  170654. ** * An == rowid constraint: cost=100.0
  170655. **
  170656. ** b) Otherwise, if there is no MATCH:
  170657. **
  170658. ** * No other constraints: cost=1000000.0
  170659. ** * One rowid range constraint: cost=750000.0
  170660. ** * Both rowid range constraints: cost=250000.0
  170661. ** * An == rowid constraint: cost=10.0
  170662. **
  170663. ** Costs are not modified by the ORDER BY clause.
  170664. */
  170665. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  170666. Fts5Table *pTab = (Fts5Table*)pVTab;
  170667. Fts5Config *pConfig = pTab->pConfig;
  170668. int idxFlags = 0; /* Parameter passed through to xFilter() */
  170669. int bHasMatch;
  170670. int iNext;
  170671. int i;
  170672. struct Constraint {
  170673. int op; /* Mask against sqlite3_index_constraint.op */
  170674. int fts5op; /* FTS5 mask for idxFlags */
  170675. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  170676. int omit; /* True to omit this if found */
  170677. int iConsIndex; /* Index in pInfo->aConstraint[] */
  170678. } aConstraint[] = {
  170679. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  170680. FTS5_BI_MATCH, 1, 1, -1},
  170681. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  170682. FTS5_BI_RANK, 2, 1, -1},
  170683. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  170684. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  170685. FTS5_BI_ROWID_LE, 0, 0, -1},
  170686. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  170687. FTS5_BI_ROWID_GE, 0, 0, -1},
  170688. };
  170689. int aColMap[3];
  170690. aColMap[0] = -1;
  170691. aColMap[1] = pConfig->nCol;
  170692. aColMap[2] = pConfig->nCol+1;
  170693. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  170694. for(i=0; i<pInfo->nConstraint; i++){
  170695. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  170696. int j;
  170697. for(j=0; j<ArraySize(aConstraint); j++){
  170698. struct Constraint *pC = &aConstraint[j];
  170699. if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
  170700. if( p->usable ){
  170701. pC->iConsIndex = i;
  170702. idxFlags |= pC->fts5op;
  170703. }else if( j==0 ){
  170704. /* As there exists an unusable MATCH constraint this is an
  170705. ** unusable plan. Set a prohibitively high cost. */
  170706. pInfo->estimatedCost = 1e50;
  170707. return SQLITE_OK;
  170708. }
  170709. }
  170710. }
  170711. }
  170712. /* Set idxFlags flags for the ORDER BY clause */
  170713. if( pInfo->nOrderBy==1 ){
  170714. int iSort = pInfo->aOrderBy[0].iColumn;
  170715. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  170716. idxFlags |= FTS5_BI_ORDER_RANK;
  170717. }else if( iSort==-1 ){
  170718. idxFlags |= FTS5_BI_ORDER_ROWID;
  170719. }
  170720. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  170721. pInfo->orderByConsumed = 1;
  170722. if( pInfo->aOrderBy[0].desc ){
  170723. idxFlags |= FTS5_BI_ORDER_DESC;
  170724. }
  170725. }
  170726. }
  170727. /* Calculate the estimated cost based on the flags set in idxFlags. */
  170728. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  170729. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  170730. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  170731. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  170732. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  170733. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  170734. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  170735. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  170736. }else{
  170737. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  170738. }
  170739. /* Assign argvIndex values to each constraint in use. */
  170740. iNext = 1;
  170741. for(i=0; i<ArraySize(aConstraint); i++){
  170742. struct Constraint *pC = &aConstraint[i];
  170743. if( pC->iConsIndex>=0 ){
  170744. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  170745. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  170746. }
  170747. }
  170748. pInfo->idxNum = idxFlags;
  170749. return SQLITE_OK;
  170750. }
  170751. static int fts5NewTransaction(Fts5Table *pTab){
  170752. Fts5Cursor *pCsr;
  170753. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  170754. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  170755. }
  170756. return sqlite3Fts5StorageReset(pTab->pStorage);
  170757. }
  170758. /*
  170759. ** Implementation of xOpen method.
  170760. */
  170761. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  170762. Fts5Table *pTab = (Fts5Table*)pVTab;
  170763. Fts5Config *pConfig = pTab->pConfig;
  170764. Fts5Cursor *pCsr = 0; /* New cursor object */
  170765. int nByte; /* Bytes of space to allocate */
  170766. int rc; /* Return code */
  170767. rc = fts5NewTransaction(pTab);
  170768. if( rc==SQLITE_OK ){
  170769. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  170770. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  170771. if( pCsr ){
  170772. Fts5Global *pGlobal = pTab->pGlobal;
  170773. memset(pCsr, 0, nByte);
  170774. pCsr->aColumnSize = (int*)&pCsr[1];
  170775. pCsr->pNext = pGlobal->pCsr;
  170776. pGlobal->pCsr = pCsr;
  170777. pCsr->iCsrId = ++pGlobal->iNextId;
  170778. }else{
  170779. rc = SQLITE_NOMEM;
  170780. }
  170781. }
  170782. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  170783. return rc;
  170784. }
  170785. static int fts5StmtType(Fts5Cursor *pCsr){
  170786. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  170787. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  170788. }
  170789. return FTS5_STMT_LOOKUP;
  170790. }
  170791. /*
  170792. ** This function is called after the cursor passed as the only argument
  170793. ** is moved to point at a different row. It clears all cached data
  170794. ** specific to the previous row stored by the cursor object.
  170795. */
  170796. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  170797. CsrFlagSet(pCsr,
  170798. FTS5CSR_REQUIRE_CONTENT
  170799. | FTS5CSR_REQUIRE_DOCSIZE
  170800. | FTS5CSR_REQUIRE_INST
  170801. | FTS5CSR_REQUIRE_POSLIST
  170802. );
  170803. }
  170804. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  170805. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  170806. Fts5Auxdata *pData;
  170807. Fts5Auxdata *pNext;
  170808. sqlite3_free(pCsr->aInstIter);
  170809. sqlite3_free(pCsr->aInst);
  170810. if( pCsr->pStmt ){
  170811. int eStmt = fts5StmtType(pCsr);
  170812. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  170813. }
  170814. if( pCsr->pSorter ){
  170815. Fts5Sorter *pSorter = pCsr->pSorter;
  170816. sqlite3_finalize(pSorter->pStmt);
  170817. sqlite3_free(pSorter);
  170818. }
  170819. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  170820. sqlite3Fts5ExprFree(pCsr->pExpr);
  170821. }
  170822. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  170823. pNext = pData->pNext;
  170824. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  170825. sqlite3_free(pData);
  170826. }
  170827. sqlite3_finalize(pCsr->pRankArgStmt);
  170828. sqlite3_free(pCsr->apRankArg);
  170829. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  170830. sqlite3_free(pCsr->zRank);
  170831. sqlite3_free(pCsr->zRankArgs);
  170832. }
  170833. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  170834. }
  170835. /*
  170836. ** Close the cursor. For additional information see the documentation
  170837. ** on the xClose method of the virtual table interface.
  170838. */
  170839. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  170840. if( pCursor ){
  170841. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  170842. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  170843. Fts5Cursor **pp;
  170844. fts5FreeCursorComponents(pCsr);
  170845. /* Remove the cursor from the Fts5Global.pCsr list */
  170846. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  170847. *pp = pCsr->pNext;
  170848. sqlite3_free(pCsr);
  170849. }
  170850. return SQLITE_OK;
  170851. }
  170852. static int fts5SorterNext(Fts5Cursor *pCsr){
  170853. Fts5Sorter *pSorter = pCsr->pSorter;
  170854. int rc;
  170855. rc = sqlite3_step(pSorter->pStmt);
  170856. if( rc==SQLITE_DONE ){
  170857. rc = SQLITE_OK;
  170858. CsrFlagSet(pCsr, FTS5CSR_EOF);
  170859. }else if( rc==SQLITE_ROW ){
  170860. const u8 *a;
  170861. const u8 *aBlob;
  170862. int nBlob;
  170863. int i;
  170864. int iOff = 0;
  170865. rc = SQLITE_OK;
  170866. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  170867. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  170868. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  170869. /* nBlob==0 in detail=none mode. */
  170870. if( nBlob>0 ){
  170871. for(i=0; i<(pSorter->nIdx-1); i++){
  170872. int iVal;
  170873. a += fts5GetVarint32(a, iVal);
  170874. iOff += iVal;
  170875. pSorter->aIdx[i] = iOff;
  170876. }
  170877. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  170878. pSorter->aPoslist = a;
  170879. }
  170880. fts5CsrNewrow(pCsr);
  170881. }
  170882. return rc;
  170883. }
  170884. /*
  170885. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  170886. ** open on table pTab.
  170887. */
  170888. static void fts5TripCursors(Fts5Table *pTab){
  170889. Fts5Cursor *pCsr;
  170890. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  170891. if( pCsr->ePlan==FTS5_PLAN_MATCH
  170892. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  170893. ){
  170894. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  170895. }
  170896. }
  170897. }
  170898. /*
  170899. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  170900. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  170901. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  170902. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  170903. **
  170904. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  170905. ** to 1 before returning. Otherwise, leave it unchanged.
  170906. **
  170907. ** Return SQLITE_OK if successful or if no reseek was required, or an
  170908. ** error code if an error occurred.
  170909. */
  170910. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  170911. int rc = SQLITE_OK;
  170912. assert( *pbSkip==0 );
  170913. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  170914. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  170915. int bDesc = pCsr->bDesc;
  170916. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  170917. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  170918. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  170919. *pbSkip = 1;
  170920. }
  170921. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  170922. fts5CsrNewrow(pCsr);
  170923. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  170924. CsrFlagSet(pCsr, FTS5CSR_EOF);
  170925. *pbSkip = 1;
  170926. }
  170927. }
  170928. return rc;
  170929. }
  170930. /*
  170931. ** Advance the cursor to the next row in the table that matches the
  170932. ** search criteria.
  170933. **
  170934. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  170935. ** even if we reach end-of-file. The fts5EofMethod() will be called
  170936. ** subsequently to determine whether or not an EOF was hit.
  170937. */
  170938. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  170939. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  170940. int rc;
  170941. assert( (pCsr->ePlan<3)==
  170942. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  170943. );
  170944. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  170945. if( pCsr->ePlan<3 ){
  170946. int bSkip = 0;
  170947. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  170948. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  170949. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  170950. fts5CsrNewrow(pCsr);
  170951. }else{
  170952. switch( pCsr->ePlan ){
  170953. case FTS5_PLAN_SPECIAL: {
  170954. CsrFlagSet(pCsr, FTS5CSR_EOF);
  170955. rc = SQLITE_OK;
  170956. break;
  170957. }
  170958. case FTS5_PLAN_SORTED_MATCH: {
  170959. rc = fts5SorterNext(pCsr);
  170960. break;
  170961. }
  170962. default:
  170963. rc = sqlite3_step(pCsr->pStmt);
  170964. if( rc!=SQLITE_ROW ){
  170965. CsrFlagSet(pCsr, FTS5CSR_EOF);
  170966. rc = sqlite3_reset(pCsr->pStmt);
  170967. }else{
  170968. rc = SQLITE_OK;
  170969. }
  170970. break;
  170971. }
  170972. }
  170973. return rc;
  170974. }
  170975. static int fts5PrepareStatement(
  170976. sqlite3_stmt **ppStmt,
  170977. Fts5Config *pConfig,
  170978. const char *zFmt,
  170979. ...
  170980. ){
  170981. sqlite3_stmt *pRet = 0;
  170982. int rc;
  170983. char *zSql;
  170984. va_list ap;
  170985. va_start(ap, zFmt);
  170986. zSql = sqlite3_vmprintf(zFmt, ap);
  170987. if( zSql==0 ){
  170988. rc = SQLITE_NOMEM;
  170989. }else{
  170990. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
  170991. if( rc!=SQLITE_OK ){
  170992. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  170993. }
  170994. sqlite3_free(zSql);
  170995. }
  170996. va_end(ap);
  170997. *ppStmt = pRet;
  170998. return rc;
  170999. }
  171000. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  171001. Fts5Config *pConfig = pTab->pConfig;
  171002. Fts5Sorter *pSorter;
  171003. int nPhrase;
  171004. int nByte;
  171005. int rc;
  171006. const char *zRank = pCsr->zRank;
  171007. const char *zRankArgs = pCsr->zRankArgs;
  171008. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  171009. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  171010. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  171011. if( pSorter==0 ) return SQLITE_NOMEM;
  171012. memset(pSorter, 0, nByte);
  171013. pSorter->nIdx = nPhrase;
  171014. /* TODO: It would be better to have some system for reusing statement
  171015. ** handles here, rather than preparing a new one for each query. But that
  171016. ** is not possible as SQLite reference counts the virtual table objects.
  171017. ** And since the statement required here reads from this very virtual
  171018. ** table, saving it creates a circular reference.
  171019. **
  171020. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  171021. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  171022. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  171023. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  171024. (zRankArgs ? ", " : ""),
  171025. (zRankArgs ? zRankArgs : ""),
  171026. bDesc ? "DESC" : "ASC"
  171027. );
  171028. pCsr->pSorter = pSorter;
  171029. if( rc==SQLITE_OK ){
  171030. assert( pTab->pSortCsr==0 );
  171031. pTab->pSortCsr = pCsr;
  171032. rc = fts5SorterNext(pCsr);
  171033. pTab->pSortCsr = 0;
  171034. }
  171035. if( rc!=SQLITE_OK ){
  171036. sqlite3_finalize(pSorter->pStmt);
  171037. sqlite3_free(pSorter);
  171038. pCsr->pSorter = 0;
  171039. }
  171040. return rc;
  171041. }
  171042. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  171043. int rc;
  171044. Fts5Expr *pExpr = pCsr->pExpr;
  171045. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  171046. if( sqlite3Fts5ExprEof(pExpr) ){
  171047. CsrFlagSet(pCsr, FTS5CSR_EOF);
  171048. }
  171049. fts5CsrNewrow(pCsr);
  171050. return rc;
  171051. }
  171052. /*
  171053. ** Process a "special" query. A special query is identified as one with a
  171054. ** MATCH expression that begins with a '*' character. The remainder of
  171055. ** the text passed to the MATCH operator are used as the special query
  171056. ** parameters.
  171057. */
  171058. static int fts5SpecialMatch(
  171059. Fts5Table *pTab,
  171060. Fts5Cursor *pCsr,
  171061. const char *zQuery
  171062. ){
  171063. int rc = SQLITE_OK; /* Return code */
  171064. const char *z = zQuery; /* Special query text */
  171065. int n; /* Number of bytes in text at z */
  171066. while( z[0]==' ' ) z++;
  171067. for(n=0; z[n] && z[n]!=' '; n++);
  171068. assert( pTab->base.zErrMsg==0 );
  171069. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  171070. if( 0==sqlite3_strnicmp("reads", z, n) ){
  171071. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  171072. }
  171073. else if( 0==sqlite3_strnicmp("id", z, n) ){
  171074. pCsr->iSpecial = pCsr->iCsrId;
  171075. }
  171076. else{
  171077. /* An unrecognized directive. Return an error message. */
  171078. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  171079. rc = SQLITE_ERROR;
  171080. }
  171081. return rc;
  171082. }
  171083. /*
  171084. ** Search for an auxiliary function named zName that can be used with table
  171085. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  171086. ** structure. Otherwise, if no such function exists, return NULL.
  171087. */
  171088. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  171089. Fts5Auxiliary *pAux;
  171090. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  171091. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  171092. }
  171093. /* No function of the specified name was found. Return 0. */
  171094. return 0;
  171095. }
  171096. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  171097. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  171098. Fts5Config *pConfig = pTab->pConfig;
  171099. int rc = SQLITE_OK;
  171100. Fts5Auxiliary *pAux = 0;
  171101. const char *zRank = pCsr->zRank;
  171102. const char *zRankArgs = pCsr->zRankArgs;
  171103. if( zRankArgs ){
  171104. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  171105. if( zSql ){
  171106. sqlite3_stmt *pStmt = 0;
  171107. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
  171108. sqlite3_free(zSql);
  171109. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  171110. if( rc==SQLITE_OK ){
  171111. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  171112. int nByte;
  171113. pCsr->nRankArg = sqlite3_column_count(pStmt);
  171114. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  171115. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  171116. if( rc==SQLITE_OK ){
  171117. int i;
  171118. for(i=0; i<pCsr->nRankArg; i++){
  171119. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  171120. }
  171121. }
  171122. pCsr->pRankArgStmt = pStmt;
  171123. }else{
  171124. rc = sqlite3_finalize(pStmt);
  171125. assert( rc!=SQLITE_OK );
  171126. }
  171127. }
  171128. }
  171129. }
  171130. if( rc==SQLITE_OK ){
  171131. pAux = fts5FindAuxiliary(pTab, zRank);
  171132. if( pAux==0 ){
  171133. assert( pTab->base.zErrMsg==0 );
  171134. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  171135. rc = SQLITE_ERROR;
  171136. }
  171137. }
  171138. pCsr->pRank = pAux;
  171139. return rc;
  171140. }
  171141. static int fts5CursorParseRank(
  171142. Fts5Config *pConfig,
  171143. Fts5Cursor *pCsr,
  171144. sqlite3_value *pRank
  171145. ){
  171146. int rc = SQLITE_OK;
  171147. if( pRank ){
  171148. const char *z = (const char*)sqlite3_value_text(pRank);
  171149. char *zRank = 0;
  171150. char *zRankArgs = 0;
  171151. if( z==0 ){
  171152. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  171153. }else{
  171154. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  171155. }
  171156. if( rc==SQLITE_OK ){
  171157. pCsr->zRank = zRank;
  171158. pCsr->zRankArgs = zRankArgs;
  171159. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  171160. }else if( rc==SQLITE_ERROR ){
  171161. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  171162. "parse error in rank function: %s", z
  171163. );
  171164. }
  171165. }else{
  171166. if( pConfig->zRank ){
  171167. pCsr->zRank = (char*)pConfig->zRank;
  171168. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  171169. }else{
  171170. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  171171. pCsr->zRankArgs = 0;
  171172. }
  171173. }
  171174. return rc;
  171175. }
  171176. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  171177. if( pVal ){
  171178. int eType = sqlite3_value_numeric_type(pVal);
  171179. if( eType==SQLITE_INTEGER ){
  171180. return sqlite3_value_int64(pVal);
  171181. }
  171182. }
  171183. return iDefault;
  171184. }
  171185. /*
  171186. ** This is the xFilter interface for the virtual table. See
  171187. ** the virtual table xFilter method documentation for additional
  171188. ** information.
  171189. **
  171190. ** There are three possible query strategies:
  171191. **
  171192. ** 1. Full-text search using a MATCH operator.
  171193. ** 2. A by-rowid lookup.
  171194. ** 3. A full-table scan.
  171195. */
  171196. static int fts5FilterMethod(
  171197. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  171198. int idxNum, /* Strategy index */
  171199. const char *zUnused, /* Unused */
  171200. int nVal, /* Number of elements in apVal */
  171201. sqlite3_value **apVal /* Arguments for the indexing scheme */
  171202. ){
  171203. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  171204. Fts5Config *pConfig = pTab->pConfig;
  171205. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  171206. int rc = SQLITE_OK; /* Error code */
  171207. int iVal = 0; /* Counter for apVal[] */
  171208. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  171209. int bOrderByRank; /* True if ORDER BY rank */
  171210. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  171211. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  171212. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  171213. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  171214. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  171215. char **pzErrmsg = pConfig->pzErrmsg;
  171216. UNUSED_PARAM(zUnused);
  171217. UNUSED_PARAM(nVal);
  171218. if( pCsr->ePlan ){
  171219. fts5FreeCursorComponents(pCsr);
  171220. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  171221. }
  171222. assert( pCsr->pStmt==0 );
  171223. assert( pCsr->pExpr==0 );
  171224. assert( pCsr->csrflags==0 );
  171225. assert( pCsr->pRank==0 );
  171226. assert( pCsr->zRank==0 );
  171227. assert( pCsr->zRankArgs==0 );
  171228. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  171229. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  171230. /* Decode the arguments passed through to this function.
  171231. **
  171232. ** Note: The following set of if(...) statements must be in the same
  171233. ** order as the corresponding entries in the struct at the top of
  171234. ** fts5BestIndexMethod(). */
  171235. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  171236. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  171237. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  171238. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  171239. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  171240. assert( iVal==nVal );
  171241. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  171242. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  171243. /* Set the cursor upper and lower rowid limits. Only some strategies
  171244. ** actually use them. This is ok, as the xBestIndex() method leaves the
  171245. ** sqlite3_index_constraint.omit flag clear for range constraints
  171246. ** on the rowid field. */
  171247. if( pRowidEq ){
  171248. pRowidLe = pRowidGe = pRowidEq;
  171249. }
  171250. if( bDesc ){
  171251. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  171252. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  171253. }else{
  171254. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  171255. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  171256. }
  171257. if( pTab->pSortCsr ){
  171258. /* If pSortCsr is non-NULL, then this call is being made as part of
  171259. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  171260. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  171261. ** return results to the user for this query. The current cursor
  171262. ** (pCursor) is used to execute the query issued by function
  171263. ** fts5CursorFirstSorted() above. */
  171264. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  171265. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  171266. assert( pCsr->iLastRowid==LARGEST_INT64 );
  171267. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  171268. pCsr->ePlan = FTS5_PLAN_SOURCE;
  171269. pCsr->pExpr = pTab->pSortCsr->pExpr;
  171270. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  171271. sqlite3Fts5ExprClearEof(pCsr->pExpr);
  171272. }else if( pMatch ){
  171273. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  171274. if( zExpr==0 ) zExpr = "";
  171275. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  171276. if( rc==SQLITE_OK ){
  171277. if( zExpr[0]=='*' ){
  171278. /* The user has issued a query of the form "MATCH '*...'". This
  171279. ** indicates that the MATCH expression is not a full text query,
  171280. ** but a request for an internal parameter. */
  171281. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  171282. }else{
  171283. char **pzErr = &pTab->base.zErrMsg;
  171284. rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
  171285. if( rc==SQLITE_OK ){
  171286. if( bOrderByRank ){
  171287. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  171288. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  171289. }else{
  171290. pCsr->ePlan = FTS5_PLAN_MATCH;
  171291. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  171292. }
  171293. }
  171294. }
  171295. }
  171296. }else if( pConfig->zContent==0 ){
  171297. *pConfig->pzErrmsg = sqlite3_mprintf(
  171298. "%s: table does not support scanning", pConfig->zName
  171299. );
  171300. rc = SQLITE_ERROR;
  171301. }else{
  171302. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  171303. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  171304. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  171305. rc = sqlite3Fts5StorageStmt(
  171306. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  171307. );
  171308. if( rc==SQLITE_OK ){
  171309. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  171310. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  171311. }else{
  171312. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  171313. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  171314. }
  171315. rc = fts5NextMethod(pCursor);
  171316. }
  171317. }
  171318. pConfig->pzErrmsg = pzErrmsg;
  171319. return rc;
  171320. }
  171321. /*
  171322. ** This is the xEof method of the virtual table. SQLite calls this
  171323. ** routine to find out if it has reached the end of a result set.
  171324. */
  171325. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  171326. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  171327. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  171328. }
  171329. /*
  171330. ** Return the rowid that the cursor currently points to.
  171331. */
  171332. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  171333. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  171334. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  171335. || pCsr->ePlan==FTS5_PLAN_SOURCE
  171336. );
  171337. if( pCsr->pSorter ){
  171338. return pCsr->pSorter->iRowid;
  171339. }else{
  171340. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  171341. }
  171342. }
  171343. /*
  171344. ** This is the xRowid method. The SQLite core calls this routine to
  171345. ** retrieve the rowid for the current row of the result set. fts5
  171346. ** exposes %_content.rowid as the rowid for the virtual table. The
  171347. ** rowid should be written to *pRowid.
  171348. */
  171349. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  171350. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  171351. int ePlan = pCsr->ePlan;
  171352. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  171353. switch( ePlan ){
  171354. case FTS5_PLAN_SPECIAL:
  171355. *pRowid = 0;
  171356. break;
  171357. case FTS5_PLAN_SOURCE:
  171358. case FTS5_PLAN_MATCH:
  171359. case FTS5_PLAN_SORTED_MATCH:
  171360. *pRowid = fts5CursorRowid(pCsr);
  171361. break;
  171362. default:
  171363. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  171364. break;
  171365. }
  171366. return SQLITE_OK;
  171367. }
  171368. /*
  171369. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  171370. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  171371. **
  171372. ** If argument bErrormsg is true and an error occurs, an error message may
  171373. ** be left in sqlite3_vtab.zErrMsg.
  171374. */
  171375. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  171376. int rc = SQLITE_OK;
  171377. /* If the cursor does not yet have a statement handle, obtain one now. */
  171378. if( pCsr->pStmt==0 ){
  171379. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  171380. int eStmt = fts5StmtType(pCsr);
  171381. rc = sqlite3Fts5StorageStmt(
  171382. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  171383. );
  171384. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  171385. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  171386. }
  171387. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  171388. assert( pCsr->pExpr );
  171389. sqlite3_reset(pCsr->pStmt);
  171390. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  171391. rc = sqlite3_step(pCsr->pStmt);
  171392. if( rc==SQLITE_ROW ){
  171393. rc = SQLITE_OK;
  171394. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  171395. }else{
  171396. rc = sqlite3_reset(pCsr->pStmt);
  171397. if( rc==SQLITE_OK ){
  171398. rc = FTS5_CORRUPT;
  171399. }
  171400. }
  171401. }
  171402. return rc;
  171403. }
  171404. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  171405. va_list ap; /* ... printf arguments */
  171406. va_start(ap, zFormat);
  171407. assert( p->base.zErrMsg==0 );
  171408. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  171409. va_end(ap);
  171410. }
  171411. /*
  171412. ** This function is called to handle an FTS INSERT command. In other words,
  171413. ** an INSERT statement of the form:
  171414. **
  171415. ** INSERT INTO fts(fts) VALUES($pCmd)
  171416. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  171417. **
  171418. ** Argument pVal is the value assigned to column "fts" by the INSERT
  171419. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  171420. ** error code if an error occurs.
  171421. **
  171422. ** The commands implemented by this function are documented in the "Special
  171423. ** INSERT Directives" section of the documentation. It should be updated if
  171424. ** more commands are added to this function.
  171425. */
  171426. static int fts5SpecialInsert(
  171427. Fts5Table *pTab, /* Fts5 table object */
  171428. const char *zCmd, /* Text inserted into table-name column */
  171429. sqlite3_value *pVal /* Value inserted into rank column */
  171430. ){
  171431. Fts5Config *pConfig = pTab->pConfig;
  171432. int rc = SQLITE_OK;
  171433. int bError = 0;
  171434. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  171435. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  171436. fts5SetVtabError(pTab,
  171437. "'delete-all' may only be used with a "
  171438. "contentless or external content fts5 table"
  171439. );
  171440. rc = SQLITE_ERROR;
  171441. }else{
  171442. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  171443. }
  171444. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  171445. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  171446. fts5SetVtabError(pTab,
  171447. "'rebuild' may not be used with a contentless fts5 table"
  171448. );
  171449. rc = SQLITE_ERROR;
  171450. }else{
  171451. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  171452. }
  171453. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  171454. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  171455. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  171456. int nMerge = sqlite3_value_int(pVal);
  171457. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  171458. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  171459. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  171460. #ifdef SQLITE_DEBUG
  171461. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  171462. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  171463. #endif
  171464. }else{
  171465. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  171466. if( rc==SQLITE_OK ){
  171467. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  171468. }
  171469. if( rc==SQLITE_OK ){
  171470. if( bError ){
  171471. rc = SQLITE_ERROR;
  171472. }else{
  171473. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  171474. }
  171475. }
  171476. }
  171477. return rc;
  171478. }
  171479. static int fts5SpecialDelete(
  171480. Fts5Table *pTab,
  171481. sqlite3_value **apVal
  171482. ){
  171483. int rc = SQLITE_OK;
  171484. int eType1 = sqlite3_value_type(apVal[1]);
  171485. if( eType1==SQLITE_INTEGER ){
  171486. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  171487. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  171488. }
  171489. return rc;
  171490. }
  171491. static void fts5StorageInsert(
  171492. int *pRc,
  171493. Fts5Table *pTab,
  171494. sqlite3_value **apVal,
  171495. i64 *piRowid
  171496. ){
  171497. int rc = *pRc;
  171498. if( rc==SQLITE_OK ){
  171499. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  171500. }
  171501. if( rc==SQLITE_OK ){
  171502. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  171503. }
  171504. *pRc = rc;
  171505. }
  171506. /*
  171507. ** This function is the implementation of the xUpdate callback used by
  171508. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  171509. ** inserted, updated or deleted.
  171510. **
  171511. ** A delete specifies a single argument - the rowid of the row to remove.
  171512. **
  171513. ** Update and insert operations pass:
  171514. **
  171515. ** 1. The "old" rowid, or NULL.
  171516. ** 2. The "new" rowid.
  171517. ** 3. Values for each of the nCol matchable columns.
  171518. ** 4. Values for the two hidden columns (<tablename> and "rank").
  171519. */
  171520. static int fts5UpdateMethod(
  171521. sqlite3_vtab *pVtab, /* Virtual table handle */
  171522. int nArg, /* Size of argument array */
  171523. sqlite3_value **apVal, /* Array of arguments */
  171524. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  171525. ){
  171526. Fts5Table *pTab = (Fts5Table*)pVtab;
  171527. Fts5Config *pConfig = pTab->pConfig;
  171528. int eType0; /* value_type() of apVal[0] */
  171529. int rc = SQLITE_OK; /* Return code */
  171530. /* A transaction must be open when this is called. */
  171531. assert( pTab->ts.eState==1 );
  171532. assert( pVtab->zErrMsg==0 );
  171533. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  171534. assert( nArg==1
  171535. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  171536. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  171537. );
  171538. assert( pTab->pConfig->pzErrmsg==0 );
  171539. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  171540. /* Put any active cursors into REQUIRE_SEEK state. */
  171541. fts5TripCursors(pTab);
  171542. eType0 = sqlite3_value_type(apVal[0]);
  171543. if( eType0==SQLITE_NULL
  171544. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  171545. ){
  171546. /* A "special" INSERT op. These are handled separately. */
  171547. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  171548. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  171549. && 0==sqlite3_stricmp("delete", z)
  171550. ){
  171551. rc = fts5SpecialDelete(pTab, apVal);
  171552. }else{
  171553. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  171554. }
  171555. }else{
  171556. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  171557. ** any conflict on the rowid value must be detected before any
  171558. ** modifications are made to the database file. There are 4 cases:
  171559. **
  171560. ** 1) DELETE
  171561. ** 2) UPDATE (rowid not modified)
  171562. ** 3) UPDATE (rowid modified)
  171563. ** 4) INSERT
  171564. **
  171565. ** Cases 3 and 4 may violate the rowid constraint.
  171566. */
  171567. int eConflict = SQLITE_ABORT;
  171568. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  171569. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  171570. }
  171571. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  171572. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  171573. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  171574. ** This is not suported. */
  171575. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  171576. pTab->base.zErrMsg = sqlite3_mprintf(
  171577. "cannot %s contentless fts5 table: %s",
  171578. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  171579. );
  171580. rc = SQLITE_ERROR;
  171581. }
  171582. /* DELETE */
  171583. else if( nArg==1 ){
  171584. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  171585. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  171586. }
  171587. /* INSERT */
  171588. else if( eType0!=SQLITE_INTEGER ){
  171589. /* If this is a REPLACE, first remove the current entry (if any) */
  171590. if( eConflict==SQLITE_REPLACE
  171591. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  171592. ){
  171593. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  171594. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  171595. }
  171596. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  171597. }
  171598. /* UPDATE */
  171599. else{
  171600. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  171601. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  171602. if( iOld!=iNew ){
  171603. if( eConflict==SQLITE_REPLACE ){
  171604. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  171605. if( rc==SQLITE_OK ){
  171606. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  171607. }
  171608. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  171609. }else{
  171610. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  171611. if( rc==SQLITE_OK ){
  171612. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  171613. }
  171614. if( rc==SQLITE_OK ){
  171615. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  171616. }
  171617. }
  171618. }else{
  171619. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  171620. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  171621. }
  171622. }
  171623. }
  171624. pTab->pConfig->pzErrmsg = 0;
  171625. return rc;
  171626. }
  171627. /*
  171628. ** Implementation of xSync() method.
  171629. */
  171630. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  171631. int rc;
  171632. Fts5Table *pTab = (Fts5Table*)pVtab;
  171633. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  171634. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  171635. fts5TripCursors(pTab);
  171636. rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
  171637. pTab->pConfig->pzErrmsg = 0;
  171638. return rc;
  171639. }
  171640. /*
  171641. ** Implementation of xBegin() method.
  171642. */
  171643. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  171644. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  171645. fts5NewTransaction((Fts5Table*)pVtab);
  171646. return SQLITE_OK;
  171647. }
  171648. /*
  171649. ** Implementation of xCommit() method. This is a no-op. The contents of
  171650. ** the pending-terms hash-table have already been flushed into the database
  171651. ** by fts5SyncMethod().
  171652. */
  171653. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  171654. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  171655. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  171656. return SQLITE_OK;
  171657. }
  171658. /*
  171659. ** Implementation of xRollback(). Discard the contents of the pending-terms
  171660. ** hash-table. Any changes made to the database are reverted by SQLite.
  171661. */
  171662. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  171663. int rc;
  171664. Fts5Table *pTab = (Fts5Table*)pVtab;
  171665. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  171666. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  171667. return rc;
  171668. }
  171669. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  171670. static void *fts5ApiUserData(Fts5Context *pCtx){
  171671. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171672. return pCsr->pAux->pUserData;
  171673. }
  171674. static int fts5ApiColumnCount(Fts5Context *pCtx){
  171675. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171676. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  171677. }
  171678. static int fts5ApiColumnTotalSize(
  171679. Fts5Context *pCtx,
  171680. int iCol,
  171681. sqlite3_int64 *pnToken
  171682. ){
  171683. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171684. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  171685. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  171686. }
  171687. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  171688. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171689. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  171690. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  171691. }
  171692. static int fts5ApiTokenize(
  171693. Fts5Context *pCtx,
  171694. const char *pText, int nText,
  171695. void *pUserData,
  171696. int (*xToken)(void*, int, const char*, int, int, int)
  171697. ){
  171698. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171699. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  171700. return sqlite3Fts5Tokenize(
  171701. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  171702. );
  171703. }
  171704. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  171705. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171706. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  171707. }
  171708. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  171709. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171710. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  171711. }
  171712. static int fts5ApiColumnText(
  171713. Fts5Context *pCtx,
  171714. int iCol,
  171715. const char **pz,
  171716. int *pn
  171717. ){
  171718. int rc = SQLITE_OK;
  171719. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171720. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  171721. *pz = 0;
  171722. *pn = 0;
  171723. }else{
  171724. rc = fts5SeekCursor(pCsr, 0);
  171725. if( rc==SQLITE_OK ){
  171726. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  171727. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  171728. }
  171729. }
  171730. return rc;
  171731. }
  171732. static int fts5CsrPoslist(
  171733. Fts5Cursor *pCsr,
  171734. int iPhrase,
  171735. const u8 **pa,
  171736. int *pn
  171737. ){
  171738. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  171739. int rc = SQLITE_OK;
  171740. int bLive = (pCsr->pSorter==0);
  171741. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  171742. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  171743. Fts5PoslistPopulator *aPopulator;
  171744. int i;
  171745. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  171746. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  171747. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  171748. int n; const char *z;
  171749. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  171750. if( rc==SQLITE_OK ){
  171751. rc = sqlite3Fts5ExprPopulatePoslists(
  171752. pConfig, pCsr->pExpr, aPopulator, i, z, n
  171753. );
  171754. }
  171755. }
  171756. sqlite3_free(aPopulator);
  171757. if( pCsr->pSorter ){
  171758. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  171759. }
  171760. }
  171761. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  171762. }
  171763. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  171764. Fts5Sorter *pSorter = pCsr->pSorter;
  171765. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  171766. *pn = pSorter->aIdx[iPhrase] - i1;
  171767. *pa = &pSorter->aPoslist[i1];
  171768. }else{
  171769. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  171770. }
  171771. return rc;
  171772. }
  171773. /*
  171774. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  171775. ** correctly for the current view. Return SQLITE_OK if successful, or an
  171776. ** SQLite error code otherwise.
  171777. */
  171778. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  171779. int rc = SQLITE_OK;
  171780. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  171781. int nIter; /* Number of iterators/phrases */
  171782. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  171783. if( pCsr->aInstIter==0 ){
  171784. int nByte = sizeof(Fts5PoslistReader) * nIter;
  171785. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  171786. }
  171787. aIter = pCsr->aInstIter;
  171788. if( aIter ){
  171789. int nInst = 0; /* Number instances seen so far */
  171790. int i;
  171791. /* Initialize all iterators */
  171792. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  171793. const u8 *a;
  171794. int n;
  171795. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  171796. if( rc==SQLITE_OK ){
  171797. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  171798. }
  171799. }
  171800. if( rc==SQLITE_OK ){
  171801. while( 1 ){
  171802. int *aInst;
  171803. int iBest = -1;
  171804. for(i=0; i<nIter; i++){
  171805. if( (aIter[i].bEof==0)
  171806. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  171807. ){
  171808. iBest = i;
  171809. }
  171810. }
  171811. if( iBest<0 ) break;
  171812. nInst++;
  171813. if( nInst>=pCsr->nInstAlloc ){
  171814. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  171815. aInst = (int*)sqlite3_realloc(
  171816. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  171817. );
  171818. if( aInst ){
  171819. pCsr->aInst = aInst;
  171820. }else{
  171821. rc = SQLITE_NOMEM;
  171822. break;
  171823. }
  171824. }
  171825. aInst = &pCsr->aInst[3 * (nInst-1)];
  171826. aInst[0] = iBest;
  171827. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  171828. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  171829. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  171830. }
  171831. }
  171832. pCsr->nInstCount = nInst;
  171833. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  171834. }
  171835. return rc;
  171836. }
  171837. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  171838. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171839. int rc = SQLITE_OK;
  171840. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  171841. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  171842. *pnInst = pCsr->nInstCount;
  171843. }
  171844. return rc;
  171845. }
  171846. static int fts5ApiInst(
  171847. Fts5Context *pCtx,
  171848. int iIdx,
  171849. int *piPhrase,
  171850. int *piCol,
  171851. int *piOff
  171852. ){
  171853. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171854. int rc = SQLITE_OK;
  171855. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  171856. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  171857. ){
  171858. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  171859. rc = SQLITE_RANGE;
  171860. #if 0
  171861. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  171862. *piPhrase = pCsr->aInst[iIdx*3];
  171863. *piCol = pCsr->aInst[iIdx*3 + 2];
  171864. *piOff = -1;
  171865. #endif
  171866. }else{
  171867. *piPhrase = pCsr->aInst[iIdx*3];
  171868. *piCol = pCsr->aInst[iIdx*3 + 1];
  171869. *piOff = pCsr->aInst[iIdx*3 + 2];
  171870. }
  171871. }
  171872. return rc;
  171873. }
  171874. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  171875. return fts5CursorRowid((Fts5Cursor*)pCtx);
  171876. }
  171877. static int fts5ColumnSizeCb(
  171878. void *pContext, /* Pointer to int */
  171879. int tflags,
  171880. const char *pUnused, /* Buffer containing token */
  171881. int nUnused, /* Size of token in bytes */
  171882. int iUnused1, /* Start offset of token */
  171883. int iUnused2 /* End offset of token */
  171884. ){
  171885. int *pCnt = (int*)pContext;
  171886. UNUSED_PARAM2(pUnused, nUnused);
  171887. UNUSED_PARAM2(iUnused1, iUnused2);
  171888. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  171889. (*pCnt)++;
  171890. }
  171891. return SQLITE_OK;
  171892. }
  171893. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  171894. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171895. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  171896. Fts5Config *pConfig = pTab->pConfig;
  171897. int rc = SQLITE_OK;
  171898. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  171899. if( pConfig->bColumnsize ){
  171900. i64 iRowid = fts5CursorRowid(pCsr);
  171901. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  171902. }else if( pConfig->zContent==0 ){
  171903. int i;
  171904. for(i=0; i<pConfig->nCol; i++){
  171905. if( pConfig->abUnindexed[i]==0 ){
  171906. pCsr->aColumnSize[i] = -1;
  171907. }
  171908. }
  171909. }else{
  171910. int i;
  171911. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  171912. if( pConfig->abUnindexed[i]==0 ){
  171913. const char *z; int n;
  171914. void *p = (void*)(&pCsr->aColumnSize[i]);
  171915. pCsr->aColumnSize[i] = 0;
  171916. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  171917. if( rc==SQLITE_OK ){
  171918. rc = sqlite3Fts5Tokenize(
  171919. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  171920. );
  171921. }
  171922. }
  171923. }
  171924. }
  171925. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  171926. }
  171927. if( iCol<0 ){
  171928. int i;
  171929. *pnToken = 0;
  171930. for(i=0; i<pConfig->nCol; i++){
  171931. *pnToken += pCsr->aColumnSize[i];
  171932. }
  171933. }else if( iCol<pConfig->nCol ){
  171934. *pnToken = pCsr->aColumnSize[iCol];
  171935. }else{
  171936. *pnToken = 0;
  171937. rc = SQLITE_RANGE;
  171938. }
  171939. return rc;
  171940. }
  171941. /*
  171942. ** Implementation of the xSetAuxdata() method.
  171943. */
  171944. static int fts5ApiSetAuxdata(
  171945. Fts5Context *pCtx, /* Fts5 context */
  171946. void *pPtr, /* Pointer to save as auxdata */
  171947. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  171948. ){
  171949. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171950. Fts5Auxdata *pData;
  171951. /* Search through the cursors list of Fts5Auxdata objects for one that
  171952. ** corresponds to the currently executing auxiliary function. */
  171953. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  171954. if( pData->pAux==pCsr->pAux ) break;
  171955. }
  171956. if( pData ){
  171957. if( pData->xDelete ){
  171958. pData->xDelete(pData->pPtr);
  171959. }
  171960. }else{
  171961. int rc = SQLITE_OK;
  171962. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  171963. if( pData==0 ){
  171964. if( xDelete ) xDelete(pPtr);
  171965. return rc;
  171966. }
  171967. pData->pAux = pCsr->pAux;
  171968. pData->pNext = pCsr->pAuxdata;
  171969. pCsr->pAuxdata = pData;
  171970. }
  171971. pData->xDelete = xDelete;
  171972. pData->pPtr = pPtr;
  171973. return SQLITE_OK;
  171974. }
  171975. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  171976. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  171977. Fts5Auxdata *pData;
  171978. void *pRet = 0;
  171979. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  171980. if( pData->pAux==pCsr->pAux ) break;
  171981. }
  171982. if( pData ){
  171983. pRet = pData->pPtr;
  171984. if( bClear ){
  171985. pData->pPtr = 0;
  171986. pData->xDelete = 0;
  171987. }
  171988. }
  171989. return pRet;
  171990. }
  171991. static void fts5ApiPhraseNext(
  171992. Fts5Context *pUnused,
  171993. Fts5PhraseIter *pIter,
  171994. int *piCol, int *piOff
  171995. ){
  171996. UNUSED_PARAM(pUnused);
  171997. if( pIter->a>=pIter->b ){
  171998. *piCol = -1;
  171999. *piOff = -1;
  172000. }else{
  172001. int iVal;
  172002. pIter->a += fts5GetVarint32(pIter->a, iVal);
  172003. if( iVal==1 ){
  172004. pIter->a += fts5GetVarint32(pIter->a, iVal);
  172005. *piCol = iVal;
  172006. *piOff = 0;
  172007. pIter->a += fts5GetVarint32(pIter->a, iVal);
  172008. }
  172009. *piOff += (iVal-2);
  172010. }
  172011. }
  172012. static int fts5ApiPhraseFirst(
  172013. Fts5Context *pCtx,
  172014. int iPhrase,
  172015. Fts5PhraseIter *pIter,
  172016. int *piCol, int *piOff
  172017. ){
  172018. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  172019. int n;
  172020. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  172021. if( rc==SQLITE_OK ){
  172022. pIter->b = &pIter->a[n];
  172023. *piCol = 0;
  172024. *piOff = 0;
  172025. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  172026. }
  172027. return rc;
  172028. }
  172029. static void fts5ApiPhraseNextColumn(
  172030. Fts5Context *pCtx,
  172031. Fts5PhraseIter *pIter,
  172032. int *piCol
  172033. ){
  172034. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  172035. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  172036. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  172037. if( pIter->a>=pIter->b ){
  172038. *piCol = -1;
  172039. }else{
  172040. int iIncr;
  172041. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  172042. *piCol += (iIncr-2);
  172043. }
  172044. }else{
  172045. while( 1 ){
  172046. int dummy;
  172047. if( pIter->a>=pIter->b ){
  172048. *piCol = -1;
  172049. return;
  172050. }
  172051. if( pIter->a[0]==0x01 ) break;
  172052. pIter->a += fts5GetVarint32(pIter->a, dummy);
  172053. }
  172054. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  172055. }
  172056. }
  172057. static int fts5ApiPhraseFirstColumn(
  172058. Fts5Context *pCtx,
  172059. int iPhrase,
  172060. Fts5PhraseIter *pIter,
  172061. int *piCol
  172062. ){
  172063. int rc = SQLITE_OK;
  172064. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  172065. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  172066. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  172067. Fts5Sorter *pSorter = pCsr->pSorter;
  172068. int n;
  172069. if( pSorter ){
  172070. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  172071. n = pSorter->aIdx[iPhrase] - i1;
  172072. pIter->a = &pSorter->aPoslist[i1];
  172073. }else{
  172074. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  172075. }
  172076. if( rc==SQLITE_OK ){
  172077. pIter->b = &pIter->a[n];
  172078. *piCol = 0;
  172079. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  172080. }
  172081. }else{
  172082. int n;
  172083. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  172084. if( rc==SQLITE_OK ){
  172085. pIter->b = &pIter->a[n];
  172086. if( n<=0 ){
  172087. *piCol = -1;
  172088. }else if( pIter->a[0]==0x01 ){
  172089. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  172090. }else{
  172091. *piCol = 0;
  172092. }
  172093. }
  172094. }
  172095. return rc;
  172096. }
  172097. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  172098. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  172099. );
  172100. static const Fts5ExtensionApi sFts5Api = {
  172101. 2, /* iVersion */
  172102. fts5ApiUserData,
  172103. fts5ApiColumnCount,
  172104. fts5ApiRowCount,
  172105. fts5ApiColumnTotalSize,
  172106. fts5ApiTokenize,
  172107. fts5ApiPhraseCount,
  172108. fts5ApiPhraseSize,
  172109. fts5ApiInstCount,
  172110. fts5ApiInst,
  172111. fts5ApiRowid,
  172112. fts5ApiColumnText,
  172113. fts5ApiColumnSize,
  172114. fts5ApiQueryPhrase,
  172115. fts5ApiSetAuxdata,
  172116. fts5ApiGetAuxdata,
  172117. fts5ApiPhraseFirst,
  172118. fts5ApiPhraseNext,
  172119. fts5ApiPhraseFirstColumn,
  172120. fts5ApiPhraseNextColumn,
  172121. };
  172122. /*
  172123. ** Implementation of API function xQueryPhrase().
  172124. */
  172125. static int fts5ApiQueryPhrase(
  172126. Fts5Context *pCtx,
  172127. int iPhrase,
  172128. void *pUserData,
  172129. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  172130. ){
  172131. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  172132. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  172133. int rc;
  172134. Fts5Cursor *pNew = 0;
  172135. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  172136. if( rc==SQLITE_OK ){
  172137. pNew->ePlan = FTS5_PLAN_MATCH;
  172138. pNew->iFirstRowid = SMALLEST_INT64;
  172139. pNew->iLastRowid = LARGEST_INT64;
  172140. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  172141. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  172142. }
  172143. if( rc==SQLITE_OK ){
  172144. for(rc = fts5CursorFirst(pTab, pNew, 0);
  172145. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  172146. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  172147. ){
  172148. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  172149. if( rc!=SQLITE_OK ){
  172150. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  172151. break;
  172152. }
  172153. }
  172154. }
  172155. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  172156. return rc;
  172157. }
  172158. static void fts5ApiInvoke(
  172159. Fts5Auxiliary *pAux,
  172160. Fts5Cursor *pCsr,
  172161. sqlite3_context *context,
  172162. int argc,
  172163. sqlite3_value **argv
  172164. ){
  172165. assert( pCsr->pAux==0 );
  172166. pCsr->pAux = pAux;
  172167. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  172168. pCsr->pAux = 0;
  172169. }
  172170. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  172171. Fts5Cursor *pCsr;
  172172. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  172173. if( pCsr->iCsrId==iCsrId ) break;
  172174. }
  172175. return pCsr;
  172176. }
  172177. static void fts5ApiCallback(
  172178. sqlite3_context *context,
  172179. int argc,
  172180. sqlite3_value **argv
  172181. ){
  172182. Fts5Auxiliary *pAux;
  172183. Fts5Cursor *pCsr;
  172184. i64 iCsrId;
  172185. assert( argc>=1 );
  172186. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  172187. iCsrId = sqlite3_value_int64(argv[0]);
  172188. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  172189. if( pCsr==0 ){
  172190. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  172191. sqlite3_result_error(context, zErr, -1);
  172192. sqlite3_free(zErr);
  172193. }else{
  172194. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  172195. }
  172196. }
  172197. /*
  172198. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  172199. ** object. Or NULL If the cursor id does not exist.
  172200. **
  172201. ** If successful, set *ppConfig to point to the associated config object
  172202. ** before returning.
  172203. */
  172204. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  172205. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  172206. i64 iCsrId, /* Id of cursor to find */
  172207. Fts5Config **ppConfig /* OUT: Configuration object */
  172208. ){
  172209. Fts5Cursor *pCsr;
  172210. Fts5Table *pTab;
  172211. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  172212. pTab = (Fts5Table*)pCsr->base.pVtab;
  172213. *ppConfig = pTab->pConfig;
  172214. return pTab->pIndex;
  172215. }
  172216. /*
  172217. ** Return a "position-list blob" corresponding to the current position of
  172218. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  172219. ** the current position-list for each phrase in the query associated with
  172220. ** cursor pCsr.
  172221. **
  172222. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  172223. ** the number of phrases in the query. Following the varints are the
  172224. ** concatenated position lists for each phrase, in order.
  172225. **
  172226. ** The first varint (if it exists) contains the size of the position list
  172227. ** for phrase 0. The second (same disclaimer) contains the size of position
  172228. ** list 1. And so on. There is no size field for the final position list,
  172229. ** as it can be derived from the total size of the blob.
  172230. */
  172231. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  172232. int i;
  172233. int rc = SQLITE_OK;
  172234. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  172235. Fts5Buffer val;
  172236. memset(&val, 0, sizeof(Fts5Buffer));
  172237. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  172238. case FTS5_DETAIL_FULL:
  172239. /* Append the varints */
  172240. for(i=0; i<(nPhrase-1); i++){
  172241. const u8 *dummy;
  172242. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  172243. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  172244. }
  172245. /* Append the position lists */
  172246. for(i=0; i<nPhrase; i++){
  172247. const u8 *pPoslist;
  172248. int nPoslist;
  172249. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  172250. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  172251. }
  172252. break;
  172253. case FTS5_DETAIL_COLUMNS:
  172254. /* Append the varints */
  172255. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  172256. const u8 *dummy;
  172257. int nByte;
  172258. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  172259. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  172260. }
  172261. /* Append the position lists */
  172262. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  172263. const u8 *pPoslist;
  172264. int nPoslist;
  172265. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  172266. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  172267. }
  172268. break;
  172269. default:
  172270. break;
  172271. }
  172272. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  172273. return rc;
  172274. }
  172275. /*
  172276. ** This is the xColumn method, called by SQLite to request a value from
  172277. ** the row that the supplied cursor currently points to.
  172278. */
  172279. static int fts5ColumnMethod(
  172280. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  172281. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  172282. int iCol /* Index of column to read value from */
  172283. ){
  172284. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  172285. Fts5Config *pConfig = pTab->pConfig;
  172286. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  172287. int rc = SQLITE_OK;
  172288. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  172289. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  172290. if( iCol==pConfig->nCol ){
  172291. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  172292. }
  172293. }else
  172294. if( iCol==pConfig->nCol ){
  172295. /* User is requesting the value of the special column with the same name
  172296. ** as the table. Return the cursor integer id number. This value is only
  172297. ** useful in that it may be passed as the first argument to an FTS5
  172298. ** auxiliary function. */
  172299. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  172300. }else if( iCol==pConfig->nCol+1 ){
  172301. /* The value of the "rank" column. */
  172302. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  172303. fts5PoslistBlob(pCtx, pCsr);
  172304. }else if(
  172305. pCsr->ePlan==FTS5_PLAN_MATCH
  172306. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  172307. ){
  172308. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  172309. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  172310. }
  172311. }
  172312. }else if( !fts5IsContentless(pTab) ){
  172313. rc = fts5SeekCursor(pCsr, 1);
  172314. if( rc==SQLITE_OK ){
  172315. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  172316. }
  172317. }
  172318. return rc;
  172319. }
  172320. /*
  172321. ** This routine implements the xFindFunction method for the FTS3
  172322. ** virtual table.
  172323. */
  172324. static int fts5FindFunctionMethod(
  172325. sqlite3_vtab *pVtab, /* Virtual table handle */
  172326. int nUnused, /* Number of SQL function arguments */
  172327. const char *zName, /* Name of SQL function */
  172328. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  172329. void **ppArg /* OUT: User data for *pxFunc */
  172330. ){
  172331. Fts5Table *pTab = (Fts5Table*)pVtab;
  172332. Fts5Auxiliary *pAux;
  172333. UNUSED_PARAM(nUnused);
  172334. pAux = fts5FindAuxiliary(pTab, zName);
  172335. if( pAux ){
  172336. *pxFunc = fts5ApiCallback;
  172337. *ppArg = (void*)pAux;
  172338. return 1;
  172339. }
  172340. /* No function of the specified name was found. Return 0. */
  172341. return 0;
  172342. }
  172343. /*
  172344. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  172345. */
  172346. static int fts5RenameMethod(
  172347. sqlite3_vtab *pVtab, /* Virtual table handle */
  172348. const char *zName /* New name of table */
  172349. ){
  172350. Fts5Table *pTab = (Fts5Table*)pVtab;
  172351. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  172352. }
  172353. /*
  172354. ** The xSavepoint() method.
  172355. **
  172356. ** Flush the contents of the pending-terms table to disk.
  172357. */
  172358. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  172359. Fts5Table *pTab = (Fts5Table*)pVtab;
  172360. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  172361. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  172362. fts5TripCursors(pTab);
  172363. return sqlite3Fts5StorageSync(pTab->pStorage, 0);
  172364. }
  172365. /*
  172366. ** The xRelease() method.
  172367. **
  172368. ** This is a no-op.
  172369. */
  172370. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  172371. Fts5Table *pTab = (Fts5Table*)pVtab;
  172372. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  172373. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  172374. fts5TripCursors(pTab);
  172375. return sqlite3Fts5StorageSync(pTab->pStorage, 0);
  172376. }
  172377. /*
  172378. ** The xRollbackTo() method.
  172379. **
  172380. ** Discard the contents of the pending terms table.
  172381. */
  172382. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  172383. Fts5Table *pTab = (Fts5Table*)pVtab;
  172384. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  172385. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  172386. fts5TripCursors(pTab);
  172387. return sqlite3Fts5StorageRollback(pTab->pStorage);
  172388. }
  172389. /*
  172390. ** Register a new auxiliary function with global context pGlobal.
  172391. */
  172392. static int fts5CreateAux(
  172393. fts5_api *pApi, /* Global context (one per db handle) */
  172394. const char *zName, /* Name of new function */
  172395. void *pUserData, /* User data for aux. function */
  172396. fts5_extension_function xFunc, /* Aux. function implementation */
  172397. void(*xDestroy)(void*) /* Destructor for pUserData */
  172398. ){
  172399. Fts5Global *pGlobal = (Fts5Global*)pApi;
  172400. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  172401. if( rc==SQLITE_OK ){
  172402. Fts5Auxiliary *pAux;
  172403. int nName; /* Size of zName in bytes, including \0 */
  172404. int nByte; /* Bytes of space to allocate */
  172405. nName = (int)strlen(zName) + 1;
  172406. nByte = sizeof(Fts5Auxiliary) + nName;
  172407. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  172408. if( pAux ){
  172409. memset(pAux, 0, nByte);
  172410. pAux->zFunc = (char*)&pAux[1];
  172411. memcpy(pAux->zFunc, zName, nName);
  172412. pAux->pGlobal = pGlobal;
  172413. pAux->pUserData = pUserData;
  172414. pAux->xFunc = xFunc;
  172415. pAux->xDestroy = xDestroy;
  172416. pAux->pNext = pGlobal->pAux;
  172417. pGlobal->pAux = pAux;
  172418. }else{
  172419. rc = SQLITE_NOMEM;
  172420. }
  172421. }
  172422. return rc;
  172423. }
  172424. /*
  172425. ** Register a new tokenizer. This is the implementation of the
  172426. ** fts5_api.xCreateTokenizer() method.
  172427. */
  172428. static int fts5CreateTokenizer(
  172429. fts5_api *pApi, /* Global context (one per db handle) */
  172430. const char *zName, /* Name of new function */
  172431. void *pUserData, /* User data for aux. function */
  172432. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  172433. void(*xDestroy)(void*) /* Destructor for pUserData */
  172434. ){
  172435. Fts5Global *pGlobal = (Fts5Global*)pApi;
  172436. Fts5TokenizerModule *pNew;
  172437. int nName; /* Size of zName and its \0 terminator */
  172438. int nByte; /* Bytes of space to allocate */
  172439. int rc = SQLITE_OK;
  172440. nName = (int)strlen(zName) + 1;
  172441. nByte = sizeof(Fts5TokenizerModule) + nName;
  172442. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  172443. if( pNew ){
  172444. memset(pNew, 0, nByte);
  172445. pNew->zName = (char*)&pNew[1];
  172446. memcpy(pNew->zName, zName, nName);
  172447. pNew->pUserData = pUserData;
  172448. pNew->x = *pTokenizer;
  172449. pNew->xDestroy = xDestroy;
  172450. pNew->pNext = pGlobal->pTok;
  172451. pGlobal->pTok = pNew;
  172452. if( pNew->pNext==0 ){
  172453. pGlobal->pDfltTok = pNew;
  172454. }
  172455. }else{
  172456. rc = SQLITE_NOMEM;
  172457. }
  172458. return rc;
  172459. }
  172460. static Fts5TokenizerModule *fts5LocateTokenizer(
  172461. Fts5Global *pGlobal,
  172462. const char *zName
  172463. ){
  172464. Fts5TokenizerModule *pMod = 0;
  172465. if( zName==0 ){
  172466. pMod = pGlobal->pDfltTok;
  172467. }else{
  172468. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  172469. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  172470. }
  172471. }
  172472. return pMod;
  172473. }
  172474. /*
  172475. ** Find a tokenizer. This is the implementation of the
  172476. ** fts5_api.xFindTokenizer() method.
  172477. */
  172478. static int fts5FindTokenizer(
  172479. fts5_api *pApi, /* Global context (one per db handle) */
  172480. const char *zName, /* Name of new function */
  172481. void **ppUserData,
  172482. fts5_tokenizer *pTokenizer /* Populate this object */
  172483. ){
  172484. int rc = SQLITE_OK;
  172485. Fts5TokenizerModule *pMod;
  172486. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  172487. if( pMod ){
  172488. *pTokenizer = pMod->x;
  172489. *ppUserData = pMod->pUserData;
  172490. }else{
  172491. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  172492. rc = SQLITE_ERROR;
  172493. }
  172494. return rc;
  172495. }
  172496. static int sqlite3Fts5GetTokenizer(
  172497. Fts5Global *pGlobal,
  172498. const char **azArg,
  172499. int nArg,
  172500. Fts5Tokenizer **ppTok,
  172501. fts5_tokenizer **ppTokApi,
  172502. char **pzErr
  172503. ){
  172504. Fts5TokenizerModule *pMod;
  172505. int rc = SQLITE_OK;
  172506. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  172507. if( pMod==0 ){
  172508. assert( nArg>0 );
  172509. rc = SQLITE_ERROR;
  172510. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  172511. }else{
  172512. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  172513. *ppTokApi = &pMod->x;
  172514. if( rc!=SQLITE_OK && pzErr ){
  172515. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  172516. }
  172517. }
  172518. if( rc!=SQLITE_OK ){
  172519. *ppTokApi = 0;
  172520. *ppTok = 0;
  172521. }
  172522. return rc;
  172523. }
  172524. static void fts5ModuleDestroy(void *pCtx){
  172525. Fts5TokenizerModule *pTok, *pNextTok;
  172526. Fts5Auxiliary *pAux, *pNextAux;
  172527. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  172528. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  172529. pNextAux = pAux->pNext;
  172530. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  172531. sqlite3_free(pAux);
  172532. }
  172533. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  172534. pNextTok = pTok->pNext;
  172535. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  172536. sqlite3_free(pTok);
  172537. }
  172538. sqlite3_free(pGlobal);
  172539. }
  172540. static void fts5Fts5Func(
  172541. sqlite3_context *pCtx, /* Function call context */
  172542. int nArg, /* Number of args */
  172543. sqlite3_value **apUnused /* Function arguments */
  172544. ){
  172545. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  172546. char buf[8];
  172547. UNUSED_PARAM2(nArg, apUnused);
  172548. assert( nArg==0 );
  172549. assert( sizeof(buf)>=sizeof(pGlobal) );
  172550. memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
  172551. sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
  172552. }
  172553. /*
  172554. ** Implementation of fts5_source_id() function.
  172555. */
  172556. static void fts5SourceIdFunc(
  172557. sqlite3_context *pCtx, /* Function call context */
  172558. int nArg, /* Number of args */
  172559. sqlite3_value **apUnused /* Function arguments */
  172560. ){
  172561. assert( nArg==0 );
  172562. UNUSED_PARAM2(nArg, apUnused);
  172563. sqlite3_result_text(pCtx, "fts5: 2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d", -1, SQLITE_TRANSIENT);
  172564. }
  172565. static int fts5Init(sqlite3 *db){
  172566. static const sqlite3_module fts5Mod = {
  172567. /* iVersion */ 2,
  172568. /* xCreate */ fts5CreateMethod,
  172569. /* xConnect */ fts5ConnectMethod,
  172570. /* xBestIndex */ fts5BestIndexMethod,
  172571. /* xDisconnect */ fts5DisconnectMethod,
  172572. /* xDestroy */ fts5DestroyMethod,
  172573. /* xOpen */ fts5OpenMethod,
  172574. /* xClose */ fts5CloseMethod,
  172575. /* xFilter */ fts5FilterMethod,
  172576. /* xNext */ fts5NextMethod,
  172577. /* xEof */ fts5EofMethod,
  172578. /* xColumn */ fts5ColumnMethod,
  172579. /* xRowid */ fts5RowidMethod,
  172580. /* xUpdate */ fts5UpdateMethod,
  172581. /* xBegin */ fts5BeginMethod,
  172582. /* xSync */ fts5SyncMethod,
  172583. /* xCommit */ fts5CommitMethod,
  172584. /* xRollback */ fts5RollbackMethod,
  172585. /* xFindFunction */ fts5FindFunctionMethod,
  172586. /* xRename */ fts5RenameMethod,
  172587. /* xSavepoint */ fts5SavepointMethod,
  172588. /* xRelease */ fts5ReleaseMethod,
  172589. /* xRollbackTo */ fts5RollbackToMethod,
  172590. };
  172591. int rc;
  172592. Fts5Global *pGlobal = 0;
  172593. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  172594. if( pGlobal==0 ){
  172595. rc = SQLITE_NOMEM;
  172596. }else{
  172597. void *p = (void*)pGlobal;
  172598. memset(pGlobal, 0, sizeof(Fts5Global));
  172599. pGlobal->db = db;
  172600. pGlobal->api.iVersion = 2;
  172601. pGlobal->api.xCreateFunction = fts5CreateAux;
  172602. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  172603. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  172604. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  172605. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  172606. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  172607. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  172608. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  172609. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  172610. if( rc==SQLITE_OK ){
  172611. rc = sqlite3_create_function(
  172612. db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  172613. );
  172614. }
  172615. if( rc==SQLITE_OK ){
  172616. rc = sqlite3_create_function(
  172617. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  172618. );
  172619. }
  172620. }
  172621. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  172622. ** fts5_test_mi.c is compiled and linked into the executable. And call
  172623. ** its entry point to enable the matchinfo() demo. */
  172624. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  172625. if( rc==SQLITE_OK ){
  172626. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  172627. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  172628. }
  172629. #endif
  172630. return rc;
  172631. }
  172632. /*
  172633. ** The following functions are used to register the module with SQLite. If
  172634. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  172635. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  172636. **
  172637. ** Or, if this module is being built as a loadable extension,
  172638. ** sqlite3Fts5Init() is omitted and the two standard entry points
  172639. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  172640. */
  172641. #ifndef SQLITE_CORE
  172642. #ifdef _WIN32
  172643. __declspec(dllexport)
  172644. #endif
  172645. SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
  172646. sqlite3 *db,
  172647. char **pzErrMsg,
  172648. const sqlite3_api_routines *pApi
  172649. ){
  172650. SQLITE_EXTENSION_INIT2(pApi);
  172651. (void)pzErrMsg; /* Unused parameter */
  172652. return fts5Init(db);
  172653. }
  172654. #ifdef _WIN32
  172655. __declspec(dllexport)
  172656. #endif
  172657. SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
  172658. sqlite3 *db,
  172659. char **pzErrMsg,
  172660. const sqlite3_api_routines *pApi
  172661. ){
  172662. SQLITE_EXTENSION_INIT2(pApi);
  172663. (void)pzErrMsg; /* Unused parameter */
  172664. return fts5Init(db);
  172665. }
  172666. #else
  172667. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  172668. return fts5Init(db);
  172669. }
  172670. #endif
  172671. /*
  172672. ** 2014 May 31
  172673. **
  172674. ** The author disclaims copyright to this source code. In place of
  172675. ** a legal notice, here is a blessing:
  172676. **
  172677. ** May you do good and not evil.
  172678. ** May you find forgiveness for yourself and forgive others.
  172679. ** May you share freely, never taking more than you give.
  172680. **
  172681. ******************************************************************************
  172682. **
  172683. */
  172684. /* #include "fts5Int.h" */
  172685. struct Fts5Storage {
  172686. Fts5Config *pConfig;
  172687. Fts5Index *pIndex;
  172688. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  172689. i64 nTotalRow; /* Total number of rows in FTS table */
  172690. i64 *aTotalSize; /* Total sizes of each column */
  172691. sqlite3_stmt *aStmt[11];
  172692. };
  172693. #if FTS5_STMT_SCAN_ASC!=0
  172694. # error "FTS5_STMT_SCAN_ASC mismatch"
  172695. #endif
  172696. #if FTS5_STMT_SCAN_DESC!=1
  172697. # error "FTS5_STMT_SCAN_DESC mismatch"
  172698. #endif
  172699. #if FTS5_STMT_LOOKUP!=2
  172700. # error "FTS5_STMT_LOOKUP mismatch"
  172701. #endif
  172702. #define FTS5_STMT_INSERT_CONTENT 3
  172703. #define FTS5_STMT_REPLACE_CONTENT 4
  172704. #define FTS5_STMT_DELETE_CONTENT 5
  172705. #define FTS5_STMT_REPLACE_DOCSIZE 6
  172706. #define FTS5_STMT_DELETE_DOCSIZE 7
  172707. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  172708. #define FTS5_STMT_REPLACE_CONFIG 9
  172709. #define FTS5_STMT_SCAN 10
  172710. /*
  172711. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  172712. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  172713. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  172714. ** occurs.
  172715. */
  172716. static int fts5StorageGetStmt(
  172717. Fts5Storage *p, /* Storage handle */
  172718. int eStmt, /* FTS5_STMT_XXX constant */
  172719. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  172720. char **pzErrMsg /* OUT: Error message (if any) */
  172721. ){
  172722. int rc = SQLITE_OK;
  172723. /* If there is no %_docsize table, there should be no requests for
  172724. ** statements to operate on it. */
  172725. assert( p->pConfig->bColumnsize || (
  172726. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  172727. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  172728. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  172729. ));
  172730. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  172731. if( p->aStmt[eStmt]==0 ){
  172732. const char *azStmt[] = {
  172733. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  172734. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  172735. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  172736. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  172737. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  172738. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  172739. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  172740. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  172741. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  172742. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  172743. "SELECT %s FROM %s AS T", /* SCAN */
  172744. };
  172745. Fts5Config *pC = p->pConfig;
  172746. char *zSql = 0;
  172747. switch( eStmt ){
  172748. case FTS5_STMT_SCAN:
  172749. zSql = sqlite3_mprintf(azStmt[eStmt],
  172750. pC->zContentExprlist, pC->zContent
  172751. );
  172752. break;
  172753. case FTS5_STMT_SCAN_ASC:
  172754. case FTS5_STMT_SCAN_DESC:
  172755. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  172756. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  172757. pC->zContentRowid
  172758. );
  172759. break;
  172760. case FTS5_STMT_LOOKUP:
  172761. zSql = sqlite3_mprintf(azStmt[eStmt],
  172762. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  172763. );
  172764. break;
  172765. case FTS5_STMT_INSERT_CONTENT:
  172766. case FTS5_STMT_REPLACE_CONTENT: {
  172767. int nCol = pC->nCol + 1;
  172768. char *zBind;
  172769. int i;
  172770. zBind = sqlite3_malloc(1 + nCol*2);
  172771. if( zBind ){
  172772. for(i=0; i<nCol; i++){
  172773. zBind[i*2] = '?';
  172774. zBind[i*2 + 1] = ',';
  172775. }
  172776. zBind[i*2-1] = '\0';
  172777. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  172778. sqlite3_free(zBind);
  172779. }
  172780. break;
  172781. }
  172782. default:
  172783. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  172784. break;
  172785. }
  172786. if( zSql==0 ){
  172787. rc = SQLITE_NOMEM;
  172788. }else{
  172789. rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
  172790. sqlite3_free(zSql);
  172791. if( rc!=SQLITE_OK && pzErrMsg ){
  172792. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  172793. }
  172794. }
  172795. }
  172796. *ppStmt = p->aStmt[eStmt];
  172797. sqlite3_reset(*ppStmt);
  172798. return rc;
  172799. }
  172800. static int fts5ExecPrintf(
  172801. sqlite3 *db,
  172802. char **pzErr,
  172803. const char *zFormat,
  172804. ...
  172805. ){
  172806. int rc;
  172807. va_list ap; /* ... printf arguments */
  172808. char *zSql;
  172809. va_start(ap, zFormat);
  172810. zSql = sqlite3_vmprintf(zFormat, ap);
  172811. if( zSql==0 ){
  172812. rc = SQLITE_NOMEM;
  172813. }else{
  172814. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  172815. sqlite3_free(zSql);
  172816. }
  172817. va_end(ap);
  172818. return rc;
  172819. }
  172820. /*
  172821. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  172822. ** code otherwise.
  172823. */
  172824. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  172825. int rc = fts5ExecPrintf(pConfig->db, 0,
  172826. "DROP TABLE IF EXISTS %Q.'%q_data';"
  172827. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  172828. "DROP TABLE IF EXISTS %Q.'%q_config';",
  172829. pConfig->zDb, pConfig->zName,
  172830. pConfig->zDb, pConfig->zName,
  172831. pConfig->zDb, pConfig->zName
  172832. );
  172833. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  172834. rc = fts5ExecPrintf(pConfig->db, 0,
  172835. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  172836. pConfig->zDb, pConfig->zName
  172837. );
  172838. }
  172839. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  172840. rc = fts5ExecPrintf(pConfig->db, 0,
  172841. "DROP TABLE IF EXISTS %Q.'%q_content';",
  172842. pConfig->zDb, pConfig->zName
  172843. );
  172844. }
  172845. return rc;
  172846. }
  172847. static void fts5StorageRenameOne(
  172848. Fts5Config *pConfig, /* Current FTS5 configuration */
  172849. int *pRc, /* IN/OUT: Error code */
  172850. const char *zTail, /* Tail of table name e.g. "data", "config" */
  172851. const char *zName /* New name of FTS5 table */
  172852. ){
  172853. if( *pRc==SQLITE_OK ){
  172854. *pRc = fts5ExecPrintf(pConfig->db, 0,
  172855. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  172856. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  172857. );
  172858. }
  172859. }
  172860. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  172861. Fts5Config *pConfig = pStorage->pConfig;
  172862. int rc = sqlite3Fts5StorageSync(pStorage, 1);
  172863. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  172864. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  172865. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  172866. if( pConfig->bColumnsize ){
  172867. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  172868. }
  172869. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  172870. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  172871. }
  172872. return rc;
  172873. }
  172874. /*
  172875. ** Create the shadow table named zPost, with definition zDefn. Return
  172876. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  172877. */
  172878. static int sqlite3Fts5CreateTable(
  172879. Fts5Config *pConfig, /* FTS5 configuration */
  172880. const char *zPost, /* Shadow table to create (e.g. "content") */
  172881. const char *zDefn, /* Columns etc. for shadow table */
  172882. int bWithout, /* True for without rowid */
  172883. char **pzErr /* OUT: Error message */
  172884. ){
  172885. int rc;
  172886. char *zErr = 0;
  172887. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  172888. pConfig->zDb, pConfig->zName, zPost, zDefn, bWithout?" WITHOUT ROWID":""
  172889. );
  172890. if( zErr ){
  172891. *pzErr = sqlite3_mprintf(
  172892. "fts5: error creating shadow table %q_%s: %s",
  172893. pConfig->zName, zPost, zErr
  172894. );
  172895. sqlite3_free(zErr);
  172896. }
  172897. return rc;
  172898. }
  172899. /*
  172900. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  172901. ** and initialize the underlying tables
  172902. **
  172903. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  172904. ** Otherwise, set *pp to NULL and return an SQLite error code.
  172905. */
  172906. static int sqlite3Fts5StorageOpen(
  172907. Fts5Config *pConfig,
  172908. Fts5Index *pIndex,
  172909. int bCreate,
  172910. Fts5Storage **pp,
  172911. char **pzErr /* OUT: Error message */
  172912. ){
  172913. int rc = SQLITE_OK;
  172914. Fts5Storage *p; /* New object */
  172915. int nByte; /* Bytes of space to allocate */
  172916. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  172917. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  172918. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  172919. if( !p ) return SQLITE_NOMEM;
  172920. memset(p, 0, nByte);
  172921. p->aTotalSize = (i64*)&p[1];
  172922. p->pConfig = pConfig;
  172923. p->pIndex = pIndex;
  172924. if( bCreate ){
  172925. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  172926. int nDefn = 32 + pConfig->nCol*10;
  172927. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  172928. if( zDefn==0 ){
  172929. rc = SQLITE_NOMEM;
  172930. }else{
  172931. int i;
  172932. int iOff;
  172933. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  172934. iOff = (int)strlen(zDefn);
  172935. for(i=0; i<pConfig->nCol; i++){
  172936. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  172937. iOff += (int)strlen(&zDefn[iOff]);
  172938. }
  172939. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  172940. }
  172941. sqlite3_free(zDefn);
  172942. }
  172943. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  172944. rc = sqlite3Fts5CreateTable(
  172945. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  172946. );
  172947. }
  172948. if( rc==SQLITE_OK ){
  172949. rc = sqlite3Fts5CreateTable(
  172950. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  172951. );
  172952. }
  172953. if( rc==SQLITE_OK ){
  172954. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  172955. }
  172956. }
  172957. if( rc ){
  172958. sqlite3Fts5StorageClose(p);
  172959. *pp = 0;
  172960. }
  172961. return rc;
  172962. }
  172963. /*
  172964. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  172965. */
  172966. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  172967. int rc = SQLITE_OK;
  172968. if( p ){
  172969. int i;
  172970. /* Finalize all SQL statements */
  172971. for(i=0; i<ArraySize(p->aStmt); i++){
  172972. sqlite3_finalize(p->aStmt[i]);
  172973. }
  172974. sqlite3_free(p);
  172975. }
  172976. return rc;
  172977. }
  172978. typedef struct Fts5InsertCtx Fts5InsertCtx;
  172979. struct Fts5InsertCtx {
  172980. Fts5Storage *pStorage;
  172981. int iCol;
  172982. int szCol; /* Size of column value in tokens */
  172983. };
  172984. /*
  172985. ** Tokenization callback used when inserting tokens into the FTS index.
  172986. */
  172987. static int fts5StorageInsertCallback(
  172988. void *pContext, /* Pointer to Fts5InsertCtx object */
  172989. int tflags,
  172990. const char *pToken, /* Buffer containing token */
  172991. int nToken, /* Size of token in bytes */
  172992. int iUnused1, /* Start offset of token */
  172993. int iUnused2 /* End offset of token */
  172994. ){
  172995. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  172996. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  172997. UNUSED_PARAM2(iUnused1, iUnused2);
  172998. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  172999. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  173000. pCtx->szCol++;
  173001. }
  173002. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  173003. }
  173004. /*
  173005. ** If a row with rowid iDel is present in the %_content table, add the
  173006. ** delete-markers to the FTS index necessary to delete it. Do not actually
  173007. ** remove the %_content row at this time though.
  173008. */
  173009. static int fts5StorageDeleteFromIndex(
  173010. Fts5Storage *p,
  173011. i64 iDel,
  173012. sqlite3_value **apVal
  173013. ){
  173014. Fts5Config *pConfig = p->pConfig;
  173015. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  173016. int rc; /* Return code */
  173017. int rc2; /* sqlite3_reset() return code */
  173018. int iCol;
  173019. Fts5InsertCtx ctx;
  173020. if( apVal==0 ){
  173021. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  173022. if( rc!=SQLITE_OK ) return rc;
  173023. sqlite3_bind_int64(pSeek, 1, iDel);
  173024. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  173025. return sqlite3_reset(pSeek);
  173026. }
  173027. }
  173028. ctx.pStorage = p;
  173029. ctx.iCol = -1;
  173030. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  173031. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  173032. if( pConfig->abUnindexed[iCol-1]==0 ){
  173033. const char *zText;
  173034. int nText;
  173035. if( pSeek ){
  173036. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  173037. nText = sqlite3_column_bytes(pSeek, iCol);
  173038. }else{
  173039. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  173040. nText = sqlite3_value_bytes(apVal[iCol-1]);
  173041. }
  173042. ctx.szCol = 0;
  173043. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  173044. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  173045. );
  173046. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  173047. }
  173048. }
  173049. p->nTotalRow--;
  173050. rc2 = sqlite3_reset(pSeek);
  173051. if( rc==SQLITE_OK ) rc = rc2;
  173052. return rc;
  173053. }
  173054. /*
  173055. ** Insert a record into the %_docsize table. Specifically, do:
  173056. **
  173057. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  173058. **
  173059. ** If there is no %_docsize table (as happens if the columnsize=0 option
  173060. ** is specified when the FTS5 table is created), this function is a no-op.
  173061. */
  173062. static int fts5StorageInsertDocsize(
  173063. Fts5Storage *p, /* Storage module to write to */
  173064. i64 iRowid, /* id value */
  173065. Fts5Buffer *pBuf /* sz value */
  173066. ){
  173067. int rc = SQLITE_OK;
  173068. if( p->pConfig->bColumnsize ){
  173069. sqlite3_stmt *pReplace = 0;
  173070. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  173071. if( rc==SQLITE_OK ){
  173072. sqlite3_bind_int64(pReplace, 1, iRowid);
  173073. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  173074. sqlite3_step(pReplace);
  173075. rc = sqlite3_reset(pReplace);
  173076. }
  173077. }
  173078. return rc;
  173079. }
  173080. /*
  173081. ** Load the contents of the "averages" record from disk into the
  173082. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  173083. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  173084. ** that the contents of aTotalSize[] and nTotalRow are valid until
  173085. ** further notice.
  173086. **
  173087. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  173088. ** occurs.
  173089. */
  173090. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  173091. int rc = SQLITE_OK;
  173092. if( p->bTotalsValid==0 ){
  173093. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  173094. p->bTotalsValid = bCache;
  173095. }
  173096. return rc;
  173097. }
  173098. /*
  173099. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  173100. ** variables in the "averages" record on disk.
  173101. **
  173102. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  173103. ** occurs.
  173104. */
  173105. static int fts5StorageSaveTotals(Fts5Storage *p){
  173106. int nCol = p->pConfig->nCol;
  173107. int i;
  173108. Fts5Buffer buf;
  173109. int rc = SQLITE_OK;
  173110. memset(&buf, 0, sizeof(buf));
  173111. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  173112. for(i=0; i<nCol; i++){
  173113. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  173114. }
  173115. if( rc==SQLITE_OK ){
  173116. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  173117. }
  173118. sqlite3_free(buf.p);
  173119. return rc;
  173120. }
  173121. /*
  173122. ** Remove a row from the FTS table.
  173123. */
  173124. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  173125. Fts5Config *pConfig = p->pConfig;
  173126. int rc;
  173127. sqlite3_stmt *pDel = 0;
  173128. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  173129. rc = fts5StorageLoadTotals(p, 1);
  173130. /* Delete the index records */
  173131. if( rc==SQLITE_OK ){
  173132. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  173133. }
  173134. /* Delete the %_docsize record */
  173135. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  173136. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  173137. if( rc==SQLITE_OK ){
  173138. sqlite3_bind_int64(pDel, 1, iDel);
  173139. sqlite3_step(pDel);
  173140. rc = sqlite3_reset(pDel);
  173141. }
  173142. }
  173143. /* Delete the %_content record */
  173144. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  173145. if( rc==SQLITE_OK ){
  173146. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  173147. }
  173148. if( rc==SQLITE_OK ){
  173149. sqlite3_bind_int64(pDel, 1, iDel);
  173150. sqlite3_step(pDel);
  173151. rc = sqlite3_reset(pDel);
  173152. }
  173153. }
  173154. /* Write the averages record */
  173155. if( rc==SQLITE_OK ){
  173156. rc = fts5StorageSaveTotals(p);
  173157. }
  173158. return rc;
  173159. }
  173160. /*
  173161. ** Delete all entries in the FTS5 index.
  173162. */
  173163. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  173164. Fts5Config *pConfig = p->pConfig;
  173165. int rc;
  173166. /* Delete the contents of the %_data and %_docsize tables. */
  173167. rc = fts5ExecPrintf(pConfig->db, 0,
  173168. "DELETE FROM %Q.'%q_data';"
  173169. "DELETE FROM %Q.'%q_idx';",
  173170. pConfig->zDb, pConfig->zName,
  173171. pConfig->zDb, pConfig->zName
  173172. );
  173173. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  173174. rc = fts5ExecPrintf(pConfig->db, 0,
  173175. "DELETE FROM %Q.'%q_docsize';",
  173176. pConfig->zDb, pConfig->zName
  173177. );
  173178. }
  173179. /* Reinitialize the %_data table. This call creates the initial structure
  173180. ** and averages records. */
  173181. if( rc==SQLITE_OK ){
  173182. rc = sqlite3Fts5IndexReinit(p->pIndex);
  173183. }
  173184. if( rc==SQLITE_OK ){
  173185. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  173186. }
  173187. return rc;
  173188. }
  173189. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  173190. Fts5Buffer buf = {0,0,0};
  173191. Fts5Config *pConfig = p->pConfig;
  173192. sqlite3_stmt *pScan = 0;
  173193. Fts5InsertCtx ctx;
  173194. int rc;
  173195. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  173196. ctx.pStorage = p;
  173197. rc = sqlite3Fts5StorageDeleteAll(p);
  173198. if( rc==SQLITE_OK ){
  173199. rc = fts5StorageLoadTotals(p, 1);
  173200. }
  173201. if( rc==SQLITE_OK ){
  173202. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  173203. }
  173204. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  173205. i64 iRowid = sqlite3_column_int64(pScan, 0);
  173206. sqlite3Fts5BufferZero(&buf);
  173207. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  173208. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  173209. ctx.szCol = 0;
  173210. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  173211. rc = sqlite3Fts5Tokenize(pConfig,
  173212. FTS5_TOKENIZE_DOCUMENT,
  173213. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  173214. sqlite3_column_bytes(pScan, ctx.iCol+1),
  173215. (void*)&ctx,
  173216. fts5StorageInsertCallback
  173217. );
  173218. }
  173219. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  173220. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  173221. }
  173222. p->nTotalRow++;
  173223. if( rc==SQLITE_OK ){
  173224. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  173225. }
  173226. }
  173227. sqlite3_free(buf.p);
  173228. /* Write the averages record */
  173229. if( rc==SQLITE_OK ){
  173230. rc = fts5StorageSaveTotals(p);
  173231. }
  173232. return rc;
  173233. }
  173234. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  173235. return sqlite3Fts5IndexOptimize(p->pIndex);
  173236. }
  173237. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  173238. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  173239. }
  173240. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  173241. return sqlite3Fts5IndexReset(p->pIndex);
  173242. }
  173243. /*
  173244. ** Allocate a new rowid. This is used for "external content" tables when
  173245. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  173246. ** by inserting a dummy row into the %_docsize table. The dummy will be
  173247. ** overwritten later.
  173248. **
  173249. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  173250. ** this case the user is required to provide a rowid explicitly.
  173251. */
  173252. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  173253. int rc = SQLITE_MISMATCH;
  173254. if( p->pConfig->bColumnsize ){
  173255. sqlite3_stmt *pReplace = 0;
  173256. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  173257. if( rc==SQLITE_OK ){
  173258. sqlite3_bind_null(pReplace, 1);
  173259. sqlite3_bind_null(pReplace, 2);
  173260. sqlite3_step(pReplace);
  173261. rc = sqlite3_reset(pReplace);
  173262. }
  173263. if( rc==SQLITE_OK ){
  173264. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  173265. }
  173266. }
  173267. return rc;
  173268. }
  173269. /*
  173270. ** Insert a new row into the FTS content table.
  173271. */
  173272. static int sqlite3Fts5StorageContentInsert(
  173273. Fts5Storage *p,
  173274. sqlite3_value **apVal,
  173275. i64 *piRowid
  173276. ){
  173277. Fts5Config *pConfig = p->pConfig;
  173278. int rc = SQLITE_OK;
  173279. /* Insert the new row into the %_content table. */
  173280. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  173281. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  173282. *piRowid = sqlite3_value_int64(apVal[1]);
  173283. }else{
  173284. rc = fts5StorageNewRowid(p, piRowid);
  173285. }
  173286. }else{
  173287. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  173288. int i; /* Counter variable */
  173289. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  173290. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  173291. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  173292. }
  173293. if( rc==SQLITE_OK ){
  173294. sqlite3_step(pInsert);
  173295. rc = sqlite3_reset(pInsert);
  173296. }
  173297. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  173298. }
  173299. return rc;
  173300. }
  173301. /*
  173302. ** Insert new entries into the FTS index and %_docsize table.
  173303. */
  173304. static int sqlite3Fts5StorageIndexInsert(
  173305. Fts5Storage *p,
  173306. sqlite3_value **apVal,
  173307. i64 iRowid
  173308. ){
  173309. Fts5Config *pConfig = p->pConfig;
  173310. int rc = SQLITE_OK; /* Return code */
  173311. Fts5InsertCtx ctx; /* Tokenization callback context object */
  173312. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  173313. memset(&buf, 0, sizeof(Fts5Buffer));
  173314. ctx.pStorage = p;
  173315. rc = fts5StorageLoadTotals(p, 1);
  173316. if( rc==SQLITE_OK ){
  173317. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  173318. }
  173319. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  173320. ctx.szCol = 0;
  173321. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  173322. rc = sqlite3Fts5Tokenize(pConfig,
  173323. FTS5_TOKENIZE_DOCUMENT,
  173324. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  173325. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  173326. (void*)&ctx,
  173327. fts5StorageInsertCallback
  173328. );
  173329. }
  173330. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  173331. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  173332. }
  173333. p->nTotalRow++;
  173334. /* Write the %_docsize record */
  173335. if( rc==SQLITE_OK ){
  173336. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  173337. }
  173338. sqlite3_free(buf.p);
  173339. /* Write the averages record */
  173340. if( rc==SQLITE_OK ){
  173341. rc = fts5StorageSaveTotals(p);
  173342. }
  173343. return rc;
  173344. }
  173345. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  173346. Fts5Config *pConfig = p->pConfig;
  173347. char *zSql;
  173348. int rc;
  173349. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  173350. pConfig->zDb, pConfig->zName, zSuffix
  173351. );
  173352. if( zSql==0 ){
  173353. rc = SQLITE_NOMEM;
  173354. }else{
  173355. sqlite3_stmt *pCnt = 0;
  173356. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  173357. if( rc==SQLITE_OK ){
  173358. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  173359. *pnRow = sqlite3_column_int64(pCnt, 0);
  173360. }
  173361. rc = sqlite3_finalize(pCnt);
  173362. }
  173363. }
  173364. sqlite3_free(zSql);
  173365. return rc;
  173366. }
  173367. /*
  173368. ** Context object used by sqlite3Fts5StorageIntegrity().
  173369. */
  173370. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  173371. struct Fts5IntegrityCtx {
  173372. i64 iRowid;
  173373. int iCol;
  173374. int szCol;
  173375. u64 cksum;
  173376. Fts5Termset *pTermset;
  173377. Fts5Config *pConfig;
  173378. };
  173379. /*
  173380. ** Tokenization callback used by integrity check.
  173381. */
  173382. static int fts5StorageIntegrityCallback(
  173383. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  173384. int tflags,
  173385. const char *pToken, /* Buffer containing token */
  173386. int nToken, /* Size of token in bytes */
  173387. int iUnused1, /* Start offset of token */
  173388. int iUnused2 /* End offset of token */
  173389. ){
  173390. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  173391. Fts5Termset *pTermset = pCtx->pTermset;
  173392. int bPresent;
  173393. int ii;
  173394. int rc = SQLITE_OK;
  173395. int iPos;
  173396. int iCol;
  173397. UNUSED_PARAM2(iUnused1, iUnused2);
  173398. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  173399. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  173400. pCtx->szCol++;
  173401. }
  173402. switch( pCtx->pConfig->eDetail ){
  173403. case FTS5_DETAIL_FULL:
  173404. iPos = pCtx->szCol-1;
  173405. iCol = pCtx->iCol;
  173406. break;
  173407. case FTS5_DETAIL_COLUMNS:
  173408. iPos = pCtx->iCol;
  173409. iCol = 0;
  173410. break;
  173411. default:
  173412. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  173413. iPos = 0;
  173414. iCol = 0;
  173415. break;
  173416. }
  173417. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  173418. if( rc==SQLITE_OK && bPresent==0 ){
  173419. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  173420. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  173421. );
  173422. }
  173423. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  173424. const int nChar = pCtx->pConfig->aPrefix[ii];
  173425. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  173426. if( nByte ){
  173427. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  173428. if( bPresent==0 ){
  173429. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  173430. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  173431. );
  173432. }
  173433. }
  173434. }
  173435. return rc;
  173436. }
  173437. /*
  173438. ** Check that the contents of the FTS index match that of the %_content
  173439. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  173440. ** some other SQLite error code if an error occurs while attempting to
  173441. ** determine this.
  173442. */
  173443. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  173444. Fts5Config *pConfig = p->pConfig;
  173445. int rc; /* Return code */
  173446. int *aColSize; /* Array of size pConfig->nCol */
  173447. i64 *aTotalSize; /* Array of size pConfig->nCol */
  173448. Fts5IntegrityCtx ctx;
  173449. sqlite3_stmt *pScan;
  173450. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  173451. ctx.pConfig = p->pConfig;
  173452. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  173453. if( !aTotalSize ) return SQLITE_NOMEM;
  173454. aColSize = (int*)&aTotalSize[pConfig->nCol];
  173455. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  173456. /* Generate the expected index checksum based on the contents of the
  173457. ** %_content table. This block stores the checksum in ctx.cksum. */
  173458. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  173459. if( rc==SQLITE_OK ){
  173460. int rc2;
  173461. while( SQLITE_ROW==sqlite3_step(pScan) ){
  173462. int i;
  173463. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  173464. ctx.szCol = 0;
  173465. if( pConfig->bColumnsize ){
  173466. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  173467. }
  173468. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  173469. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  173470. }
  173471. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  173472. if( pConfig->abUnindexed[i] ) continue;
  173473. ctx.iCol = i;
  173474. ctx.szCol = 0;
  173475. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  173476. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  173477. }
  173478. if( rc==SQLITE_OK ){
  173479. rc = sqlite3Fts5Tokenize(pConfig,
  173480. FTS5_TOKENIZE_DOCUMENT,
  173481. (const char*)sqlite3_column_text(pScan, i+1),
  173482. sqlite3_column_bytes(pScan, i+1),
  173483. (void*)&ctx,
  173484. fts5StorageIntegrityCallback
  173485. );
  173486. }
  173487. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  173488. rc = FTS5_CORRUPT;
  173489. }
  173490. aTotalSize[i] += ctx.szCol;
  173491. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  173492. sqlite3Fts5TermsetFree(ctx.pTermset);
  173493. ctx.pTermset = 0;
  173494. }
  173495. }
  173496. sqlite3Fts5TermsetFree(ctx.pTermset);
  173497. ctx.pTermset = 0;
  173498. if( rc!=SQLITE_OK ) break;
  173499. }
  173500. rc2 = sqlite3_reset(pScan);
  173501. if( rc==SQLITE_OK ) rc = rc2;
  173502. }
  173503. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  173504. if( rc==SQLITE_OK ){
  173505. int i;
  173506. rc = fts5StorageLoadTotals(p, 0);
  173507. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  173508. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  173509. }
  173510. }
  173511. /* Check that the %_docsize and %_content tables contain the expected
  173512. ** number of rows. */
  173513. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  173514. i64 nRow = 0;
  173515. rc = fts5StorageCount(p, "content", &nRow);
  173516. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  173517. }
  173518. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  173519. i64 nRow = 0;
  173520. rc = fts5StorageCount(p, "docsize", &nRow);
  173521. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  173522. }
  173523. /* Pass the expected checksum down to the FTS index module. It will
  173524. ** verify, amongst other things, that it matches the checksum generated by
  173525. ** inspecting the index itself. */
  173526. if( rc==SQLITE_OK ){
  173527. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  173528. }
  173529. sqlite3_free(aTotalSize);
  173530. return rc;
  173531. }
  173532. /*
  173533. ** Obtain an SQLite statement handle that may be used to read data from the
  173534. ** %_content table.
  173535. */
  173536. static int sqlite3Fts5StorageStmt(
  173537. Fts5Storage *p,
  173538. int eStmt,
  173539. sqlite3_stmt **pp,
  173540. char **pzErrMsg
  173541. ){
  173542. int rc;
  173543. assert( eStmt==FTS5_STMT_SCAN_ASC
  173544. || eStmt==FTS5_STMT_SCAN_DESC
  173545. || eStmt==FTS5_STMT_LOOKUP
  173546. );
  173547. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  173548. if( rc==SQLITE_OK ){
  173549. assert( p->aStmt[eStmt]==*pp );
  173550. p->aStmt[eStmt] = 0;
  173551. }
  173552. return rc;
  173553. }
  173554. /*
  173555. ** Release an SQLite statement handle obtained via an earlier call to
  173556. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  173557. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  173558. */
  173559. static void sqlite3Fts5StorageStmtRelease(
  173560. Fts5Storage *p,
  173561. int eStmt,
  173562. sqlite3_stmt *pStmt
  173563. ){
  173564. assert( eStmt==FTS5_STMT_SCAN_ASC
  173565. || eStmt==FTS5_STMT_SCAN_DESC
  173566. || eStmt==FTS5_STMT_LOOKUP
  173567. );
  173568. if( p->aStmt[eStmt]==0 ){
  173569. sqlite3_reset(pStmt);
  173570. p->aStmt[eStmt] = pStmt;
  173571. }else{
  173572. sqlite3_finalize(pStmt);
  173573. }
  173574. }
  173575. static int fts5StorageDecodeSizeArray(
  173576. int *aCol, int nCol, /* Array to populate */
  173577. const u8 *aBlob, int nBlob /* Record to read varints from */
  173578. ){
  173579. int i;
  173580. int iOff = 0;
  173581. for(i=0; i<nCol; i++){
  173582. if( iOff>=nBlob ) return 1;
  173583. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  173584. }
  173585. return (iOff!=nBlob);
  173586. }
  173587. /*
  173588. ** Argument aCol points to an array of integers containing one entry for
  173589. ** each table column. This function reads the %_docsize record for the
  173590. ** specified rowid and populates aCol[] with the results.
  173591. **
  173592. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  173593. ** otherwise.
  173594. */
  173595. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  173596. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  173597. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  173598. int rc; /* Return Code */
  173599. assert( p->pConfig->bColumnsize );
  173600. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  173601. if( rc==SQLITE_OK ){
  173602. int bCorrupt = 1;
  173603. sqlite3_bind_int64(pLookup, 1, iRowid);
  173604. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  173605. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  173606. int nBlob = sqlite3_column_bytes(pLookup, 0);
  173607. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  173608. bCorrupt = 0;
  173609. }
  173610. }
  173611. rc = sqlite3_reset(pLookup);
  173612. if( bCorrupt && rc==SQLITE_OK ){
  173613. rc = FTS5_CORRUPT;
  173614. }
  173615. }
  173616. return rc;
  173617. }
  173618. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  173619. int rc = fts5StorageLoadTotals(p, 0);
  173620. if( rc==SQLITE_OK ){
  173621. *pnToken = 0;
  173622. if( iCol<0 ){
  173623. int i;
  173624. for(i=0; i<p->pConfig->nCol; i++){
  173625. *pnToken += p->aTotalSize[i];
  173626. }
  173627. }else if( iCol<p->pConfig->nCol ){
  173628. *pnToken = p->aTotalSize[iCol];
  173629. }else{
  173630. rc = SQLITE_RANGE;
  173631. }
  173632. }
  173633. return rc;
  173634. }
  173635. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  173636. int rc = fts5StorageLoadTotals(p, 0);
  173637. if( rc==SQLITE_OK ){
  173638. *pnRow = p->nTotalRow;
  173639. }
  173640. return rc;
  173641. }
  173642. /*
  173643. ** Flush any data currently held in-memory to disk.
  173644. */
  173645. static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
  173646. if( bCommit && p->bTotalsValid ){
  173647. int rc = fts5StorageSaveTotals(p);
  173648. p->bTotalsValid = 0;
  173649. if( rc!=SQLITE_OK ) return rc;
  173650. }
  173651. return sqlite3Fts5IndexSync(p->pIndex, bCommit);
  173652. }
  173653. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  173654. p->bTotalsValid = 0;
  173655. return sqlite3Fts5IndexRollback(p->pIndex);
  173656. }
  173657. static int sqlite3Fts5StorageConfigValue(
  173658. Fts5Storage *p,
  173659. const char *z,
  173660. sqlite3_value *pVal,
  173661. int iVal
  173662. ){
  173663. sqlite3_stmt *pReplace = 0;
  173664. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  173665. if( rc==SQLITE_OK ){
  173666. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  173667. if( pVal ){
  173668. sqlite3_bind_value(pReplace, 2, pVal);
  173669. }else{
  173670. sqlite3_bind_int(pReplace, 2, iVal);
  173671. }
  173672. sqlite3_step(pReplace);
  173673. rc = sqlite3_reset(pReplace);
  173674. }
  173675. if( rc==SQLITE_OK && pVal ){
  173676. int iNew = p->pConfig->iCookie + 1;
  173677. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  173678. if( rc==SQLITE_OK ){
  173679. p->pConfig->iCookie = iNew;
  173680. }
  173681. }
  173682. return rc;
  173683. }
  173684. /*
  173685. ** 2014 May 31
  173686. **
  173687. ** The author disclaims copyright to this source code. In place of
  173688. ** a legal notice, here is a blessing:
  173689. **
  173690. ** May you do good and not evil.
  173691. ** May you find forgiveness for yourself and forgive others.
  173692. ** May you share freely, never taking more than you give.
  173693. **
  173694. ******************************************************************************
  173695. */
  173696. /* #include "fts5Int.h" */
  173697. /**************************************************************************
  173698. ** Start of ascii tokenizer implementation.
  173699. */
  173700. /*
  173701. ** For tokenizers with no "unicode" modifier, the set of token characters
  173702. ** is the same as the set of ASCII range alphanumeric characters.
  173703. */
  173704. static unsigned char aAsciiTokenChar[128] = {
  173705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  173706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  173707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  173708. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  173709. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  173710. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  173711. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  173712. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  173713. };
  173714. typedef struct AsciiTokenizer AsciiTokenizer;
  173715. struct AsciiTokenizer {
  173716. unsigned char aTokenChar[128];
  173717. };
  173718. static void fts5AsciiAddExceptions(
  173719. AsciiTokenizer *p,
  173720. const char *zArg,
  173721. int bTokenChars
  173722. ){
  173723. int i;
  173724. for(i=0; zArg[i]; i++){
  173725. if( (zArg[i] & 0x80)==0 ){
  173726. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  173727. }
  173728. }
  173729. }
  173730. /*
  173731. ** Delete a "ascii" tokenizer.
  173732. */
  173733. static void fts5AsciiDelete(Fts5Tokenizer *p){
  173734. sqlite3_free(p);
  173735. }
  173736. /*
  173737. ** Create an "ascii" tokenizer.
  173738. */
  173739. static int fts5AsciiCreate(
  173740. void *pUnused,
  173741. const char **azArg, int nArg,
  173742. Fts5Tokenizer **ppOut
  173743. ){
  173744. int rc = SQLITE_OK;
  173745. AsciiTokenizer *p = 0;
  173746. UNUSED_PARAM(pUnused);
  173747. if( nArg%2 ){
  173748. rc = SQLITE_ERROR;
  173749. }else{
  173750. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  173751. if( p==0 ){
  173752. rc = SQLITE_NOMEM;
  173753. }else{
  173754. int i;
  173755. memset(p, 0, sizeof(AsciiTokenizer));
  173756. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  173757. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  173758. const char *zArg = azArg[i+1];
  173759. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  173760. fts5AsciiAddExceptions(p, zArg, 1);
  173761. }else
  173762. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  173763. fts5AsciiAddExceptions(p, zArg, 0);
  173764. }else{
  173765. rc = SQLITE_ERROR;
  173766. }
  173767. }
  173768. if( rc!=SQLITE_OK ){
  173769. fts5AsciiDelete((Fts5Tokenizer*)p);
  173770. p = 0;
  173771. }
  173772. }
  173773. }
  173774. *ppOut = (Fts5Tokenizer*)p;
  173775. return rc;
  173776. }
  173777. static void asciiFold(char *aOut, const char *aIn, int nByte){
  173778. int i;
  173779. for(i=0; i<nByte; i++){
  173780. char c = aIn[i];
  173781. if( c>='A' && c<='Z' ) c += 32;
  173782. aOut[i] = c;
  173783. }
  173784. }
  173785. /*
  173786. ** Tokenize some text using the ascii tokenizer.
  173787. */
  173788. static int fts5AsciiTokenize(
  173789. Fts5Tokenizer *pTokenizer,
  173790. void *pCtx,
  173791. int iUnused,
  173792. const char *pText, int nText,
  173793. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  173794. ){
  173795. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  173796. int rc = SQLITE_OK;
  173797. int ie;
  173798. int is = 0;
  173799. char aFold[64];
  173800. int nFold = sizeof(aFold);
  173801. char *pFold = aFold;
  173802. unsigned char *a = p->aTokenChar;
  173803. UNUSED_PARAM(iUnused);
  173804. while( is<nText && rc==SQLITE_OK ){
  173805. int nByte;
  173806. /* Skip any leading divider characters. */
  173807. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  173808. is++;
  173809. }
  173810. if( is==nText ) break;
  173811. /* Count the token characters */
  173812. ie = is+1;
  173813. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  173814. ie++;
  173815. }
  173816. /* Fold to lower case */
  173817. nByte = ie-is;
  173818. if( nByte>nFold ){
  173819. if( pFold!=aFold ) sqlite3_free(pFold);
  173820. pFold = sqlite3_malloc(nByte*2);
  173821. if( pFold==0 ){
  173822. rc = SQLITE_NOMEM;
  173823. break;
  173824. }
  173825. nFold = nByte*2;
  173826. }
  173827. asciiFold(pFold, &pText[is], nByte);
  173828. /* Invoke the token callback */
  173829. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  173830. is = ie+1;
  173831. }
  173832. if( pFold!=aFold ) sqlite3_free(pFold);
  173833. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  173834. return rc;
  173835. }
  173836. /**************************************************************************
  173837. ** Start of unicode61 tokenizer implementation.
  173838. */
  173839. /*
  173840. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  173841. ** from the sqlite3 source file utf.c. If this file is compiled as part
  173842. ** of the amalgamation, they are not required.
  173843. */
  173844. #ifndef SQLITE_AMALGAMATION
  173845. static const unsigned char sqlite3Utf8Trans1[] = {
  173846. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  173847. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  173848. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  173849. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  173850. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  173851. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  173852. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  173853. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  173854. };
  173855. #define READ_UTF8(zIn, zTerm, c) \
  173856. c = *(zIn++); \
  173857. if( c>=0xc0 ){ \
  173858. c = sqlite3Utf8Trans1[c-0xc0]; \
  173859. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  173860. c = (c<<6) + (0x3f & *(zIn++)); \
  173861. } \
  173862. if( c<0x80 \
  173863. || (c&0xFFFFF800)==0xD800 \
  173864. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  173865. }
  173866. #define WRITE_UTF8(zOut, c) { \
  173867. if( c<0x00080 ){ \
  173868. *zOut++ = (unsigned char)(c&0xFF); \
  173869. } \
  173870. else if( c<0x00800 ){ \
  173871. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  173872. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  173873. } \
  173874. else if( c<0x10000 ){ \
  173875. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  173876. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  173877. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  173878. }else{ \
  173879. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  173880. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  173881. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  173882. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  173883. } \
  173884. }
  173885. #endif /* ifndef SQLITE_AMALGAMATION */
  173886. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  173887. struct Unicode61Tokenizer {
  173888. unsigned char aTokenChar[128]; /* ASCII range token characters */
  173889. char *aFold; /* Buffer to fold text into */
  173890. int nFold; /* Size of aFold[] in bytes */
  173891. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  173892. int nException;
  173893. int *aiException;
  173894. };
  173895. static int fts5UnicodeAddExceptions(
  173896. Unicode61Tokenizer *p, /* Tokenizer object */
  173897. const char *z, /* Characters to treat as exceptions */
  173898. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  173899. ){
  173900. int rc = SQLITE_OK;
  173901. int n = (int)strlen(z);
  173902. int *aNew;
  173903. if( n>0 ){
  173904. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  173905. if( aNew ){
  173906. int nNew = p->nException;
  173907. const unsigned char *zCsr = (const unsigned char*)z;
  173908. const unsigned char *zTerm = (const unsigned char*)&z[n];
  173909. while( zCsr<zTerm ){
  173910. int iCode;
  173911. int bToken;
  173912. READ_UTF8(zCsr, zTerm, iCode);
  173913. if( iCode<128 ){
  173914. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  173915. }else{
  173916. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  173917. assert( (bToken==0 || bToken==1) );
  173918. assert( (bTokenChars==0 || bTokenChars==1) );
  173919. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  173920. int i;
  173921. for(i=0; i<nNew; i++){
  173922. if( aNew[i]>iCode ) break;
  173923. }
  173924. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  173925. aNew[i] = iCode;
  173926. nNew++;
  173927. }
  173928. }
  173929. }
  173930. p->aiException = aNew;
  173931. p->nException = nNew;
  173932. }else{
  173933. rc = SQLITE_NOMEM;
  173934. }
  173935. }
  173936. return rc;
  173937. }
  173938. /*
  173939. ** Return true if the p->aiException[] array contains the value iCode.
  173940. */
  173941. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  173942. if( p->nException>0 ){
  173943. int *a = p->aiException;
  173944. int iLo = 0;
  173945. int iHi = p->nException-1;
  173946. while( iHi>=iLo ){
  173947. int iTest = (iHi + iLo) / 2;
  173948. if( iCode==a[iTest] ){
  173949. return 1;
  173950. }else if( iCode>a[iTest] ){
  173951. iLo = iTest+1;
  173952. }else{
  173953. iHi = iTest-1;
  173954. }
  173955. }
  173956. }
  173957. return 0;
  173958. }
  173959. /*
  173960. ** Delete a "unicode61" tokenizer.
  173961. */
  173962. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  173963. if( pTok ){
  173964. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  173965. sqlite3_free(p->aiException);
  173966. sqlite3_free(p->aFold);
  173967. sqlite3_free(p);
  173968. }
  173969. return;
  173970. }
  173971. /*
  173972. ** Create a "unicode61" tokenizer.
  173973. */
  173974. static int fts5UnicodeCreate(
  173975. void *pUnused,
  173976. const char **azArg, int nArg,
  173977. Fts5Tokenizer **ppOut
  173978. ){
  173979. int rc = SQLITE_OK; /* Return code */
  173980. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  173981. UNUSED_PARAM(pUnused);
  173982. if( nArg%2 ){
  173983. rc = SQLITE_ERROR;
  173984. }else{
  173985. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  173986. if( p ){
  173987. int i;
  173988. memset(p, 0, sizeof(Unicode61Tokenizer));
  173989. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  173990. p->bRemoveDiacritic = 1;
  173991. p->nFold = 64;
  173992. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  173993. if( p->aFold==0 ){
  173994. rc = SQLITE_NOMEM;
  173995. }
  173996. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  173997. const char *zArg = azArg[i+1];
  173998. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  173999. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  174000. rc = SQLITE_ERROR;
  174001. }
  174002. p->bRemoveDiacritic = (zArg[0]=='1');
  174003. }else
  174004. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  174005. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  174006. }else
  174007. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  174008. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  174009. }else{
  174010. rc = SQLITE_ERROR;
  174011. }
  174012. }
  174013. }else{
  174014. rc = SQLITE_NOMEM;
  174015. }
  174016. if( rc!=SQLITE_OK ){
  174017. fts5UnicodeDelete((Fts5Tokenizer*)p);
  174018. p = 0;
  174019. }
  174020. *ppOut = (Fts5Tokenizer*)p;
  174021. }
  174022. return rc;
  174023. }
  174024. /*
  174025. ** Return true if, for the purposes of tokenizing with the tokenizer
  174026. ** passed as the first argument, codepoint iCode is considered a token
  174027. ** character (not a separator).
  174028. */
  174029. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  174030. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  174031. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  174032. }
  174033. static int fts5UnicodeTokenize(
  174034. Fts5Tokenizer *pTokenizer,
  174035. void *pCtx,
  174036. int iUnused,
  174037. const char *pText, int nText,
  174038. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  174039. ){
  174040. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  174041. int rc = SQLITE_OK;
  174042. unsigned char *a = p->aTokenChar;
  174043. unsigned char *zTerm = (unsigned char*)&pText[nText];
  174044. unsigned char *zCsr = (unsigned char *)pText;
  174045. /* Output buffer */
  174046. char *aFold = p->aFold;
  174047. int nFold = p->nFold;
  174048. const char *pEnd = &aFold[nFold-6];
  174049. UNUSED_PARAM(iUnused);
  174050. /* Each iteration of this loop gobbles up a contiguous run of separators,
  174051. ** then the next token. */
  174052. while( rc==SQLITE_OK ){
  174053. int iCode; /* non-ASCII codepoint read from input */
  174054. char *zOut = aFold;
  174055. int is;
  174056. int ie;
  174057. /* Skip any separator characters. */
  174058. while( 1 ){
  174059. if( zCsr>=zTerm ) goto tokenize_done;
  174060. if( *zCsr & 0x80 ) {
  174061. /* A character outside of the ascii range. Skip past it if it is
  174062. ** a separator character. Or break out of the loop if it is not. */
  174063. is = zCsr - (unsigned char*)pText;
  174064. READ_UTF8(zCsr, zTerm, iCode);
  174065. if( fts5UnicodeIsAlnum(p, iCode) ){
  174066. goto non_ascii_tokenchar;
  174067. }
  174068. }else{
  174069. if( a[*zCsr] ){
  174070. is = zCsr - (unsigned char*)pText;
  174071. goto ascii_tokenchar;
  174072. }
  174073. zCsr++;
  174074. }
  174075. }
  174076. /* Run through the tokenchars. Fold them into the output buffer along
  174077. ** the way. */
  174078. while( zCsr<zTerm ){
  174079. /* Grow the output buffer so that there is sufficient space to fit the
  174080. ** largest possible utf-8 character. */
  174081. if( zOut>pEnd ){
  174082. aFold = sqlite3_malloc(nFold*2);
  174083. if( aFold==0 ){
  174084. rc = SQLITE_NOMEM;
  174085. goto tokenize_done;
  174086. }
  174087. zOut = &aFold[zOut - p->aFold];
  174088. memcpy(aFold, p->aFold, nFold);
  174089. sqlite3_free(p->aFold);
  174090. p->aFold = aFold;
  174091. p->nFold = nFold = nFold*2;
  174092. pEnd = &aFold[nFold-6];
  174093. }
  174094. if( *zCsr & 0x80 ){
  174095. /* An non-ascii-range character. Fold it into the output buffer if
  174096. ** it is a token character, or break out of the loop if it is not. */
  174097. READ_UTF8(zCsr, zTerm, iCode);
  174098. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  174099. non_ascii_tokenchar:
  174100. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  174101. if( iCode ) WRITE_UTF8(zOut, iCode);
  174102. }else{
  174103. break;
  174104. }
  174105. }else if( a[*zCsr]==0 ){
  174106. /* An ascii-range separator character. End of token. */
  174107. break;
  174108. }else{
  174109. ascii_tokenchar:
  174110. if( *zCsr>='A' && *zCsr<='Z' ){
  174111. *zOut++ = *zCsr + 32;
  174112. }else{
  174113. *zOut++ = *zCsr;
  174114. }
  174115. zCsr++;
  174116. }
  174117. ie = zCsr - (unsigned char*)pText;
  174118. }
  174119. /* Invoke the token callback */
  174120. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  174121. }
  174122. tokenize_done:
  174123. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  174124. return rc;
  174125. }
  174126. /**************************************************************************
  174127. ** Start of porter stemmer implementation.
  174128. */
  174129. /* Any tokens larger than this (in bytes) are passed through without
  174130. ** stemming. */
  174131. #define FTS5_PORTER_MAX_TOKEN 64
  174132. typedef struct PorterTokenizer PorterTokenizer;
  174133. struct PorterTokenizer {
  174134. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  174135. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  174136. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  174137. };
  174138. /*
  174139. ** Delete a "porter" tokenizer.
  174140. */
  174141. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  174142. if( pTok ){
  174143. PorterTokenizer *p = (PorterTokenizer*)pTok;
  174144. if( p->pTokenizer ){
  174145. p->tokenizer.xDelete(p->pTokenizer);
  174146. }
  174147. sqlite3_free(p);
  174148. }
  174149. }
  174150. /*
  174151. ** Create a "porter" tokenizer.
  174152. */
  174153. static int fts5PorterCreate(
  174154. void *pCtx,
  174155. const char **azArg, int nArg,
  174156. Fts5Tokenizer **ppOut
  174157. ){
  174158. fts5_api *pApi = (fts5_api*)pCtx;
  174159. int rc = SQLITE_OK;
  174160. PorterTokenizer *pRet;
  174161. void *pUserdata = 0;
  174162. const char *zBase = "unicode61";
  174163. if( nArg>0 ){
  174164. zBase = azArg[0];
  174165. }
  174166. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  174167. if( pRet ){
  174168. memset(pRet, 0, sizeof(PorterTokenizer));
  174169. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  174170. }else{
  174171. rc = SQLITE_NOMEM;
  174172. }
  174173. if( rc==SQLITE_OK ){
  174174. int nArg2 = (nArg>0 ? nArg-1 : 0);
  174175. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  174176. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  174177. }
  174178. if( rc!=SQLITE_OK ){
  174179. fts5PorterDelete((Fts5Tokenizer*)pRet);
  174180. pRet = 0;
  174181. }
  174182. *ppOut = (Fts5Tokenizer*)pRet;
  174183. return rc;
  174184. }
  174185. typedef struct PorterContext PorterContext;
  174186. struct PorterContext {
  174187. void *pCtx;
  174188. int (*xToken)(void*, int, const char*, int, int, int);
  174189. char *aBuf;
  174190. };
  174191. typedef struct PorterRule PorterRule;
  174192. struct PorterRule {
  174193. const char *zSuffix;
  174194. int nSuffix;
  174195. int (*xCond)(char *zStem, int nStem);
  174196. const char *zOutput;
  174197. int nOutput;
  174198. };
  174199. #if 0
  174200. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  174201. int ret = -1;
  174202. int nBuf = *pnBuf;
  174203. PorterRule *p;
  174204. for(p=aRule; p->zSuffix; p++){
  174205. assert( strlen(p->zSuffix)==p->nSuffix );
  174206. assert( strlen(p->zOutput)==p->nOutput );
  174207. if( nBuf<p->nSuffix ) continue;
  174208. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  174209. }
  174210. if( p->zSuffix ){
  174211. int nStem = nBuf - p->nSuffix;
  174212. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  174213. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  174214. *pnBuf = nStem + p->nOutput;
  174215. ret = p - aRule;
  174216. }
  174217. }
  174218. return ret;
  174219. }
  174220. #endif
  174221. static int fts5PorterIsVowel(char c, int bYIsVowel){
  174222. return (
  174223. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  174224. );
  174225. }
  174226. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  174227. int i;
  174228. int bCons = bPrevCons;
  174229. /* Scan for a vowel */
  174230. for(i=0; i<nStem; i++){
  174231. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  174232. }
  174233. /* Scan for a consonent */
  174234. for(i++; i<nStem; i++){
  174235. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  174236. }
  174237. return 0;
  174238. }
  174239. /* porter rule condition: (m > 0) */
  174240. static int fts5Porter_MGt0(char *zStem, int nStem){
  174241. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  174242. }
  174243. /* porter rule condition: (m > 1) */
  174244. static int fts5Porter_MGt1(char *zStem, int nStem){
  174245. int n;
  174246. n = fts5PorterGobbleVC(zStem, nStem, 0);
  174247. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  174248. return 1;
  174249. }
  174250. return 0;
  174251. }
  174252. /* porter rule condition: (m = 1) */
  174253. static int fts5Porter_MEq1(char *zStem, int nStem){
  174254. int n;
  174255. n = fts5PorterGobbleVC(zStem, nStem, 0);
  174256. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  174257. return 1;
  174258. }
  174259. return 0;
  174260. }
  174261. /* porter rule condition: (*o) */
  174262. static int fts5Porter_Ostar(char *zStem, int nStem){
  174263. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  174264. return 0;
  174265. }else{
  174266. int i;
  174267. int mask = 0;
  174268. int bCons = 0;
  174269. for(i=0; i<nStem; i++){
  174270. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  174271. assert( bCons==0 || bCons==1 );
  174272. mask = (mask << 1) + bCons;
  174273. }
  174274. return ((mask & 0x0007)==0x0005);
  174275. }
  174276. }
  174277. /* porter rule condition: (m > 1 and (*S or *T)) */
  174278. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  174279. assert( nStem>0 );
  174280. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  174281. && fts5Porter_MGt1(zStem, nStem);
  174282. }
  174283. /* porter rule condition: (*v*) */
  174284. static int fts5Porter_Vowel(char *zStem, int nStem){
  174285. int i;
  174286. for(i=0; i<nStem; i++){
  174287. if( fts5PorterIsVowel(zStem[i], i>0) ){
  174288. return 1;
  174289. }
  174290. }
  174291. return 0;
  174292. }
  174293. /**************************************************************************
  174294. ***************************************************************************
  174295. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  174296. */
  174297. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  174298. int ret = 0;
  174299. int nBuf = *pnBuf;
  174300. switch( aBuf[nBuf-2] ){
  174301. case 'a':
  174302. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  174303. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  174304. *pnBuf = nBuf - 2;
  174305. }
  174306. }
  174307. break;
  174308. case 'c':
  174309. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  174310. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  174311. *pnBuf = nBuf - 4;
  174312. }
  174313. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  174314. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  174315. *pnBuf = nBuf - 4;
  174316. }
  174317. }
  174318. break;
  174319. case 'e':
  174320. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  174321. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  174322. *pnBuf = nBuf - 2;
  174323. }
  174324. }
  174325. break;
  174326. case 'i':
  174327. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  174328. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  174329. *pnBuf = nBuf - 2;
  174330. }
  174331. }
  174332. break;
  174333. case 'l':
  174334. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  174335. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  174336. *pnBuf = nBuf - 4;
  174337. }
  174338. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  174339. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  174340. *pnBuf = nBuf - 4;
  174341. }
  174342. }
  174343. break;
  174344. case 'n':
  174345. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  174346. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174347. *pnBuf = nBuf - 3;
  174348. }
  174349. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  174350. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  174351. *pnBuf = nBuf - 5;
  174352. }
  174353. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  174354. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  174355. *pnBuf = nBuf - 4;
  174356. }
  174357. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  174358. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174359. *pnBuf = nBuf - 3;
  174360. }
  174361. }
  174362. break;
  174363. case 'o':
  174364. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  174365. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  174366. *pnBuf = nBuf - 3;
  174367. }
  174368. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  174369. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  174370. *pnBuf = nBuf - 2;
  174371. }
  174372. }
  174373. break;
  174374. case 's':
  174375. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  174376. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174377. *pnBuf = nBuf - 3;
  174378. }
  174379. }
  174380. break;
  174381. case 't':
  174382. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  174383. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174384. *pnBuf = nBuf - 3;
  174385. }
  174386. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  174387. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174388. *pnBuf = nBuf - 3;
  174389. }
  174390. }
  174391. break;
  174392. case 'u':
  174393. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  174394. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174395. *pnBuf = nBuf - 3;
  174396. }
  174397. }
  174398. break;
  174399. case 'v':
  174400. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  174401. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174402. *pnBuf = nBuf - 3;
  174403. }
  174404. }
  174405. break;
  174406. case 'z':
  174407. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  174408. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  174409. *pnBuf = nBuf - 3;
  174410. }
  174411. }
  174412. break;
  174413. }
  174414. return ret;
  174415. }
  174416. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  174417. int ret = 0;
  174418. int nBuf = *pnBuf;
  174419. switch( aBuf[nBuf-2] ){
  174420. case 'a':
  174421. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  174422. memcpy(&aBuf[nBuf-2], "ate", 3);
  174423. *pnBuf = nBuf - 2 + 3;
  174424. ret = 1;
  174425. }
  174426. break;
  174427. case 'b':
  174428. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  174429. memcpy(&aBuf[nBuf-2], "ble", 3);
  174430. *pnBuf = nBuf - 2 + 3;
  174431. ret = 1;
  174432. }
  174433. break;
  174434. case 'i':
  174435. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  174436. memcpy(&aBuf[nBuf-2], "ize", 3);
  174437. *pnBuf = nBuf - 2 + 3;
  174438. ret = 1;
  174439. }
  174440. break;
  174441. }
  174442. return ret;
  174443. }
  174444. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  174445. int ret = 0;
  174446. int nBuf = *pnBuf;
  174447. switch( aBuf[nBuf-2] ){
  174448. case 'a':
  174449. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  174450. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  174451. memcpy(&aBuf[nBuf-7], "ate", 3);
  174452. *pnBuf = nBuf - 7 + 3;
  174453. }
  174454. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  174455. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  174456. memcpy(&aBuf[nBuf-6], "tion", 4);
  174457. *pnBuf = nBuf - 6 + 4;
  174458. }
  174459. }
  174460. break;
  174461. case 'c':
  174462. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  174463. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174464. memcpy(&aBuf[nBuf-4], "ence", 4);
  174465. *pnBuf = nBuf - 4 + 4;
  174466. }
  174467. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  174468. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174469. memcpy(&aBuf[nBuf-4], "ance", 4);
  174470. *pnBuf = nBuf - 4 + 4;
  174471. }
  174472. }
  174473. break;
  174474. case 'e':
  174475. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  174476. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174477. memcpy(&aBuf[nBuf-4], "ize", 3);
  174478. *pnBuf = nBuf - 4 + 3;
  174479. }
  174480. }
  174481. break;
  174482. case 'g':
  174483. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  174484. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174485. memcpy(&aBuf[nBuf-4], "log", 3);
  174486. *pnBuf = nBuf - 4 + 3;
  174487. }
  174488. }
  174489. break;
  174490. case 'l':
  174491. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  174492. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  174493. memcpy(&aBuf[nBuf-3], "ble", 3);
  174494. *pnBuf = nBuf - 3 + 3;
  174495. }
  174496. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  174497. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174498. memcpy(&aBuf[nBuf-4], "al", 2);
  174499. *pnBuf = nBuf - 4 + 2;
  174500. }
  174501. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  174502. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174503. memcpy(&aBuf[nBuf-5], "ent", 3);
  174504. *pnBuf = nBuf - 5 + 3;
  174505. }
  174506. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  174507. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  174508. memcpy(&aBuf[nBuf-3], "e", 1);
  174509. *pnBuf = nBuf - 3 + 1;
  174510. }
  174511. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  174512. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174513. memcpy(&aBuf[nBuf-5], "ous", 3);
  174514. *pnBuf = nBuf - 5 + 3;
  174515. }
  174516. }
  174517. break;
  174518. case 'o':
  174519. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  174520. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  174521. memcpy(&aBuf[nBuf-7], "ize", 3);
  174522. *pnBuf = nBuf - 7 + 3;
  174523. }
  174524. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  174525. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174526. memcpy(&aBuf[nBuf-5], "ate", 3);
  174527. *pnBuf = nBuf - 5 + 3;
  174528. }
  174529. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  174530. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174531. memcpy(&aBuf[nBuf-4], "ate", 3);
  174532. *pnBuf = nBuf - 4 + 3;
  174533. }
  174534. }
  174535. break;
  174536. case 's':
  174537. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  174538. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174539. memcpy(&aBuf[nBuf-5], "al", 2);
  174540. *pnBuf = nBuf - 5 + 2;
  174541. }
  174542. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  174543. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  174544. memcpy(&aBuf[nBuf-7], "ive", 3);
  174545. *pnBuf = nBuf - 7 + 3;
  174546. }
  174547. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  174548. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  174549. memcpy(&aBuf[nBuf-7], "ful", 3);
  174550. *pnBuf = nBuf - 7 + 3;
  174551. }
  174552. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  174553. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  174554. memcpy(&aBuf[nBuf-7], "ous", 3);
  174555. *pnBuf = nBuf - 7 + 3;
  174556. }
  174557. }
  174558. break;
  174559. case 't':
  174560. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  174561. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174562. memcpy(&aBuf[nBuf-5], "al", 2);
  174563. *pnBuf = nBuf - 5 + 2;
  174564. }
  174565. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  174566. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174567. memcpy(&aBuf[nBuf-5], "ive", 3);
  174568. *pnBuf = nBuf - 5 + 3;
  174569. }
  174570. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  174571. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  174572. memcpy(&aBuf[nBuf-6], "ble", 3);
  174573. *pnBuf = nBuf - 6 + 3;
  174574. }
  174575. }
  174576. break;
  174577. }
  174578. return ret;
  174579. }
  174580. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  174581. int ret = 0;
  174582. int nBuf = *pnBuf;
  174583. switch( aBuf[nBuf-2] ){
  174584. case 'a':
  174585. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  174586. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174587. memcpy(&aBuf[nBuf-4], "ic", 2);
  174588. *pnBuf = nBuf - 4 + 2;
  174589. }
  174590. }
  174591. break;
  174592. case 's':
  174593. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  174594. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  174595. *pnBuf = nBuf - 4;
  174596. }
  174597. }
  174598. break;
  174599. case 't':
  174600. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  174601. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174602. memcpy(&aBuf[nBuf-5], "ic", 2);
  174603. *pnBuf = nBuf - 5 + 2;
  174604. }
  174605. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  174606. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174607. memcpy(&aBuf[nBuf-5], "ic", 2);
  174608. *pnBuf = nBuf - 5 + 2;
  174609. }
  174610. }
  174611. break;
  174612. case 'u':
  174613. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  174614. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  174615. *pnBuf = nBuf - 3;
  174616. }
  174617. }
  174618. break;
  174619. case 'v':
  174620. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  174621. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174622. *pnBuf = nBuf - 5;
  174623. }
  174624. }
  174625. break;
  174626. case 'z':
  174627. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  174628. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  174629. memcpy(&aBuf[nBuf-5], "al", 2);
  174630. *pnBuf = nBuf - 5 + 2;
  174631. }
  174632. }
  174633. break;
  174634. }
  174635. return ret;
  174636. }
  174637. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  174638. int ret = 0;
  174639. int nBuf = *pnBuf;
  174640. switch( aBuf[nBuf-2] ){
  174641. case 'e':
  174642. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  174643. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  174644. memcpy(&aBuf[nBuf-3], "ee", 2);
  174645. *pnBuf = nBuf - 3 + 2;
  174646. }
  174647. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  174648. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  174649. *pnBuf = nBuf - 2;
  174650. ret = 1;
  174651. }
  174652. }
  174653. break;
  174654. case 'n':
  174655. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  174656. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  174657. *pnBuf = nBuf - 3;
  174658. ret = 1;
  174659. }
  174660. }
  174661. break;
  174662. }
  174663. return ret;
  174664. }
  174665. /*
  174666. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  174667. ***************************************************************************
  174668. **************************************************************************/
  174669. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  174670. int nBuf = *pnBuf;
  174671. if( aBuf[nBuf-1]=='s' ){
  174672. if( aBuf[nBuf-2]=='e' ){
  174673. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  174674. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  174675. ){
  174676. *pnBuf = nBuf-2;
  174677. }else{
  174678. *pnBuf = nBuf-1;
  174679. }
  174680. }
  174681. else if( aBuf[nBuf-2]!='s' ){
  174682. *pnBuf = nBuf-1;
  174683. }
  174684. }
  174685. }
  174686. static int fts5PorterCb(
  174687. void *pCtx,
  174688. int tflags,
  174689. const char *pToken,
  174690. int nToken,
  174691. int iStart,
  174692. int iEnd
  174693. ){
  174694. PorterContext *p = (PorterContext*)pCtx;
  174695. char *aBuf;
  174696. int nBuf;
  174697. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  174698. aBuf = p->aBuf;
  174699. nBuf = nToken;
  174700. memcpy(aBuf, pToken, nBuf);
  174701. /* Step 1. */
  174702. fts5PorterStep1A(aBuf, &nBuf);
  174703. if( fts5PorterStep1B(aBuf, &nBuf) ){
  174704. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  174705. char c = aBuf[nBuf-1];
  174706. if( fts5PorterIsVowel(c, 0)==0
  174707. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  174708. ){
  174709. nBuf--;
  174710. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  174711. aBuf[nBuf++] = 'e';
  174712. }
  174713. }
  174714. }
  174715. /* Step 1C. */
  174716. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  174717. aBuf[nBuf-1] = 'i';
  174718. }
  174719. /* Steps 2 through 4. */
  174720. fts5PorterStep2(aBuf, &nBuf);
  174721. fts5PorterStep3(aBuf, &nBuf);
  174722. fts5PorterStep4(aBuf, &nBuf);
  174723. /* Step 5a. */
  174724. assert( nBuf>0 );
  174725. if( aBuf[nBuf-1]=='e' ){
  174726. if( fts5Porter_MGt1(aBuf, nBuf-1)
  174727. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  174728. ){
  174729. nBuf--;
  174730. }
  174731. }
  174732. /* Step 5b. */
  174733. if( nBuf>1 && aBuf[nBuf-1]=='l'
  174734. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  174735. ){
  174736. nBuf--;
  174737. }
  174738. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  174739. pass_through:
  174740. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  174741. }
  174742. /*
  174743. ** Tokenize using the porter tokenizer.
  174744. */
  174745. static int fts5PorterTokenize(
  174746. Fts5Tokenizer *pTokenizer,
  174747. void *pCtx,
  174748. int flags,
  174749. const char *pText, int nText,
  174750. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  174751. ){
  174752. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  174753. PorterContext sCtx;
  174754. sCtx.xToken = xToken;
  174755. sCtx.pCtx = pCtx;
  174756. sCtx.aBuf = p->aBuf;
  174757. return p->tokenizer.xTokenize(
  174758. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  174759. );
  174760. }
  174761. /*
  174762. ** Register all built-in tokenizers with FTS5.
  174763. */
  174764. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  174765. struct BuiltinTokenizer {
  174766. const char *zName;
  174767. fts5_tokenizer x;
  174768. } aBuiltin[] = {
  174769. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  174770. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  174771. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  174772. };
  174773. int rc = SQLITE_OK; /* Return code */
  174774. int i; /* To iterate through builtin functions */
  174775. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  174776. rc = pApi->xCreateTokenizer(pApi,
  174777. aBuiltin[i].zName,
  174778. (void*)pApi,
  174779. &aBuiltin[i].x,
  174780. 0
  174781. );
  174782. }
  174783. return rc;
  174784. }
  174785. /*
  174786. ** 2012 May 25
  174787. **
  174788. ** The author disclaims copyright to this source code. In place of
  174789. ** a legal notice, here is a blessing:
  174790. **
  174791. ** May you do good and not evil.
  174792. ** May you find forgiveness for yourself and forgive others.
  174793. ** May you share freely, never taking more than you give.
  174794. **
  174795. ******************************************************************************
  174796. */
  174797. /*
  174798. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  174799. */
  174800. /* #include <assert.h> */
  174801. /*
  174802. ** Return true if the argument corresponds to a unicode codepoint
  174803. ** classified as either a letter or a number. Otherwise false.
  174804. **
  174805. ** The results are undefined if the value passed to this function
  174806. ** is less than zero.
  174807. */
  174808. static int sqlite3Fts5UnicodeIsalnum(int c){
  174809. /* Each unsigned integer in the following array corresponds to a contiguous
  174810. ** range of unicode codepoints that are not either letters or numbers (i.e.
  174811. ** codepoints for which this function should return 0).
  174812. **
  174813. ** The most significant 22 bits in each 32-bit value contain the first
  174814. ** codepoint in the range. The least significant 10 bits are used to store
  174815. ** the size of the range (always at least 1). In other words, the value
  174816. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  174817. ** C. It is not possible to represent a range larger than 1023 codepoints
  174818. ** using this format.
  174819. */
  174820. static const unsigned int aEntry[] = {
  174821. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  174822. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  174823. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  174824. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  174825. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  174826. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  174827. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  174828. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  174829. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  174830. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  174831. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  174832. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  174833. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  174834. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  174835. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  174836. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  174837. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  174838. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  174839. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  174840. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  174841. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  174842. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  174843. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  174844. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  174845. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  174846. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  174847. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  174848. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  174849. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  174850. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  174851. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  174852. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  174853. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  174854. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  174855. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  174856. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  174857. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  174858. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  174859. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  174860. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  174861. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  174862. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  174863. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  174864. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  174865. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  174866. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  174867. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  174868. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  174869. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  174870. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  174871. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  174872. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  174873. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  174874. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  174875. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  174876. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  174877. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  174878. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  174879. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  174880. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  174881. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  174882. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  174883. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  174884. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  174885. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  174886. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  174887. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  174888. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  174889. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  174890. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  174891. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  174892. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  174893. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  174894. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  174895. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  174896. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  174897. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  174898. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  174899. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  174900. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  174901. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  174902. 0x380400F0,
  174903. };
  174904. static const unsigned int aAscii[4] = {
  174905. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  174906. };
  174907. if( (unsigned int)c<128 ){
  174908. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  174909. }else if( (unsigned int)c<(1<<22) ){
  174910. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  174911. int iRes = 0;
  174912. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  174913. int iLo = 0;
  174914. while( iHi>=iLo ){
  174915. int iTest = (iHi + iLo) / 2;
  174916. if( key >= aEntry[iTest] ){
  174917. iRes = iTest;
  174918. iLo = iTest+1;
  174919. }else{
  174920. iHi = iTest-1;
  174921. }
  174922. }
  174923. assert( aEntry[0]<key );
  174924. assert( key>=aEntry[iRes] );
  174925. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  174926. }
  174927. return 1;
  174928. }
  174929. /*
  174930. ** If the argument is a codepoint corresponding to a lowercase letter
  174931. ** in the ASCII range with a diacritic added, return the codepoint
  174932. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  174933. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  174934. ** E"). The resuls of passing a codepoint that corresponds to an
  174935. ** uppercase letter are undefined.
  174936. */
  174937. static int fts5_remove_diacritic(int c){
  174938. unsigned short aDia[] = {
  174939. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  174940. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  174941. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  174942. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  174943. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  174944. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  174945. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  174946. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  174947. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  174948. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  174949. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  174950. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  174951. 62924, 63050, 63082, 63274, 63390,
  174952. };
  174953. char aChar[] = {
  174954. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  174955. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  174956. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  174957. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  174958. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  174959. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  174960. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  174961. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  174962. 'e', 'i', 'o', 'u', 'y',
  174963. };
  174964. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  174965. int iRes = 0;
  174966. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  174967. int iLo = 0;
  174968. while( iHi>=iLo ){
  174969. int iTest = (iHi + iLo) / 2;
  174970. if( key >= aDia[iTest] ){
  174971. iRes = iTest;
  174972. iLo = iTest+1;
  174973. }else{
  174974. iHi = iTest-1;
  174975. }
  174976. }
  174977. assert( key>=aDia[iRes] );
  174978. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  174979. }
  174980. /*
  174981. ** Return true if the argument interpreted as a unicode codepoint
  174982. ** is a diacritical modifier character.
  174983. */
  174984. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  174985. unsigned int mask0 = 0x08029FDF;
  174986. unsigned int mask1 = 0x000361F8;
  174987. if( c<768 || c>817 ) return 0;
  174988. return (c < 768+32) ?
  174989. (mask0 & (1 << (c-768))) :
  174990. (mask1 & (1 << (c-768-32)));
  174991. }
  174992. /*
  174993. ** Interpret the argument as a unicode codepoint. If the codepoint
  174994. ** is an upper case character that has a lower case equivalent,
  174995. ** return the codepoint corresponding to the lower case version.
  174996. ** Otherwise, return a copy of the argument.
  174997. **
  174998. ** The results are undefined if the value passed to this function
  174999. ** is less than zero.
  175000. */
  175001. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  175002. /* Each entry in the following array defines a rule for folding a range
  175003. ** of codepoints to lower case. The rule applies to a range of nRange
  175004. ** codepoints starting at codepoint iCode.
  175005. **
  175006. ** If the least significant bit in flags is clear, then the rule applies
  175007. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  175008. ** need to be folded). Or, if it is set, then the rule only applies to
  175009. ** every second codepoint in the range, starting with codepoint C.
  175010. **
  175011. ** The 7 most significant bits in flags are an index into the aiOff[]
  175012. ** array. If a specific codepoint C does require folding, then its lower
  175013. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  175014. **
  175015. ** The contents of this array are generated by parsing the CaseFolding.txt
  175016. ** file distributed as part of the "Unicode Character Database". See
  175017. ** http://www.unicode.org for details.
  175018. */
  175019. static const struct TableEntry {
  175020. unsigned short iCode;
  175021. unsigned char flags;
  175022. unsigned char nRange;
  175023. } aEntry[] = {
  175024. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  175025. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  175026. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  175027. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  175028. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  175029. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  175030. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  175031. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  175032. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  175033. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  175034. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  175035. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  175036. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  175037. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  175038. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  175039. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  175040. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  175041. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  175042. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  175043. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  175044. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  175045. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  175046. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  175047. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  175048. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  175049. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  175050. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  175051. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  175052. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  175053. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  175054. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  175055. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  175056. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  175057. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  175058. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  175059. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  175060. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  175061. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  175062. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  175063. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  175064. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  175065. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  175066. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  175067. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  175068. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  175069. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  175070. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  175071. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  175072. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  175073. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  175074. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  175075. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  175076. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  175077. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  175078. {65313, 14, 26},
  175079. };
  175080. static const unsigned short aiOff[] = {
  175081. 1, 2, 8, 15, 16, 26, 28, 32,
  175082. 37, 38, 40, 48, 63, 64, 69, 71,
  175083. 79, 80, 116, 202, 203, 205, 206, 207,
  175084. 209, 210, 211, 213, 214, 217, 218, 219,
  175085. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  175086. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  175087. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  175088. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  175089. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  175090. 65514, 65521, 65527, 65528, 65529,
  175091. };
  175092. int ret = c;
  175093. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  175094. if( c<128 ){
  175095. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  175096. }else if( c<65536 ){
  175097. const struct TableEntry *p;
  175098. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  175099. int iLo = 0;
  175100. int iRes = -1;
  175101. assert( c>aEntry[0].iCode );
  175102. while( iHi>=iLo ){
  175103. int iTest = (iHi + iLo) / 2;
  175104. int cmp = (c - aEntry[iTest].iCode);
  175105. if( cmp>=0 ){
  175106. iRes = iTest;
  175107. iLo = iTest+1;
  175108. }else{
  175109. iHi = iTest-1;
  175110. }
  175111. }
  175112. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  175113. p = &aEntry[iRes];
  175114. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  175115. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  175116. assert( ret>0 );
  175117. }
  175118. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  175119. }
  175120. else if( c>=66560 && c<66600 ){
  175121. ret = c + 40;
  175122. }
  175123. return ret;
  175124. }
  175125. /*
  175126. ** 2015 May 30
  175127. **
  175128. ** The author disclaims copyright to this source code. In place of
  175129. ** a legal notice, here is a blessing:
  175130. **
  175131. ** May you do good and not evil.
  175132. ** May you find forgiveness for yourself and forgive others.
  175133. ** May you share freely, never taking more than you give.
  175134. **
  175135. ******************************************************************************
  175136. **
  175137. ** Routines for varint serialization and deserialization.
  175138. */
  175139. /* #include "fts5Int.h" */
  175140. /*
  175141. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  175142. ** Except, this version does handle the single byte case that the core
  175143. ** version depends on being handled before its function is called.
  175144. */
  175145. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  175146. u32 a,b;
  175147. /* The 1-byte case. Overwhelmingly the most common. */
  175148. a = *p;
  175149. /* a: p0 (unmasked) */
  175150. if (!(a&0x80))
  175151. {
  175152. /* Values between 0 and 127 */
  175153. *v = a;
  175154. return 1;
  175155. }
  175156. /* The 2-byte case */
  175157. p++;
  175158. b = *p;
  175159. /* b: p1 (unmasked) */
  175160. if (!(b&0x80))
  175161. {
  175162. /* Values between 128 and 16383 */
  175163. a &= 0x7f;
  175164. a = a<<7;
  175165. *v = a | b;
  175166. return 2;
  175167. }
  175168. /* The 3-byte case */
  175169. p++;
  175170. a = a<<14;
  175171. a |= *p;
  175172. /* a: p0<<14 | p2 (unmasked) */
  175173. if (!(a&0x80))
  175174. {
  175175. /* Values between 16384 and 2097151 */
  175176. a &= (0x7f<<14)|(0x7f);
  175177. b &= 0x7f;
  175178. b = b<<7;
  175179. *v = a | b;
  175180. return 3;
  175181. }
  175182. /* A 32-bit varint is used to store size information in btrees.
  175183. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  175184. ** A 3-byte varint is sufficient, for example, to record the size
  175185. ** of a 1048569-byte BLOB or string.
  175186. **
  175187. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  175188. ** rare larger cases can be handled by the slower 64-bit varint
  175189. ** routine.
  175190. */
  175191. {
  175192. u64 v64;
  175193. u8 n;
  175194. p -= 2;
  175195. n = sqlite3Fts5GetVarint(p, &v64);
  175196. *v = (u32)v64;
  175197. assert( n>3 && n<=9 );
  175198. return n;
  175199. }
  175200. }
  175201. /*
  175202. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  175203. ** are defined here rather than simply putting the constant expressions
  175204. ** inline in order to work around bugs in the RVT compiler.
  175205. **
  175206. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  175207. **
  175208. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  175209. */
  175210. #define SLOT_2_0 0x001fc07f
  175211. #define SLOT_4_2_0 0xf01fc07f
  175212. /*
  175213. ** Read a 64-bit variable-length integer from memory starting at p[0].
  175214. ** Return the number of bytes read. The value is stored in *v.
  175215. */
  175216. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  175217. u32 a,b,s;
  175218. a = *p;
  175219. /* a: p0 (unmasked) */
  175220. if (!(a&0x80))
  175221. {
  175222. *v = a;
  175223. return 1;
  175224. }
  175225. p++;
  175226. b = *p;
  175227. /* b: p1 (unmasked) */
  175228. if (!(b&0x80))
  175229. {
  175230. a &= 0x7f;
  175231. a = a<<7;
  175232. a |= b;
  175233. *v = a;
  175234. return 2;
  175235. }
  175236. /* Verify that constants are precomputed correctly */
  175237. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  175238. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  175239. p++;
  175240. a = a<<14;
  175241. a |= *p;
  175242. /* a: p0<<14 | p2 (unmasked) */
  175243. if (!(a&0x80))
  175244. {
  175245. a &= SLOT_2_0;
  175246. b &= 0x7f;
  175247. b = b<<7;
  175248. a |= b;
  175249. *v = a;
  175250. return 3;
  175251. }
  175252. /* CSE1 from below */
  175253. a &= SLOT_2_0;
  175254. p++;
  175255. b = b<<14;
  175256. b |= *p;
  175257. /* b: p1<<14 | p3 (unmasked) */
  175258. if (!(b&0x80))
  175259. {
  175260. b &= SLOT_2_0;
  175261. /* moved CSE1 up */
  175262. /* a &= (0x7f<<14)|(0x7f); */
  175263. a = a<<7;
  175264. a |= b;
  175265. *v = a;
  175266. return 4;
  175267. }
  175268. /* a: p0<<14 | p2 (masked) */
  175269. /* b: p1<<14 | p3 (unmasked) */
  175270. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  175271. /* moved CSE1 up */
  175272. /* a &= (0x7f<<14)|(0x7f); */
  175273. b &= SLOT_2_0;
  175274. s = a;
  175275. /* s: p0<<14 | p2 (masked) */
  175276. p++;
  175277. a = a<<14;
  175278. a |= *p;
  175279. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  175280. if (!(a&0x80))
  175281. {
  175282. /* we can skip these cause they were (effectively) done above in calc'ing s */
  175283. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  175284. /* b &= (0x7f<<14)|(0x7f); */
  175285. b = b<<7;
  175286. a |= b;
  175287. s = s>>18;
  175288. *v = ((u64)s)<<32 | a;
  175289. return 5;
  175290. }
  175291. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  175292. s = s<<7;
  175293. s |= b;
  175294. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  175295. p++;
  175296. b = b<<14;
  175297. b |= *p;
  175298. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  175299. if (!(b&0x80))
  175300. {
  175301. /* we can skip this cause it was (effectively) done above in calc'ing s */
  175302. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  175303. a &= SLOT_2_0;
  175304. a = a<<7;
  175305. a |= b;
  175306. s = s>>18;
  175307. *v = ((u64)s)<<32 | a;
  175308. return 6;
  175309. }
  175310. p++;
  175311. a = a<<14;
  175312. a |= *p;
  175313. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  175314. if (!(a&0x80))
  175315. {
  175316. a &= SLOT_4_2_0;
  175317. b &= SLOT_2_0;
  175318. b = b<<7;
  175319. a |= b;
  175320. s = s>>11;
  175321. *v = ((u64)s)<<32 | a;
  175322. return 7;
  175323. }
  175324. /* CSE2 from below */
  175325. a &= SLOT_2_0;
  175326. p++;
  175327. b = b<<14;
  175328. b |= *p;
  175329. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  175330. if (!(b&0x80))
  175331. {
  175332. b &= SLOT_4_2_0;
  175333. /* moved CSE2 up */
  175334. /* a &= (0x7f<<14)|(0x7f); */
  175335. a = a<<7;
  175336. a |= b;
  175337. s = s>>4;
  175338. *v = ((u64)s)<<32 | a;
  175339. return 8;
  175340. }
  175341. p++;
  175342. a = a<<15;
  175343. a |= *p;
  175344. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  175345. /* moved CSE2 up */
  175346. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  175347. b &= SLOT_2_0;
  175348. b = b<<8;
  175349. a |= b;
  175350. s = s<<4;
  175351. b = p[-4];
  175352. b &= 0x7f;
  175353. b = b>>3;
  175354. s |= b;
  175355. *v = ((u64)s)<<32 | a;
  175356. return 9;
  175357. }
  175358. /*
  175359. ** The variable-length integer encoding is as follows:
  175360. **
  175361. ** KEY:
  175362. ** A = 0xxxxxxx 7 bits of data and one flag bit
  175363. ** B = 1xxxxxxx 7 bits of data and one flag bit
  175364. ** C = xxxxxxxx 8 bits of data
  175365. **
  175366. ** 7 bits - A
  175367. ** 14 bits - BA
  175368. ** 21 bits - BBA
  175369. ** 28 bits - BBBA
  175370. ** 35 bits - BBBBA
  175371. ** 42 bits - BBBBBA
  175372. ** 49 bits - BBBBBBA
  175373. ** 56 bits - BBBBBBBA
  175374. ** 64 bits - BBBBBBBBC
  175375. */
  175376. #ifdef SQLITE_NOINLINE
  175377. # define FTS5_NOINLINE SQLITE_NOINLINE
  175378. #else
  175379. # define FTS5_NOINLINE
  175380. #endif
  175381. /*
  175382. ** Write a 64-bit variable-length integer to memory starting at p[0].
  175383. ** The length of data write will be between 1 and 9 bytes. The number
  175384. ** of bytes written is returned.
  175385. **
  175386. ** A variable-length integer consists of the lower 7 bits of each byte
  175387. ** for all bytes that have the 8th bit set and one byte with the 8th
  175388. ** bit clear. Except, if we get to the 9th byte, it stores the full
  175389. ** 8 bits and is the last byte.
  175390. */
  175391. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  175392. int i, j, n;
  175393. u8 buf[10];
  175394. if( v & (((u64)0xff000000)<<32) ){
  175395. p[8] = (u8)v;
  175396. v >>= 8;
  175397. for(i=7; i>=0; i--){
  175398. p[i] = (u8)((v & 0x7f) | 0x80);
  175399. v >>= 7;
  175400. }
  175401. return 9;
  175402. }
  175403. n = 0;
  175404. do{
  175405. buf[n++] = (u8)((v & 0x7f) | 0x80);
  175406. v >>= 7;
  175407. }while( v!=0 );
  175408. buf[0] &= 0x7f;
  175409. assert( n<=9 );
  175410. for(i=0, j=n-1; j>=0; j--, i++){
  175411. p[i] = buf[j];
  175412. }
  175413. return n;
  175414. }
  175415. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  175416. if( v<=0x7f ){
  175417. p[0] = v&0x7f;
  175418. return 1;
  175419. }
  175420. if( v<=0x3fff ){
  175421. p[0] = ((v>>7)&0x7f)|0x80;
  175422. p[1] = v&0x7f;
  175423. return 2;
  175424. }
  175425. return fts5PutVarint64(p,v);
  175426. }
  175427. static int sqlite3Fts5GetVarintLen(u32 iVal){
  175428. #if 0
  175429. if( iVal<(1 << 7 ) ) return 1;
  175430. #endif
  175431. assert( iVal>=(1 << 7) );
  175432. if( iVal<(1 << 14) ) return 2;
  175433. if( iVal<(1 << 21) ) return 3;
  175434. if( iVal<(1 << 28) ) return 4;
  175435. return 5;
  175436. }
  175437. /*
  175438. ** 2015 May 08
  175439. **
  175440. ** The author disclaims copyright to this source code. In place of
  175441. ** a legal notice, here is a blessing:
  175442. **
  175443. ** May you do good and not evil.
  175444. ** May you find forgiveness for yourself and forgive others.
  175445. ** May you share freely, never taking more than you give.
  175446. **
  175447. ******************************************************************************
  175448. **
  175449. ** This is an SQLite virtual table module implementing direct access to an
  175450. ** existing FTS5 index. The module may create several different types of
  175451. ** tables:
  175452. **
  175453. ** col:
  175454. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  175455. **
  175456. ** One row for each term/column combination. The value of $doc is set to
  175457. ** the number of fts5 rows that contain at least one instance of term
  175458. ** $term within column $col. Field $cnt is set to the total number of
  175459. ** instances of term $term in column $col (in any row of the fts5 table).
  175460. **
  175461. ** row:
  175462. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  175463. **
  175464. ** One row for each term in the database. The value of $doc is set to
  175465. ** the number of fts5 rows that contain at least one instance of term
  175466. ** $term. Field $cnt is set to the total number of instances of term
  175467. ** $term in the database.
  175468. */
  175469. /* #include "fts5Int.h" */
  175470. typedef struct Fts5VocabTable Fts5VocabTable;
  175471. typedef struct Fts5VocabCursor Fts5VocabCursor;
  175472. struct Fts5VocabTable {
  175473. sqlite3_vtab base;
  175474. char *zFts5Tbl; /* Name of fts5 table */
  175475. char *zFts5Db; /* Db containing fts5 table */
  175476. sqlite3 *db; /* Database handle */
  175477. Fts5Global *pGlobal; /* FTS5 global object for this database */
  175478. int eType; /* FTS5_VOCAB_COL or ROW */
  175479. };
  175480. struct Fts5VocabCursor {
  175481. sqlite3_vtab_cursor base;
  175482. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  175483. Fts5Index *pIndex; /* Associated FTS5 index */
  175484. int bEof; /* True if this cursor is at EOF */
  175485. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  175486. int nLeTerm; /* Size of zLeTerm in bytes */
  175487. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  175488. /* These are used by 'col' tables only */
  175489. Fts5Config *pConfig; /* Fts5 table configuration */
  175490. int iCol;
  175491. i64 *aCnt;
  175492. i64 *aDoc;
  175493. /* Output values used by 'row' and 'col' tables */
  175494. i64 rowid; /* This table's current rowid value */
  175495. Fts5Buffer term; /* Current value of 'term' column */
  175496. };
  175497. #define FTS5_VOCAB_COL 0
  175498. #define FTS5_VOCAB_ROW 1
  175499. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  175500. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  175501. /*
  175502. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  175503. */
  175504. #define FTS5_VOCAB_TERM_EQ 0x01
  175505. #define FTS5_VOCAB_TERM_GE 0x02
  175506. #define FTS5_VOCAB_TERM_LE 0x04
  175507. /*
  175508. ** Translate a string containing an fts5vocab table type to an
  175509. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  175510. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  175511. ** and return SQLITE_ERROR.
  175512. */
  175513. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  175514. int rc = SQLITE_OK;
  175515. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  175516. if( rc==SQLITE_OK ){
  175517. sqlite3Fts5Dequote(zCopy);
  175518. if( sqlite3_stricmp(zCopy, "col")==0 ){
  175519. *peType = FTS5_VOCAB_COL;
  175520. }else
  175521. if( sqlite3_stricmp(zCopy, "row")==0 ){
  175522. *peType = FTS5_VOCAB_ROW;
  175523. }else
  175524. {
  175525. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  175526. rc = SQLITE_ERROR;
  175527. }
  175528. sqlite3_free(zCopy);
  175529. }
  175530. return rc;
  175531. }
  175532. /*
  175533. ** The xDisconnect() virtual table method.
  175534. */
  175535. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  175536. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  175537. sqlite3_free(pTab);
  175538. return SQLITE_OK;
  175539. }
  175540. /*
  175541. ** The xDestroy() virtual table method.
  175542. */
  175543. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  175544. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  175545. sqlite3_free(pTab);
  175546. return SQLITE_OK;
  175547. }
  175548. /*
  175549. ** This function is the implementation of both the xConnect and xCreate
  175550. ** methods of the FTS3 virtual table.
  175551. **
  175552. ** The argv[] array contains the following:
  175553. **
  175554. ** argv[0] -> module name ("fts5vocab")
  175555. ** argv[1] -> database name
  175556. ** argv[2] -> table name
  175557. **
  175558. ** then:
  175559. **
  175560. ** argv[3] -> name of fts5 table
  175561. ** argv[4] -> type of fts5vocab table
  175562. **
  175563. ** or, for tables in the TEMP schema only.
  175564. **
  175565. ** argv[3] -> name of fts5 tables database
  175566. ** argv[4] -> name of fts5 table
  175567. ** argv[5] -> type of fts5vocab table
  175568. */
  175569. static int fts5VocabInitVtab(
  175570. sqlite3 *db, /* The SQLite database connection */
  175571. void *pAux, /* Pointer to Fts5Global object */
  175572. int argc, /* Number of elements in argv array */
  175573. const char * const *argv, /* xCreate/xConnect argument array */
  175574. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  175575. char **pzErr /* Write any error message here */
  175576. ){
  175577. const char *azSchema[] = {
  175578. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  175579. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
  175580. };
  175581. Fts5VocabTable *pRet = 0;
  175582. int rc = SQLITE_OK; /* Return code */
  175583. int bDb;
  175584. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  175585. if( argc!=5 && bDb==0 ){
  175586. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  175587. rc = SQLITE_ERROR;
  175588. }else{
  175589. int nByte; /* Bytes of space to allocate */
  175590. const char *zDb = bDb ? argv[3] : argv[1];
  175591. const char *zTab = bDb ? argv[4] : argv[3];
  175592. const char *zType = bDb ? argv[5] : argv[4];
  175593. int nDb = (int)strlen(zDb)+1;
  175594. int nTab = (int)strlen(zTab)+1;
  175595. int eType = 0;
  175596. rc = fts5VocabTableType(zType, pzErr, &eType);
  175597. if( rc==SQLITE_OK ){
  175598. assert( eType>=0 && eType<ArraySize(azSchema) );
  175599. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  175600. }
  175601. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  175602. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  175603. if( pRet ){
  175604. pRet->pGlobal = (Fts5Global*)pAux;
  175605. pRet->eType = eType;
  175606. pRet->db = db;
  175607. pRet->zFts5Tbl = (char*)&pRet[1];
  175608. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  175609. memcpy(pRet->zFts5Tbl, zTab, nTab);
  175610. memcpy(pRet->zFts5Db, zDb, nDb);
  175611. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  175612. sqlite3Fts5Dequote(pRet->zFts5Db);
  175613. }
  175614. }
  175615. *ppVTab = (sqlite3_vtab*)pRet;
  175616. return rc;
  175617. }
  175618. /*
  175619. ** The xConnect() and xCreate() methods for the virtual table. All the
  175620. ** work is done in function fts5VocabInitVtab().
  175621. */
  175622. static int fts5VocabConnectMethod(
  175623. sqlite3 *db, /* Database connection */
  175624. void *pAux, /* Pointer to tokenizer hash table */
  175625. int argc, /* Number of elements in argv array */
  175626. const char * const *argv, /* xCreate/xConnect argument array */
  175627. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  175628. char **pzErr /* OUT: sqlite3_malloc'd error message */
  175629. ){
  175630. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  175631. }
  175632. static int fts5VocabCreateMethod(
  175633. sqlite3 *db, /* Database connection */
  175634. void *pAux, /* Pointer to tokenizer hash table */
  175635. int argc, /* Number of elements in argv array */
  175636. const char * const *argv, /* xCreate/xConnect argument array */
  175637. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  175638. char **pzErr /* OUT: sqlite3_malloc'd error message */
  175639. ){
  175640. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  175641. }
  175642. /*
  175643. ** Implementation of the xBestIndex method.
  175644. */
  175645. static int fts5VocabBestIndexMethod(
  175646. sqlite3_vtab *pUnused,
  175647. sqlite3_index_info *pInfo
  175648. ){
  175649. int i;
  175650. int iTermEq = -1;
  175651. int iTermGe = -1;
  175652. int iTermLe = -1;
  175653. int idxNum = 0;
  175654. int nArg = 0;
  175655. UNUSED_PARAM(pUnused);
  175656. for(i=0; i<pInfo->nConstraint; i++){
  175657. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  175658. if( p->usable==0 ) continue;
  175659. if( p->iColumn==0 ){ /* term column */
  175660. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  175661. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  175662. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  175663. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  175664. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  175665. }
  175666. }
  175667. if( iTermEq>=0 ){
  175668. idxNum |= FTS5_VOCAB_TERM_EQ;
  175669. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  175670. pInfo->estimatedCost = 100;
  175671. }else{
  175672. pInfo->estimatedCost = 1000000;
  175673. if( iTermGe>=0 ){
  175674. idxNum |= FTS5_VOCAB_TERM_GE;
  175675. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  175676. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  175677. }
  175678. if( iTermLe>=0 ){
  175679. idxNum |= FTS5_VOCAB_TERM_LE;
  175680. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  175681. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  175682. }
  175683. }
  175684. pInfo->idxNum = idxNum;
  175685. return SQLITE_OK;
  175686. }
  175687. /*
  175688. ** Implementation of xOpen method.
  175689. */
  175690. static int fts5VocabOpenMethod(
  175691. sqlite3_vtab *pVTab,
  175692. sqlite3_vtab_cursor **ppCsr
  175693. ){
  175694. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  175695. Fts5Index *pIndex = 0;
  175696. Fts5Config *pConfig = 0;
  175697. Fts5VocabCursor *pCsr = 0;
  175698. int rc = SQLITE_OK;
  175699. sqlite3_stmt *pStmt = 0;
  175700. char *zSql = 0;
  175701. zSql = sqlite3Fts5Mprintf(&rc,
  175702. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  175703. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  175704. );
  175705. if( zSql ){
  175706. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  175707. }
  175708. sqlite3_free(zSql);
  175709. assert( rc==SQLITE_OK || pStmt==0 );
  175710. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  175711. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  175712. i64 iId = sqlite3_column_int64(pStmt, 0);
  175713. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  175714. }
  175715. if( rc==SQLITE_OK && pIndex==0 ){
  175716. rc = sqlite3_finalize(pStmt);
  175717. pStmt = 0;
  175718. if( rc==SQLITE_OK ){
  175719. pVTab->zErrMsg = sqlite3_mprintf(
  175720. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  175721. );
  175722. rc = SQLITE_ERROR;
  175723. }
  175724. }
  175725. if( rc==SQLITE_OK ){
  175726. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  175727. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  175728. }
  175729. if( pCsr ){
  175730. pCsr->pIndex = pIndex;
  175731. pCsr->pStmt = pStmt;
  175732. pCsr->pConfig = pConfig;
  175733. pCsr->aCnt = (i64*)&pCsr[1];
  175734. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  175735. }else{
  175736. sqlite3_finalize(pStmt);
  175737. }
  175738. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  175739. return rc;
  175740. }
  175741. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  175742. pCsr->rowid = 0;
  175743. sqlite3Fts5IterClose(pCsr->pIter);
  175744. pCsr->pIter = 0;
  175745. sqlite3_free(pCsr->zLeTerm);
  175746. pCsr->nLeTerm = -1;
  175747. pCsr->zLeTerm = 0;
  175748. }
  175749. /*
  175750. ** Close the cursor. For additional information see the documentation
  175751. ** on the xClose method of the virtual table interface.
  175752. */
  175753. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  175754. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  175755. fts5VocabResetCursor(pCsr);
  175756. sqlite3Fts5BufferFree(&pCsr->term);
  175757. sqlite3_finalize(pCsr->pStmt);
  175758. sqlite3_free(pCsr);
  175759. return SQLITE_OK;
  175760. }
  175761. /*
  175762. ** Advance the cursor to the next row in the table.
  175763. */
  175764. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  175765. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  175766. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  175767. int rc = SQLITE_OK;
  175768. int nCol = pCsr->pConfig->nCol;
  175769. pCsr->rowid++;
  175770. if( pTab->eType==FTS5_VOCAB_COL ){
  175771. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  175772. if( pCsr->aDoc[pCsr->iCol] ) break;
  175773. }
  175774. }
  175775. if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
  175776. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  175777. pCsr->bEof = 1;
  175778. }else{
  175779. const char *zTerm;
  175780. int nTerm;
  175781. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  175782. if( pCsr->nLeTerm>=0 ){
  175783. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  175784. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  175785. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  175786. pCsr->bEof = 1;
  175787. return SQLITE_OK;
  175788. }
  175789. }
  175790. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  175791. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  175792. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  175793. pCsr->iCol = 0;
  175794. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  175795. while( rc==SQLITE_OK ){
  175796. const u8 *pPos; int nPos; /* Position list */
  175797. i64 iPos = 0; /* 64-bit position read from poslist */
  175798. int iOff = 0; /* Current offset within position list */
  175799. pPos = pCsr->pIter->pData;
  175800. nPos = pCsr->pIter->nData;
  175801. switch( pCsr->pConfig->eDetail ){
  175802. case FTS5_DETAIL_FULL:
  175803. pPos = pCsr->pIter->pData;
  175804. nPos = pCsr->pIter->nData;
  175805. if( pTab->eType==FTS5_VOCAB_ROW ){
  175806. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  175807. pCsr->aCnt[0]++;
  175808. }
  175809. pCsr->aDoc[0]++;
  175810. }else{
  175811. int iCol = -1;
  175812. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  175813. int ii = FTS5_POS2COLUMN(iPos);
  175814. pCsr->aCnt[ii]++;
  175815. if( iCol!=ii ){
  175816. if( ii>=nCol ){
  175817. rc = FTS5_CORRUPT;
  175818. break;
  175819. }
  175820. pCsr->aDoc[ii]++;
  175821. iCol = ii;
  175822. }
  175823. }
  175824. }
  175825. break;
  175826. case FTS5_DETAIL_COLUMNS:
  175827. if( pTab->eType==FTS5_VOCAB_ROW ){
  175828. pCsr->aDoc[0]++;
  175829. }else{
  175830. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  175831. assert_nc( iPos>=0 && iPos<nCol );
  175832. if( iPos>=nCol ){
  175833. rc = FTS5_CORRUPT;
  175834. break;
  175835. }
  175836. pCsr->aDoc[iPos]++;
  175837. }
  175838. }
  175839. break;
  175840. default:
  175841. assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
  175842. pCsr->aDoc[0]++;
  175843. break;
  175844. }
  175845. if( rc==SQLITE_OK ){
  175846. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  175847. }
  175848. if( rc==SQLITE_OK ){
  175849. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  175850. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  175851. break;
  175852. }
  175853. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  175854. }
  175855. }
  175856. }
  175857. }
  175858. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  175859. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  175860. assert( pCsr->iCol<pCsr->pConfig->nCol );
  175861. }
  175862. return rc;
  175863. }
  175864. /*
  175865. ** This is the xFilter implementation for the virtual table.
  175866. */
  175867. static int fts5VocabFilterMethod(
  175868. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  175869. int idxNum, /* Strategy index */
  175870. const char *zUnused, /* Unused */
  175871. int nUnused, /* Number of elements in apVal */
  175872. sqlite3_value **apVal /* Arguments for the indexing scheme */
  175873. ){
  175874. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  175875. int rc = SQLITE_OK;
  175876. int iVal = 0;
  175877. int f = FTS5INDEX_QUERY_SCAN;
  175878. const char *zTerm = 0;
  175879. int nTerm = 0;
  175880. sqlite3_value *pEq = 0;
  175881. sqlite3_value *pGe = 0;
  175882. sqlite3_value *pLe = 0;
  175883. UNUSED_PARAM2(zUnused, nUnused);
  175884. fts5VocabResetCursor(pCsr);
  175885. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  175886. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  175887. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  175888. if( pEq ){
  175889. zTerm = (const char *)sqlite3_value_text(pEq);
  175890. nTerm = sqlite3_value_bytes(pEq);
  175891. f = 0;
  175892. }else{
  175893. if( pGe ){
  175894. zTerm = (const char *)sqlite3_value_text(pGe);
  175895. nTerm = sqlite3_value_bytes(pGe);
  175896. }
  175897. if( pLe ){
  175898. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  175899. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  175900. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  175901. if( pCsr->zLeTerm==0 ){
  175902. rc = SQLITE_NOMEM;
  175903. }else{
  175904. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  175905. }
  175906. }
  175907. }
  175908. if( rc==SQLITE_OK ){
  175909. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  175910. }
  175911. if( rc==SQLITE_OK ){
  175912. rc = fts5VocabNextMethod(pCursor);
  175913. }
  175914. return rc;
  175915. }
  175916. /*
  175917. ** This is the xEof method of the virtual table. SQLite calls this
  175918. ** routine to find out if it has reached the end of a result set.
  175919. */
  175920. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  175921. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  175922. return pCsr->bEof;
  175923. }
  175924. static int fts5VocabColumnMethod(
  175925. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  175926. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  175927. int iCol /* Index of column to read value from */
  175928. ){
  175929. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  175930. int eDetail = pCsr->pConfig->eDetail;
  175931. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  175932. i64 iVal = 0;
  175933. if( iCol==0 ){
  175934. sqlite3_result_text(
  175935. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  175936. );
  175937. }else if( eType==FTS5_VOCAB_COL ){
  175938. assert( iCol==1 || iCol==2 || iCol==3 );
  175939. if( iCol==1 ){
  175940. if( eDetail!=FTS5_DETAIL_NONE ){
  175941. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  175942. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  175943. }
  175944. }else if( iCol==2 ){
  175945. iVal = pCsr->aDoc[pCsr->iCol];
  175946. }else{
  175947. iVal = pCsr->aCnt[pCsr->iCol];
  175948. }
  175949. }else{
  175950. assert( iCol==1 || iCol==2 );
  175951. if( iCol==1 ){
  175952. iVal = pCsr->aDoc[0];
  175953. }else{
  175954. iVal = pCsr->aCnt[0];
  175955. }
  175956. }
  175957. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  175958. return SQLITE_OK;
  175959. }
  175960. /*
  175961. ** This is the xRowid method. The SQLite core calls this routine to
  175962. ** retrieve the rowid for the current row of the result set. The
  175963. ** rowid should be written to *pRowid.
  175964. */
  175965. static int fts5VocabRowidMethod(
  175966. sqlite3_vtab_cursor *pCursor,
  175967. sqlite_int64 *pRowid
  175968. ){
  175969. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  175970. *pRowid = pCsr->rowid;
  175971. return SQLITE_OK;
  175972. }
  175973. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  175974. static const sqlite3_module fts5Vocab = {
  175975. /* iVersion */ 2,
  175976. /* xCreate */ fts5VocabCreateMethod,
  175977. /* xConnect */ fts5VocabConnectMethod,
  175978. /* xBestIndex */ fts5VocabBestIndexMethod,
  175979. /* xDisconnect */ fts5VocabDisconnectMethod,
  175980. /* xDestroy */ fts5VocabDestroyMethod,
  175981. /* xOpen */ fts5VocabOpenMethod,
  175982. /* xClose */ fts5VocabCloseMethod,
  175983. /* xFilter */ fts5VocabFilterMethod,
  175984. /* xNext */ fts5VocabNextMethod,
  175985. /* xEof */ fts5VocabEofMethod,
  175986. /* xColumn */ fts5VocabColumnMethod,
  175987. /* xRowid */ fts5VocabRowidMethod,
  175988. /* xUpdate */ 0,
  175989. /* xBegin */ 0,
  175990. /* xSync */ 0,
  175991. /* xCommit */ 0,
  175992. /* xRollback */ 0,
  175993. /* xFindFunction */ 0,
  175994. /* xRename */ 0,
  175995. /* xSavepoint */ 0,
  175996. /* xRelease */ 0,
  175997. /* xRollbackTo */ 0,
  175998. };
  175999. void *p = (void*)pGlobal;
  176000. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  176001. }
  176002. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  176003. /************** End of fts5.c ************************************************/